diff --git a/Cmfcmf/OpenWeatherMap/Util/Unit.php b/Cmfcmf/OpenWeatherMap/Util/Unit.php index 9ad7a76..577db62 100644 --- a/Cmfcmf/OpenWeatherMap/Util/Unit.php +++ b/Cmfcmf/OpenWeatherMap/Util/Unit.php @@ -18,10 +18,12 @@ namespace Cmfcmf\OpenWeatherMap\Util; +use JsonSerializable; + /** * The unit class representing a unit object. */ -class Unit +class Unit implements JsonSerializable { /** * @var float The value. @@ -144,4 +146,19 @@ public function getFormatted() return (string)$this->getValue(); } } + + /** + * Get Unit properties when encoding to JSON + * + * @return array + */ + public function jsonSerialize() + { + return [ + 'value' => $this->getValue(), + 'unit' => $this->getUnit(), + 'description' => $this->getDescription(), + 'precision' => $this->getPrecision() + ]; + } } diff --git a/tests/Util/UnitTest.php b/tests/Util/UnitTest.php index 358ffdd..c03d09f 100644 --- a/tests/Util/UnitTest.php +++ b/tests/Util/UnitTest.php @@ -167,4 +167,10 @@ public function testToString() $this->assertEquals($this->unit->getFormatted(), $this->unit); } + + public function testToJSON() + { + $unit = new Unit(42.5, "°C", "hot", "2.5"); + $this->assertEquals(json_encode($unit), '{"value":42.5,"unit":"\u00b0C","description":"hot","precision":2.5}'); + } }