Skip to content

Commit e606524

Browse files
authored
Merge pull request #145 from 1Franck/master
Added interface JsonSerializable to Util\Unit class
2 parents 065c6ea + f9e2bae commit e606524

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

Cmfcmf/OpenWeatherMap/Util/Unit.php

+18-1
Original file line numberDiff line numberDiff line change
@@ -18,10 +18,12 @@
1818

1919
namespace Cmfcmf\OpenWeatherMap\Util;
2020

21+
use JsonSerializable;
22+
2123
/**
2224
* The unit class representing a unit object.
2325
*/
24-
class Unit
26+
class Unit implements JsonSerializable
2527
{
2628
/**
2729
* @var float The value.
@@ -144,4 +146,19 @@ public function getFormatted()
144146
return (string)$this->getValue();
145147
}
146148
}
149+
150+
/**
151+
* Get Unit properties when encoding to JSON
152+
*
153+
* @return array
154+
*/
155+
public function jsonSerialize()
156+
{
157+
return [
158+
'value' => $this->getValue(),
159+
'unit' => $this->getUnit(),
160+
'description' => $this->getDescription(),
161+
'precision' => $this->getPrecision()
162+
];
163+
}
147164
}

tests/Util/UnitTest.php

+6
Original file line numberDiff line numberDiff line change
@@ -167,4 +167,10 @@ public function testToString()
167167

168168
$this->assertEquals($this->unit->getFormatted(), $this->unit);
169169
}
170+
171+
public function testToJSON()
172+
{
173+
$unit = new Unit(42.5, "°C", "hot", "2.5");
174+
$this->assertEquals(json_encode($unit), '{"value":42.5,"unit":"\u00b0C","description":"hot","precision":2.5}');
175+
}
170176
}

0 commit comments

Comments
 (0)