Skip to content

Commit 87b45ff

Browse files
authored
Merge pull request #69 from Daanvm/67-implement-jsonserializable
Implement JsonSerializable, fixes #67
2 parents df89d1f + feb4b6b commit 87b45ff

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

src/Enum.php

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
* @author Daniel Costa <[email protected]>
1616
* @author Mirosław Filip <[email protected]>
1717
*/
18-
abstract class Enum
18+
abstract class Enum implements \JsonSerializable
1919
{
2020
/**
2121
* Enum value
@@ -183,4 +183,16 @@ public static function __callStatic($name, $arguments)
183183

184184
throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class());
185185
}
186+
187+
/**
188+
* Specify data which should be serialized to JSON. This method returns data that can be serialized by json_encode()
189+
* natively.
190+
*
191+
* @return mixed
192+
* @link http://php.net/manual/en/jsonserializable.jsonserialize.php
193+
*/
194+
public function jsonSerialize()
195+
{
196+
return $this->getValue();
197+
}
186198
}

tests/EnumTest.php

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ public function testGetKey()
4040

4141
/**
4242
* @dataProvider invalidValueProvider
43-
* @expectedException UnexpectedValueException
43+
* @expectedException \UnexpectedValueException
4444
* @expectedExceptionMessage is not part of the enum MyCLabs\Tests\Enum\EnumFixture
4545
*/
4646
public function testCreatingEnumWithInvalidValue($value)
@@ -247,4 +247,18 @@ public function testEqualsConflictValues()
247247
{
248248
$this->assertFalse(EnumFixture::FOO()->equals(EnumConflict::FOO()));
249249
}
250+
251+
/**
252+
* jsonSerialize()
253+
*/
254+
public function testJsonSerialize()
255+
{
256+
$this->assertJsonStringEqualsJsonString('"foo"', json_encode(new EnumFixture(EnumFixture::FOO)));
257+
$this->assertJsonStringEqualsJsonString('"bar"', json_encode(new EnumFixture(EnumFixture::BAR)));
258+
$this->assertJsonStringEqualsJsonString('42', json_encode(new EnumFixture(EnumFixture::NUMBER)));
259+
$this->assertJsonStringEqualsJsonString('0', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_NUMBER)));
260+
$this->assertJsonStringEqualsJsonString('null', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_NULL)));
261+
$this->assertJsonStringEqualsJsonString('""', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_EMPTY_STRING)));
262+
$this->assertJsonStringEqualsJsonString('false', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_BOOLEAN_FALSE)));
263+
}
250264
}

0 commit comments

Comments
 (0)