diff --git a/src/Enum.php b/src/Enum.php index 140e722..6b89442 100755 --- 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 \Serializable { /** * Enum value @@ -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 * diff --git a/tests/EnumTest.php b/tests/EnumTest.php index 72ec873..e014c53 100755 --- a/tests/EnumTest.php +++ b/tests/EnumTest.php @@ -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)); + } }