diff --git a/src/Uuid.php b/src/Uuid.php index ce981cc9..241dac4f 100644 --- a/src/Uuid.php +++ b/src/Uuid.php @@ -187,6 +187,32 @@ public function jsonSerialize() return $this->toString(); } + /** + * Converts this UUID object to a string when the object is serialized + * with `serialize()` + * + * @return string + * @link http://php.net/manual/en/class.serializable.php + */ + public function serialize() + { + return $this->toString(); + } + + /** + * Re-constructs the object from its serialized form. + * + * @param string $serialized + * @link http://php.net/manual/en/class.serializable.php + */ + public function unserialize($serialized) + { + $uuid = self::fromString($serialized); + $this->codec = $uuid->codec; + $this->converter = $uuid->converter; + $this->fields = $uuid->fields; + } + public function compareTo(UuidInterface $other) { $comparison = 0; diff --git a/src/UuidInterface.php b/src/UuidInterface.php index fefa6fbc..792c32aa 100644 --- a/src/UuidInterface.php +++ b/src/UuidInterface.php @@ -21,7 +21,7 @@ * UuidInterface defines common functionality for all universally unique * identifiers (UUIDs) */ -interface UuidInterface extends \JsonSerializable +interface UuidInterface extends \JsonSerializable, \Serializable { /** * Compares this UUID to the specified UUID. diff --git a/tests/src/UuidTest.php b/tests/src/UuidTest.php index ea976cfd..729f1484 100644 --- a/tests/src/UuidTest.php +++ b/tests/src/UuidTest.php @@ -1840,4 +1840,12 @@ public function testJsonSerialize() $this->assertEquals('"' . $uuid->toString() . '"', json_encode($uuid)); } + + public function testSerialize() + { + $uuid = Uuid::uuid4(); + $serialized = serialize($uuid); + $unserializedUuid = unserialize($serialized); + $this->assertTrue($uuid->equals($unserializedUuid)); + } }