diff --git a/composer.json b/composer.json index 87a6119..5e8cae8 100755 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ } }, "require": { - "php": ">=5.3" + "php": ">=5.4" }, "require-dev": { "phpunit/phpunit": "4.*", diff --git a/src/Enum.php b/src/Enum.php index 2ad5aea..ef992e2 100755 --- 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 @@ -73,6 +73,19 @@ public function __toString() return (string)$this->value; } + /** + * (PHP 5 >= 5.4.0)
+ * Specify data which should be serialized to JSON + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php + * @return mixed data which can be serialized by json_encode, + * which is a value of any type other than a resource. + */ + public function jsonSerialize() + { + return $this->getValue(); + } + + /** * Returns the names (keys) of all constants in the Enum class * diff --git a/tests/EnumTest.php b/tests/EnumTest.php index 5f16ee0..d2f7c96 100755 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -71,6 +71,21 @@ public function testToString($expected, $enumObject) $this->assertSame($expected, (string) $enumObject); } + public function testJsonEncode() + { + $value = new EnumFixture(EnumFixture::FOO); + $encoded = json_encode($value); + $this->assertEquals($encoded, '"'.EnumFixture::FOO.'"'); + + $value = new EnumFixture(EnumFixture::BAR); + $encoded = json_encode($value); + $this->assertEquals($encoded, '"'.EnumFixture::BAR.'"'); + + $value = new EnumFixture(EnumFixture::NUMBER); + $encoded = json_encode($value); + $this->assertEquals($encoded, EnumFixture::NUMBER); + } + public function toStringProvider() { return array( array(EnumFixture::FOO, new EnumFixture(EnumFixture::FOO)),