File tree Expand file tree Collapse file tree 2 files changed +28
-2
lines changed Expand file tree Collapse file tree 2 files changed +28
-2
lines changed Original file line number Diff line number Diff line change 1515 * @author Daniel Costa <danielcosta@gmail.com>
1616 * @author Mirosław Filip <mirfilip@gmail.com>
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}
Original file line number Diff line number Diff 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}
You can’t perform that action at this time.
0 commit comments