Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@
},

"require": {
"php": ">=5.5.0"
"php": ">=5.5.0",
"ext-json": "*"
},

"require-dev": {
Expand Down
15 changes: 14 additions & 1 deletion source/AbstractPhysicalQuantity.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?php
namespace PhpUnitsOfMeasure;

abstract class AbstractPhysicalQuantity implements PhysicalQuantityInterface
abstract class AbstractPhysicalQuantity implements PhysicalQuantityInterface, \JsonSerializable
{
/**
* The collection of units in which this quantity can be represented.
Expand Down Expand Up @@ -189,6 +189,19 @@ public function __toString()
return trim($this->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
*/
Expand Down
26 changes: 26 additions & 0 deletions tests/AbstractPhysicalQuantityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down