diff --git a/src/Enum.php b/src/Enum.php index 7b73b73..c73486b 100644 --- a/src/Enum.php +++ b/src/Enum.php @@ -5,6 +5,7 @@ namespace IW; use InvalidArgumentException; +use JsonSerializable; use ReflectionClass; use function array_keys; use function array_values; @@ -53,7 +54,7 @@ * case Hash::SHA1: ... * } */ -abstract class Enum +abstract class Enum implements JsonSerializable { /** @var string */ private $key; @@ -145,6 +146,16 @@ final public function getValue() return $this->value; } + /** + * Returns value for JSON serialization + * + * @return mixed + */ + final public function jsonSerialize() + { + return $this->value; + } + /** * Returns list of names of constants * diff --git a/tests/EnumTest.php b/tests/EnumTest.php index 0f87199..a0e6dd2 100644 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -6,6 +6,7 @@ use InvalidArgumentException; use PHPUnit\Framework\TestCase; +use function json_encode; class EnumTest extends TestCase { @@ -81,4 +82,11 @@ public function testMethodSearch() : void $this->assertSame(IntraWorldsEnum::NEW_YORK(), IntraWorldsEnum::search(42)); $this->assertNull(IntraWorldsEnum::search(null)); } + + public function testJsonEncode() : void + { + $this->assertSame('true', json_encode(IntraWorldsEnum::PILSEN())); + $this->assertSame('0.3333333333333333', json_encode(IntraWorldsEnum::TAMPA())); + $this->assertSame('{"foo":["bar"]}', json_encode(IntraWorldsEnum::MUNICH())); + } }