Skip to content

Commit

Permalink
Merge pull request #145 from 1Franck/master
Browse files Browse the repository at this point in the history
Added interface JsonSerializable to Util\Unit class
  • Loading branch information
cmfcmf authored Mar 13, 2020
2 parents 065c6ea + f9e2bae commit e606524
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
19 changes: 18 additions & 1 deletion Cmfcmf/OpenWeatherMap/Util/Unit.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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()
];
}
}
6 changes: 6 additions & 0 deletions tests/Util/UnitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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}');
}
}

0 comments on commit e606524

Please sign in to comment.