diff --git a/.travis.yml b/.travis.yml index 451832b..92822ee 100755 --- a/.travis.yml +++ b/.travis.yml @@ -1,12 +1,12 @@ language: php php: - - 5.3 - 5.4 - 5.5 - 5.6 - 7.0 - 7.1 + - 7.2 - nightly - hhvm diff --git a/composer.json b/composer.json index e9769a3..1395658 100644 --- a/composer.json +++ b/composer.json @@ -22,7 +22,7 @@ } }, "require": { - "php": ">=5.3" + "php": ">=5.4" }, "require-dev": { "phpunit/phpunit": "^4.8.35|^5.7|^6.0", diff --git a/src/Enum.php b/src/Enum.php index 140e722..5f4a12a 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,16 @@ public static function __callStatic($name, $arguments) throw new \BadMethodCallException("No static method or enum constant '$name' in class " . get_called_class()); } + + /** + * Specify data which should be serialized to JSON. This method returns data that can be serialized by json_encode() + * natively. + * + * @return mixed + * @link http://php.net/manual/en/jsonserializable.jsonserialize.php + */ + public function jsonSerialize() + { + return $this->getValue(); + } } diff --git a/tests/EnumTest.php b/tests/EnumTest.php index c468017..4b28038 100644 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -40,7 +40,7 @@ public function testGetKey() /** * @dataProvider invalidValueProvider - * @expectedException UnexpectedValueException + * @expectedException \UnexpectedValueException * @expectedExceptionMessage is not part of the enum MyCLabs\Tests\Enum\EnumFixture */ public function testCreatingEnumWithInvalidValue($value) @@ -247,4 +247,18 @@ public function testEqualsConflictValues() { $this->assertFalse(EnumFixture::FOO()->equals(EnumConflict::FOO())); } + + /** + * jsonSerialize() + */ + public function testJsonSerialize() + { + $this->assertJsonStringEqualsJsonString('"foo"', json_encode(new EnumFixture(EnumFixture::FOO))); + $this->assertJsonStringEqualsJsonString('"bar"', json_encode(new EnumFixture(EnumFixture::BAR))); + $this->assertJsonStringEqualsJsonString('42', json_encode(new EnumFixture(EnumFixture::NUMBER))); + $this->assertJsonStringEqualsJsonString('0', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_NUMBER))); + $this->assertJsonStringEqualsJsonString('null', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_NULL))); + $this->assertJsonStringEqualsJsonString('""', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_EMPTY_STRING))); + $this->assertJsonStringEqualsJsonString('false', json_encode(new EnumFixture(EnumFixture::PROBLEMATIC_BOOLEAN_FALSE))); + } }