Skip to content

Add support for json_encode #60

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* @author Daniel Costa <[email protected]>
* @author Mirosław Filip <[email protected]>
*/
abstract class Enum
abstract class Enum implements \JsonSerializable
{
/**
* Enum value
Expand Down Expand Up @@ -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;
}
}
17 changes: 17 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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"}');
}
}