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 15
15
* @author Daniel Costa <danielcosta@gmail.com>
16
16
* @author Mirosław Filip <mirfilip@gmail.com>
17
17
*/
18
- abstract class Enum
18
+ abstract class Enum implements \JsonSerializable
19
19
{
20
20
/**
21
21
* Enum value
@@ -183,4 +183,16 @@ public static function __callStatic($name, $arguments)
183
183
184
184
throw new \BadMethodCallException ("No static method or enum constant ' $ name' in class " . get_called_class ());
185
185
}
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
+ }
186
198
}
Original file line number Diff line number Diff line change @@ -40,7 +40,7 @@ public function testGetKey()
40
40
41
41
/**
42
42
* @dataProvider invalidValueProvider
43
- * @expectedException UnexpectedValueException
43
+ * @expectedException \ UnexpectedValueException
44
44
* @expectedExceptionMessage is not part of the enum MyCLabs\Tests\Enum\EnumFixture
45
45
*/
46
46
public function testCreatingEnumWithInvalidValue ($ value )
@@ -247,4 +247,18 @@ public function testEqualsConflictValues()
247
247
{
248
248
$ this ->assertFalse (EnumFixture::FOO ()->equals (EnumConflict::FOO ()));
249
249
}
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
+ }
250
264
}
You can’t perform that action at this time.
0 commit comments