44
55
66use Prometheus \MetricFamilySamples ;
7+ use RuntimeException ;
78
89class InMemory implements Adapter
910{
@@ -60,7 +61,7 @@ private function collectHistograms()
6061 sort ($ labels );
6162 foreach ($ labels as $ labelValues ) {
6263 $ acc = 0 ;
63- $ decodedLabelValues = json_decode ($ labelValues );
64+ $ decodedLabelValues = $ this -> decodeLabelValues ($ labelValues );
6465 foreach ($ data ['buckets ' ] as $ bucket ) {
6566 $ bucket = (string )$ bucket ;
6667 if (!isset ($ histogramBuckets [$ labelValues ][$ bucket ])) {
@@ -120,7 +121,7 @@ private function internalCollect(array $metrics)
120121 $ data ['samples ' ][] = [
121122 'name ' => $ metaData ['name ' ],
122123 'labelNames ' => [],
123- 'labelValues ' => json_decode ($ labelValues ),
124+ 'labelValues ' => $ this -> decodeLabelValues ($ labelValues ),
124125 'value ' => $ value
125126 ];
126127 }
@@ -215,7 +216,7 @@ private function histogramBucketValueKey(array $data, $bucket)
215216 return implode (': ' , [
216217 $ data ['type ' ],
217218 $ data ['name ' ],
218- json_encode ($ data ['labelValues ' ]),
219+ $ this -> encodeLabelValues ($ data ['labelValues ' ]),
219220 $ bucket
220221 ]);
221222 }
@@ -238,7 +239,7 @@ private function metaKey(array $data)
238239 private function valueKey (array $ data )
239240 {
240241 return implode (': ' ,
241- [$ data ['type ' ], $ data ['name ' ], json_encode ($ data ['labelValues ' ]), 'value ' ]);
242+ [$ data ['type ' ], $ data ['name ' ], $ this -> encodeLabelValues ($ data ['labelValues ' ]), 'value ' ]);
242243 }
243244
244245 /**
@@ -261,4 +262,36 @@ private function sortSamples(array &$samples)
261262 return strcmp (implode ("" , $ a ['labelValues ' ]), implode ("" , $ b ['labelValues ' ]));
262263 });
263264 }
265+
266+ /**
267+ * @param array $values
268+ * @return string
269+ * @throws RuntimeException
270+ */
271+ private function encodeLabelValues (array $ values )
272+ {
273+ $ json = json_encode ($ values );
274+ if (false === $ json ) {
275+ throw new RuntimeException (json_last_error_msg ());
276+ }
277+ return base64_encode ($ json );
278+ }
279+
280+ /**
281+ * @param string $values
282+ * @return array
283+ * @throws RuntimeException
284+ */
285+ private function decodeLabelValues ($ values )
286+ {
287+ $ json = base64_decode ($ values , true );
288+ if (false === $ json ) {
289+ throw new RuntimeException ('Cannot base64 decode label values ' );
290+ }
291+ $ decodedValues = json_decode ($ json , true );
292+ if (false === $ decodedValues ) {
293+ throw new RuntimeException (json_last_error_msg ());
294+ }
295+ return $ decodedValues ;
296+ }
264297}
0 commit comments