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
15 changes: 14 additions & 1 deletion src/Unit.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
<?php
namespace PhpUnitConversion;

use JsonSerializable;
use InvalidArgumentException;
use PhpUnitConversion\Map as UnitMap;
use PhpUnitConversion\Exception\InvocationException;
use PhpUnitConversion\Exception\UnsupportedUnitException;
use PhpUnitConversion\Exception\UnsupportedConversionException;

class Unit
class Unit implements JsonSerializable
{
/** @var float */
protected $value;
Expand Down Expand Up @@ -467,4 +468,16 @@ public function __toString()
$symbol = $this->getSymbol();
return (string)$this->getValue() . ($symbol ? ' ' . $symbol : '');
}

/**
* @return array
*/
public function jsonSerialize()
{
return [
'value' => $this->getValue(),
'symbol' => $this->getSymbol(),
'label' => $this->getLabel(),
];
}
}
14 changes: 14 additions & 0 deletions tests/UnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down