diff --git a/src/Uuid.php b/src/Uuid.php index 40c2587d..2e44c8b8 100644 --- a/src/Uuid.php +++ b/src/Uuid.php @@ -894,6 +894,33 @@ public static function fromString($name) return new self($fields); } + /** + * Creates a UUID from either the UUID as a 128-bit integer string or a Moontoast\Math\BigNumber object. + * + * @param string|\Moontoast\Math\BigNumber $integer String/BigNumber representation of UUID integer + * @throws Exception\UnsatisfiedDependencyException If Moontoast\Math\BigNumber is not present + * @return \Rhumsaa\Uuid\Uuid + */ + public static function fromInteger($integer) + { + if (!self::hasBigNumber()) { + throw new Exception\UnsatisfiedDependencyException( + 'Cannot call ' . __METHOD__ . ' without support for large ' + . 'integers, since integer is an unsigned ' + . '128-bit integer; Moontoast\Math\BigNumber is required. ' + ); + } + + if (!$integer instanceof \Moontoast\Math\BigNumber) { + $integer = new \Moontoast\Math\BigNumber($integer); + } + + $hex = \Moontoast\Math\BigNumber::baseConvert($integer, 10, 16); + $hex = str_pad($hex, 32, '0', STR_PAD_LEFT); + + return self::fromString($hex); + } + /** * Check if a string is a valid uuid * diff --git a/tests/UuidTest.php b/tests/UuidTest.php index 19b1017e..8be8b26e 100644 --- a/tests/UuidTest.php +++ b/tests/UuidTest.php @@ -1453,6 +1453,33 @@ public function testFromBytesArgumentTooLong() Uuid::fromBytes('thisisabittoolong'); } + /** + * @covers Rhumsaa\Uuid\Uuid::fromInteger + */ + public function testFromIntegerBigNumber() + { + $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); + $integer = $uuid->getInteger(); + + $fromIntegerUuid = Uuid::fromInteger($integer); + + $this->assertTrue($uuid->equals($fromIntegerUuid)); + } + + /** + * @covers Rhumsaa\Uuid\Uuid::fromInteger + */ + public function testFromIntegerString() + { + $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); + $integer = $uuid->getInteger()->getValue(); + + $fromIntegerUuid = Uuid::fromInteger($integer); + + $this->assertTrue($uuid->equals($fromIntegerUuid)); + } + + /** * This test ensures that Rhumsaa\Uuid passes the same test cases * as the Python UUID library. @@ -1462,6 +1489,7 @@ public function testFromBytesArgumentTooLong() * * @covers Rhumsaa\Uuid\Uuid::fromString * @covers Rhumsaa\Uuid\Uuid::fromBytes + * @covers Rhumsaa\Uuid\Uuid::fromInteger * @covers Rhumsaa\Uuid\Uuid::toString * @covers Rhumsaa\Uuid\Uuid::getBytes * @covers Rhumsaa\Uuid\Uuid::getFieldsHex @@ -1772,6 +1800,7 @@ public function testUuidPassesPythonTests() Uuid::fromString($test['hex']), Uuid::fromBytes(base64_decode($test['bytes'])), Uuid::fromString($test['urn']), + Uuid::fromInteger($test['int']), ); foreach ($uuids as $uuid) { $this->assertEquals($test['string'], (string) $uuid);