Skip to content

Available serialize enum #49

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 3 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
18 changes: 17 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 <danielcosta@gmail.com>
* @author Mirosław Filip <mirfilip@gmail.com>
*/
abstract class Enum
abstract class Enum implements \Serializable
{
/**
* Enum value
Expand Down Expand Up @@ -165,6 +165,22 @@ public static function search($value)
return array_search($value, static::toArray(), true);
}

/**
* @return string
*/
public function serialize()
{
return serialize($this->value);
}

/**
* @param string $serialized
*/
public function unserialize($serialized)
{
$this->value = unserialize($serialized);
}

/**
* Returns a value when called statically like so: MyEnum::SOME_VALUE() given SOME_VALUE is a class constant
*
Expand Down
14 changes: 14 additions & 0 deletions tests/EnumTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -250,4 +250,18 @@ public function testEqualsConflictValues()
{
$this->assertFalse(EnumFixture::FOO()->equals(EnumConflict::FOO()));
}

public function testSerialize()
{
$this->assertEquals('C:30:"MyCLabs\Tests\Enum\EnumFixture":10:{s:3:"foo";}', serialize(EnumFixture::FOO()));
}

public function testUnserialize()
{
/* @var $value EnumFixture */
$value = unserialize('C:30:"MyCLabs\Tests\Enum\EnumFixture":10:{s:3:"foo";}');

$this->assertEquals(EnumFixture::FOO, $value->getValue());
$this->assertTrue(EnumFixture::FOO()->equals($value));
}
}