diff --git a/src/Metric.php b/src/Metric.php index cd8c5f3..11a9570 100644 --- a/src/Metric.php +++ b/src/Metric.php @@ -159,6 +159,10 @@ public function register(): void */ public function record(float $value, array $labels = []): void { + if (!$this->registered()) { + $this->setLabels(array_keys($labels)); + } + $this->register(); $this->_record($value, $labels); } diff --git a/tests/CounterTest.php b/tests/CounterTest.php index d0ab8ea..0c2b79a 100644 --- a/tests/CounterTest.php +++ b/tests/CounterTest.php @@ -83,4 +83,46 @@ public function testRecord_success() $this->assertTrue($counter->registered()); } + + public function testRegRec_dynLabels() + { + $namespace = 'test'; + $name = 'counter'; + $description = 'hotdogs'; + $labels = ['foo' => 'bar']; + $value = $this->randValue(); + + $phprom = $this->getMockBuilder(PHProm::class) + ->disableOriginalConstructor() + ->getMock(); + + $phprom->expects($this->once()) + ->method('registerCounter') + ->with( + $namespace, + $name, + $description, + array_keys($labels) + ) + ->willReturn($this->randBool()); + + $phprom->expects($this->once()) + ->method('recordCounter') + ->with( + $namespace, + $name, + $value, + $labels + ) + ->willReturn($this->randBool()); + + $counter = (new Counter($phprom)) + ->setNamespace($namespace) + ->setName($name) + ->setDescription($description); + + $counter->record($value, $labels); + + $this->assertTrue($counter->registered()); + } }