diff --git a/src/Enum.php b/src/Enum.php index 140e722..fe445ce 100644 --- a/src/Enum.php +++ b/src/Enum.php @@ -15,7 +15,7 @@ * @author Daniel Costa * @author Mirosław Filip */ -abstract class Enum +abstract class Enum implements \JsonSerializable { /** * Enum value @@ -183,4 +183,14 @@ public static function __callStatic($name, $arguments) throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class()); } + + /** + * Return the value when serialized with json_encode + * + * @return mixed + */ + public function jsonSerialize() + { + return $this->value; + } } diff --git a/tests/EnumTest.php b/tests/EnumTest.php index c468017..aea6b21 100644 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -247,4 +247,21 @@ public function testEqualsConflictValues() { $this->assertFalse(EnumFixture::FOO()->equals(EnumConflict::FOO())); } + + /** + * json_encode normally returns the Enum object itself, + * but it should return the value of the enum instead + */ + public function testJsonEncode() + { + $foo = new EnumFixture(EnumFixture::FOO); + + $object = (object)[ + 'myFoo' => $foo + ]; + + $json = json_encode($object); + + $this->assertEquals($json, '{"myFoo":"foo"}'); + } }