Skip to content

Commit d2ebb54

Browse files
Base Unit class implements JsonSerializable now
1 parent fff0565 commit d2ebb54

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

src/Unit.php

+14-1
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
<?php
22
namespace PhpUnitConversion;
33

4+
use JsonSerializable;
45
use InvalidArgumentException;
56
use PhpUnitConversion\Map as UnitMap;
67
use PhpUnitConversion\Exception\InvocationException;
78
use PhpUnitConversion\Exception\UnsupportedUnitException;
89
use PhpUnitConversion\Exception\UnsupportedConversionException;
910

10-
class Unit
11+
class Unit implements JsonSerializable
1112
{
1213
/** @var float */
1314
protected $value;
@@ -467,4 +468,16 @@ public function __toString()
467468
$symbol = $this->getSymbol();
468469
return (string)$this->getValue() . ($symbol ? ' ' . $symbol : '');
469470
}
471+
472+
/**
473+
* @return array
474+
*/
475+
public function jsonSerialize()
476+
{
477+
return [
478+
'value' => $this->getValue(),
479+
'symbol' => $this->getSymbol(),
480+
'label' => $this->getLabel(),
481+
];
482+
}
470483
}

tests/UnitTest.php

+14
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,20 @@ public function testToString()
108108
$this->assertEquals('1 u', (string)$unit);
109109
}
110110

111+
public function testToJson()
112+
{
113+
$unit = new MyUnitType\OneUnit(1);
114+
115+
$expected = [
116+
'value' => 1,
117+
'symbol' => 'u',
118+
'label' => 'unit',
119+
];
120+
121+
$this->assertEquals($expected, $unit->jsonSerialize());
122+
$this->assertEquals(json_encode($expected), json_encode($unit));
123+
}
124+
111125
public function testInvalidInvocation()
112126
{
113127
$this->expectException(Exception::class);

0 commit comments

Comments
 (0)