From d2ebb543079be12388e4241988f4e4d59201289e Mon Sep 17 00:00:00 2001 From: Boris Glumpler Date: Sun, 9 Jul 2023 18:20:01 +0200 Subject: [PATCH] Base Unit class implements JsonSerializable now --- src/Unit.php | 15 ++++++++++++++- tests/UnitTest.php | 14 ++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/src/Unit.php b/src/Unit.php index 753ae7f..6340b39 100644 --- a/src/Unit.php +++ b/src/Unit.php @@ -1,13 +1,14 @@ getSymbol(); return (string)$this->getValue() . ($symbol ? ' ' . $symbol : ''); } + + /** + * @return array + */ + public function jsonSerialize() + { + return [ + 'value' => $this->getValue(), + 'symbol' => $this->getSymbol(), + 'label' => $this->getLabel(), + ]; + } } diff --git a/tests/UnitTest.php b/tests/UnitTest.php index d85fa24..25cc4ad 100644 --- a/tests/UnitTest.php +++ b/tests/UnitTest.php @@ -108,6 +108,20 @@ public function testToString() $this->assertEquals('1 u', (string)$unit); } + public function testToJson() + { + $unit = new MyUnitType\OneUnit(1); + + $expected = [ + 'value' => 1, + 'symbol' => 'u', + 'label' => 'unit', + ]; + + $this->assertEquals($expected, $unit->jsonSerialize()); + $this->assertEquals(json_encode($expected), json_encode($unit)); + } + public function testInvalidInvocation() { $this->expectException(Exception::class);