diff --git a/composer.json b/composer.json index 5536905..9bd925a 100644 --- a/composer.json +++ b/composer.json @@ -27,7 +27,8 @@ }, "require": { - "php": ">=5.5.0" + "php": ">=5.5.0", + "ext-json": "*" }, "require-dev": { diff --git a/source/AbstractPhysicalQuantity.php b/source/AbstractPhysicalQuantity.php index e697b98..83359c2 100644 --- a/source/AbstractPhysicalQuantity.php +++ b/source/AbstractPhysicalQuantity.php @@ -1,7 +1,7 @@ originalValue . ' ' . static::getUnit($this->originalUnit)->getName()); } + /** + * {@inheritdoc} + * + * @return array + */ + public function jsonSerialize() + { + return [ + 'value' => $this->originalValue, + 'unit' => static::getUnit($this->originalUnit)->getName(), + ]; + } + /** * @see \PhpUnitsOfMeasure\PhysicalQuantityInterface::add */ diff --git a/tests/AbstractPhysicalQuantityTest.php b/tests/AbstractPhysicalQuantityTest.php index bbda2ed..b364ee5 100644 --- a/tests/AbstractPhysicalQuantityTest.php +++ b/tests/AbstractPhysicalQuantityTest.php @@ -141,6 +141,15 @@ public function testToString(AbstractPhysicalQuantity $value, $string) $this->assertSame($string, (string) $value); } + /** + * @dataProvider jsonSerializeProvider + * @covers \PhpUnitsOfMeasure\AbstractPhysicalQuantity::jsonSerialize + */ + public function testJsonSerialize(AbstractPhysicalQuantity $value, $serialized) + { + $this->assertSame($serialized, json_decode(json_encode($value), true)); + } + /** * * @dataProvider quantityConversionsProvider @@ -308,6 +317,23 @@ public function toStringProvider() ]; } + /** + * Provide some string conversion testing data + * 1) The object which will be json serialized + * 2) the expected resulting array from the conversion + */ + public function jsonSerializeProvider() + { + return [ + [new Wonkicity(2, 'u'), ['value' => 2, 'unit' => 'u']], + [new Wonkicity(2, 'uvee'), ['value' => 2, 'unit' => 'u']], + [new Wonkicity(2, 'v'), ['value' => 2, 'unit' => 'v']], + [new Wonkicity(2, 'vorps'), ['value' => 2, 'unit' => 'v']], + [new Woogosity(2, 'plurps'), ['value' => 2, 'unit' => 'p']], + [new Woogosity(2, 'millilupees'), ['value' => 2, 'unit' => 'ml']], + ]; + } + /** * Provide some arithmetic relations for testing * 1) Boolean - whether or not the operation shoul error out due to a type mismatch (PhysicalQuantityMismatch exception)