Skip to content

Commit

Permalink
add support for json_encode()
Browse files Browse the repository at this point in the history
  • Loading branch information
Ondřej Ešler committed Dec 7, 2019
1 parent f691535 commit 083068a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/Enum.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace IW;

use InvalidArgumentException;
use JsonSerializable;
use ReflectionClass;
use function array_keys;
use function array_values;
Expand Down Expand Up @@ -53,7 +54,7 @@
* case Hash::SHA1: ...
* }
*/
abstract class Enum
abstract class Enum implements JsonSerializable
{
/** @var string */
private $key;
Expand Down Expand Up @@ -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
*
Expand Down
8 changes: 8 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use InvalidArgumentException;
use PHPUnit\Framework\TestCase;
use function json_encode;

class EnumTest extends TestCase
{
Expand Down Expand Up @@ -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()));
}
}

0 comments on commit 083068a

Please sign in to comment.