repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/UnixTimeGenerator.php | src/Generator/UnixTimeGenerator.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Brick\Math\BigInteger;
use DateTimeInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use function assert;
use function hash;
use function pack;
use function str_pad;
use function strlen;
use function substr;
use function substr_replace;
use function unpack;
use const PHP_INT_SIZE;
use const STR_PAD_LEFT;
/**
* UnixTimeGenerator generates bytes, combining a 48-bit timestamp in milliseconds since the Unix Epoch with 80 random bits
*
* Code and concepts within this class are borrowed from the symfony/uid package and are used under the terms of the MIT
* license distributed with symfony/uid.
*
* symfony/uid is copyright (c) Fabien Potencier.
*
* @link https://symfony.com/components/Uid Symfony Uid component
* @link https://github.com/symfony/uid/blob/4f9f537e57261519808a7ce1d941490736522bbc/UuidV7.php Symfony UuidV7 class
* @link https://github.com/symfony/uid/blob/6.2/LICENSE MIT License
*/
class UnixTimeGenerator implements TimeGeneratorInterface
{
private static string $time = '';
private static ?string $seed = null;
private static int $seedIndex = 0;
/** @var int[] */
private static array $rand = [];
/** @var int[] */
private static array $seedParts;
public function __construct(
private RandomGeneratorInterface $randomGenerator,
private int $intSize = PHP_INT_SIZE,
) {
}
/**
* @param Hexadecimal | int | string | null $node Unused in this generator
* @param int | null $clockSeq Unused in this generator
* @param DateTimeInterface | null $dateTime A date-time instance to use when generating bytes
*/
public function generate($node = null, ?int $clockSeq = null, ?DateTimeInterface $dateTime = null): string
{
if ($dateTime === null) {
$time = microtime(false);
$time = substr($time, 11) . substr($time, 2, 3);
} else {
$time = $dateTime->format('Uv');
}
if ($time > self::$time || ($dateTime !== null && $time !== self::$time)) {
$this->randomize($time);
} else {
$time = $this->increment();
}
if ($this->intSize >= 8) {
$time = substr(pack('J', (int) $time), -6);
} else {
$time = str_pad(BigInteger::of($time)->toBytes(false), 6, "\x00", STR_PAD_LEFT);
}
assert(strlen($time) === 6);
return $time . pack('n*', self::$rand[1], self::$rand[2], self::$rand[3], self::$rand[4], self::$rand[5]);
}
private function randomize(string $time): void
{
if (self::$seed === null) {
$seed = $this->randomGenerator->generate(16);
self::$seed = $seed;
} else {
$seed = $this->randomGenerator->generate(10);
}
/** @var int[] $rand */
$rand = unpack('n*', $seed);
$rand[1] &= 0x03ff;
self::$rand = $rand;
self::$time = $time;
}
/**
* Special thanks to Nicolas Grekas (<https://github.com/nicolas-grekas>) for sharing the following information:
*
* Within the same ms, we increment the rand part by a random 24-bit number.
*
* Instead of getting this number from random_bytes(), which is slow, we get it by sha512-hashing self::$seed. This
* produces 64 bytes of entropy, which we need to split in a list of 24-bit numbers. `unpack()` first splits them
* into 16 x 32-bit numbers; we take the first byte of each number to get 5 extra 24-bit numbers. Then, we consume
* each number one-by-one and run this logic every 21 iterations.
*
* `self::$rand` holds the random part of the UUID, split into 5 x 16-bit numbers for x86 portability. We increment
* this random part by the next 24-bit number in the `self::$seedParts` list and decrement `self::$seedIndex`.
*/
private function increment(): string
{
if (self::$seedIndex === 0 && self::$seed !== null) {
self::$seed = hash('sha512', self::$seed, true);
/** @var int[] $s */
$s = unpack('l*', self::$seed);
$s[] = ($s[1] >> 8 & 0xff0000) | ($s[2] >> 16 & 0xff00) | ($s[3] >> 24 & 0xff);
$s[] = ($s[4] >> 8 & 0xff0000) | ($s[5] >> 16 & 0xff00) | ($s[6] >> 24 & 0xff);
$s[] = ($s[7] >> 8 & 0xff0000) | ($s[8] >> 16 & 0xff00) | ($s[9] >> 24 & 0xff);
$s[] = ($s[10] >> 8 & 0xff0000) | ($s[11] >> 16 & 0xff00) | ($s[12] >> 24 & 0xff);
$s[] = ($s[13] >> 8 & 0xff0000) | ($s[14] >> 16 & 0xff00) | ($s[15] >> 24 & 0xff);
self::$seedParts = $s;
self::$seedIndex = 21;
}
self::$rand[5] = 0xffff & $carry = self::$rand[5] + 1 + (self::$seedParts[self::$seedIndex--] & 0xffffff);
self::$rand[4] = 0xffff & $carry = self::$rand[4] + ($carry >> 16);
self::$rand[3] = 0xffff & $carry = self::$rand[3] + ($carry >> 16);
self::$rand[2] = 0xffff & $carry = self::$rand[2] + ($carry >> 16);
self::$rand[1] += $carry >> 16;
if (0xfc00 & self::$rand[1]) {
$time = self::$time;
$mtime = (int) substr($time, -9);
if ($this->intSize >= 8 || strlen($time) < 10) {
$time = (string) ((int) $time + 1);
} elseif ($mtime === 999999999) {
$time = (1 + (int) substr($time, 0, -9)) . '000000000';
} else {
$mtime++;
$time = substr_replace($time, str_pad((string) $mtime, 9, '0', STR_PAD_LEFT), -9);
}
$this->randomize($time);
}
return self::$time;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/TimeGeneratorInterface.php | src/Generator/TimeGeneratorInterface.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* A time generator generates strings of binary data based on a node ID, clock sequence, and the current time
*/
interface TimeGeneratorInterface
{
/**
* Generate a binary string from a node ID, clock sequence, and current time
*
* @param Hexadecimal | int | string | null $node A 48-bit number representing the hardware address; this number may
* be represented as an integer or a hexadecimal string
* @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set
* backwards in time or if the node ID changes
*
* @return string A binary string
*/
public function generate($node = null, ?int $clockSeq = null): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/RandomGeneratorFactory.php | src/Generator/RandomGeneratorFactory.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
/**
* RandomGeneratorFactory retrieves a default random generator, based on the environment
*/
class RandomGeneratorFactory
{
/**
* Returns a default random generator, based on the current environment
*/
public function getGenerator(): RandomGeneratorInterface
{
return new RandomBytesGenerator();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/NameGeneratorFactory.php | src/Generator/NameGeneratorFactory.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
/**
* NameGeneratorFactory retrieves a default name generator, based on the environment
*/
class NameGeneratorFactory
{
/**
* Returns a default name generator, based on the current environment
*/
public function getGenerator(): NameGeneratorInterface
{
return new DefaultNameGenerator();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/DceSecurityGenerator.php | src/Generator/DceSecurityGenerator.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Exception\DceSecurityException;
use Ramsey\Uuid\Provider\DceSecurityProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Uuid;
use function hex2bin;
use function in_array;
use function pack;
use function str_pad;
use function strlen;
use function substr_replace;
use const STR_PAD_LEFT;
/**
* DceSecurityGenerator generates strings of binary data based on a local domain, local identifier, node ID, clock
* sequence, and the current time
*/
class DceSecurityGenerator implements DceSecurityGeneratorInterface
{
private const DOMAINS = [
Uuid::DCE_DOMAIN_PERSON,
Uuid::DCE_DOMAIN_GROUP,
Uuid::DCE_DOMAIN_ORG,
];
/**
* Upper bounds for the clock sequence in DCE Security UUIDs.
*/
private const CLOCK_SEQ_HIGH = 63;
/**
* Lower bounds for the clock sequence in DCE Security UUIDs.
*/
private const CLOCK_SEQ_LOW = 0;
public function __construct(
private NumberConverterInterface $numberConverter,
private TimeGeneratorInterface $timeGenerator,
private DceSecurityProviderInterface $dceSecurityProvider,
) {
}
public function generate(
int $localDomain,
?IntegerObject $localIdentifier = null,
?Hexadecimal $node = null,
?int $clockSeq = null,
): string {
if (!in_array($localDomain, self::DOMAINS)) {
throw new DceSecurityException('Local domain must be a valid DCE Security domain');
}
if ($localIdentifier && $localIdentifier->isNegative()) {
throw new DceSecurityException(
'Local identifier out of bounds; it must be a value between 0 and 4294967295',
);
}
if ($clockSeq > self::CLOCK_SEQ_HIGH || $clockSeq < self::CLOCK_SEQ_LOW) {
throw new DceSecurityException('Clock sequence out of bounds; it must be a value between 0 and 63');
}
switch ($localDomain) {
case Uuid::DCE_DOMAIN_ORG:
if ($localIdentifier === null) {
throw new DceSecurityException('A local identifier must be provided for the org domain');
}
break;
case Uuid::DCE_DOMAIN_PERSON:
if ($localIdentifier === null) {
$localIdentifier = $this->dceSecurityProvider->getUid();
}
break;
case Uuid::DCE_DOMAIN_GROUP:
default:
if ($localIdentifier === null) {
$localIdentifier = $this->dceSecurityProvider->getGid();
}
break;
}
$identifierHex = $this->numberConverter->toHex($localIdentifier->toString());
// The maximum value for the local identifier is 0xffffffff, or 4,294,967,295. This is 8 hexadecimal digits, so
// if the length of hexadecimal digits is greater than 8, we know the value is greater than 0xffffffff.
if (strlen($identifierHex) > 8) {
throw new DceSecurityException(
'Local identifier out of bounds; it must be a value between 0 and 4294967295',
);
}
$domainByte = pack('n', $localDomain)[1];
$identifierBytes = (string) hex2bin(str_pad($identifierHex, 8, '0', STR_PAD_LEFT));
if ($node instanceof Hexadecimal) {
$node = $node->toString();
}
// Shift the clock sequence 8 bits to the left, so it matches 0x3f00.
if ($clockSeq !== null) {
$clockSeq = $clockSeq << 8;
}
$bytes = $this->timeGenerator->generate($node, $clockSeq);
// Replace bytes in the time-based UUID with DCE Security values.
$bytes = substr_replace($bytes, $identifierBytes, 0, 4);
return substr_replace($bytes, $domainByte, 9, 1);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/CombGenerator.php | src/Generator/CombGenerator.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use function bin2hex;
use function explode;
use function hex2bin;
use function microtime;
use function str_pad;
use function substr;
use const STR_PAD_LEFT;
/**
* CombGenerator generates COMBs (combined UUID/timestamp)
*
* The CombGenerator, when used with the StringCodec (and, by proxy, the TimestampLastCombCodec) or the
* TimestampFirstCombCodec, combines the current timestamp with a UUID (hence the name "COMB"). The timestamp either
* appears as the first or last 48 bits of the COMB, depending on the codec used.
*
* By default, COMBs will have the timestamp set as the last 48 bits of the identifier.
*
* ```
* $factory = new UuidFactory();
*
* $factory->setRandomGenerator(new CombGenerator(
* $factory->getRandomGenerator(),
* $factory->getNumberConverter(),
* ));
*
* $comb = $factory->uuid4();
* ```
*
* To generate a COMB with the timestamp as the first 48 bits, set the TimestampFirstCombCodec as the codec.
*
* ```
* $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder()));
* ```
*
* @deprecated Please migrate to {@link https://uuid.ramsey.dev/en/stable/rfc4122/version7.html Version 7, Unix Epoch Time UUIDs}.
*
* @link https://web.archive.org/web/20240118030355/https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys
*/
class CombGenerator implements RandomGeneratorInterface
{
public const TIMESTAMP_BYTES = 6;
public function __construct(
private RandomGeneratorInterface $generator,
private NumberConverterInterface $numberConverter
) {
}
/**
* @throws InvalidArgumentException if $length is not a positive integer greater than or equal to CombGenerator::TIMESTAMP_BYTES
*
* @inheritDoc
*/
public function generate(int $length): string
{
if ($length < self::TIMESTAMP_BYTES) {
throw new InvalidArgumentException(
'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES
);
}
if ($length % 2 !== 0) {
throw new InvalidArgumentException('Length must be an even number');
}
$hash = '';
/** @phpstan-ignore greater.alwaysTrue (TIMESTAMP_BYTES constant could change in child classes) */
if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) {
$hash = $this->generator->generate($length - self::TIMESTAMP_BYTES);
}
$lsbTime = str_pad(
$this->numberConverter->toHex($this->timestamp()),
self::TIMESTAMP_BYTES * 2,
'0',
STR_PAD_LEFT,
);
return (string) hex2bin(str_pad(bin2hex($hash), $length - self::TIMESTAMP_BYTES, '0') . $lsbTime);
}
/**
* Returns the current timestamp as a string integer, precise to 0.00001 seconds
*/
private function timestamp(): string
{
$time = explode(' ', microtime(false));
return $time[1] . substr($time[0], 2, 5);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/DceSecurityGeneratorInterface.php | src/Generator/DceSecurityGeneratorInterface.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Rfc4122\UuidV2;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
/**
* A DCE Security generator generates strings of binary data based on a local domain, local identifier, node ID, clock
* sequence, and the current time
*
* @see UuidV2
*/
interface DceSecurityGeneratorInterface
{
/**
* Generate a binary string from a local domain, local identifier, node ID, clock sequence, and current time
*
* @param int $localDomain The local domain to use when generating bytes, according to DCE Security
* @param IntegerObject | null $localIdentifier The local identifier for the given domain; this may be a UID or GID
* on POSIX systems if the local domain is "person" or "group," or it may be a site-defined identifier if the
* local domain is "org"
* @param Hexadecimal | null $node A 48-bit number representing the hardware address
* @param int | null $clockSeq A 14-bit number used to help avoid duplicates that could arise when the clock is set
* backwards in time or if the node ID changes
*
* @return string A binary string
*/
public function generate(
int $localDomain,
?IntegerObject $localIdentifier = null,
?Hexadecimal $node = null,
?int $clockSeq = null,
): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/TestCase.php | tests/TestCase.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use Mockery;
use PHPUnit\Framework\TestCase as PhpUnitTestCase;
use function current;
use function pack;
use function unpack;
class TestCase extends PhpUnitTestCase
{
protected function tearDown(): void
{
parent::tearDown();
Mockery::close();
}
public static function isLittleEndianSystem(): bool
{
/** @var int[] $unpacked */
$unpacked = unpack('v', pack('S', 0x00FF));
return current($unpacked) === 0x00FF;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/DeprecatedUuidMethodsTraitTest.php | tests/DeprecatedUuidMethodsTraitTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
class DeprecatedUuidMethodsTraitTest extends TestCase
{
public function testGetDateTime(): void
{
$calculator = new BrickMathCalculator();
$fields = new Fields((string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66'));
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = new GenericTimeConverter($calculator);
$uuid = new Uuid($fields, $numberConverter, $codec, $timeConverter);
$this->assertSame('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('1341368074.491000', $uuid->getDateTime()->format('U.u'));
}
public function testGetDateTimeThrowsException(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => 1,
'getTimestamp' => new Hexadecimal('0'),
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class, [
'convertTime' => new Time('0', '1234567'),
]);
$uuid = new Uuid($fields, $numberConverter, $codec, $timeConverter);
$this->expectException(DateTimeException::class);
$uuid->getDateTime();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/FunctionsTest.php | tests/FunctionsTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use DateTimeImmutable;
use DateTimeInterface;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV7;
use Ramsey\Uuid\Rfc4122\UuidV8;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Uuid;
use function Ramsey\Uuid\v1;
use function Ramsey\Uuid\v2;
use function Ramsey\Uuid\v3;
use function Ramsey\Uuid\v4;
use function Ramsey\Uuid\v5;
use function Ramsey\Uuid\v6;
use function Ramsey\Uuid\v7;
use function Ramsey\Uuid\v8;
class FunctionsTest extends TestCase
{
public function testV1ReturnsVersion1UuidString(): void
{
$v1 = v1();
$this->assertIsString($v1);
$this->assertSame(Uuid::UUID_TYPE_TIME, Uuid::fromString($v1)->getVersion());
}
public function testV2ReturnsVersion2UuidString(): void
{
$v2 = v2(
Uuid::DCE_DOMAIN_PERSON,
new IntegerObject('1004'),
new Hexadecimal('aabbccdd0011'),
63
);
/** @var FieldsInterface $fields */
$fields = Uuid::fromString($v2)->getFields();
$this->assertIsString($v2);
$this->assertSame(Uuid::UUID_TYPE_DCE_SECURITY, $fields->getVersion());
}
public function testV3ReturnsVersion3UuidString(): void
{
$ns = Uuid::fromString(Uuid::NAMESPACE_URL);
$v3 = v3($ns, 'https://example.com/foo');
$this->assertIsString($v3);
$this->assertSame(Uuid::UUID_TYPE_HASH_MD5, Uuid::fromString($v3)->getVersion());
}
public function testV4ReturnsVersion4UuidString(): void
{
$v4 = v4();
$this->assertIsString($v4);
$this->assertSame(Uuid::UUID_TYPE_RANDOM, Uuid::fromString($v4)->getVersion());
}
public function testV5ReturnsVersion5UuidString(): void
{
$ns = Uuid::fromString(Uuid::NAMESPACE_URL);
$v5 = v5($ns, 'https://example.com/foo');
$this->assertIsString($v5);
$this->assertSame(Uuid::UUID_TYPE_HASH_SHA1, Uuid::fromString($v5)->getVersion());
}
public function testV6ReturnsVersion6UuidString(): void
{
$v6 = v6(
new Hexadecimal('aabbccdd0011'),
1234
);
/** @var FieldsInterface $fields */
$fields = Uuid::fromString($v6)->getFields();
$this->assertIsString($v6);
$this->assertSame(Uuid::UUID_TYPE_REORDERED_TIME, $fields->getVersion());
}
public function testV7ReturnsVersion7UuidString(): void
{
$v7 = v7();
/** @var UuidV7 $uuid */
$uuid = Uuid::fromString($v7);
/** @var FieldsInterface $fields */
$fields = $uuid->getFields();
$this->assertIsString($v7);
$this->assertSame(Uuid::UUID_TYPE_UNIX_TIME, $fields->getVersion());
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
}
public function testV7WithCustomDateTimeReturnsVersion7UuidString(): void
{
$dateTime = new DateTimeImmutable('2022-09-14T22:44:33+00:00');
$v7 = v7($dateTime);
/** @var UuidV7 $uuid */
$uuid = Uuid::fromString($v7);
/** @var FieldsInterface $fields */
$fields = $uuid->getFields();
$this->assertIsString($v7);
$this->assertSame(Uuid::UUID_TYPE_UNIX_TIME, $fields->getVersion());
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame(1663195473, $uuid->getDateTime()->getTimestamp());
}
public function testV8ReturnsVersion8UuidString(): void
{
$v8 = v8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff");
/** @var UuidV8 $uuid */
$uuid = Uuid::fromString($v8);
/** @var FieldsInterface $fields */
$fields = $uuid->getFields();
$this->assertIsString($v8);
$this->assertSame(Uuid::UUID_TYPE_CUSTOM, $fields->getVersion());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/UuidTest.php | tests/UuidTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use BadMethodCallException;
use Brick\Math\BigDecimal;
use Brick\Math\RoundingMode;
use DateTimeImmutable;
use DateTimeInterface;
use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\DefaultUuidBuilder;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
use Ramsey\Uuid\Codec\TimestampLastCombCodec;
use Ramsey\Uuid\Converter\Number\BigNumberConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\FeatureSet;
use Ramsey\Uuid\Generator\CombGenerator;
use Ramsey\Uuid\Generator\RandomGeneratorFactory;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Guid\Guid;
use Ramsey\Uuid\Lazy\LazyUuidFromString;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Provider\Time\FixedTimeProvider;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\UuidFactoryInterface;
use Ramsey\Uuid\UuidInterface;
use Ramsey\Uuid\Validator\GenericValidator;
use Ramsey\Uuid\Validator\ValidatorInterface;
use Stringable;
use stdClass;
use function base64_decode;
use function base64_encode;
use function gmdate;
use function hex2bin;
use function json_encode;
use function serialize;
use function str_pad;
use function strlen;
use function strtotime;
use function strtoupper;
use function substr;
use function uniqid;
use function unserialize;
use function usleep;
class UuidTest extends TestCase
{
protected function setUp(): void
{
Uuid::setFactory(new UuidFactory());
}
public function testFromString(): void
{
$this->assertSame(
'ff6f8cb0-c57d-11e1-9b21-0800200c9a66',
Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66')
->toString()
);
}
public function testFromHexadecimal(): void
{
$hex = new Hexadecimal('0x1EA78DEB37CE625E8F1A025041000001');
$uuid = Uuid::fromHexadecimal($hex);
$this->assertInstanceOf(Uuid::class, $uuid);
$this->assertEquals('1ea78deb-37ce-625e-8f1a-025041000001', $uuid->toString());
}
public function testFromHexadecimalShort(): void
{
$hex = new Hexadecimal('0x1EA78DEB37CE625E8F1A0250410000');
$this->expectException(InvalidUuidStringException::class);
$this->expectExceptionMessage('Invalid UUID string:');
Uuid::fromHexadecimal($hex);
}
public function testFromHexadecimalThrowsWhenMethodDoesNotExist(): void
{
$factory = Mockery::mock(UuidFactoryInterface::class);
Uuid::setFactory($factory);
$hex = new Hexadecimal('0x1EA78DEB37CE625E8F1A025041000001');
$this->expectException(BadMethodCallException::class);
$this->expectExceptionMessage('The method fromHexadecimal() does not exist on the provided factory');
Uuid::fromHexadecimal($hex);
}
/**
* Tests that UUID and GUID's have the same textual representation but not
* the same binary representation.
*/
public function testFromGuidString(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
Uuid::setFactory(new UuidFactory(new FeatureSet(true)));
$guid = Guid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
// UUID's and GUID's share the same textual representation.
$this->assertSame($uuid->toString(), $guid->toString());
// But not the same binary representation.
$this->assertNotSame($uuid->getBytes(), $guid->getBytes());
}
public function testFromStringWithCurlyBraces(): void
{
$uuid = Uuid::fromString('{ff6f8cb0-c57d-11e1-9b21-0800200c9a66}');
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString());
}
public function testFromStringWithInvalidUuidString(): void
{
$this->expectException(InvalidUuidStringException::class);
$this->expectExceptionMessage('Invalid UUID string:');
Uuid::fromString('ff6f8cb0-c57d-11e1-9b21');
}
public function testFromStringWithLeadingNewLine(): void
{
$this->expectException(InvalidUuidStringException::class);
$this->expectExceptionMessage('Invalid UUID string:');
Uuid::fromString("\nd0d5f586-21d1-470c-8088-55c8857728dc");
}
public function testFromStringWithTrailingNewLine(): void
{
$this->expectException(InvalidUuidStringException::class);
$this->expectExceptionMessage('Invalid UUID string:');
Uuid::fromString("d0d5f586-21d1-470c-8088-55c8857728dc\n");
}
public function testFromStringWithUrn(): void
{
$uuid = Uuid::fromString('urn:uuid:ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString());
}
public function testFromStringWithEmptyString(): void
{
$this->expectException(InvalidUuidStringException::class);
$this->expectExceptionMessage('Invalid UUID string: ');
Uuid::fromString('');
}
public function testFromStringUppercase(): void
{
$uuid = Uuid::fromString('FF6F8CB0-C57D-11E1-9B21-0800200C9A66');
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString());
}
public function testFromStringLazyUuidFromUppercase(): void
{
$this->assertInstanceOf(LazyUuidFromString::class, Uuid::fromString('FF6F8CB0-C57D-11E1-9B21-0800200C9A66'));
}
public function testFromStringWithNilUuid(): void
{
$uuid = Uuid::fromString(Uuid::NIL);
/** @var Fields $fields */
$fields = $uuid->getFields();
$this->assertSame('00000000-0000-0000-0000-000000000000', $uuid->toString());
$this->assertTrue($fields->isNil());
$this->assertFalse($fields->isMax());
}
public function testFromStringWithMaxUuid(): void
{
$uuid = Uuid::fromString(Uuid::MAX);
/** @var Fields $fields */
$fields = $uuid->getFields();
$this->assertSame('ffffffff-ffff-ffff-ffff-ffffffffffff', $uuid->toString());
$this->assertFalse($fields->isNil());
$this->assertTrue($fields->isMax());
}
public function testGetBytes(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame(16, strlen($uuid->getBytes()));
$this->assertSame('/2+MsMV9EeGbIQgAIAyaZg==', base64_encode($uuid->getBytes()));
}
public function testGetClockSeqHiAndReserved(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('155', $uuid->getClockSeqHiAndReserved());
}
public function testGetClockSeqHiAndReservedHex(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('9b', $uuid->getClockSeqHiAndReservedHex());
}
public function testGetClockSeqLow(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('33', $uuid->getClockSeqLow());
}
public function testGetClockSeqLowHex(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('21', $uuid->getClockSeqLowHex());
}
public function testGetClockSequence(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('6945', $uuid->getClockSequence());
}
public function testGetClockSequenceHex(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('1b21', $uuid->getClockSequenceHex());
}
public function testGetDateTime(): void
{
// Check a recent date
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('1341368074.491000', $uuid->getDateTime()->format('U.u'));
// Check an old date
$uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66');
$this->assertSame('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('-12219146756.000000', $uuid->getDateTime()->format('U.u'));
// Check a future date
$uuid = Uuid::fromString('ff9785f6-ffff-1fff-9669-00007ffffffe');
$this->assertSame('5236-03-31T21:20:59+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('103072857659.999999', $uuid->getDateTime()->format('U.u'));
// Check the last possible time supported by v1 UUIDs
// See inline comments in
// {@see \Ramsey\Uuid\Test\Converter\Time\GenericTimeConverterTest::provideCalculateTime()}
$uuid = Uuid::fromString('fffffffa-ffff-1fff-8b1e-acde48001122');
$this->assertSame('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('103072857660.684697', $uuid->getDateTime()->format('U.u'));
// Check the oldest date
$uuid = Uuid::fromString('00000000-0000-1000-9669-00007ffffffe');
$this->assertSame('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('-12219292800.000000', $uuid->getDateTime()->format('U.u'));
// The Unix epoch
$uuid = Uuid::fromString('13814000-1dd2-11b2-9669-00007ffffffe');
$this->assertSame('1970-01-01T00:00:00+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('0.000000', $uuid->getDateTime()->format('U.u'));
}
public function testGetDateTimeForUuidV6(): void
{
// Check a recent date
$uuid = Uuid::fromString('1e1c57df-f6f8-6cb0-9b21-0800200c9a66');
$this->assertSame('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('1341368074.491000', $uuid->getDateTime()->format('U.u'));
// Check an old date
$uuid = Uuid::fromString('00001540-901e-6600-9b21-0800200c9a66');
$this->assertSame('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('-12219146756.000000', $uuid->getDateTime()->format('U.u'));
// Check a future date
$uuid = Uuid::fromString('ffffffff-f978-65f6-9669-00007ffffffe');
$this->assertSame('5236-03-31T21:20:59+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('103072857659.999999', $uuid->getDateTime()->format('U.u'));
// Check the last possible time supported by UUIDs
// See inline comments in
// {@see \Ramsey\Uuid\Test\Converter\Time\GenericTimeConverterTest::provideCalculateTime()}
$uuid = Uuid::fromString('ffffffff-ffff-6ffa-8b1e-acde48001122');
$this->assertSame('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('103072857660.684697', $uuid->getDateTime()->format('U.u'));
// Check the oldest date
$uuid = Uuid::fromString('00000000-0000-6000-9669-00007ffffffe');
$this->assertSame('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('-12219292800.000000', $uuid->getDateTime()->format('U.u'));
// The Unix epoch
$uuid = Uuid::fromString('1b21dd21-3814-6000-9669-00007ffffffe');
$this->assertSame('1970-01-01T00:00:00+00:00', $uuid->getDateTime()->format('c'));
$this->assertSame('0.000000', $uuid->getDateTime()->format('U.u'));
}
public function testGetDateTimeFromNonVersion1Uuid(): void
{
// Using a version 4 UUID to test
$uuid = Uuid::fromString('bf17b594-41f2-474f-bf70-4c90220f75de');
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage('Not a time-based UUID');
$uuid->getDateTime();
}
public function testGetFields(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertInstanceOf(FieldsInterface::class, $uuid->getFields());
}
public function testGetFieldsHex(): void
{
$fields = [
'time_low' => 'ff6f8cb0',
'time_mid' => 'c57d',
'time_hi_and_version' => '11e1',
'clock_seq_hi_and_reserved' => '9b',
'clock_seq_low' => '21',
'node' => '0800200c9a66',
];
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame($fields, $uuid->getFieldsHex());
}
public function testGetLeastSignificantBits(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('11178224546741000806', $uuid->getLeastSignificantBits());
}
public function testGetLeastSignificantBitsHex(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('9b210800200c9a66', $uuid->getLeastSignificantBitsHex());
}
public function testGetMostSignificantBits(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('18406084892941947361', $uuid->getMostSignificantBits());
}
public function testGetMostSignificantBitsHex(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('ff6f8cb0c57d11e1', $uuid->getMostSignificantBitsHex());
}
public function testGetNode(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('8796630719078', $uuid->getNode());
}
public function testGetNodeHex(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('0800200c9a66', $uuid->getNodeHex());
}
public function testGetTimeHiAndVersion(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('4577', $uuid->getTimeHiAndVersion());
}
public function testGetTimeHiAndVersionHex(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('11e1', $uuid->getTimeHiAndVersionHex());
}
public function testGetTimeLow(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('4285500592', $uuid->getTimeLow());
}
public function testGetTimeLowHex(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('ff6f8cb0', $uuid->getTimeLowHex());
}
public function testGetTimeMid(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('50557', $uuid->getTimeMid());
}
public function testGetTimeMidHex(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('c57d', $uuid->getTimeMidHex());
}
public function testGetTimestamp(): void
{
// Check for a recent date
/** @var Uuid $uuid */
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('135606608744910000', $uuid->getTimestamp());
// Check for an old date
/** @var Uuid $uuid */
$uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66');
$this->assertSame('1460440000000', $uuid->getTimestamp());
}
public function testGetTimestampHex(): void
{
// Check for a recent date
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('1e1c57dff6f8cb0', $uuid->getTimestampHex());
// Check for an old date
$uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66');
$this->assertSame('00001540901e600', $uuid->getTimestampHex());
}
public function testGetTimestampFromNonVersion1Uuid(): void
{
// Using a version 4 UUID to test
/** @var Uuid $uuid */
$uuid = Uuid::fromString('bf17b594-41f2-474f-bf70-4c90220f75de');
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage('Not a time-based UUID');
$uuid->getTimestamp();
}
public function testGetTimestampHexFromNonVersion1Uuid(): void
{
// Using a version 4 UUID to test
$uuid = Uuid::fromString('bf17b594-41f2-474f-bf70-4c90220f75de');
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage('Not a time-based UUID');
$uuid->getTimestampHex();
}
public function testGetUrn(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('urn:uuid:ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->getUrn());
}
/**
* @param non-empty-string $uuid
*
* @dataProvider provideVariousVariantUuids
*/
public function testGetVariantForVariousVariantUuids(string $uuid, int $variant): void
{
$uuid = Uuid::fromString($uuid);
$this->assertSame($variant, $uuid->getVariant());
}
/**
* @return array<array{0: non-empty-string, 1: int}>
*/
public function provideVariousVariantUuids(): array
{
return [
['ff6f8cb0-c57d-11e1-0b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-1b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-2b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-3b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-4b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-5b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-6b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-7b21-0800200c9a66', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', Uuid::RFC_4122],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', Uuid::RFC_4122],
['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', Uuid::RFC_4122],
['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', Uuid::RFC_4122],
['ff6f8cb0-c57d-11e1-cb21-0800200c9a66', Uuid::RESERVED_MICROSOFT],
['ff6f8cb0-c57d-11e1-db21-0800200c9a66', Uuid::RESERVED_MICROSOFT],
['ff6f8cb0-c57d-11e1-eb21-0800200c9a66', Uuid::RESERVED_FUTURE],
['ff6f8cb0-c57d-11e1-fb21-0800200c9a66', Uuid::RESERVED_FUTURE],
];
}
public function testGetVersionForVersion1(): void
{
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame(1, $uuid->getVersion());
}
public function testGetVersionForVersion2(): void
{
$uuid = Uuid::fromString('6fa459ea-ee8a-2ca4-894e-db77e160355e');
$this->assertSame(2, $uuid->getVersion());
}
public function testGetVersionForVersion3(): void
{
$uuid = Uuid::fromString('6fa459ea-ee8a-3ca4-894e-db77e160355e');
$this->assertSame(3, $uuid->getVersion());
}
public function testGetVersionForVersion4(): void
{
$uuid = Uuid::fromString('6fabf0bc-603a-42f2-925b-d9f779bd0032');
$this->assertSame(4, $uuid->getVersion());
}
public function testGetVersionForVersion5(): void
{
$uuid = Uuid::fromString('886313e1-3b8a-5372-9b90-0c9aee199e5d');
$this->assertSame(5, $uuid->getVersion());
}
public function testToString(): void
{
// Check with a recent date
$uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString());
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', (string) $uuid);
$this->assertSame(
'ff6f8cb0-c57d-11e1-9b21-0800200c9a66',
(static fn (Stringable $uuid) => (string) $uuid)($uuid)
);
// Check with an old date
$uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66');
$this->assertSame('0901e600-0154-1000-9b21-0800200c9a66', $uuid->toString());
$this->assertSame('0901e600-0154-1000-9b21-0800200c9a66', (string) $uuid);
$this->assertSame(
'0901e600-0154-1000-9b21-0800200c9a66',
(static fn (Stringable $uuid) => (string) $uuid)($uuid)
);
}
public function testUuid1(): void
{
$uuid = Uuid::uuid1();
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
}
public function testUuid1WithNodeAndClockSequence(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::uuid1('0800200c9a66', 0x1669);
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
$this->assertSame('5737', $uuid->getClockSequence());
$this->assertSame('8796630719078', $uuid->getNode());
$this->assertSame('9669-0800200c9a66', substr($uuid->toString(), 19));
}
public function testUuid1WithHexadecimalObjectNodeAndClockSequence(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::uuid1(new Hexadecimal('0800200c9a66'), 0x1669);
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
$this->assertSame('5737', $uuid->getClockSequence());
$this->assertSame('8796630719078', $uuid->getNode());
$this->assertSame('9669-0800200c9a66', substr($uuid->toString(), 19));
}
public function testUuid1WithHexadecimalNode(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::uuid1('7160355e');
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
$this->assertSame('00007160355e', $uuid->getNodeHex());
$this->assertSame('1902130526', $uuid->getNode());
}
public function testUuid1WithHexadecimalObjectNode(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::uuid1(new Hexadecimal('7160355e'));
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
$this->assertSame('00007160355e', $uuid->getNodeHex());
$this->assertSame('1902130526', $uuid->getNode());
}
public function testUuid1WithMixedCaseHexadecimalNode(): void
{
/** @var Uuid $uuid */
$uuid = Uuid::uuid1('71B0aD5e');
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
$this->assertSame('000071b0ad5e', $uuid->getNodeHex());
$this->assertSame('1907404126', $uuid->getNode());
}
public function testUuid1WithOutOfBoundsNode(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid node value');
Uuid::uuid1('9223372036854775808');
}
public function testUuid1WithNonHexadecimalNode(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid node value');
Uuid::uuid1('db77e160355g');
}
public function testUuid1WithNon48bitNumber(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid node value');
Uuid::uuid1('db77e160355ef');
}
public function testUuid1WithRandomNode(): void
{
Uuid::setFactory(new UuidFactory(new FeatureSet(false, false, false, true)));
$uuid = Uuid::uuid1();
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
}
public function testUuid1WithUserGeneratedRandomNode(): void
{
$uuid = Uuid::uuid1(new Hexadecimal((string) (new RandomNodeProvider())->getNode()));
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(1, $uuid->getVersion());
}
public function testUuid6(): void
{
$uuid = Uuid::uuid6();
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(6, $uuid->getVersion());
}
public function testUuid6WithNodeAndClockSequence(): void
{
$uuid = Uuid::uuid6(new Hexadecimal('0800200c9a66'), 0x1669);
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(6, $uuid->getVersion());
$this->assertSame('1669', $uuid->getClockSequenceHex());
$this->assertSame('0800200c9a66', $uuid->getNodeHex());
$this->assertSame('9669-0800200c9a66', substr($uuid->toString(), 19));
}
public function testUuid6WithHexadecimalNode(): void
{
$uuid = Uuid::uuid6(new Hexadecimal('7160355e'));
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(6, $uuid->getVersion());
$this->assertSame('00007160355e', $uuid->getNodeHex());
}
public function testUuid6WithMixedCaseHexadecimalNode(): void
{
$uuid = Uuid::uuid6(new Hexadecimal('71B0aD5e'));
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(6, $uuid->getVersion());
$this->assertSame('000071b0ad5e', $uuid->getNodeHex());
}
public function testUuid6WithOutOfBoundsNode(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid node value');
Uuid::uuid6(new Hexadecimal('9223372036854775808'));
}
public function testUuid6WithNon48bitNumber(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Invalid node value');
Uuid::uuid6(new Hexadecimal('db77e160355ef'));
}
public function testUuid6WithRandomNode(): void
{
Uuid::setFactory(new UuidFactory(new FeatureSet(false, false, false, true)));
$uuid = Uuid::uuid6();
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(6, $uuid->getVersion());
}
public function testUuid6WithUserGeneratedRandomNode(): void
{
$uuid = Uuid::uuid6(new Hexadecimal((string) (new RandomNodeProvider())->getNode()));
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(6, $uuid->getVersion());
}
public function testUuid7(): void
{
$uuid = Uuid::uuid7();
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(7, $uuid->getVersion());
}
public function testUuid7ThrowsExceptionForUnsupportedFactory(): void
{
/** @var UuidFactoryInterface&MockInterface $factory */
$factory = Mockery::mock(UuidFactoryInterface::class);
Uuid::setFactory($factory);
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage('The provided factory does not support the uuid7() method');
Uuid::uuid7();
}
public function testUuid7WithDateTime(): void
{
$dateTime = new DateTimeImmutable('@281474976710.655');
$uuid = Uuid::uuid7($dateTime);
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(7, $uuid->getVersion());
$this->assertSame(
'10889-08-02T05:31:50.655+00:00',
$uuid->getDateTime()->format(DateTimeInterface::RFC3339_EXTENDED),
);
}
public function testUuid7SettingTheClockBackwards(): void
{
$dates = [
new DateTimeImmutable('now'),
new DateTimeImmutable('last year'),
new DateTimeImmutable('1979-01-01 00:00:00.000000'),
];
foreach ($dates as $dateTime) {
$previous = Uuid::uuid7($dateTime);
for ($i = 0; $i < 25; $i++) {
$uuid = Uuid::uuid7($dateTime);
$this->assertGreaterThan(0, $uuid->compareTo($previous));
$this->assertSame($dateTime->format('Y-m-d H:i'), $uuid->getDateTime()->format('Y-m-d H:i'));
$previous = $uuid;
}
}
}
public function testUuid7WithMinimumDateTime(): void
{
$dateTime = new DateTimeImmutable('1979-01-01 00:00:00.000000');
$uuid = Uuid::uuid7($dateTime);
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(7, $uuid->getVersion());
$this->assertSame(
'1979-01-01T00:00:00.000+00:00',
$uuid->getDateTime()->format(DateTimeInterface::RFC3339_EXTENDED),
);
}
public function testUuid7EachUuidIsMonotonicallyIncreasing(): void
{
$previous = Uuid::uuid7();
for ($i = 0; $i < 25; $i++) {
$uuid = Uuid::uuid7();
$now = gmdate('Y-m-d H:i');
$this->assertGreaterThan(0, $uuid->compareTo($previous));
$this->assertSame($now, $uuid->getDateTime()->format('Y-m-d H:i'));
$previous = $uuid;
}
}
public function testUuid7EachUuidFromSameDateTimeIsMonotonicallyIncreasing(): void
{
$dateTime = new DateTimeImmutable();
$previous = Uuid::uuid7($dateTime);
for ($i = 0; $i < 25; $i++) {
$uuid = Uuid::uuid7($dateTime);
$this->assertGreaterThan(0, $uuid->compareTo($previous));
$this->assertSame($dateTime->format('Y-m-d H:i'), $uuid->getDateTime()->format('Y-m-d H:i'));
$previous = $uuid;
}
}
public function testUuid8(): void
{
$uuid = Uuid::uuid8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff");
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(8, $uuid->getVersion());
}
public function testUuid8ThrowsExceptionForUnsupportedFactory(): void
{
/** @var UuidFactoryInterface&MockInterface $factory */
$factory = Mockery::mock(UuidFactoryInterface::class);
Uuid::setFactory($factory);
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage('The provided factory does not support the uuid8() method');
/** @phpstan-ignore staticMethod.resultUnused */
Uuid::uuid8("\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff");
}
/**
* Tests known version-3 UUIDs
*
* Taken from the Python UUID tests in
* http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py
*
* @param non-empty-string $uuid
* @param non-empty-string $ns
* @param non-empty-string $name
*
* @dataProvider provideUuid3WithKnownUuids
*/
public function testUuid3WithKnownUuids(string $uuid, string $ns, string $name): void
{
$uobj1 = Uuid::uuid3($ns, $name);
$uobj2 = Uuid::uuid3(Uuid::fromString($ns), $name);
$this->assertSame(2, $uobj1->getVariant());
$this->assertSame(3, $uobj1->getVersion());
$this->assertSame(Uuid::fromString($uuid)->toString(), $uobj1->toString());
$this->assertTrue($uobj1->equals($uobj2));
}
/**
* @return array<array{uuid: non-empty-string, ns: non-empty-string, name: non-empty-string}>
*/
public function provideUuid3WithKnownUuids(): array
{
return [
[
'uuid' => '6fa459ea-ee8a-3ca4-894e-db77e160355e',
'ns' => Uuid::NAMESPACE_DNS,
'name' => 'python.org',
],
[
'uuid' => '9fe8e8c4-aaa8-32a9-a55c-4535a88b748d',
'ns' => Uuid::NAMESPACE_URL,
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | true |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/ExpectedBehaviorTest.php | tests/ExpectedBehaviorTest.php | <?php
namespace Ramsey\Uuid\Test;
use Brick\Math\BigInteger;
use Ramsey\Uuid\Builder\DegradedUuidBuilder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\OrderedTimeCodec;
use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
use Ramsey\Uuid\Converter\Number\DegradedNumberConverter;
use Ramsey\Uuid\Converter\Time\DegradedTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\DegradedUuid;
use Ramsey\Uuid\Generator\CombGenerator;
use Ramsey\Uuid\Generator\DefaultTimeGenerator;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use stdClass;
/**
* These tests exist to ensure a seamless upgrade path from 3.x to 4.x. If any
* of these tests fail in 4.x, then it's because we've changed functionality
* in such a way that compatibility with 3.x is broken.
*
* Naturally, there are some BC-breaks between 3.x and 4.x, but these tests
* ensure that the base-level functionality that satisfies 80% of use-cases
* does not change. The remaining 20% of use-cases should refer to the README
* for details on the easiest path to transition from 3.x to 4.x.
*
* @codingStandardsIgnoreFile
*/
class ExpectedBehaviorTest extends TestCase
{
/**
* @dataProvider provideStaticCreationMethods
*/
public function testStaticCreationMethodsAndStandardBehavior($method, $args)
{
$uuid = call_user_func_array(['Ramsey\Uuid\Uuid', $method], $args);
$this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid);
$this->assertIsInt($uuid->compareTo(Uuid::uuid1()));
$this->assertNotSame(0, $uuid->compareTo(Uuid::uuid4()));
$this->assertSame(0, $uuid->compareTo(clone $uuid));
$this->assertFalse($uuid->equals(new stdClass()));
$this->assertTrue($uuid->equals(clone $uuid));
$this->assertIsString($uuid->getBytes());
$this->assertInstanceOf('Ramsey\Uuid\Converter\NumberConverterInterface', $uuid->getNumberConverter());
$this->assertIsString((string) $uuid->getHex());
$this->assertIsArray($uuid->getFieldsHex());
$this->assertArrayHasKey('time_low', $uuid->getFieldsHex());
$this->assertArrayHasKey('time_mid', $uuid->getFieldsHex());
$this->assertArrayHasKey('time_hi_and_version', $uuid->getFieldsHex());
$this->assertArrayHasKey('clock_seq_hi_and_reserved', $uuid->getFieldsHex());
$this->assertArrayHasKey('clock_seq_low', $uuid->getFieldsHex());
$this->assertArrayHasKey('node', $uuid->getFieldsHex());
$this->assertIsString($uuid->getTimeLowHex());
$this->assertIsString($uuid->getTimeMidHex());
$this->assertIsString($uuid->getTimeHiAndVersionHex());
$this->assertIsString($uuid->getClockSeqHiAndReservedHex());
$this->assertIsString($uuid->getClockSeqLowHex());
$this->assertIsString($uuid->getNodeHex());
$this->assertSame($uuid->getFieldsHex()['time_low'], $uuid->getTimeLowHex());
$this->assertSame($uuid->getFieldsHex()['time_mid'], $uuid->getTimeMidHex());
$this->assertSame($uuid->getFieldsHex()['time_hi_and_version'], $uuid->getTimeHiAndVersionHex());
$this->assertSame($uuid->getFieldsHex()['clock_seq_hi_and_reserved'], $uuid->getClockSeqHiAndReservedHex());
$this->assertSame($uuid->getFieldsHex()['clock_seq_low'], $uuid->getClockSeqLowHex());
$this->assertSame($uuid->getFieldsHex()['node'], $uuid->getNodeHex());
$this->assertSame(substr((string) $uuid->getHex(), 16), $uuid->getLeastSignificantBitsHex());
$this->assertSame(substr((string) $uuid->getHex(), 0, 16), $uuid->getMostSignificantBitsHex());
$this->assertSame(
(string) $uuid->getHex(),
$uuid->getTimeLowHex()
. $uuid->getTimeMidHex()
. $uuid->getTimeHiAndVersionHex()
. $uuid->getClockSeqHiAndReservedHex()
. $uuid->getClockSeqLowHex()
. $uuid->getNodeHex()
);
$this->assertSame(
(string) $uuid->getHex(),
$uuid->getFieldsHex()['time_low']
. $uuid->getFieldsHex()['time_mid']
. $uuid->getFieldsHex()['time_hi_and_version']
. $uuid->getFieldsHex()['clock_seq_hi_and_reserved']
. $uuid->getFieldsHex()['clock_seq_low']
. $uuid->getFieldsHex()['node']
);
$this->assertIsString($uuid->getUrn());
$this->assertStringStartsWith('urn:uuid:', $uuid->getUrn());
$this->assertSame('urn:uuid:' . (string) $uuid->getHex(), str_replace('-', '', $uuid->getUrn()));
$this->assertSame((string) $uuid->getHex(), str_replace('-', '', $uuid->toString()));
$this->assertSame((string) $uuid->getHex(), str_replace('-', '', (string) $uuid));
$this->assertSame(
$uuid->toString(),
$uuid->getTimeLowHex() . '-'
. $uuid->getTimeMidHex() . '-'
. $uuid->getTimeHiAndVersionHex() . '-'
. $uuid->getClockSeqHiAndReservedHex()
. $uuid->getClockSeqLowHex() . '-'
. $uuid->getNodeHex()
);
$this->assertSame(
(string) $uuid,
$uuid->getTimeLowHex() . '-'
. $uuid->getTimeMidHex() . '-'
. $uuid->getTimeHiAndVersionHex() . '-'
. $uuid->getClockSeqHiAndReservedHex()
. $uuid->getClockSeqLowHex() . '-'
. $uuid->getNodeHex()
);
$this->assertSame(2, $uuid->getVariant());
$this->assertSame((int) substr($method, -1), $uuid->getVersion());
$this->assertSame(1, preg_match('/^\d+$/', (string) $uuid->getInteger()));
}
public function provideStaticCreationMethods()
{
return [
['uuid1', []],
['uuid1', ['00000fffffff']],
['uuid1', [null, 1234]],
['uuid1', ['00000fffffff', 1234]],
['uuid1', ['00000fffffff', null]],
['uuid1', [268435455]],
['uuid1', [268435455, 1234]],
['uuid1', [268435455, null]],
['uuid3', [Uuid::NAMESPACE_URL, 'https://example.com/foo']],
['uuid4', []],
['uuid5', [Uuid::NAMESPACE_URL, 'https://example.com/foo']],
];
}
public function testUuidVersion1MethodBehavior()
{
$uuid = Uuid::uuid1('00000fffffff', 0xffff);
$this->assertInstanceOf('DateTimeInterface', $uuid->getDateTime());
$this->assertSame('00000fffffff', $uuid->getNodeHex());
$this->assertSame('3fff', $uuid->getClockSequenceHex());
$this->assertSame('16383', (string) $uuid->getClockSequence());
}
public function testUuidVersion1MethodBehavior64Bit()
{
$uuid = Uuid::uuid1('ffffffffffff', 0xffff);
$this->assertInstanceOf('DateTimeInterface', $uuid->getDateTime());
$this->assertSame('ffffffffffff', $uuid->getNodeHex());
$this->assertSame('281474976710655', (string) $uuid->getNode());
$this->assertSame('3fff', $uuid->getClockSequenceHex());
$this->assertSame('16383', (string) $uuid->getClockSequence());
$this->assertSame(1, preg_match('/^\d+$/', (string) $uuid->getTimestamp()));
}
/**
* @dataProvider provideIsValid
*/
public function testIsValid($uuid, $expected)
{
$this->assertSame($expected, Uuid::isValid($uuid), "{$uuid} is not a valid UUID");
$this->assertSame($expected, Uuid::isValid(strtoupper($uuid)), strtoupper($uuid) . ' is not a valid UUID');
}
public function provideIsValid()
{
return [
// RFC 4122 UUIDs
['00000000-0000-0000-0000-000000000000', true],
['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', true],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', true],
['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', true],
['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', true],
['ff6f8cb0-c57d-21e1-8b21-0800200c9a66', true],
['ff6f8cb0-c57d-21e1-9b21-0800200c9a66', true],
['ff6f8cb0-c57d-21e1-ab21-0800200c9a66', true],
['ff6f8cb0-c57d-21e1-bb21-0800200c9a66', true],
['ff6f8cb0-c57d-31e1-8b21-0800200c9a66', true],
['ff6f8cb0-c57d-31e1-9b21-0800200c9a66', true],
['ff6f8cb0-c57d-31e1-ab21-0800200c9a66', true],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', true],
['ff6f8cb0-c57d-41e1-8b21-0800200c9a66', true],
['ff6f8cb0-c57d-41e1-9b21-0800200c9a66', true],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', true],
['ff6f8cb0-c57d-41e1-bb21-0800200c9a66', true],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', true],
['ff6f8cb0-c57d-51e1-9b21-0800200c9a66', true],
['ff6f8cb0-c57d-51e1-ab21-0800200c9a66', true],
['ff6f8cb0-c57d-51e1-bb21-0800200c9a66', true],
// Non RFC 4122 UUIDs
['ffffffff-ffff-ffff-ffff-ffffffffffff', true],
['00000000-0000-0000-0000-000000000000', true],
['ff6f8cb0-c57d-01e1-0b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-1b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-2b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-3b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-4b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-5b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-6b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-7b21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-db21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-eb21-0800200c9a66', true],
['ff6f8cb0-c57d-01e1-fb21-0800200c9a66', true],
// Other valid patterns
['{ff6f8cb0-c57d-01e1-fb21-0800200c9a66}', true],
['urn:uuid:ff6f8cb0-c57d-01e1-fb21-0800200c9a66', true],
// Invalid UUIDs
['ffffffffffffffffffffffffffffffff', false],
['00000000000000000000000000000000', false],
[0, false],
['foobar', false],
['ff6f8cb0c57d51e1bb210800200c9a66', false],
['gf6f8cb0-c57d-51e1-bb21-0800200c9a66', false],
];
}
/**
* @dataProvider provideFromStringInteger
*/
public function testSerialization($string)
{
$uuid = Uuid::fromString($string);
$serialized = serialize($uuid);
$unserialized = unserialize($serialized);
$this->assertSame(0, $uuid->compareTo($unserialized));
$this->assertTrue($uuid->equals($unserialized));
$this->assertSame("\"{$string}\"", json_encode($uuid));
}
/**
* @dataProvider provideFromStringInteger
*/
public function testSerializationWithOrderedTimeCodec($string)
{
$factory = new UuidFactory();
$factory->setCodec(new OrderedTimeCodec(
$factory->getUuidBuilder()
));
$previousFactory = Uuid::getFactory();
Uuid::setFactory($factory);
$uuid = Uuid::fromString($string);
$serialized = serialize($uuid);
$unserialized = unserialize($serialized);
Uuid::setFactory($previousFactory);
$this->assertSame(0, $uuid->compareTo($unserialized));
$this->assertTrue($uuid->equals($unserialized));
$this->assertSame("\"{$string}\"", json_encode($uuid));
}
/**
* @dataProvider provideFromStringInteger
*/
public function testNumericReturnValues($string)
{
$leastSignificantBitsHex = substr(str_replace('-', '', $string), 16);
$mostSignificantBitsHex = substr(str_replace('-', '', $string), 0, 16);
$leastSignificantBits = BigInteger::fromBase($leastSignificantBitsHex, 16)->__toString();
$mostSignificantBits = BigInteger::fromBase($mostSignificantBitsHex, 16)->__toString();
$components = explode('-', $string);
array_walk($components, function (&$value) {
$value = BigInteger::fromBase($value, 16)->__toString();
});
if (strtolower($string) === Uuid::MAX) {
$clockSeq = (int) $components[3];
} else {
$clockSeq = (int) $components[3] & 0x3fff;
}
$clockSeqHiAndReserved = (int) $components[3] >> 8;
$clockSeqLow = (int) $components[3] & 0x00ff;
$uuid = Uuid::fromString($string);
$this->assertSame($components[0], (string) $uuid->getTimeLow());
$this->assertSame($components[1], (string) $uuid->getTimeMid());
$this->assertSame($components[2], (string) $uuid->getTimeHiAndVersion());
$this->assertSame((string) $clockSeq, (string) $uuid->getClockSequence());
$this->assertSame((string) $clockSeqHiAndReserved, (string) $uuid->getClockSeqHiAndReserved());
$this->assertSame((string) $clockSeqLow, (string) $uuid->getClockSeqLow());
$this->assertSame($components[4], (string) $uuid->getNode());
$this->assertSame($leastSignificantBits, (string) $uuid->getLeastSignificantBits());
$this->assertSame($mostSignificantBits, (string) $uuid->getMostSignificantBits());
}
/**
* @dataProvider provideFromStringInteger
*/
public function testFromBytes($string, $version, $variant, $integer)
{
$bytes = hex2bin(str_replace('-', '', $string));
$uuid = Uuid::fromBytes($bytes);
$this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid);
$this->assertSame($string, $uuid->toString());
$this->assertSame($version, $uuid->getVersion());
$this->assertSame($variant, $uuid->getVariant());
$components = explode('-', $string);
$this->assertSame($components[0], $uuid->getTimeLowHex());
$this->assertSame($components[1], $uuid->getTimeMidHex());
$this->assertSame($components[2], $uuid->getTimeHiAndVersionHex());
$this->assertSame($components[3], $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex());
$this->assertSame($components[4], $uuid->getNodeHex());
$this->assertSame($integer, (string) $uuid->getInteger());
$this->assertSame($bytes, $uuid->getBytes());
}
/**
* @dataProvider provideFromStringInteger
*/
public function testFromInteger($string, $version, $variant, $integer)
{
$bytes = hex2bin(str_replace('-', '', $string));
$uuid = Uuid::fromInteger($integer);
$this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid);
$this->assertSame($string, $uuid->toString());
$this->assertSame($version, $uuid->getVersion());
$this->assertSame($variant, $uuid->getVariant());
$components = explode('-', $string);
$this->assertSame($components[0], $uuid->getTimeLowHex());
$this->assertSame($components[1], $uuid->getTimeMidHex());
$this->assertSame($components[2], $uuid->getTimeHiAndVersionHex());
$this->assertSame($components[3], $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex());
$this->assertSame($components[4], $uuid->getNodeHex());
$this->assertSame($integer, (string) $uuid->getInteger());
$this->assertSame($bytes, $uuid->getBytes());
}
/**
* @dataProvider provideFromStringInteger
*/
public function testFromString($string, $version, $variant, $integer)
{
$bytes = hex2bin(str_replace('-', '', $string));
$uuid = Uuid::fromString($string);
$this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid);
$this->assertSame($string, $uuid->toString());
$this->assertSame($version, $uuid->getVersion());
$this->assertSame($variant, $uuid->getVariant());
$components = explode('-', $string);
$this->assertSame($components[0], $uuid->getTimeLowHex());
$this->assertSame($components[1], $uuid->getTimeMidHex());
$this->assertSame($components[2], $uuid->getTimeHiAndVersionHex());
$this->assertSame($components[3], $uuid->getClockSeqHiAndReservedHex() . $uuid->getClockSeqLowHex());
$this->assertSame($components[4], $uuid->getNodeHex());
$this->assertSame($integer, (string) $uuid->getInteger());
$this->assertSame($bytes, $uuid->getBytes());
}
public function provideFromStringInteger()
{
return [
['00000000-0000-0000-0000-000000000000', null, 0, '0'],
['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', 1, 2, '339532337419071774304650190139318639206'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 1, 2, '339532337419071774305803111643925486182'],
['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', 1, 2, '339532337419071774306956033148532333158'],
['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', 1, 2, '339532337419071774308108954653139180134'],
['ff6f8cb0-c57d-21e1-8b21-0800200c9a66', 2, 2, '339532337419071849862513916053642058342'],
['ff6f8cb0-c57d-21e1-9b21-0800200c9a66', 2, 2, '339532337419071849863666837558248905318'],
['ff6f8cb0-c57d-21e1-ab21-0800200c9a66', 2, 2, '339532337419071849864819759062855752294'],
['ff6f8cb0-c57d-21e1-bb21-0800200c9a66', 2, 2, '339532337419071849865972680567462599270'],
['ff6f8cb0-c57d-31e1-8b21-0800200c9a66', 3, 2, '339532337419071925420377641967965477478'],
['ff6f8cb0-c57d-31e1-9b21-0800200c9a66', 3, 2, '339532337419071925421530563472572324454'],
['ff6f8cb0-c57d-31e1-ab21-0800200c9a66', 3, 2, '339532337419071925422683484977179171430'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 3, 2, '339532337419071925423836406481786018406'],
['ff6f8cb0-c57d-41e1-8b21-0800200c9a66', 4, 2, '339532337419072000978241367882288896614'],
['ff6f8cb0-c57d-41e1-9b21-0800200c9a66', 4, 2, '339532337419072000979394289386895743590'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 4, 2, '339532337419072000980547210891502590566'],
['ff6f8cb0-c57d-41e1-bb21-0800200c9a66', 4, 2, '339532337419072000981700132396109437542'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 5, 2, '339532337419072076536105093796612315750'],
['ff6f8cb0-c57d-51e1-9b21-0800200c9a66', 5, 2, '339532337419072076537258015301219162726'],
['ff6f8cb0-c57d-51e1-ab21-0800200c9a66', 5, 2, '339532337419072076538410936805826009702'],
['ff6f8cb0-c57d-51e1-bb21-0800200c9a66', 5, 2, '339532337419072076539563858310432856678'],
['ff6f8cb0-c57d-01e1-0b21-0800200c9a66', null, 0, '339532337419071698737563092188140444262'],
['ff6f8cb0-c57d-01e1-1b21-0800200c9a66', null, 0, '339532337419071698738716013692747291238'],
['ff6f8cb0-c57d-01e1-2b21-0800200c9a66', null, 0, '339532337419071698739868935197354138214'],
['ff6f8cb0-c57d-01e1-3b21-0800200c9a66', null, 0, '339532337419071698741021856701960985190'],
['ff6f8cb0-c57d-01e1-4b21-0800200c9a66', null, 0, '339532337419071698742174778206567832166'],
['ff6f8cb0-c57d-01e1-5b21-0800200c9a66', null, 0, '339532337419071698743327699711174679142'],
['ff6f8cb0-c57d-01e1-6b21-0800200c9a66', null, 0, '339532337419071698744480621215781526118'],
['ff6f8cb0-c57d-01e1-7b21-0800200c9a66', null, 0, '339532337419071698745633542720388373094'],
['ff6f8cb0-c57d-01e1-cb21-0800200c9a66', null, 6, '339532337419071698751398150243422607974'],
['ff6f8cb0-c57d-01e1-db21-0800200c9a66', null, 6, '339532337419071698752551071748029454950'],
['ff6f8cb0-c57d-01e1-eb21-0800200c9a66', null, 7, '339532337419071698753703993252636301926'],
['ff6f8cb0-c57d-01e1-fb21-0800200c9a66', null, 7, '339532337419071698754856914757243148902'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', null, 7, '340282366920938463463374607431768211455'],
];
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetSetFactory()
{
$this->assertInstanceOf('Ramsey\Uuid\UuidFactory', Uuid::getFactory());
$factory = \Mockery::mock('Ramsey\Uuid\UuidFactory');
Uuid::setFactory($factory);
$this->assertSame($factory, Uuid::getFactory());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testFactoryProvidesFunctionality()
{
$uuid = \Mockery::mock('Ramsey\Uuid\UuidInterface');
$factory = \Mockery::mock('Ramsey\Uuid\UuidFactoryInterface', [
'uuid1' => $uuid,
'uuid3' => $uuid,
'uuid4' => $uuid,
'uuid5' => $uuid,
'fromBytes' => $uuid,
'fromString' => $uuid,
'fromInteger' => $uuid,
]);
Uuid::setFactory($factory);
$this->assertSame($uuid, Uuid::uuid1('ffffffffffff', 0xffff));
$this->assertSame($uuid, Uuid::uuid3(Uuid::NAMESPACE_URL, 'https://example.com/foo'));
$this->assertSame($uuid, Uuid::uuid4());
$this->assertSame($uuid, Uuid::uuid5(Uuid::NAMESPACE_URL, 'https://example.com/foo'));
$this->assertSame($uuid, Uuid::fromBytes(hex2bin('ffffffffffffffffffffffffffffffff')));
$this->assertSame($uuid, Uuid::fromString('ffffffff-ffff-ffff-ffff-ffffffffffff'));
$this->assertSame($uuid, Uuid::fromInteger('340282366920938463463374607431768211455'));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testUsingDegradedFeatures()
{
$numberConverter = new DegradedNumberConverter();
$builder = new DegradedUuidBuilder($numberConverter);
$factory = new UuidFactory();
$factory->setNumberConverter($numberConverter);
$factory->setUuidBuilder($builder);
Uuid::setFactory($factory);
$uuid = Uuid::uuid1();
$this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid);
$this->assertInstanceOf('Ramsey\Uuid\DegradedUuid', $uuid);
$this->assertInstanceOf('Ramsey\Uuid\Converter\Number\DegradedNumberConverter', $uuid->getNumberConverter());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testUsingCustomCodec()
{
$mockUuid = \Mockery::mock('Ramsey\Uuid\UuidInterface');
$codec = \Mockery::mock('Ramsey\Uuid\Codec\CodecInterface', [
'encode' => 'abcd1234',
'encodeBinary' => hex2bin('abcd1234'),
'decode' => $mockUuid,
'decodeBytes' => $mockUuid,
]);
$factory = new UuidFactory();
$factory->setCodec($codec);
Uuid::setFactory($factory);
$uuid = Uuid::uuid4();
$this->assertSame('abcd1234', $uuid->toString());
$this->assertSame(hex2bin('abcd1234'), $uuid->getBytes());
$this->assertSame($mockUuid, Uuid::fromString('f00ba2'));
$this->assertSame($mockUuid, Uuid::fromBytes(hex2bin('f00ba2')));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testUsingCustomRandomGenerator()
{
$generator = \Mockery::mock('Ramsey\Uuid\Generator\RandomGeneratorInterface', [
'generate' => hex2bin('01234567abcd5432dcba0123456789ab'),
]);
$factory = new UuidFactory();
$factory->setRandomGenerator($generator);
Uuid::setFactory($factory);
$uuid = Uuid::uuid4();
$this->assertSame('01234567-abcd-4432-9cba-0123456789ab', $uuid->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testUsingCustomTimeGenerator()
{
$generator = \Mockery::mock('Ramsey\Uuid\Generator\TimeGeneratorInterface', [
'generate' => hex2bin('01234567abcd5432dcba0123456789ab'),
]);
$factory = new UuidFactory();
$factory->setTimeGenerator($generator);
Uuid::setFactory($factory);
$uuid = Uuid::uuid1();
$this->assertSame('01234567-abcd-1432-9cba-0123456789ab', $uuid->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testUsingDefaultTimeGeneratorWithCustomProviders()
{
$nodeProvider = \Mockery::mock('Ramsey\Uuid\Provider\NodeProviderInterface', [
'getNode' => new Hexadecimal('0123456789ab'),
]);
$timeConverter = \Mockery::mock('Ramsey\Uuid\Converter\TimeConverterInterface');
$timeConverter
->shouldReceive('calculateTime')
->andReturnUsing(function ($seconds, $microseconds) {
return new Hexadecimal('abcd' . dechex($microseconds) . dechex($seconds));
});
$timeProvider = \Mockery::mock('Ramsey\Uuid\Provider\TimeProviderInterface', [
'currentTime' => [
'sec' => 1578522046,
'usec' => 10000,
],
'getTime' => new Time(1578522046, 10000),
]);
$generator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider);
$factory = new UuidFactory();
$factory->setTimeGenerator($generator);
Uuid::setFactory($factory);
$uuid = Uuid::uuid1(null, 4095);
$this->assertSame('5e1655be-2710-1bcd-8fff-0123456789ab', $uuid->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testHelperFunctions()
{
$uuid1 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [
'toString' => 'aVersion1Uuid',
]);
$uuid3 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [
'toString' => 'aVersion3Uuid',
]);
$uuid4 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [
'toString' => 'aVersion4Uuid',
]);
$uuid5 = \Mockery::mock('Ramsey\Uuid\UuidInterface', [
'toString' => 'aVersion5Uuid',
]);
$factory = \Mockery::mock('Ramsey\Uuid\UuidFactoryInterface', [
'uuid1' => $uuid1,
'uuid3' => $uuid3,
'uuid4' => $uuid4,
'uuid5' => $uuid5,
]);
Uuid::setFactory($factory);
$this->assertSame('aVersion1Uuid', \Ramsey\Uuid\v1('ffffffffffff', 0xffff));
$this->assertSame('aVersion3Uuid', \Ramsey\Uuid\v3(Uuid::NAMESPACE_URL, 'https://example.com/foo'));
$this->assertSame('aVersion4Uuid', \Ramsey\Uuid\v4());
$this->assertSame('aVersion5Uuid', \Ramsey\Uuid\v5(Uuid::NAMESPACE_URL, 'https://example.com/foo'));
}
/**
* @link https://git.io/JvJZo Use of TimestampFirstCombCodec in laravel/framework
*/
public function testUseOfTimestampFirstCombCodec()
{
$factory = new UuidFactory();
$factory->setRandomGenerator(new CombGenerator(
$factory->getRandomGenerator(),
$factory->getNumberConverter()
));
$factory->setCodec(new TimestampFirstCombCodec(
$factory->getUuidBuilder()
));
$uuid = $factory->uuid4();
// Swap fields according to the rules for TimestampFirstCombCodec.
$fields = array_values($uuid->getFieldsHex());
$last48Bits = $fields[5];
$fields[5] = $fields[0] . $fields[1];
$fields[0] = substr($last48Bits, 0, 8);
$fields[1] = substr($last48Bits, 8, 4);
$expectedHex = implode('', $fields);
$expectedBytes = hex2bin($expectedHex);
$this->assertInstanceOf('Ramsey\Uuid\UuidInterface', $uuid);
$this->assertSame(2, $uuid->getVariant());
$this->assertSame(4, $uuid->getVersion());
$this->assertSame($expectedBytes, $uuid->getBytes());
$this->assertSame($expectedHex, (string) $uuid->getHex());
}
/**
* @dataProvider provideUuidConstantTests
*/
public function testUuidConstants($constantName, $expected)
{
$this->assertSame($expected, constant("Ramsey\\Uuid\\Uuid::{$constantName}"));
}
public function provideUuidConstantTests()
{
return [
['NAMESPACE_DNS', '6ba7b810-9dad-11d1-80b4-00c04fd430c8'],
['NAMESPACE_URL', '6ba7b811-9dad-11d1-80b4-00c04fd430c8'],
['NAMESPACE_OID', '6ba7b812-9dad-11d1-80b4-00c04fd430c8'],
['NAMESPACE_X500', '6ba7b814-9dad-11d1-80b4-00c04fd430c8'],
['NIL', '00000000-0000-0000-0000-000000000000'],
['MAX', 'ffffffff-ffff-ffff-ffff-ffffffffffff'],
['RESERVED_NCS', 0],
['RFC_4122', 2],
['RESERVED_MICROSOFT', 6],
['RESERVED_FUTURE', 7],
['VALID_PATTERN', '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$'],
['UUID_TYPE_TIME', 1],
['UUID_TYPE_IDENTIFIER', 2],
['UUID_TYPE_HASH_MD5', 3],
['UUID_TYPE_RANDOM', 4],
['UUID_TYPE_HASH_SHA1', 5],
['UUID_TYPE_REORDERED_TIME', 6],
['UUID_TYPE_UNIX_TIME', 7],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/UuidFactoryTest.php | tests/UuidFactoryTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use DateTime;
use DateTimeImmutable;
use DateTimeInterface;
use Mockery;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\FeatureSet;
use Ramsey\Uuid\Generator\DceSecurityGeneratorInterface;
use Ramsey\Uuid\Generator\DefaultNameGenerator;
use Ramsey\Uuid\Generator\NameGeneratorInterface;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Generator\TimeGeneratorInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\Validator\ValidatorInterface;
use function hex2bin;
use function strtoupper;
class UuidFactoryTest extends TestCase
{
public function testParsesUuidCorrectly(): void
{
$factory = new UuidFactory();
$uuid = $factory->fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString());
$this->assertSame(hex2bin('ff6f8cb0c57d11e19b210800200c9a66'), $uuid->getBytes());
}
public function testParsesGuidCorrectly(): void
{
$factory = new UuidFactory(new FeatureSet(true));
$uuid = $factory->fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
$this->assertSame('ff6f8cb0-c57d-11e1-9b21-0800200c9a66', $uuid->toString());
$this->assertSame(hex2bin('b08c6fff7dc5e1119b210800200c9a66'), $uuid->getBytes());
}
public function testFromStringParsesUuidInLowercase(): void
{
$uuidString = 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66';
$uuidUpper = strtoupper($uuidString);
$factory = new UuidFactory(new FeatureSet(true));
$uuid = $factory->fromString($uuidUpper);
$this->assertSame($uuidString, $uuid->toString());
}
public function testGettersReturnValueFromFeatureSet(): void
{
$codec = Mockery::mock(CodecInterface::class);
$nodeProvider = Mockery::mock(NodeProviderInterface::class);
$randomGenerator = Mockery::mock(RandomGeneratorInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$unixTimeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$nameGenerator = Mockery::mock(NameGeneratorInterface::class);
$dceSecurityGenerator = Mockery::mock(DceSecurityGeneratorInterface::class);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$builder = Mockery::mock(UuidBuilderInterface::class);
$validator = Mockery::mock(ValidatorInterface::class);
$featureSet = Mockery::mock(FeatureSet::class, [
'getCodec' => $codec,
'getNodeProvider' => $nodeProvider,
'getRandomGenerator' => $randomGenerator,
'getTimeConverter' => $timeConverter,
'getTimeGenerator' => $timeGenerator,
'getNameGenerator' => $nameGenerator,
'getDceSecurityGenerator' => $dceSecurityGenerator,
'getNumberConverter' => $numberConverter,
'getBuilder' => $builder,
'getValidator' => $validator,
'getUnixTimeGenerator' => $unixTimeGenerator,
]);
$uuidFactory = new UuidFactory($featureSet);
$this->assertSame(
$codec,
$uuidFactory->getCodec(),
'getCodec did not return CodecInterface from FeatureSet'
);
$this->assertSame(
$nodeProvider,
$uuidFactory->getNodeProvider(),
'getNodeProvider did not return NodeProviderInterface from FeatureSet'
);
$this->assertSame(
$randomGenerator,
$uuidFactory->getRandomGenerator(),
'getRandomGenerator did not return RandomGeneratorInterface from FeatureSet'
);
$this->assertSame(
$timeGenerator,
$uuidFactory->getTimeGenerator(),
'getTimeGenerator did not return TimeGeneratorInterface from FeatureSet'
);
}
public function testSettersSetValueForGetters(): void
{
$uuidFactory = new UuidFactory();
/** @var MockObject & CodecInterface $codec */
$codec = $this->getMockBuilder(CodecInterface::class)->getMock();
$uuidFactory->setCodec($codec);
$this->assertSame($codec, $uuidFactory->getCodec());
/** @var MockObject & TimeGeneratorInterface $timeGenerator */
$timeGenerator = $this->getMockBuilder(TimeGeneratorInterface::class)->getMock();
$uuidFactory->setTimeGenerator($timeGenerator);
$this->assertSame($timeGenerator, $uuidFactory->getTimeGenerator());
/** @var MockObject & NumberConverterInterface $numberConverter */
$numberConverter = $this->getMockBuilder(NumberConverterInterface::class)->getMock();
$uuidFactory->setNumberConverter($numberConverter);
$this->assertSame($numberConverter, $uuidFactory->getNumberConverter());
/** @var MockObject & UuidBuilderInterface $uuidBuilder */
$uuidBuilder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock();
$uuidFactory->setUuidBuilder($uuidBuilder);
$this->assertSame($uuidBuilder, $uuidFactory->getUuidBuilder());
}
/**
* @dataProvider provideDateTime
*/
public function testFromDateTime(
DateTimeInterface $dateTime,
?Hexadecimal $node,
?int $clockSeq,
string $expectedUuidFormat,
string $expectedTime
): void {
$factory = new UuidFactory();
$uuid = $factory->fromDateTime($dateTime, $node, $clockSeq);
$this->assertStringMatchesFormat($expectedUuidFormat, $uuid->toString());
$this->assertSame($expectedTime, $uuid->getDateTime()->format('U.u'));
}
/**
* @return array<array{0: DateTimeInterface, 1: Hexadecimal | null, 2: int | null, 3: string, 4: string}>
*/
public function provideDateTime(): array
{
return [
[
new DateTimeImmutable('2012-07-04 02:14:34.491000'),
null,
null,
'ff6f8cb0-c57d-11e1-%s',
'1341368074.491000',
],
[
new DateTimeImmutable('1582-10-16 16:34:04'),
new Hexadecimal('0800200c9a66'),
15137,
'0901e600-0154-1000-%cb21-0800200c9a66',
'-12219146756.000000',
],
[
new DateTime('5236-03-31 21:20:59.999999'),
new Hexadecimal('00007ffffffe'),
1641,
'ff9785f6-ffff-1fff-%c669-00007ffffffe',
'103072857659.999999',
],
[
new DateTime('1582-10-15 00:00:00'),
new Hexadecimal('00007ffffffe'),
1641,
'00000000-0000-1000-%c669-00007ffffffe',
'-12219292800.000000',
],
[
new DateTimeImmutable('@103072857660.684697'),
new Hexadecimal('0'),
0,
'fffffffa-ffff-1fff-%c000-000000000000',
'103072857660.684697',
],
[
new DateTimeImmutable('5236-03-31 21:21:00.684697'),
null,
null,
'fffffffa-ffff-1fff-%s',
'103072857660.684697',
],
];
}
public function testFactoryReturnsDefaultNameGenerator(): void
{
$factory = new UuidFactory();
$this->assertInstanceOf(DefaultNameGenerator::class, $factory->getNameGenerator());
}
public function testFactoryReturnsSetNameGenerator(): void
{
$factory = new UuidFactory();
$this->assertInstanceOf(DefaultNameGenerator::class, $factory->getNameGenerator());
$nameGenerator = Mockery::mock(NameGeneratorInterface::class);
$factory->setNameGenerator($nameGenerator);
$this->assertSame($nameGenerator, $factory->getNameGenerator());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/FeatureSetTest.php | tests/FeatureSetTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use Mockery;
use Ramsey\Uuid\Builder\FallbackBuilder;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\FeatureSet;
use Ramsey\Uuid\Generator\DefaultNameGenerator;
use Ramsey\Uuid\Generator\PeclUuidTimeGenerator;
use Ramsey\Uuid\Generator\UnixTimeGenerator;
use Ramsey\Uuid\Guid\GuidBuilder;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Validator\ValidatorInterface;
class FeatureSetTest extends TestCase
{
public function testGuidBuilderIsSelected(): void
{
$featureSet = new FeatureSet(true, true);
$this->assertInstanceOf(GuidBuilder::class, $featureSet->getBuilder());
}
public function testFallbackBuilderIsSelected(): void
{
$featureSet = new FeatureSet(false, true);
$this->assertInstanceOf(FallbackBuilder::class, $featureSet->getBuilder());
}
public function testSetValidatorSetsTheProvidedValidator(): void
{
$validator = Mockery::mock(ValidatorInterface::class);
$featureSet = new FeatureSet();
$featureSet->setValidator($validator);
$this->assertSame($validator, $featureSet->getValidator());
}
public function testGetTimeConverter(): void
{
$featureSet = new FeatureSet();
/** @phpstan-ignore method.alreadyNarrowedType */
$this->assertInstanceOf(TimeConverterInterface::class, $featureSet->getTimeConverter());
}
public function testDefaultNameGeneratorIsSelected(): void
{
$featureSet = new FeatureSet();
$this->assertInstanceOf(DefaultNameGenerator::class, $featureSet->getNameGenerator());
}
public function testPeclUuidTimeGeneratorIsSelected(): void
{
$featureSet = new FeatureSet(false, false, false, false, true);
$this->assertInstanceOf(PeclUuidTimeGenerator::class, $featureSet->getTimeGenerator());
}
public function testGetCalculator(): void
{
$featureSet = new FeatureSet();
$this->assertInstanceOf(BrickMathCalculator::class, $featureSet->getCalculator());
}
public function testSetNodeProvider(): void
{
$nodeProvider = Mockery::mock(NodeProviderInterface::class);
$featureSet = new FeatureSet();
$featureSet->setNodeProvider($nodeProvider);
$this->assertSame($nodeProvider, $featureSet->getNodeProvider());
}
public function testGetUnixTimeGenerator(): void
{
$featureSet = new FeatureSet();
$this->assertInstanceOf(UnixTimeGenerator::class, $featureSet->getUnixTimeGenerator());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/BinaryUtilsTest.php | tests/BinaryUtilsTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test;
use Ramsey\Uuid\BinaryUtils;
use function dechex;
class BinaryUtilsTest extends TestCase
{
/**
* @dataProvider provideVersionTestValues
*/
public function testApplyVersion(int $timeHi, int $version, int $expectedInt, string $expectedHex): void
{
$this->assertSame($expectedInt, BinaryUtils::applyVersion($timeHi, $version));
$this->assertSame($expectedHex, dechex(BinaryUtils::applyVersion($timeHi, $version)));
}
/**
* @dataProvider provideVariantTestValues
*/
public function testApplyVariant(int $clockSeq, int $expectedInt, string $expectedHex): void
{
$this->assertSame($expectedInt, BinaryUtils::applyVariant($clockSeq));
$this->assertSame($expectedHex, dechex(BinaryUtils::applyVariant($clockSeq)));
}
/**
* @return array<array{timeHi: int, version: int, expectedInt: int, expectedHex: non-empty-string}>
*/
public function provideVersionTestValues(): array
{
return [
[
'timeHi' => 1001,
'version' => 1,
'expectedInt' => 5097,
'expectedHex' => '13e9',
],
[
'timeHi' => 1001,
'version' => 2,
'expectedInt' => 9193,
'expectedHex' => '23e9',
],
[
'timeHi' => 1001,
'version' => 3,
'expectedInt' => 13289,
'expectedHex' => '33e9',
],
[
'timeHi' => 1001,
'version' => 4,
'expectedInt' => 17385,
'expectedHex' => '43e9',
],
[
'timeHi' => 1001,
'version' => 5,
'expectedInt' => 21481,
'expectedHex' => '53e9',
],
[
'timeHi' => 65535,
'version' => 1,
'expectedInt' => 8191,
'expectedHex' => '1fff',
],
[
'timeHi' => 65535,
'version' => 2,
'expectedInt' => 12287,
'expectedHex' => '2fff',
],
[
'timeHi' => 65535,
'version' => 3,
'expectedInt' => 16383,
'expectedHex' => '3fff',
],
[
'timeHi' => 65535,
'version' => 4,
'expectedInt' => 20479,
'expectedHex' => '4fff',
],
[
'timeHi' => 65535,
'version' => 5,
'expectedInt' => 24575,
'expectedHex' => '5fff',
],
[
'timeHi' => 0,
'version' => 1,
'expectedInt' => 4096,
'expectedHex' => '1000',
],
[
'timeHi' => 0,
'version' => 2,
'expectedInt' => 8192,
'expectedHex' => '2000',
],
[
'timeHi' => 0,
'version' => 3,
'expectedInt' => 12288,
'expectedHex' => '3000',
],
[
'timeHi' => 0,
'version' => 4,
'expectedInt' => 16384,
'expectedHex' => '4000',
],
[
'timeHi' => 0,
'version' => 5,
'expectedInt' => 20480,
'expectedHex' => '5000',
],
];
}
/**
* @return array<array{clockSeq: int, expectedInt: int, expectedHex: non-empty-string}>
*/
public function provideVariantTestValues(): array
{
return [
[
'clockSeq' => 0,
'expectedInt' => 32768,
'expectedHex' => '8000',
],
[
'clockSeq' => 4096,
'expectedInt' => 36864,
'expectedHex' => '9000',
],
[
'clockSeq' => 8192,
'expectedInt' => 40960,
'expectedHex' => 'a000',
],
[
'clockSeq' => 12288,
'expectedInt' => 45056,
'expectedHex' => 'b000',
],
[
'clockSeq' => 4095,
'expectedInt' => 36863,
'expectedHex' => '8fff',
],
[
'clockSeq' => 8191,
'expectedInt' => 40959,
'expectedHex' => '9fff',
],
[
'clockSeq' => 12287,
'expectedInt' => 45055,
'expectedHex' => 'afff',
],
[
'clockSeq' => 16383,
'expectedInt' => 49151,
'expectedHex' => 'bfff',
],
[
'clockSeq' => 16384,
'expectedInt' => 32768,
'expectedHex' => '8000',
],
[
'clockSeq' => 20480,
'expectedInt' => 36864,
'expectedHex' => '9000',
],
[
'clockSeq' => 24576,
'expectedInt' => 40960,
'expectedHex' => 'a000',
],
[
'clockSeq' => 28672,
'expectedInt' => 45056,
'expectedHex' => 'b000',
],
[
'clockSeq' => 32768,
'expectedInt' => 32768,
'expectedHex' => '8000',
],
[
'clockSeq' => 36864,
'expectedInt' => 36864,
'expectedHex' => '9000',
],
[
'clockSeq' => 40960,
'expectedInt' => 40960,
'expectedHex' => 'a000',
],
[
'clockSeq' => 45056,
'expectedInt' => 45056,
'expectedHex' => 'b000',
],
[
'clockSeq' => 36863,
'expectedInt' => 36863,
'expectedHex' => '8fff',
],
[
'clockSeq' => 40959,
'expectedInt' => 40959,
'expectedHex' => '9fff',
],
[
'clockSeq' => 45055,
'expectedInt' => 45055,
'expectedHex' => 'afff',
],
[
'clockSeq' => 49151,
'expectedInt' => 49151,
'expectedHex' => 'bfff',
],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/bootstrap.php | tests/bootstrap.php | <?php
/**
* Test bootstrap
*
* @codingStandardsIgnoreFile
*/
// Ensure floating-point precision is set to 14 (the default) for tests.
ini_set('precision', '14');
require_once __DIR__ . '/../vendor/autoload.php';
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Builder/DefaultUuidBuilderTest.php | tests/Builder/DefaultUuidBuilderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Builder;
use Mockery;
use Ramsey\Uuid\Builder\DefaultUuidBuilder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Uuid;
use function hex2bin;
use function implode;
class DefaultUuidBuilderTest extends TestCase
{
public function testBuildCreatesUuid(): void
{
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$builder = new DefaultUuidBuilder($numberConverter, $timeConverter);
$fields = [
'time_low' => '754cd475',
'time_mid' => '7e58',
'time_hi_and_version' => '4411',
'clock_seq_hi_and_reserved' => '93',
'clock_seq_low' => '22',
'node' => 'be0725c8ce01',
];
$bytes = (string) hex2bin(implode('', $fields));
$result = $builder->build($codec, $bytes);
$this->assertInstanceOf(Uuid::class, $result);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Builder/FallbackBuilderTest.php | tests/Builder/FallbackBuilderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Builder;
use Mockery;
use Ramsey\Uuid\Builder\FallbackBuilder;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\Time\PhpTimeConverter;
use Ramsey\Uuid\Exception\BuilderNotFoundException;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\Guid\GuidBuilder;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Nonstandard\UuidBuilder as NonstandardUuidBuilder;
use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Rfc4122\UuidV2;
use Ramsey\Uuid\Rfc4122\UuidV6;
use Ramsey\Uuid\Test\TestCase;
class FallbackBuilderTest extends TestCase
{
public function testBuildThrowsExceptionAfterAllConfiguredBuildersHaveErrored(): void
{
$codec = Mockery::mock(CodecInterface::class);
$bytes = 'foobar';
$builder1 = Mockery::mock(UuidBuilderInterface::class);
$builder1
->shouldReceive('build')
->once()
->with($codec, $bytes)
->andThrow(UnableToBuildUuidException::class);
$builder2 = Mockery::mock(UuidBuilderInterface::class);
$builder2
->shouldReceive('build')
->once()
->with($codec, $bytes)
->andThrow(UnableToBuildUuidException::class);
$builder3 = Mockery::mock(UuidBuilderInterface::class);
$builder3
->shouldReceive('build')
->once()
->with($codec, $bytes)
->andThrow(UnableToBuildUuidException::class);
$fallbackBuilder = new FallbackBuilder([$builder1, $builder2, $builder3]);
$this->expectException(BuilderNotFoundException::class);
$this->expectExceptionMessage(
'Could not find a suitable builder for the provided codec and fields'
);
$fallbackBuilder->build($codec, $bytes);
}
/**
* @dataProvider provideBytes
*/
public function testSerializationOfBuilderCollection(string $bytes): void
{
$calculator = new BrickMathCalculator();
$genericNumberConverter = new GenericNumberConverter($calculator);
$genericTimeConverter = new GenericTimeConverter($calculator);
$phpTimeConverter = new PhpTimeConverter($calculator, $genericTimeConverter);
// Use the GenericTimeConverter.
$guidBuilder = new GuidBuilder($genericNumberConverter, $genericTimeConverter);
$rfc4122Builder = new Rfc4122UuidBuilder($genericNumberConverter, $genericTimeConverter);
$nonstandardBuilder = new NonstandardUuidBuilder($genericNumberConverter, $genericTimeConverter);
// Use the PhpTimeConverter.
$guidBuilder2 = new GuidBuilder($genericNumberConverter, $phpTimeConverter);
$rfc4122Builder2 = new Rfc4122UuidBuilder($genericNumberConverter, $phpTimeConverter);
$nonstandardBuilder2 = new NonstandardUuidBuilder($genericNumberConverter, $phpTimeConverter);
/** @var list<UuidBuilderInterface> $unserializedBuilderCollection */
$unserializedBuilderCollection = unserialize(serialize([
$guidBuilder,
$guidBuilder2,
$rfc4122Builder,
$rfc4122Builder2,
$nonstandardBuilder,
$nonstandardBuilder2,
]));
foreach ($unserializedBuilderCollection as $builder) {
$codec = new StringCodec($builder);
$this->assertInstanceOf(UuidBuilderInterface::class, $builder);
try {
$uuid = $builder->build($codec, $bytes);
if (($uuid instanceof UuidV1) || ($uuid instanceof UuidV2) || ($uuid instanceof UuidV6)) {
$this->assertNotEmpty($uuid->getDateTime()->format('r'));
}
} catch (UnableToBuildUuidException $exception) {
switch ($exception->getMessage()) {
case 'The byte string received does not contain a valid version':
case 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) variant':
case 'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) '
. 'or Microsoft Corporation variants':
// This is expected; ignoring.
break;
default:
throw $exception;
}
}
}
}
/**
* @return array<array{bytes: string}>
*/
public function provideBytes(): array
{
return [
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1110b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1111b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1112b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1113b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1114b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1115b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1116b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e1117b210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e111eb210800200c9a66'),
],
[
// GUID bytes
'bytes' => (string) hex2bin('b08c6fff7dc5e111fb210800200c9a66'),
],
[
// Version 1 bytes
'bytes' => (string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66'),
],
[
// Version 2 bytes
'bytes' => (string) hex2bin('000001f55cde21ea84000242ac130003'),
],
[
// Version 3 bytes
'bytes' => (string) hex2bin('ff6f8cb0c57d31e1bb210800200c9a66'),
],
[
// Version 4 bytes
'bytes' => (string) hex2bin('ff6f8cb0c57d41e1ab210800200c9a66'),
],
[
// Version 5 bytes
'bytes' => (string) hex2bin('ff6f8cb0c57d51e18b210800200c9a66'),
],
[
// Version 6 bytes
'bytes' => (string) hex2bin('ff6f8cb0c57d61e18b210800200c9a66'),
],
[
// NIL bytes
'bytes' => (string) hex2bin('00000000000000000000000000000000'),
],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Type/HexadecimalTest.php | tests/Type/HexadecimalTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Type;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use function json_encode;
use function serialize;
use function sprintf;
use function unserialize;
class HexadecimalTest extends TestCase
{
/**
* @dataProvider provideHex
*/
public function testHexadecimalType(string $value, string $expected): void
{
$hexadecimal = new Hexadecimal($value);
$this->assertSame($expected, $hexadecimal->toString());
$this->assertSame($expected, (string) $hexadecimal);
}
/**
* @return array<array{value: string, expected: string}>
*/
public function provideHex(): array
{
return [
[
'value' => '0xFFFF',
'expected' => 'ffff',
],
[
'value' => '0123456789abcdef',
'expected' => '0123456789abcdef',
],
[
'value' => 'ABCDEF',
'expected' => 'abcdef',
],
];
}
/**
* @dataProvider provideHexBadValues
*/
public function testHexadecimalTypeThrowsExceptionForBadValues(string $value): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a hexadecimal number'
);
new Hexadecimal($value);
}
/**
* @return array<array{0: string}>
*/
public function provideHexBadValues(): array
{
return [
['-123456.789'],
['123456.789'],
['foobar'],
['0xfoobar'],
];
}
/**
* @dataProvider provideHex
*/
public function testSerializeUnserializeHexadecimal(string $value, string $expected): void
{
$hexadecimal = new Hexadecimal($value);
$serializedHexadecimal = serialize($hexadecimal);
/** @var Hexadecimal $unserializedHexadecimal */
$unserializedHexadecimal = unserialize($serializedHexadecimal);
$this->assertSame($expected, $unserializedHexadecimal->toString());
}
/**
* @dataProvider provideHex
*/
public function testJsonSerialize(string $value, string $expected): void
{
$hexadecimal = new Hexadecimal($value);
$expectedJson = sprintf('"%s"', $expected);
$this->assertSame($expectedJson, json_encode($hexadecimal));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Type/DecimalTest.php | tests/Type/DecimalTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Type;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Decimal;
use function json_encode;
use function serialize;
use function sprintf;
use function unserialize;
class DecimalTest extends TestCase
{
/**
* @param int|float|string|Decimal $value
*
* @dataProvider provideDecimal
*/
public function testDecimalValueType($value, string $expected, bool $expectedIsNegative): void
{
$decimal = new Decimal($value);
$this->assertSame($expected, $decimal->toString());
$this->assertSame($expected, (string) $decimal);
$this->assertSame($expectedIsNegative, $decimal->isNegative());
}
/**
* @return array<array{value: int|float|string|Decimal, expected: string, expectedIsNegative: bool}>
*/
public function provideDecimal(): array
{
return [
[
'value' => '-11386878954224802805705605120',
'expected' => '-11386878954224802805705605120',
'expectedIsNegative' => true,
],
[
'value' => '-9223372036854775808',
'expected' => '-9223372036854775808',
'expectedIsNegative' => true,
],
[
'value' => -99986838650880,
'expected' => '-99986838650880',
'expectedIsNegative' => true,
],
[
'value' => -4294967296,
'expected' => '-4294967296',
'expectedIsNegative' => true,
],
[
'value' => -2147483649,
'expected' => '-2147483649',
'expectedIsNegative' => true,
],
[
'value' => -123456.0,
'expected' => '-123456',
'expectedIsNegative' => true,
],
[
'value' => -1.00000000000001,
'expected' => '-1',
'expectedIsNegative' => true,
],
[
'value' => -1,
'expected' => '-1',
'expectedIsNegative' => true,
],
[
'value' => '-1',
'expected' => '-1',
'expectedIsNegative' => true,
],
[
'value' => 0,
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => -0,
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '-0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '+0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => 1,
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => '1',
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => '+1',
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => 1.00000000000001,
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => 123456.0,
'expected' => '123456',
'expectedIsNegative' => false,
],
[
'value' => 2147483648,
'expected' => '2147483648',
'expectedIsNegative' => false,
],
[
'value' => 4294967294,
'expected' => '4294967294',
'expectedIsNegative' => false,
],
[
'value' => 99965363767850,
'expected' => '99965363767850',
'expectedIsNegative' => false,
],
[
'value' => '9223372036854775808',
'expected' => '9223372036854775808',
'expectedIsNegative' => false,
],
[
'value' => '11386878954224802805705605120',
'expected' => '11386878954224802805705605120',
'expectedIsNegative' => false,
],
[
'value' => -9223372036854775809,
'expected' => '-9.2233720368548E+18',
'expectedIsNegative' => true,
],
[
'value' => 9223372036854775808,
'expected' => '9.2233720368548E+18',
'expectedIsNegative' => false,
],
[
'value' => -123456.789,
'expected' => '-123456.789',
'expectedIsNegative' => true,
],
[
'value' => -1.0000000000001,
'expected' => '-1.0000000000001',
'expectedIsNegative' => true,
],
[
'value' => -0.5,
'expected' => '-0.5',
'expectedIsNegative' => true,
],
[
'value' => 0.5,
'expected' => '0.5',
'expectedIsNegative' => false,
],
[
'value' => 1.0000000000001,
'expected' => '1.0000000000001',
'expectedIsNegative' => false,
],
[
'value' => 123456.789,
'expected' => '123456.789',
'expectedIsNegative' => false,
],
[
'value' => '-0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '+0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => -0.00000000,
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => 0.00000000,
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => -0.0001,
'expected' => '-0.0001',
'expectedIsNegative' => true,
],
[
'value' => 0.0001,
'expected' => '0.0001',
'expectedIsNegative' => false,
],
[
'value' => -0.00001,
'expected' => '-1.0E-5',
'expectedIsNegative' => true,
],
[
'value' => 0.00001,
'expected' => '1.0E-5',
'expectedIsNegative' => false,
],
[
'value' => '+1234.56',
'expected' => '1234.56',
'expectedIsNegative' => false,
],
];
}
/**
* @param int|float|string $value
*
* @dataProvider provideDecimalBadValues
*/
public function testDecimalTypeThrowsExceptionForBadValues($value): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed decimal or a string containing only '
. 'digits 0-9 and, optionally, a decimal point or sign (+ or -)'
);
new Decimal($value);
}
/**
* @return array<array{0: int|float|string}>
*/
public function provideDecimalBadValues(): array
{
return [
['123abc'],
['abc123'],
['foobar'],
['123.456a'],
['+abcd'],
['-0012.a'],
];
}
/**
* @param float|int|string|Decimal $value
*
* @dataProvider provideDecimal
*/
public function testSerializeUnserializeDecimal($value, string $expected): void
{
$decimal = new Decimal($value);
$serializedDecimal = serialize($decimal);
/** @var Decimal $unserializedDecimal */
$unserializedDecimal = unserialize($serializedDecimal);
$this->assertSame($expected, $unserializedDecimal->toString());
}
/**
* @param float|int|string|Decimal $value
*
* @dataProvider provideDecimal
*/
public function testJsonSerialize($value, string $expected): void
{
$decimal = new Decimal($value);
$expectedJson = sprintf('"%s"', $expected);
$this->assertSame($expectedJson, json_encode($decimal));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Type/IntegerTest.php | tests/Type/IntegerTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Type;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use function json_encode;
use function serialize;
use function sprintf;
use function unserialize;
class IntegerTest extends TestCase
{
/**
* @param int|float|string|IntegerObject $value
*
* @dataProvider provideInteger
*/
public function testIntegerType($value, string $expected, bool $expectedIsNegative): void
{
$integer = new IntegerObject($value);
$this->assertSame($expected, $integer->toString());
$this->assertSame($expected, (string) $integer);
$this->assertSame($expectedIsNegative, $integer->isNegative());
}
/**
* @return array<array{value: int|float|string|IntegerObject, expected: string, expectedIsNegative: bool}>
*/
public function provideInteger(): array
{
return [
[
'value' => '-11386878954224802805705605120',
'expected' => '-11386878954224802805705605120',
'expectedIsNegative' => true,
],
[
'value' => '-9223372036854775808',
'expected' => '-9223372036854775808',
'expectedIsNegative' => true,
],
[
'value' => -99986838650880,
'expected' => '-99986838650880',
'expectedIsNegative' => true,
],
[
'value' => -4294967296,
'expected' => '-4294967296',
'expectedIsNegative' => true,
],
[
'value' => -2147483649,
'expected' => '-2147483649',
'expectedIsNegative' => true,
],
[
'value' => -123456.0,
'expected' => '-123456',
'expectedIsNegative' => true,
],
[
'value' => -1.00000000000001,
'expected' => '-1',
'expectedIsNegative' => true,
],
[
'value' => -1,
'expected' => '-1',
'expectedIsNegative' => true,
],
[
'value' => '-1',
'expected' => '-1',
'expectedIsNegative' => true,
],
[
'value' => 0,
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => -0,
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '-0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => '+0',
'expected' => '0',
'expectedIsNegative' => false,
],
[
'value' => 1,
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => '1',
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => '+1',
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => 1.00000000000001,
'expected' => '1',
'expectedIsNegative' => false,
],
[
'value' => 123456.0,
'expected' => '123456',
'expectedIsNegative' => false,
],
[
'value' => 2147483648,
'expected' => '2147483648',
'expectedIsNegative' => false,
],
[
'value' => 4294967294,
'expected' => '4294967294',
'expectedIsNegative' => false,
],
[
'value' => 99965363767850,
'expected' => '99965363767850',
'expectedIsNegative' => false,
],
[
'value' => '9223372036854775808',
'expected' => '9223372036854775808',
'expectedIsNegative' => false,
],
[
'value' => '11386878954224802805705605120',
'expected' => '11386878954224802805705605120',
'expectedIsNegative' => false,
],
];
}
/**
* @param int|float|string $value
*
* @dataProvider provideIntegerBadValues
*/
public function testIntegerTypeThrowsExceptionForBadValues($value): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed integer or a string containing only '
. 'digits 0-9 and, optionally, a sign (+ or -)'
);
new IntegerObject($value);
}
/**
* @return array<array{0: int|float|string}>
*/
public function provideIntegerBadValues(): array
{
return [
[-9223372036854775809], // String value is "-9.2233720368548E+18"
[-123456.789],
[-1.0000000000001],
[-0.5],
[0.5],
[1.0000000000001],
[123456.789],
[9223372036854775808], // String value is "9.2233720368548E+18"
['123abc'],
['abc123'],
['foobar'],
];
}
/**
* @param int|float|string|IntegerObject $value
*
* @dataProvider provideInteger
*/
public function testSerializeUnserializeInteger($value, string $expected): void
{
$integer = new IntegerObject($value);
$serializedInteger = serialize($integer);
/** @var IntegerObject $unserializedInteger */
$unserializedInteger = unserialize($serializedInteger);
$this->assertSame($expected, $unserializedInteger->toString());
}
/**
* @param int|float|string|IntegerObject $value
*
* @dataProvider provideInteger
*/
public function testJsonSerialize($value, string $expected): void
{
$integer = new IntegerObject($value);
$expectedJson = sprintf('"%s"', $expected);
$this->assertSame($expectedJson, json_encode($integer));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Type/TimeTest.php | tests/Type/TimeTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Type;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
use function json_encode;
use function serialize;
use function unserialize;
class TimeTest extends TestCase
{
/**
* @param int|float|string|IntegerObject $seconds
* @param int|float|string|IntegerObject|null $microseconds
*
* @dataProvider provideTimeValues
*/
public function testTime($seconds, $microseconds): void
{
$params = [$seconds];
$timeString = (string) $seconds;
if ($microseconds !== null) {
$params[] = $microseconds;
$timeString .= sprintf('.%06s', (string) $microseconds);
} else {
$timeString .= '.000000';
}
$time = new Time(...$params);
$this->assertSame((string) $seconds, $time->getSeconds()->toString());
$this->assertSame(
(string) $microseconds ?: '0',
$time->getMicroseconds()->toString()
);
$this->assertSame($timeString, (string) $time);
}
/**
* @return array<array{seconds: int|float|string|IntegerObject, microseconds: int|float|string|IntegerObject|null}>
*/
public function provideTimeValues(): array
{
return [
[
'seconds' => 103072857659,
'microseconds' => null,
],
[
'seconds' => -12219292800,
'microseconds' => 1234,
],
];
}
/**
* @param int|float|string|IntegerObject $seconds
* @param int|float|string|IntegerObject|null $microseconds
*
* @dataProvider provideTimeValues
*/
public function testSerializeUnserializeTime($seconds, $microseconds): void
{
$params = [$seconds];
if ($microseconds !== null) {
$params[] = $microseconds;
}
$time = new Time(...$params);
$serializedTime = serialize($time);
/** @var Time $unserializedTime */
$unserializedTime = unserialize($serializedTime);
$this->assertSame((string) $seconds, $unserializedTime->getSeconds()->toString());
$this->assertSame(
(string) $microseconds ?: '0',
$unserializedTime->getMicroseconds()->toString()
);
}
public function testUnserializeOfInvalidValueException(): void
{
$invalidSerialization = 'C:21:"Ramsey\\Uuid\\Type\\Time":13:{{"foo":"bar"}}';
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage('Attempted to unserialize an invalid value');
unserialize($invalidSerialization);
}
/**
* @param int|float|string|IntegerObject $seconds
* @param int|float|string|IntegerObject|null $microseconds
*
* @dataProvider provideTimeValues
*/
public function testJsonSerialize($seconds, $microseconds): void
{
$time = [
'seconds' => (string) $seconds,
'microseconds' => (string) $microseconds ?: '0',
];
$expectedJson = json_encode($time);
$params = [$seconds];
if ($microseconds !== null) {
$params[] = $microseconds;
}
$time = new Time(...$params);
$this->assertSame($expectedJson, json_encode($time));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Guid/FieldsTest.php | tests/Guid/FieldsTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Guid;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Guid\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use function hex2bin;
use function serialize;
use function unserialize;
class FieldsTest extends TestCase
{
public function testConstructorThrowsExceptionIfNotSixteenByteString(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string must be 16 bytes long; received 6 bytes'
);
new Fields('foobar');
}
/**
* @param non-empty-string $guid
*
* @dataProvider nonRfc4122GuidVariantProvider
*/
public function testConstructorThrowsExceptionIfNotRfc4122Variant(string $guid): void
{
$bytes = (string) hex2bin($guid);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) or '
. 'Microsoft Corporation variants'
);
new Fields($bytes);
}
/**
* These values are already in GUID byte order, for easy testing.
*
* @return array<array{0: non-empty-string}>
*/
public function nonRfc4122GuidVariantProvider(): array
{
// In string representation, the following IDs would begin as:
// ff6f8cb0-c57d-11e1-...
return [
['b08c6fff7dc5e1110b210800200c9a66'],
['b08c6fff7dc5e1111b210800200c9a66'],
['b08c6fff7dc5e1112b210800200c9a66'],
['b08c6fff7dc5e1113b210800200c9a66'],
['b08c6fff7dc5e1114b210800200c9a66'],
['b08c6fff7dc5e1115b210800200c9a66'],
['b08c6fff7dc5e1116b210800200c9a66'],
['b08c6fff7dc5e1117b210800200c9a66'],
['b08c6fff7dc5e111eb210800200c9a66'],
['b08c6fff7dc5e111fb210800200c9a66'],
];
}
/**
* @param non-empty-string $guid
*
* @dataProvider invalidVersionProvider
*/
public function testConstructorThrowsExceptionIfInvalidVersion(string $guid): void
{
$bytes = (string) hex2bin($guid);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string received does not contain a valid version'
);
new Fields($bytes);
}
/**
* @return array<array{0: non-empty-string}>
*/
public function invalidVersionProvider(): array
{
// The following UUIDs are in GUID byte order. Dashes have
// been removed in the tests to distinguish these from string
// representations, which are never in GUID byte order.
return [
['b08c6fff7dc5e1018b210800200c9a66'],
['b08c6fff7dc5e191bb210800200c9a66'],
['b08c6fff7dc5e1a19b210800200c9a66'],
['b08c6fff7dc5e1b1ab210800200c9a66'],
['b08c6fff7dc5e1c1ab210800200c9a66'],
['b08c6fff7dc5e1d1ab210800200c9a66'],
['b08c6fff7dc5e1e1ab210800200c9a66'],
['b08c6fff7dc5e1f1ab210800200c9a66'],
];
}
/**
* @param non-empty-string $bytes
* @param non-empty-string $methodName
* @param non-empty-string | bool | int | null $expectedValue
*
* @dataProvider fieldGetterMethodProvider
*/
public function testFieldGetterMethods(
string $bytes,
string $methodName,
bool | int | string | null $expectedValue,
): void {
$bytes = (string) hex2bin($bytes);
$fields = new Fields($bytes);
$result = $fields->$methodName();
if ($result instanceof Hexadecimal) {
$this->assertSame($expectedValue, $result->toString());
} else {
$this->assertSame($expectedValue, $result);
}
}
/**
* @return array<array{0: non-empty-string, 1: non-empty-string, 2: non-empty-string | int | bool | null}>
*/
public function fieldGetterMethodProvider(): array
{
// The following UUIDs are in GUID byte order. Dashes have
// been removed in the tests to distinguish these from string
// representations, which are never in GUID byte order.
return [
// For ff6f8cb0-c57d-11e1-cb21-0800200c9a66
['b08c6fff7dc5e111cb210800200c9a66', 'getClockSeq', '0b21'],
['b08c6fff7dc5e111cb210800200c9a66', 'getClockSeqHiAndReserved', 'cb'],
['b08c6fff7dc5e111cb210800200c9a66', 'getClockSeqLow', '21'],
['b08c6fff7dc5e111cb210800200c9a66', 'getNode', '0800200c9a66'],
['b08c6fff7dc5e111cb210800200c9a66', 'getTimeHiAndVersion', '11e1'],
['b08c6fff7dc5e111cb210800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['b08c6fff7dc5e111cb210800200c9a66', 'getTimeMid', 'c57d'],
['b08c6fff7dc5e111cb210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['b08c6fff7dc5e111cb210800200c9a66', 'getVariant', 6],
['b08c6fff7dc5e111cb210800200c9a66', 'getVersion', 1],
['b08c6fff7dc5e111cb210800200c9a66', 'isNil', false],
['b08c6fff7dc5e111cb210800200c9a66', 'isMax', false],
// For ff6f8cb0-c57d-41e1-db21-0800200c9a66
['b08c6fff7dc5e141db210800200c9a66', 'getClockSeq', '1b21'],
['b08c6fff7dc5e141db210800200c9a66', 'getClockSeqHiAndReserved', 'db'],
['b08c6fff7dc5e141db210800200c9a66', 'getClockSeqLow', '21'],
['b08c6fff7dc5e141db210800200c9a66', 'getNode', '0800200c9a66'],
['b08c6fff7dc5e141db210800200c9a66', 'getTimeHiAndVersion', '41e1'],
['b08c6fff7dc5e141db210800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['b08c6fff7dc5e141db210800200c9a66', 'getTimeMid', 'c57d'],
['b08c6fff7dc5e141db210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['b08c6fff7dc5e141db210800200c9a66', 'getVariant', 6],
['b08c6fff7dc5e141db210800200c9a66', 'getVersion', 4],
['b08c6fff7dc5e141db210800200c9a66', 'isNil', false],
['b08c6fff7dc5e141db210800200c9a66', 'isMax', false],
// For ff6f8cb0-c57d-31e1-8b21-0800200c9a66
['b08c6fff7dc5e1318b210800200c9a66', 'getClockSeq', '0b21'],
['b08c6fff7dc5e1318b210800200c9a66', 'getClockSeqHiAndReserved', '8b'],
['b08c6fff7dc5e1318b210800200c9a66', 'getClockSeqLow', '21'],
['b08c6fff7dc5e1318b210800200c9a66', 'getNode', '0800200c9a66'],
['b08c6fff7dc5e1318b210800200c9a66', 'getTimeHiAndVersion', '31e1'],
['b08c6fff7dc5e1318b210800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['b08c6fff7dc5e1318b210800200c9a66', 'getTimeMid', 'c57d'],
['b08c6fff7dc5e1318b210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['b08c6fff7dc5e1318b210800200c9a66', 'getVariant', 2],
['b08c6fff7dc5e1318b210800200c9a66', 'getVersion', 3],
['b08c6fff7dc5e1318b210800200c9a66', 'isNil', false],
['b08c6fff7dc5e1318b210800200c9a66', 'isMax', false],
// For ff6f8cb0-c57d-51e1-9b21-0800200c9a66
['b08c6fff7dc5e1519b210800200c9a66', 'getClockSeq', '1b21'],
['b08c6fff7dc5e1519b210800200c9a66', 'getClockSeqHiAndReserved', '9b'],
['b08c6fff7dc5e1519b210800200c9a66', 'getClockSeqLow', '21'],
['b08c6fff7dc5e1519b210800200c9a66', 'getNode', '0800200c9a66'],
['b08c6fff7dc5e1519b210800200c9a66', 'getTimeHiAndVersion', '51e1'],
['b08c6fff7dc5e1519b210800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['b08c6fff7dc5e1519b210800200c9a66', 'getTimeMid', 'c57d'],
['b08c6fff7dc5e1519b210800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['b08c6fff7dc5e1519b210800200c9a66', 'getVariant', 2],
['b08c6fff7dc5e1519b210800200c9a66', 'getVersion', 5],
['b08c6fff7dc5e1519b210800200c9a66', 'isNil', false],
['b08c6fff7dc5e1519b210800200c9a66', 'isMax', false],
// For 00000000-0000-0000-0000-000000000000
['00000000000000000000000000000000', 'getClockSeq', '0000'],
['00000000000000000000000000000000', 'getClockSeqHiAndReserved', '00'],
['00000000000000000000000000000000', 'getClockSeqLow', '00'],
['00000000000000000000000000000000', 'getNode', '000000000000'],
['00000000000000000000000000000000', 'getTimeHiAndVersion', '0000'],
['00000000000000000000000000000000', 'getTimeLow', '00000000'],
['00000000000000000000000000000000', 'getTimeMid', '0000'],
['00000000000000000000000000000000', 'getTimestamp', '000000000000000'],
['00000000000000000000000000000000', 'getVariant', 0],
['00000000000000000000000000000000', 'getVersion', null],
['00000000000000000000000000000000', 'isNil', true],
['00000000000000000000000000000000', 'isMax', false],
// For ffffffff-ffff-ffff-ffff-ffffffffffff
['ffffffffffffffffffffffffffffffff', 'getClockSeq', 'ffff'],
['ffffffffffffffffffffffffffffffff', 'getClockSeqHiAndReserved', 'ff'],
['ffffffffffffffffffffffffffffffff', 'getClockSeqLow', 'ff'],
['ffffffffffffffffffffffffffffffff', 'getNode', 'ffffffffffff'],
['ffffffffffffffffffffffffffffffff', 'getTimeHiAndVersion', 'ffff'],
['ffffffffffffffffffffffffffffffff', 'getTimeLow', 'ffffffff'],
['ffffffffffffffffffffffffffffffff', 'getTimeMid', 'ffff'],
['ffffffffffffffffffffffffffffffff', 'getTimestamp', 'fffffffffffffff'],
['ffffffffffffffffffffffffffffffff', 'getVariant', 7],
['ffffffffffffffffffffffffffffffff', 'getVersion', null],
['ffffffffffffffffffffffffffffffff', 'isNil', false],
['ffffffffffffffffffffffffffffffff', 'isMax', true],
];
}
public function testSerializingFields(): void
{
$bytes = (string) hex2bin('b08c6fff7dc5e111cb210800200c9a66');
$fields = new Fields($bytes);
$serializedFields = serialize($fields);
/** @var Fields $unserializedFields */
$unserializedFields = unserialize($serializedFields);
$this->assertSame($fields->getBytes(), $unserializedFields->getBytes());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Guid/GuidBuilderTest.php | tests/Guid/GuidBuilderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Guid;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\Guid\GuidBuilder;
use Ramsey\Uuid\Test\TestCase;
use RuntimeException;
class GuidBuilderTest extends TestCase
{
public function testBuildThrowsException(): void
{
$codec = Mockery::mock(CodecInterface::class);
$builder = Mockery::mock(GuidBuilder::class);
$builder->shouldAllowMockingProtectedMethods();
$builder->shouldReceive('buildFields')->andThrow(
RuntimeException::class,
'exception thrown'
);
$builder->shouldReceive('build')->passthru();
$this->expectException(UnableToBuildUuidException::class);
$this->expectExceptionMessage('exception thrown');
$builder->build($codec, 'foobar');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/benchmark/GuidConversionBench.php | tests/benchmark/GuidConversionBench.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Benchmark;
use Ramsey\Uuid\FeatureSet;
use Ramsey\Uuid\Guid\Guid;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\UuidInterface;
final class GuidConversionBench
{
private const UUID_BYTES = [
"\x1e\x94\x42\x33\x98\x10\x41\x38\x96\x22\x56\xe1\xf9\x0c\x56\xed",
];
private UuidInterface $uuid;
public function __construct()
{
$factory = new UuidFactory(new FeatureSet(useGuids: true));
$this->uuid = $factory->fromBytes(self::UUID_BYTES[0]);
assert($this->uuid instanceof Guid);
}
public function benchStringConversionOfGuid(): void
{
$this->uuid->toString();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/benchmark/UuidStringConversionBench.php | tests/benchmark/UuidStringConversionBench.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Benchmark;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use function array_map;
final class UuidStringConversionBench
{
private const TINY_UUID = '00000000-0000-0000-0000-000000000001';
private const HUGE_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
private const UUIDS_TO_BE_SHORTENED = [
'0ae0cac5-2a40-465c-99ed-3d331b7cf72a',
'5759b9ce-07b5-4e89-b33a-f864317a2951',
'20c8664e-81a8-498d-9e98-444973ef3122',
'16fcbcf3-bb47-4227-90bd-3485d60510c3',
'fa83ae94-38e0-4903-bc6a-0a3eca6e9ef5',
'51c9e011-0429-4d77-a753-702bd67dcd84',
'1bd8857a-d6d7-4bd6-8734-b3dfedbcda7b',
'7aa38b71-37c3-4561-9b2e-ca227f1c9c55',
'e6b8854c-435c-4bb1-b6ad-1800b5d3e6bb',
'4e2b0031-8b09-46e2-8244-3814c46a2f53',
'bedd0850-da1a-4808-95c4-25fef0abbaa7',
'516b9052-d6fb-4828-bfc1-dffdef2d56d2',
'5d60a7e7-9139-4779-9f28-e6316b9fe3b7',
'65aa3d74-c1fb-4bdd-9a00-ce88a5270c57',
'27c2e339-74ed-49a7-a3c4-1a0172e9f945',
'e89b7727-4847-41ab-98d7-4148216eea8c',
'd79efaf3-b5dc-43a0-b3a5-c492155a7e0d',
'ee9ee6e7-5b7d-4e18-ab88-ce03d569305f',
'fe90c911-c13b-4103-bf33-16757aa87ff5',
'4d7ff67a-0074-4195-95d7-cf8b84eba079',
'abe5d378-d021-4905-93f4-0e76a7848365',
'19d21907-d121-4d85-8a34-a65d04ce8977',
'c421b8ad-33a4-42aa-b0cc-8f5f94b2cff7',
'f3dbbe55-3c80-453e-ab39-a6fe5001a7fc',
'f48d3eb2-6060-458f-809f-b5e887f9a17f',
'd189e406-de29-4889-8470-7bfa0d020c0c',
'71627018-9f21-4034-aafe-4c8b17151217',
'0c6a9278-0963-4460-9cae-6dc6f5420f4f',
'c833ac35-cce0-4315-8df3-3ed76656a548',
'78e94126-1d0a-472a-9b99-37840784318f',
'6e684707-ce4b-42df-8a77-71e57b54b581',
'811df139-e7a3-4cd8-b778-c81494d239ee',
'c263c5d8-c166-4599-9219-3e975e506f45',
'b31e7c5d-95ba-41d4-bc29-e6357c96f005',
'16ae2983-7f8f-4eee-9afb-6d4617836a01',
'ecbbfac7-f92a-4b41-996e-3e4724aa0e23',
'2c6b3db9-a5ee-4425-a837-8880a86faaa0',
'3d67a99a-b39a-4295-b7f8-0bf71ead5b2d',
'ca421bb7-ad73-41ea-9648-70073862ad5a',
'5ba156fa-853d-460f-a884-ca8dd3a27314',
'42a4359a-1df2-4086-b454-7477dbb726ff',
'7db9517b-f6ba-4bcf-ae26-6a88a7dbb034',
'bc758bd6-eb50-425b-ada1-07e6bb312032',
'254cf6d0-696d-4ff0-b579-ac3b633f03c0',
'f8f34b37-4c71-4177-bac5-6b99bb1929af',
'b0cc6179-f2b1-4ddf-8fe2-2251c3d935a3',
'333ad834-fa3b-4cf4-b9ba-fdb1c481c497',
'011fc3bc-a97d-4535-8cb0-81766e361e78',
'acf2262b-4ccf-4f1d-b5c1-5e44641884c6',
'6bf661b1-2f85-4277-8dba-6552141e7e42',
'a76df66b-8c50-488f-b4e7-4f4d3c05afff',
'b5c5df47-f939-4536-a340-442bf00bd70d',
'd4914d41-0011-49fb-a1c2-fe69108e4983',
'efd5fa37-b0de-43b0-9fe7-1b7a7a6523f8',
'6048f863-7faa-43f2-8202-4b349ae34810',
'659a0024-fa05-4068-aed0-e61239554b6d',
'6ec80af3-0415-429e-91e9-8491ab5745c0',
'0e6f754c-0533-4336-b4f0-e2e35518efa1',
'47469672-7e55-4316-b5d4-c458e43d2404',
'0c5ad756-a823-4a3f-8449-840fac080f45',
'8f8345da-1dd9-499b-bda5-57100bb305d5',
'4a31d059-e375-4571-9d28-ea0de51740e7',
'ed7fb50c-1b3a-4594-920b-9a461abce57c',
'3d8fe6f6-e603-44c0-b550-3568523c3224',
'809259bc-7912-427a-a975-7298ee5626db',
'ec88d77e-5612-466c-b269-ad146abd70d0',
'bd308a10-8073-45ae-9bfb-9a663ad5dd10',
'83a6a4cc-3079-46d8-9263-8f57af4fd4c7',
'557f0041-7e7f-447c-988c-eafa6e396915',
'6ad0fa1c-7425-41e9-9b74-19c4935750a2',
'a9193e21-e529-43cf-9421-6ed09b59d86e',
'2a09f6e6-4fb2-4da0-97bf-6f32858ba977',
'd66e0940-087f-4e71-8292-fc38e306d9f7',
'0dfc58b3-d591-40be-803d-e17a52e5d262',
'a46c6902-de10-45cc-8dac-600d68860532',
'5200f9dc-b967-4d1e-ab01-51c726c152ba',
'acd8498b-ee8b-4d58-b0ef-c353fb1b5a45',
'36adf355-cccc-406f-a814-6333ec4e31bf',
'd6d64c6f-8388-4de3-9db1-de07f02071b6',
'daf3fde9-41d0-422f-a0e3-8c7a93a77091',
'160f4fac-a229-4169-893e-4e9e6864c098',
'170c4be9-1fe6-4838-8a77-dee364ae9a95',
'2864fed0-868c-4bd1-a3fa-ae3bb3de20f4',
'8ea6639c-36dc-463c-8299-8f9a12b10898',
'626bef95-2f24-47c2-a792-f06e8f13a11e',
'ede75c44-5a1d-484c-942d-87407f27db23',
'966ec42b-0bf7-4923-9672-7a41fee377bc',
'399d7ce6-b28f-4751-ac50-73e31b079f22',
'ab2b4086-e181-4f02-aee1-a94afed40b50',
'3cfc33a6-73f7-49f7-9c01-fbcf84e604d0',
'40cf06c6-74ca-4016-b388-17dc0334770d',
'58f9ecd3-14ab-4100-b32a-cc2622f06c81',
'a5c35e34-5d05-4724-bb6c-613b5d306a18',
'5133ae3e-e38b-47fa-a3dc-965c738be792',
'594acd2f-7100-4b2b-8b8a-6097cb1cec3d',
'08b3da92-6b32-43d8-9fdd-53eaa996d649',
'93dcdc27-ab2c-4828-9074-4876ee7ab257',
'8260a154-23cc-4510-a5df-cc5119f457fb',
'732a6571-9729-4935-92be-1a74b3242636',
'c15f5581-e047-45b7-a36f-dfef4e7ba4bb',
];
/** @var UuidInterface */
private $tinyUuid;
/** @var UuidInterface */
private $hugeUuid;
/** @var UuidInterface */
private $uuid;
/**
* @var non-empty-list<UuidInterface>
*/
private $promiscuousUuids;
/**
* @var non-empty-string
*/
private $tinyUuidBytes;
/**
* @var non-empty-string
*/
private $hugeUuidBytes;
/**
* @var non-empty-string
*/
private $uuidBytes;
/**
* @var non-empty-list<non-empty-string>
*/
private $promiscuousUuidsBytes;
public function __construct()
{
$this->tinyUuid = Uuid::fromString(self::TINY_UUID);
$this->hugeUuid = Uuid::fromString(self::HUGE_UUID);
$this->uuid = Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]);
$this->promiscuousUuids = array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED);
$this->tinyUuidBytes = $this->tinyUuid->getBytes();
$this->hugeUuidBytes = $this->hugeUuid->getBytes();
$this->uuidBytes = $this->uuid->getBytes();
$this->promiscuousUuidsBytes = array_map(static function (UuidInterface $uuid): string {
return $uuid->getBytes();
}, $this->promiscuousUuids);
}
public function benchCreationOfTinyUuidFromString(): void
{
Uuid::fromString(self::TINY_UUID);
}
public function benchCreationOfHugeUuidFromString(): void
{
Uuid::fromString(self::HUGE_UUID);
}
public function benchCreationOfUuidFromString(): void
{
Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]);
}
public function benchCreationOfPromiscuousUuidsFromString(): void
{
array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED);
}
public function benchCreationOfTinyUuidFromBytes(): void
{
Uuid::fromBytes($this->tinyUuidBytes);
}
public function benchCreationOfHugeUuidFromBytes(): void
{
Uuid::fromBytes($this->hugeUuidBytes);
}
public function benchCreationOfUuidFromBytes(): void
{
Uuid::fromBytes($this->uuidBytes);
}
public function benchCreationOfPromiscuousUuidsFromBytes(): void
{
array_map([Uuid::class, 'fromBytes'], $this->promiscuousUuidsBytes);
}
public function benchStringConversionOfTinyUuid(): void
{
$this->tinyUuid->toString();
}
public function benchStringConversionOfHugeUuid(): void
{
$this->hugeUuid->toString();
}
public function benchStringConversionOfUuid(): void
{
$this->uuid->toString();
}
public function benchStringConversionOfPromiscuousUuids(): void
{
array_map(static function (UuidInterface $uuid): string {
return $uuid->toString();
}, $this->promiscuousUuids);
}
public function benchBytesConversionOfTinyUuid(): void
{
$this->tinyUuid->getBytes();
}
public function benchBytesConversionOfHugeUuid(): void
{
$this->hugeUuid->getBytes();
}
public function benchBytesConversionOfUuid(): void
{
$this->uuid->getBytes();
}
public function benchBytesConversionOfPromiscuousUuids(): void
{
array_map(static function (UuidInterface $uuid): string {
return $uuid->getBytes();
}, $this->promiscuousUuids);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/benchmark/NonLazyUuidConversionBench.php | tests/benchmark/NonLazyUuidConversionBench.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Benchmark;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\UuidInterface;
final class NonLazyUuidConversionBench
{
private const UUID_BYTES = [
"\x1e\x94\x42\x33\x98\x10\x41\x38\x96\x22\x56\xe1\xf9\x0c\x56\xed",
];
private UuidInterface $uuid;
public function __construct()
{
$factory = new UuidFactory();
$this->uuid = $factory->fromBytes(self::UUID_BYTES[0]);
}
public function benchStringConversionOfUuid(): void
{
$this->uuid->toString();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/benchmark/UuidSerializationBench.php | tests/benchmark/UuidSerializationBench.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Benchmark;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use function array_map;
use function serialize;
final class UuidSerializationBench
{
private const TINY_UUID = '00000000-0000-0000-0000-000000000001';
private const HUGE_UUID = 'ffffffff-ffff-ffff-ffff-ffffffffffff';
private const UUIDS_TO_BE_SHORTENED = [
'0ae0cac5-2a40-465c-99ed-3d331b7cf72a',
'5759b9ce-07b5-4e89-b33a-f864317a2951',
'20c8664e-81a8-498d-9e98-444973ef3122',
'16fcbcf3-bb47-4227-90bd-3485d60510c3',
'fa83ae94-38e0-4903-bc6a-0a3eca6e9ef5',
'51c9e011-0429-4d77-a753-702bd67dcd84',
'1bd8857a-d6d7-4bd6-8734-b3dfedbcda7b',
'7aa38b71-37c3-4561-9b2e-ca227f1c9c55',
'e6b8854c-435c-4bb1-b6ad-1800b5d3e6bb',
'4e2b0031-8b09-46e2-8244-3814c46a2f53',
'bedd0850-da1a-4808-95c4-25fef0abbaa7',
'516b9052-d6fb-4828-bfc1-dffdef2d56d2',
'5d60a7e7-9139-4779-9f28-e6316b9fe3b7',
'65aa3d74-c1fb-4bdd-9a00-ce88a5270c57',
'27c2e339-74ed-49a7-a3c4-1a0172e9f945',
'e89b7727-4847-41ab-98d7-4148216eea8c',
'd79efaf3-b5dc-43a0-b3a5-c492155a7e0d',
'ee9ee6e7-5b7d-4e18-ab88-ce03d569305f',
'fe90c911-c13b-4103-bf33-16757aa87ff5',
'4d7ff67a-0074-4195-95d7-cf8b84eba079',
'abe5d378-d021-4905-93f4-0e76a7848365',
'19d21907-d121-4d85-8a34-a65d04ce8977',
'c421b8ad-33a4-42aa-b0cc-8f5f94b2cff7',
'f3dbbe55-3c80-453e-ab39-a6fe5001a7fc',
'f48d3eb2-6060-458f-809f-b5e887f9a17f',
'd189e406-de29-4889-8470-7bfa0d020c0c',
'71627018-9f21-4034-aafe-4c8b17151217',
'0c6a9278-0963-4460-9cae-6dc6f5420f4f',
'c833ac35-cce0-4315-8df3-3ed76656a548',
'78e94126-1d0a-472a-9b99-37840784318f',
'6e684707-ce4b-42df-8a77-71e57b54b581',
'811df139-e7a3-4cd8-b778-c81494d239ee',
'c263c5d8-c166-4599-9219-3e975e506f45',
'b31e7c5d-95ba-41d4-bc29-e6357c96f005',
'16ae2983-7f8f-4eee-9afb-6d4617836a01',
'ecbbfac7-f92a-4b41-996e-3e4724aa0e23',
'2c6b3db9-a5ee-4425-a837-8880a86faaa0',
'3d67a99a-b39a-4295-b7f8-0bf71ead5b2d',
'ca421bb7-ad73-41ea-9648-70073862ad5a',
'5ba156fa-853d-460f-a884-ca8dd3a27314',
'42a4359a-1df2-4086-b454-7477dbb726ff',
'7db9517b-f6ba-4bcf-ae26-6a88a7dbb034',
'bc758bd6-eb50-425b-ada1-07e6bb312032',
'254cf6d0-696d-4ff0-b579-ac3b633f03c0',
'f8f34b37-4c71-4177-bac5-6b99bb1929af',
'b0cc6179-f2b1-4ddf-8fe2-2251c3d935a3',
'333ad834-fa3b-4cf4-b9ba-fdb1c481c497',
'011fc3bc-a97d-4535-8cb0-81766e361e78',
'acf2262b-4ccf-4f1d-b5c1-5e44641884c6',
'6bf661b1-2f85-4277-8dba-6552141e7e42',
'a76df66b-8c50-488f-b4e7-4f4d3c05afff',
'b5c5df47-f939-4536-a340-442bf00bd70d',
'd4914d41-0011-49fb-a1c2-fe69108e4983',
'efd5fa37-b0de-43b0-9fe7-1b7a7a6523f8',
'6048f863-7faa-43f2-8202-4b349ae34810',
'659a0024-fa05-4068-aed0-e61239554b6d',
'6ec80af3-0415-429e-91e9-8491ab5745c0',
'0e6f754c-0533-4336-b4f0-e2e35518efa1',
'47469672-7e55-4316-b5d4-c458e43d2404',
'0c5ad756-a823-4a3f-8449-840fac080f45',
'8f8345da-1dd9-499b-bda5-57100bb305d5',
'4a31d059-e375-4571-9d28-ea0de51740e7',
'ed7fb50c-1b3a-4594-920b-9a461abce57c',
'3d8fe6f6-e603-44c0-b550-3568523c3224',
'809259bc-7912-427a-a975-7298ee5626db',
'ec88d77e-5612-466c-b269-ad146abd70d0',
'bd308a10-8073-45ae-9bfb-9a663ad5dd10',
'83a6a4cc-3079-46d8-9263-8f57af4fd4c7',
'557f0041-7e7f-447c-988c-eafa6e396915',
'6ad0fa1c-7425-41e9-9b74-19c4935750a2',
'a9193e21-e529-43cf-9421-6ed09b59d86e',
'2a09f6e6-4fb2-4da0-97bf-6f32858ba977',
'd66e0940-087f-4e71-8292-fc38e306d9f7',
'0dfc58b3-d591-40be-803d-e17a52e5d262',
'a46c6902-de10-45cc-8dac-600d68860532',
'5200f9dc-b967-4d1e-ab01-51c726c152ba',
'acd8498b-ee8b-4d58-b0ef-c353fb1b5a45',
'36adf355-cccc-406f-a814-6333ec4e31bf',
'd6d64c6f-8388-4de3-9db1-de07f02071b6',
'daf3fde9-41d0-422f-a0e3-8c7a93a77091',
'160f4fac-a229-4169-893e-4e9e6864c098',
'170c4be9-1fe6-4838-8a77-dee364ae9a95',
'2864fed0-868c-4bd1-a3fa-ae3bb3de20f4',
'8ea6639c-36dc-463c-8299-8f9a12b10898',
'626bef95-2f24-47c2-a792-f06e8f13a11e',
'ede75c44-5a1d-484c-942d-87407f27db23',
'966ec42b-0bf7-4923-9672-7a41fee377bc',
'399d7ce6-b28f-4751-ac50-73e31b079f22',
'ab2b4086-e181-4f02-aee1-a94afed40b50',
'3cfc33a6-73f7-49f7-9c01-fbcf84e604d0',
'40cf06c6-74ca-4016-b388-17dc0334770d',
'58f9ecd3-14ab-4100-b32a-cc2622f06c81',
'a5c35e34-5d05-4724-bb6c-613b5d306a18',
'5133ae3e-e38b-47fa-a3dc-965c738be792',
'594acd2f-7100-4b2b-8b8a-6097cb1cec3d',
'08b3da92-6b32-43d8-9fdd-53eaa996d649',
'93dcdc27-ab2c-4828-9074-4876ee7ab257',
'8260a154-23cc-4510-a5df-cc5119f457fb',
'732a6571-9729-4935-92be-1a74b3242636',
'c15f5581-e047-45b7-a36f-dfef4e7ba4bb',
];
/** @var UuidInterface */
private $tinyUuid;
/** @var UuidInterface */
private $hugeUuid;
/** @var UuidInterface */
private $uuid;
/**
* @var non-empty-list<UuidInterface>
*/
private $promiscuousUuids;
/** @var string */
private $serializedTinyUuid;
/** @var string */
private $serializedHugeUuid;
/** @var string */
private $serializedUuid;
/**
* @var non-empty-list<string>
*/
private $serializedPromiscuousUuids;
public function __construct()
{
$this->tinyUuid = Uuid::fromString(self::TINY_UUID);
$this->hugeUuid = Uuid::fromString(self::HUGE_UUID);
$this->uuid = Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]);
$this->promiscuousUuids = array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED);
$this->serializedTinyUuid = serialize(Uuid::fromString(self::TINY_UUID));
$this->serializedHugeUuid = serialize(Uuid::fromString(self::HUGE_UUID));
$this->serializedUuid = serialize(Uuid::fromString(self::UUIDS_TO_BE_SHORTENED[0]));
$this->serializedPromiscuousUuids = array_map(
'serialize',
array_map([Uuid::class, 'fromString'], self::UUIDS_TO_BE_SHORTENED)
);
}
public function benchSerializationOfTinyUuid(): void
{
serialize($this->tinyUuid);
}
public function benchSerializationOfHugeUuid(): void
{
serialize($this->hugeUuid);
}
public function benchSerializationOfUuid(): void
{
serialize($this->uuid);
}
public function benchSerializationOfPromiscuousUuids(): void
{
array_map('serialize', $this->promiscuousUuids);
}
public function benchDeSerializationOfTinyUuid(): void
{
unserialize($this->serializedTinyUuid);
}
public function benchDeSerializationOfHugeUuid(): void
{
unserialize($this->serializedHugeUuid);
}
public function benchDeSerializationOfUuid(): void
{
unserialize($this->serializedUuid);
}
public function benchDeSerializationOfPromiscuousUuids(): void
{
array_map('unserialize', $this->serializedPromiscuousUuids);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/benchmark/UuidFieldExtractionBench.php | tests/benchmark/UuidFieldExtractionBench.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Benchmark;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
final class UuidFieldExtractionBench
{
/** @var UuidInterface */
private $uuid;
public function __construct()
{
$this->uuid = Uuid::fromString('0ae0cac5-2a40-465c-99ed-3d331b7cf72a');
}
public function benchGetFields(): void
{
$this->uuid->getFields();
}
public function benchGetFields10Times(): void
{
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
$this->uuid->getFields();
}
public function benchGetHex(): void
{
$this->uuid->getHex();
}
public function benchGetHex10Times(): void
{
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
$this->uuid->getHex();
}
public function benchGetInteger(): void
{
$this->uuid->getInteger();
}
public function benchGetInteger10Times(): void
{
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
$this->uuid->getInteger();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/benchmark/UuidGenerationBench.php | tests/benchmark/UuidGenerationBench.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Benchmark;
use DateTimeImmutable;
use Ramsey\Uuid\Provider\Node\StaticNodeProvider;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerIdentifier;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
final class UuidGenerationBench
{
/** @var Hexadecimal */
private $node;
/** @var int */
private $clockSequence;
/** @var IntegerIdentifier */
private $localIdentifier;
/** @var UuidInterface */
private $namespace;
public function __construct()
{
$this->node = (new StaticNodeProvider(new Hexadecimal('121212121212')))
->getNode();
$this->clockSequence = 16383;
$this->localIdentifier = new IntegerIdentifier(5);
$this->namespace = Uuid::fromString('c485840e-9389-4548-a276-aeecd9730e50');
}
public function benchUuid1GenerationWithoutParameters(): void
{
Uuid::uuid1();
}
public function benchUuid1GenerationWithNode(): void
{
Uuid::uuid1($this->node);
}
public function benchUuid1GenerationWithNodeAndClockSequence(): void
{
Uuid::uuid1($this->node, $this->clockSequence);
}
public function benchUuid2GenerationWithDomainAndLocalIdentifier(): void
{
Uuid::uuid2(Uuid::DCE_DOMAIN_ORG, $this->localIdentifier);
}
public function benchUuid2GenerationWithDomainAndLocalIdentifierAndNode(): void
{
Uuid::uuid2(Uuid::DCE_DOMAIN_ORG, $this->localIdentifier, $this->node);
}
public function benchUuid2GenerationWithDomainAndLocalIdentifierAndNodeAndClockSequence(): void
{
Uuid::uuid2(Uuid::DCE_DOMAIN_ORG, $this->localIdentifier, $this->node, 63);
}
public function benchUuid3Generation(): void
{
Uuid::uuid3($this->namespace, 'name');
}
public function benchUuid4Generation(): void
{
Uuid::uuid4();
}
public function benchUuid5Generation(): void
{
Uuid::uuid5($this->namespace, 'name');
}
public function benchUuid6GenerationWithoutParameters(): void
{
Uuid::uuid6();
}
public function benchUuid6GenerationWithNode(): void
{
Uuid::uuid6($this->node);
}
public function benchUuid6GenerationWithNodeAndClockSequence(): void
{
Uuid::uuid6($this->node, $this->clockSequence);
}
public function benchUuid7Generation(): void
{
Uuid::uuid7();
}
public function benchUuid7GenerationWithDateTime(): void
{
Uuid::uuid7(new DateTimeImmutable('@1663203901.667000'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Math/BrickMathCalculatorTest.php | tests/Math/BrickMathCalculatorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Math;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Math\RoundingMode;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Integer as IntegerObject;
class BrickMathCalculatorTest extends TestCase
{
public function testAdd(): void
{
$int1 = new IntegerObject(5);
$int2 = new IntegerObject(6);
$int3 = new IntegerObject(7);
$calculator = new BrickMathCalculator();
$result = $calculator->add($int1, $int2, $int3);
$this->assertSame('18', $result->toString());
}
public function testSubtract(): void
{
$int1 = new IntegerObject(5);
$int2 = new IntegerObject(6);
$int3 = new IntegerObject(7);
$calculator = new BrickMathCalculator();
$result = $calculator->subtract($int1, $int2, $int3);
$this->assertSame('-8', $result->toString());
}
public function testMultiply(): void
{
$int1 = new IntegerObject(5);
$int2 = new IntegerObject(6);
$int3 = new IntegerObject(7);
$calculator = new BrickMathCalculator();
$result = $calculator->multiply($int1, $int2, $int3);
$this->assertSame('210', $result->toString());
}
public function testDivide(): void
{
$int1 = new IntegerObject(1023);
$int2 = new IntegerObject(6);
$int3 = new IntegerObject(7);
$calculator = new BrickMathCalculator();
$result = $calculator->divide(RoundingMode::HALF_UP, 0, $int1, $int2, $int3);
$this->assertSame('24', $result->toString());
}
public function testFromBase(): void
{
$calculator = new BrickMathCalculator();
$result = $calculator->fromBase('ffffffffffffffffffff', 16);
$this->assertSame('1208925819614629174706175', $result->toString());
}
public function testToBase(): void
{
$intValue = new IntegerObject('1208925819614629174706175');
$calculator = new BrickMathCalculator();
$this->assertSame('ffffffffffffffffffff', $calculator->toBase($intValue, 16));
}
public function testToHexadecimal(): void
{
$intValue = new IntegerObject('1208925819614629174706175');
$calculator = new BrickMathCalculator();
$result = $calculator->toHexadecimal($intValue);
$this->assertSame('ffffffffffffffffffff', $result->toString());
}
public function testFromBaseThrowsException(): void
{
$calculator = new BrickMathCalculator();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('"o" is not a valid character in base 16');
$calculator->fromBase('foobar', 16);
}
public function testToBaseThrowsException(): void
{
$calculator = new BrickMathCalculator();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Base 1024 is out of range [2, 36]');
$calculator->toBase(new IntegerObject(42), 1024);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Nonstandard/FieldsTest.php | tests/Nonstandard/FieldsTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Nonstandard;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Nonstandard\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Uuid;
use function hex2bin;
use function serialize;
use function str_replace;
use function unserialize;
class FieldsTest extends TestCase
{
public function testConstructorThrowsExceptionIfNotSixteenByteString(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string must be 16 bytes long; received 6 bytes'
);
new Fields('foobar');
}
/**
* @param non-empty-string $uuid
* @param non-empty-string $methodName
* @param non-empty-string | int | bool | null $expectedValue
*
* @dataProvider fieldGetterMethodProvider
*/
public function testFieldGetterMethods(
string $uuid,
string $methodName,
bool | int | string | null $expectedValue,
): void {
$bytes = (string) hex2bin(str_replace('-', '', $uuid));
$fields = new Fields($bytes);
$result = $fields->$methodName();
if ($result instanceof Hexadecimal) {
$this->assertSame($expectedValue, $result->toString());
} else {
$this->assertSame($expectedValue, $result);
}
}
/**
* @return array<array{0: non-empty-string, 1: non-empty-string, 2: non-empty-string | int | bool | null}>
*/
public function fieldGetterMethodProvider(): array
{
return [
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getClockSeq', '0b21'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getClockSeqHiAndReserved', '0b'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getClockSeqLow', '21'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getNode', '0800200c9a66'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimeHiAndVersion', '91e1'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimeMid', 'c57d'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getVariant', Uuid::RESERVED_NCS],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'getVersion', null],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'isNil', false],
['ff6f8cb0-c57d-91e1-0b21-0800200c9a66', 'isMax', false],
];
}
public function testSerializingFields(): void
{
$bytes = (string) hex2bin(str_replace('-', '', 'ff6f8cb0-c57d-91e1-0b21-0800200c9a66'));
$fields = new Fields($bytes);
$serializedFields = serialize($fields);
/** @var Fields $unserializedFields */
$unserializedFields = unserialize($serializedFields);
$this->assertSame($fields->getBytes(), $unserializedFields->getBytes());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Nonstandard/UuidV6Test.php | tests/Nonstandard/UuidV6Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Nonstandard;
use DateTimeImmutable;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Lazy\LazyUuidFromString;
use Ramsey\Uuid\Nonstandard\UuidV6;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
class UuidV6Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV6 must represent a '
. 'version 6 (reordered time) UUID'
);
new UuidV6($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 3],
['version' => 4],
['version' => 5],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
/**
* @param non-empty-string $uuid
*
* @dataProvider provideUuidV6WithOddMicroseconds
*/
public function testGetDateTimeProperlyHandlesLongMicroseconds(string $uuid, string $expected): void
{
/** @var UuidV6 $object */
$object = Uuid::fromString($uuid);
$date = $object->getDateTime();
$this->assertInstanceOf(DateTimeImmutable::class, $date);
$this->assertSame($expected, $date->format('U.u'));
}
/**
* @return array<array{uuid: non-empty-string, expected: non-empty-string}>
*/
public function provideUuidV6WithOddMicroseconds(): array
{
return [
[
'uuid' => '1b21dd21-4814-6000-9669-00007ffffffe',
'expected' => '1.677722',
],
[
'uuid' => '1b21dd21-3714-6000-9669-00007ffffffe',
'expected' => '0.104858',
],
[
'uuid' => '1b21dd21-3713-6000-9669-00007ffffffe',
'expected' => '0.105267',
],
[
'uuid' => '1b21dd21-2e8a-6980-8d4f-acde48001122',
'expected' => '-1.000000',
],
];
}
/**
* @param non-empty-string $uuidv6
* @param non-empty-string $uuidv1
*
* @dataProvider provideUuidV1UuidV6Equivalents
*/
public function testToUuidV1(string $uuidv6, string $uuidv1): void
{
/** @var UuidV6 $uuid6 */
$uuid6 = Uuid::fromString($uuidv6);
$uuid1 = $uuid6->toUuidV1();
$this->assertSame($uuidv6, $uuid6->toString());
$this->assertSame($uuidv1, $uuid1->toString());
$this->assertSame(
$uuid6->getDateTime()->format('U.u'),
$uuid1->getDateTime()->format('U.u')
);
}
/**
* @param non-empty-string $uuidv6
* @param non-empty-string $uuidv1
*
* @dataProvider provideUuidV1UuidV6Equivalents
*/
public function testFromUuidV1(string $uuidv6, string $uuidv1): void
{
/** @var LazyUuidFromString $uuid */
$uuid = Uuid::fromString($uuidv1);
$uuid1 = $uuid->toUuidV1();
$uuid6 = UuidV6::fromUuidV1($uuid1);
$this->assertSame($uuidv1, $uuid1->toString());
$this->assertSame($uuidv6, $uuid6->toString());
$this->assertSame(
$uuid1->getDateTime()->format('U.u'),
$uuid6->getDateTime()->format('U.u')
);
}
/**
* @return array<array{uuidv6: non-empty-string, uuidv1: non-empty-string}>
*/
public function provideUuidV1UuidV6Equivalents(): array
{
return [
[
'uuidv6' => '1b21dd21-4814-6000-9669-00007ffffffe',
'uuidv1' => '14814000-1dd2-11b2-9669-00007ffffffe',
],
[
'uuidv6' => '1b21dd21-3714-6000-9669-00007ffffffe',
'uuidv1' => '13714000-1dd2-11b2-9669-00007ffffffe',
],
[
'uuidv6' => '1b21dd21-3713-6000-9669-00007ffffffe',
'uuidv1' => '13713000-1dd2-11b2-9669-00007ffffffe',
],
[
'uuidv6' => '1b21dd21-2e8a-6980-8d4f-acde48001122',
'uuidv1' => '12e8a980-1dd2-11b2-8d4f-acde48001122',
],
];
}
public function testGetDateTimeThrowsException(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => 6,
'getTimestamp' => new Hexadecimal('0'),
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class, [
'convertTime' => new Time('0', '1234567'),
]);
$uuid = new UuidV6($fields, $numberConverter, $codec, $timeConverter);
$this->expectException(DateTimeException::class);
$uuid->getDateTime();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Nonstandard/UuidBuilderTest.php | tests/Nonstandard/UuidBuilderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Nonstandard;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\Nonstandard\UuidBuilder;
use Ramsey\Uuid\Test\TestCase;
use RuntimeException;
class UuidBuilderTest extends TestCase
{
public function testBuildThrowsException(): void
{
$codec = Mockery::mock(CodecInterface::class);
$builder = Mockery::mock(UuidBuilder::class);
$builder->shouldAllowMockingProtectedMethods();
$builder->shouldReceive('buildFields')->andThrow(
RuntimeException::class,
'exception thrown'
);
$builder->shouldReceive('build')->passthru();
$this->expectException(UnableToBuildUuidException::class);
$this->expectExceptionMessage('exception thrown');
$builder->build($codec, 'foobar');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV1Test.php | tests/Rfc4122/UuidV1Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use DateTimeImmutable;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
class UuidV1Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV1 must represent a '
. 'version 1 (time-based) UUID'
);
new UuidV1($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 2],
['version' => 3],
['version' => 4],
['version' => 5],
['version' => 6],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
/**
* @param non-empty-string $uuid
* @param numeric-string $expected
*
* @dataProvider provideUuidV1WithOddMicroseconds
*/
public function testGetDateTimeProperlyHandlesLongMicroseconds(string $uuid, string $expected): void
{
/** @var UuidV1 $object */
$object = Uuid::fromString($uuid);
$date = $object->getDateTime();
$this->assertInstanceOf(DateTimeImmutable::class, $date);
$this->assertSame($expected, $date->format('U.u'));
}
/**
* @return array<array{uuid: non-empty-string, expected: numeric-string}>
*/
public function provideUuidV1WithOddMicroseconds(): array
{
return [
[
'uuid' => '14814000-1dd2-11b2-9669-00007ffffffe',
'expected' => '1.677722',
],
[
'uuid' => '13714000-1dd2-11b2-9669-00007ffffffe',
'expected' => '0.104858',
],
[
'uuid' => '13713000-1dd2-11b2-9669-00007ffffffe',
'expected' => '0.105267',
],
[
'uuid' => '12e8a980-1dd2-11b2-8d4f-acde48001122',
'expected' => '-1.000000',
],
];
}
public function testGetDateTimeThrowsException(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => 1,
'getTimestamp' => new Hexadecimal('0'),
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class, [
'convertTime' => new Time('0', '1234567'),
]);
$uuid = new UuidV1($fields, $numberConverter, $codec, $timeConverter);
$this->expectException(DateTimeException::class);
$uuid->getDateTime();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/FieldsTest.php | tests/Rfc4122/FieldsTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use function hex2bin;
use function serialize;
use function str_replace;
use function unserialize;
class FieldsTest extends TestCase
{
public function testConstructorThrowsExceptionIfNotSixteenByteString(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string must be 16 bytes long; received 6 bytes'
);
new Fields('foobar');
}
/**
* @param non-empty-string $uuid
*
* @dataProvider nonRfc4122VariantProvider
*/
public function testConstructorThrowsExceptionIfNotRfc4122Variant(string $uuid): void
{
$bytes = (string) hex2bin(str_replace('-', '', $uuid));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) variant'
);
new Fields($bytes);
}
/**
* @return array<array{0: non-empty-string}>
*/
public function nonRfc4122VariantProvider(): array
{
return [
['ff6f8cb0-c57d-11e1-0b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-1b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-2b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-3b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-4b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-5b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-6b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-7b21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-cb21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-db21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-eb21-0800200c9a66'],
['ff6f8cb0-c57d-11e1-fb21-0800200c9a66'],
];
}
/**
* @param non-empty-string $uuid
*
* @dataProvider invalidVersionProvider
*/
public function testConstructorThrowsExceptionIfInvalidVersion(string $uuid): void
{
$bytes = (string) hex2bin(str_replace('-', '', $uuid));
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'The byte string received does not contain a valid RFC 9562 (formerly RFC 4122) version'
);
new Fields($bytes);
}
/**
* @return array<array{0: non-empty-string}>
*/
public function invalidVersionProvider(): array
{
return [
['ff6f8cb0-c57d-01e1-8b21-0800200c9a66'],
['ff6f8cb0-c57d-91e1-bb21-0800200c9a66'],
['ff6f8cb0-c57d-a1e1-9b21-0800200c9a66'],
['ff6f8cb0-c57d-b1e1-ab21-0800200c9a66'],
['ff6f8cb0-c57d-c1e1-ab21-0800200c9a66'],
['ff6f8cb0-c57d-d1e1-ab21-0800200c9a66'],
['ff6f8cb0-c57d-e1e1-ab21-0800200c9a66'],
['ff6f8cb0-c57d-f1e1-ab21-0800200c9a66'],
];
}
/**
* @param non-empty-string $uuid
* @param non-empty-string $methodName
* @param non-empty-string | int | bool | null $expectedValue
*
* @dataProvider fieldGetterMethodProvider
*/
public function testFieldGetterMethods(
string $uuid,
string $methodName,
bool | int | string | null $expectedValue,
): void {
$bytes = (string) hex2bin(str_replace('-', '', $uuid));
$fields = new Fields($bytes);
$result = $fields->$methodName();
if ($result instanceof Hexadecimal) {
$this->assertSame($expectedValue, $result->toString());
} else {
$this->assertSame($expectedValue, $result);
}
}
/**
* @return array<array{0: non-empty-string, 1: non-empty-string, 2: non-empty-string | int | bool | null}>
*/
public function fieldGetterMethodProvider(): array
{
return [
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getClockSeq', '1b21'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getClockSeqHiAndReserved', '9b'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getClockSeqLow', '21'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getNode', '0800200c9a66'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimeHiAndVersion', '11e1'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimeMid', 'c57d'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getVariant', 2],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'getVersion', 1],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'isNil', false],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 'isMax', false],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getClockSeq', '2b21'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getClockSeqHiAndReserved', 'ab'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getClockSeqLow', '21'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getNode', '0800200c9a66'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimeHiAndVersion', '41e1'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimeMid', 'c57d'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getVariant', 2],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'getVersion', 4],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'isNil', false],
['ff6f8cb0-c57d-41e1-ab21-0800200c9a66', 'isMax', false],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getClockSeq', '3b21'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getClockSeqHiAndReserved', 'bb'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getClockSeqLow', '21'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getNode', '0800200c9a66'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimeHiAndVersion', '31e1'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimeMid', 'c57d'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getVariant', 2],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'getVersion', 3],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'isNil', false],
['ff6f8cb0-c57d-31e1-bb21-0800200c9a66', 'isMax', false],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getClockSeq', '0b21'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getClockSeqHiAndReserved', '8b'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getClockSeqLow', '21'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getNode', '0800200c9a66'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimeHiAndVersion', '51e1'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimeMid', 'c57d'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getTimestamp', '1e1c57dff6f8cb0'],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getVariant', 2],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'getVersion', 5],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'isNil', false],
['ff6f8cb0-c57d-51e1-8b21-0800200c9a66', 'isMax', false],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getClockSeq', '0b21'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getClockSeqHiAndReserved', '8b'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getClockSeqLow', '21'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getNode', '0800200c9a66'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimeHiAndVersion', '61e1'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimeLow', 'ff6f8cb0'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimeMid', 'c57d'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getTimestamp', 'ff6f8cb0c57d1e1'],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getVariant', 2],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'getVersion', 6],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'isNil', false],
['ff6f8cb0-c57d-61e1-8b21-0800200c9a66', 'isMax', false],
['00000000-0000-0000-0000-000000000000', 'getClockSeq', '0000'],
['00000000-0000-0000-0000-000000000000', 'getClockSeqHiAndReserved', '00'],
['00000000-0000-0000-0000-000000000000', 'getClockSeqLow', '00'],
['00000000-0000-0000-0000-000000000000', 'getNode', '000000000000'],
['00000000-0000-0000-0000-000000000000', 'getTimeHiAndVersion', '0000'],
['00000000-0000-0000-0000-000000000000', 'getTimeLow', '00000000'],
['00000000-0000-0000-0000-000000000000', 'getTimeMid', '0000'],
['00000000-0000-0000-0000-000000000000', 'getTimestamp', '000000000000000'],
['00000000-0000-0000-0000-000000000000', 'getVariant', 0],
['00000000-0000-0000-0000-000000000000', 'getVersion', null],
['00000000-0000-0000-0000-000000000000', 'isNil', true],
['00000000-0000-0000-0000-000000000000', 'isMax', false],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getClockSeq', 'ffff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getClockSeqHiAndReserved', 'ff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getClockSeqLow', 'ff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getNode', 'ffffffffffff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimeHiAndVersion', 'ffff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimeLow', 'ffffffff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimeMid', 'ffff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getTimestamp', 'fffffffffffffff'],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getVariant', 7],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'getVersion', null],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'isNil', false],
['ffffffff-ffff-ffff-ffff-ffffffffffff', 'isMax', true],
['000001f5-5cde-21ea-8400-0242ac130003', 'getClockSeq', '0400'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getClockSeqHiAndReserved', '84'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getClockSeqLow', '00'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getNode', '0242ac130003'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getTimeHiAndVersion', '21ea'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getTimeLow', '000001f5'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getTimeMid', '5cde'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getTimestamp', '1ea5cde00000000'],
['000001f5-5cde-21ea-8400-0242ac130003', 'getVariant', 2],
['000001f5-5cde-21ea-8400-0242ac130003', 'getVersion', 2],
['000001f5-5cde-21ea-8400-0242ac130003', 'isNil', false],
['000001f5-5cde-21ea-8400-0242ac130003', 'isMax', false],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getClockSeq', '1b21'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getClockSeqHiAndReserved', '9b'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getClockSeqLow', '21'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getNode', '0800200c9a66'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimeHiAndVersion', '71e1'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimeLow', '018339f0'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimeMid', '1b83'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getTimestamp', '000018339f01b83'],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getVariant', 2],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'getVersion', 7],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'isNil', false],
['018339f0-1b83-71e1-9b21-0800200c9a66', 'isMax', false],
];
}
public function testSerializingFields(): void
{
$bytes = (string) hex2bin(str_replace('-', '', 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66'));
$fields = new Fields($bytes);
$serializedFields = serialize($fields);
/** @var Fields $unserializedFields */
$unserializedFields = unserialize($serializedFields);
$this->assertSame($fields->getBytes(), $unserializedFields->getBytes());
}
public function testSerializingFieldsWithOldFormat(): void
{
$fields = new Fields("\xb3\xcd\x58\x6a\xe3\xca\x44\xf3\x98\x8c\xf4\xd6\x66\xc1\xbf\x4d");
$serializedFields = 'C:26:"Ramsey\Uuid\Rfc4122\Fields":24:{s81YauPKRPOYjPTWZsG/TQ==}';
/** @var Fields $unserializedFields */
$unserializedFields = unserialize($serializedFields);
$this->assertSame($fields->getBytes(), $unserializedFields->getBytes());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV8Test.php | tests/Rfc4122/UuidV8Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV8;
use Ramsey\Uuid\Test\TestCase;
class UuidV8Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Fields used to create a UuidV8 must represent a version 8 (custom format) UUID');
new UuidV8($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 3],
['version' => 4],
['version' => 5],
['version' => 6],
['version' => 7],
['version' => 9],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/ValidatorTest.php | tests/Rfc4122/ValidatorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Ramsey\Uuid\Rfc4122\Validator;
use Ramsey\Uuid\Test\TestCase;
use function array_merge;
use function in_array;
use function strtoupper;
class ValidatorTest extends TestCase
{
/**
* @dataProvider provideValuesForValidation
*/
public function testValidate(string $value, bool $expected): void
{
$variations = [];
$variations[] = $value;
$variations[] = 'urn:uuid:' . $value;
$variations[] = '{' . $value . '}';
foreach ($variations as $variation) {
$variations[] = strtoupper($variation);
}
$validator = new Validator();
foreach ($variations as $variation) {
$this->assertSame(
$expected,
$validator->validate($variation),
sprintf(
'Expected "%s" to be %s',
$variation,
$expected ? 'valid' : 'not valid',
),
);
}
}
/**
* @return array<array{value: string, expected: bool}>
*/
public function provideValuesForValidation(): array
{
$hexMutations = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
$trueVersions = [1, 2, 3, 4, 5, 6, 7, 8];
$trueVariants = [8, 9, 'a', 'b'];
$testValues = [];
foreach ($hexMutations as $version) {
foreach ($hexMutations as $variant) {
$testValues[] = [
'value' => "ff6f8cb0-c57d-{$version}1e1-{$variant}b21-0800200c9a66",
'expected' => in_array($variant, $trueVariants, true) && in_array($version, $trueVersions, true),
];
}
}
return array_merge($testValues, [
[
'value' => 'zf6f8cb0-c57d-11e1-9b21-0800200c9a66',
'expected' => false,
],
[
'value' => '3f6f8cb0-c57d-11e1-9b21-0800200c9a6',
'expected' => false,
],
[
'value' => 'af6f8cb-c57d-11e1-9b21-0800200c9a66',
'expected' => false,
],
[
'value' => 'af6f8cb0c57d11e19b210800200c9a66',
'expected' => false,
],
[
'value' => 'ff6f8cb0-c57da-51e1-9b21-0800200c9a66',
'expected' => false,
],
[
'value' => "ff6f8cb0-c57d-11e1-1b21-0800200c9a66\n",
'expected' => false,
],
[
'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66",
'expected' => false,
],
[
'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66\n",
'expected' => false,
],
[
'value' => '00000000-0000-0000-0000-000000000000',
'expected' => true,
],
[
'value' => 'ffffffff-ffff-ffff-ffff-ffffffffffff',
'expected' => true,
],
[
'value' => 'FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF',
'expected' => true,
],
]);
}
public function testGetPattern(): void
{
$expectedPattern = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-'
. '[1-8][0-9A-Fa-f]{3}-[ABab89][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}\z';
$validator = new Validator();
$this->assertSame($expectedPattern, $validator->getPattern());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV3Test.php | tests/Rfc4122/UuidV3Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV3;
use Ramsey\Uuid\Test\TestCase;
class UuidV3Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV3 must represent a '
. 'version 3 (name-based, MD5-hashed) UUID'
);
new UuidV3($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 4],
['version' => 5],
['version' => 6],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV6Test.php | tests/Rfc4122/UuidV6Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use DateTimeImmutable;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Lazy\LazyUuidFromString;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV6;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
class UuidV6Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV6 must represent a '
. 'version 6 (reordered time) UUID'
);
new UuidV6($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 3],
['version' => 4],
['version' => 5],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
/**
* @param non-empty-string $uuid
* @param non-empty-string $expected
*
* @dataProvider provideUuidV6WithOddMicroseconds
*/
public function testGetDateTimeProperlyHandlesLongMicroseconds(string $uuid, string $expected): void
{
/** @var UuidV6 $object */
$object = Uuid::fromString($uuid);
$date = $object->getDateTime();
$this->assertInstanceOf(DateTimeImmutable::class, $date);
$this->assertSame($expected, $date->format('U.u'));
}
/**
* @return array<array{uuid: non-empty-string, expected: non-empty-string}>
*/
public function provideUuidV6WithOddMicroseconds(): array
{
return [
[
'uuid' => '1b21dd21-4814-6000-9669-00007ffffffe',
'expected' => '1.677722',
],
[
'uuid' => '1b21dd21-3714-6000-9669-00007ffffffe',
'expected' => '0.104858',
],
[
'uuid' => '1b21dd21-3713-6000-9669-00007ffffffe',
'expected' => '0.105267',
],
[
'uuid' => '1b21dd21-2e8a-6980-8d4f-acde48001122',
'expected' => '-1.000000',
],
];
}
/**
* @param non-empty-string $uuidv6
* @param non-empty-string $uuidv1
*
* @dataProvider provideUuidV1UuidV6Equivalents
*/
public function testToUuidV1(string $uuidv6, string $uuidv1): void
{
/** @var UuidV6 $uuid6 */
$uuid6 = Uuid::fromString($uuidv6);
$uuid1 = $uuid6->toUuidV1();
$this->assertSame($uuidv6, $uuid6->toString());
$this->assertSame($uuidv1, $uuid1->toString());
$this->assertSame(
$uuid6->getDateTime()->format('U.u'),
$uuid1->getDateTime()->format('U.u')
);
}
/**
* @param non-empty-string $uuidv6
* @param non-empty-string $uuidv1
*
* @dataProvider provideUuidV1UuidV6Equivalents
*/
public function testFromUuidV1(string $uuidv6, string $uuidv1): void
{
/** @var LazyUuidFromString $uuid */
$uuid = Uuid::fromString($uuidv1);
$uuid1 = $uuid->toUuidV1();
$uuid6 = UuidV6::fromUuidV1($uuid1);
$this->assertSame($uuidv1, $uuid1->toString());
$this->assertSame($uuidv6, $uuid6->toString());
$this->assertSame(
$uuid1->getDateTime()->format('U.u'),
$uuid6->getDateTime()->format('U.u')
);
}
/**
* @return array<array{uuidv6: non-empty-string, uuidv1: non-empty-string}>
*/
public function provideUuidV1UuidV6Equivalents(): array
{
return [
[
'uuidv6' => '1b21dd21-4814-6000-9669-00007ffffffe',
'uuidv1' => '14814000-1dd2-11b2-9669-00007ffffffe',
],
[
'uuidv6' => '1b21dd21-3714-6000-9669-00007ffffffe',
'uuidv1' => '13714000-1dd2-11b2-9669-00007ffffffe',
],
[
'uuidv6' => '1b21dd21-3713-6000-9669-00007ffffffe',
'uuidv1' => '13713000-1dd2-11b2-9669-00007ffffffe',
],
[
'uuidv6' => '1b21dd21-2e8a-6980-8d4f-acde48001122',
'uuidv1' => '12e8a980-1dd2-11b2-8d4f-acde48001122',
],
];
}
public function testGetDateTimeThrowsException(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => 6,
'getTimestamp' => new Hexadecimal('0'),
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class, [
'convertTime' => new Time('0', '1234567'),
]);
$uuid = new UuidV6($fields, $numberConverter, $codec, $timeConverter);
$this->expectException(DateTimeException::class);
$uuid->getDateTime();
}
/**
* @link https://datatracker.ietf.org/doc/html/draft-peabody-dispatch-new-uuid-format-04#appendix-B.1
*/
public function testUsingDraftPeabodyUuidV6TestVector(): void
{
$testVector = '1EC9414C-232A-6B00-B3C8-9E6BDECED846';
/** @var UuidV6 $uuidv6 */
$uuidv6 = Uuid::fromString($testVector);
$uuidv1 = $uuidv6->toUuidV1();
/** @var FieldsInterface $fields */
$fields = $uuidv6->getFields();
$this->assertSame('1ec9414c', $fields->getTimeLow()->toString());
$this->assertSame('232a', $fields->getTimeMid()->toString());
$this->assertSame('6b00', $fields->getTimeHiAndVersion()->toString());
$this->assertSame('b3', $fields->getClockSeqHiAndReserved()->toString());
$this->assertSame('c8', $fields->getClockSeqLow()->toString());
$this->assertSame('9e6bdeced846', $fields->getNode()->toString());
$this->assertSame(1645557742, $uuidv6->getDateTime()->getTimestamp());
$this->assertSame(
'c232ab00-9414-11ec-b3c8-9e6bdeced846',
$uuidv1->toString(),
);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidBuilderTest.php | tests/Rfc4122/UuidBuilderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Mockery;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Nonstandard\UuidV6 as NonstandardUuidV6;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\MaxUuid;
use Ramsey\Uuid\Rfc4122\NilUuid;
use Ramsey\Uuid\Rfc4122\UuidBuilder;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Rfc4122\UuidV2;
use Ramsey\Uuid\Rfc4122\UuidV3;
use Ramsey\Uuid\Rfc4122\UuidV4;
use Ramsey\Uuid\Rfc4122\UuidV5;
use Ramsey\Uuid\Rfc4122\UuidV6;
use Ramsey\Uuid\Rfc4122\UuidV7;
use Ramsey\Uuid\Rfc4122\UuidV8;
use Ramsey\Uuid\Test\TestCase;
use function hex2bin;
use function str_replace;
class UuidBuilderTest extends TestCase
{
/**
* @param non-empty-string $uuid
* @param class-string $expectedClass
*
* @dataProvider provideBuildTestValues
*/
public function testBuild(string $uuid, string $expectedClass, ?int $expectedVersion): void
{
$bytes = (string) hex2bin(str_replace('-', '', $uuid));
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = new GenericTimeConverter($calculator);
$builder = new UuidBuilder($numberConverter, $timeConverter);
$codec = new StringCodec($builder);
$result = $builder->build($codec, $bytes);
/** @var Fields $fields */
$fields = $result->getFields();
$this->assertInstanceOf($expectedClass, $result);
$this->assertSame($expectedVersion, $fields->getVersion());
}
/**
* @return array<array{uuid: non-empty-string, expectedClass: class-string, expectedVersion: int | null}>
*/
public function provideBuildTestValues(): array
{
return [
[
'uuid' => '00000000-0000-0000-0000-000000000000',
'expectedClass' => NilUuid::class,
'expectedVersion' => null,
],
[
'uuid' => 'ffffffff-ffff-ffff-ffff-ffffffffffff',
'expectedClass' => MaxUuid::class,
'expectedVersion' => null,
],
[
'uuid' => 'ff6f8cb0-c57d-11e1-9b21-0800200c9a66',
'expectedClass' => UuidV1::class,
'expectedVersion' => 1,
],
[
'uuid' => 'ff6f8cb0-c57d-21e1-9b21-0800200c9a66',
'expectedClass' => UuidV2::class,
'expectedVersion' => 2,
],
[
'uuid' => 'ff6f8cb0-c57d-31e1-9b21-0800200c9a66',
'expectedClass' => UuidV3::class,
'expectedVersion' => 3,
],
[
'uuid' => 'ff6f8cb0-c57d-41e1-9b21-0800200c9a66',
'expectedClass' => UuidV4::class,
'expectedVersion' => 4,
],
[
'uuid' => 'ff6f8cb0-c57d-51e1-9b21-0800200c9a66',
'expectedClass' => UuidV5::class,
'expectedVersion' => 5,
],
[
'uuid' => 'ff6f8cb0-c57d-61e1-9b21-0800200c9a66',
'expectedClass' => UuidV6::class,
'expectedVersion' => 6,
],
// The same UUIDv6 will also be of the expected class type
// \Ramsey\Uuid\Nonstandard\UuidV6.
[
'uuid' => 'ff6f8cb0-c57d-61e1-9b21-0800200c9a66',
'expectedClass' => NonstandardUuidV6::class,
'expectedVersion' => 6,
],
[
'uuid' => 'ff6f8cb0-c57d-71e1-9b21-0800200c9a66',
'expectedClass' => UuidV7::class,
'expectedVersion' => 7,
],
[
'uuid' => 'ff6f8cb0-c57d-81e1-9b21-0800200c9a66',
'expectedClass' => UuidV8::class,
'expectedVersion' => 8,
],
];
}
public function testBuildThrowsUnableToBuildException(): void
{
$bytes = (string) hex2bin(str_replace('-', '', 'ff6f8cb0-c57d-51e1-9b21-0800200c9a'));
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = new GenericTimeConverter($calculator);
$builder = new UuidBuilder($numberConverter, $timeConverter);
$codec = new StringCodec($builder);
$this->expectException(UnableToBuildUuidException::class);
$this->expectExceptionMessage(
'The byte string must be 16 bytes long; received 15 bytes'
);
$builder->build($codec, $bytes);
}
public function testBuildThrowsUnableToBuildExceptionForIncorrectVersionFields(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'isNil' => false,
'isMax' => false,
'getVersion' => 255,
]);
$builder = Mockery::mock(UuidBuilder::class);
$builder->shouldAllowMockingProtectedMethods();
$builder->shouldReceive('buildFields')->andReturn($fields);
$builder->shouldReceive('build')->passthru();
$codec = Mockery::mock(StringCodec::class);
$this->expectException(UnableToBuildUuidException::class);
$this->expectExceptionMessage(
'The UUID version in the given fields is not supported by this UUID builder'
);
$builder->build($codec, 'foobar');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV5Test.php | tests/Rfc4122/UuidV5Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV5;
use Ramsey\Uuid\Test\TestCase;
class UuidV5Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV5 must represent a '
. 'version 5 (named-based, SHA1-hashed) UUID'
);
new UuidV5($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 3],
['version' => 4],
['version' => 6],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV2Test.php | tests/Rfc4122/UuidV2Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use DateTimeInterface;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Generator\DceSecurityGenerator;
use Ramsey\Uuid\Generator\DefaultTimeGenerator;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider;
use Ramsey\Uuid\Provider\Node\StaticNodeProvider;
use Ramsey\Uuid\Provider\Time\FixedTimeProvider;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV2;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use const PHP_VERSION_ID;
class UuidV2Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV2 must represent a '
. 'version 2 (DCE Security) UUID'
);
new UuidV2($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 3],
['version' => 4],
['version' => 5],
['version' => 6],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
/**
* @dataProvider provideLocalDomainAndIdentifierForTests
*/
public function testGetLocalDomainAndIdentifier(
int $domain,
IntegerObject $identifier,
Time $time,
int $expectedDomain,
string $expectedDomainName,
string $expectedIdentifier,
string $expectedTimestamp,
string $expectedTime
): void {
$calculator = new BrickMathCalculator();
$genericConverter = new GenericTimeConverter($calculator);
$numberConverter = new GenericNumberConverter($calculator);
$nodeProvider = new StaticNodeProvider(new Hexadecimal('1234567890ab'));
$timeProvider = new FixedTimeProvider($time);
$timeGenerator = new DefaultTimeGenerator($nodeProvider, $genericConverter, $timeProvider);
$dceProvider = new SystemDceSecurityProvider();
$dceGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceProvider);
$factory = new UuidFactory();
$factory->setTimeGenerator($timeGenerator);
$factory->setDceSecurityGenerator($dceGenerator);
/** @var UuidV2 $uuid */
$uuid = $factory->uuid2($domain, $identifier);
/** @var FieldsInterface $fields */
$fields = $uuid->getFields();
$this->assertSame($expectedDomain, $uuid->getLocalDomain());
$this->assertSame($expectedDomainName, $uuid->getLocalDomainName());
$this->assertInstanceOf(IntegerObject::class, $uuid->getLocalIdentifier());
$this->assertSame($expectedIdentifier, $uuid->getLocalIdentifier()->toString());
$this->assertSame($expectedTimestamp, $fields->getTimestamp()->toString());
$this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime());
$this->assertSame($expectedTime, $uuid->getDateTime()->format('U.u'));
$this->assertSame('1334567890ab', $fields->getNode()->toString());
}
/**
* @return array<array{
* domain: int,
* identifier: IntegerObject,
* time: Time,
* expectedDomain: int,
* expectedDomainName: non-empty-string,
* expectedIdentifier: non-empty-string,
* expectedTimestamp: non-empty-string,
* expectedTime: non-empty-string,
* }>
*/
public function provideLocalDomainAndIdentifierForTests(): array
{
// https://github.com/php/php-src/issues/7758
$isGH7758Fixed = PHP_VERSION_ID >= 80107;
return [
[
'domain' => Uuid::DCE_DOMAIN_PERSON,
'identifier' => new IntegerObject('12345678'),
'time' => new Time(0, 0),
'expectedDomain' => 0,
'expectedDomainName' => 'person',
'expectedIdentifier' => '12345678',
'expectedTimestamp' => '1b21dd200000000',
'expectedTime' => $isGH7758Fixed ? '-33.276237' : '-32.723763',
],
[
'domain' => Uuid::DCE_DOMAIN_GROUP,
'identifier' => new IntegerObject('87654321'),
'time' => new Time(0, 0),
'expectedDomain' => 1,
'expectedDomainName' => 'group',
'expectedIdentifier' => '87654321',
'expectedTimestamp' => '1b21dd200000000',
'expectedTime' => $isGH7758Fixed ? '-33.276237' : '-32.723763',
],
[
'domain' => Uuid::DCE_DOMAIN_ORG,
'identifier' => new IntegerObject('1'),
'time' => new Time(0, 0),
'expectedDomain' => 2,
'expectedDomainName' => 'org',
'expectedIdentifier' => '1',
'expectedTimestamp' => '1b21dd200000000',
'expectedTime' => $isGH7758Fixed ? '-33.276237' : '-32.723763',
],
[
'domain' => Uuid::DCE_DOMAIN_PERSON,
'identifier' => new IntegerObject('0'),
'time' => new Time(1583208664, 444109),
'expectedDomain' => 0,
'expectedDomainName' => 'person',
'expectedIdentifier' => '0',
'expectedTimestamp' => '1ea5d0500000000',
'expectedTime' => '1583208664.444109',
],
[
'domain' => Uuid::DCE_DOMAIN_PERSON,
'identifier' => new IntegerObject('2147483647'),
'time' => new Time(1583208879, 500000),
'expectedDomain' => 0,
'expectedDomainName' => 'person',
'expectedIdentifier' => '2147483647',
// This time is the same as in the previous test because of the
// loss of precision by setting the lowest 32 bits to zeros.
'expectedTimestamp' => '1ea5d0500000000',
'expectedTime' => '1583208664.444109',
],
[
'domain' => Uuid::DCE_DOMAIN_PERSON,
'identifier' => new IntegerObject('4294967295'),
'time' => new Time(1583208879, 500000),
'expectedDomain' => 0,
'expectedDomainName' => 'person',
'expectedIdentifier' => '4294967295',
// This time is the same as in the previous test because of the
// loss of precision by setting the lowest 32 bits to zeros.
'expectedTimestamp' => '1ea5d0500000000',
'expectedTime' => '1583208664.444109',
],
[
'domain' => Uuid::DCE_DOMAIN_PERSON,
'identifier' => new IntegerObject('4294967295'),
'time' => new Time(1583209093, 940838),
'expectedDomain' => 0,
'expectedDomainName' => 'person',
'expectedIdentifier' => '4294967295',
// This time is the same as in the previous test because of the
// loss of precision by setting the lowest 32 bits to zeros.
'expectedTimestamp' => '1ea5d0500000000',
'expectedTime' => '1583208664.444109',
],
[
'domain' => Uuid::DCE_DOMAIN_PERSON,
'identifier' => new IntegerObject('4294967295'),
'time' => new Time(1583209093, 940839),
'expectedDomain' => 0,
'expectedDomainName' => 'person',
'expectedIdentifier' => '4294967295',
'expectedTimestamp' => '1ea5d0600000000',
'expectedTime' => '1583209093.940838',
],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV4Test.php | tests/Rfc4122/UuidV4Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV4;
use Ramsey\Uuid\Test\TestCase;
class UuidV4Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV4 must represent a '
. 'version 4 (random) UUID'
);
new UuidV4($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 3],
['version' => 5],
['version' => 6],
['version' => 7],
['version' => 8],
['version' => 9],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/VariantTraitTest.php | tests/Rfc4122/VariantTraitTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use Mockery;
use Ramsey\Uuid\Exception\InvalidBytesException;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Rfc4122\VariantTrait;
use Ramsey\Uuid\Test\TestCase;
use function hex2bin;
use function str_replace;
class VariantTraitTest extends TestCase
{
/**
* @dataProvider invalidBytesProvider
*/
public function testGetVariantThrowsExceptionForWrongNumberOfBytes(string $bytes): void
{
/** @var Fields $trait */
$trait = Mockery::mock(VariantTrait::class, [
'getBytes' => $bytes,
'isMax' => false,
'isNil' => false,
]);
$this->expectException(InvalidBytesException::class);
$this->expectExceptionMessage('Invalid number of bytes');
$trait->getVariant();
}
/**
* @return array<array{0: non-empty-string}>
*/
public function invalidBytesProvider(): array
{
return [
['not16Bytes_abcd'],
['not16Bytes_abcdef'],
];
}
/**
* @dataProvider uuidVariantProvider
*/
public function testGetVariant(string $uuid, int $expectedVariant): void
{
$bytes = (string) hex2bin(str_replace('-', '', $uuid));
/** @var Fields $trait */
$trait = Mockery::mock(VariantTrait::class, [
'getBytes' => $bytes,
'isMax' => false,
'isNil' => false,
]);
$this->assertSame($expectedVariant, $trait->getVariant());
}
/**
* @return array<array{0: non-empty-string, 1: int}>
*/
public function uuidVariantProvider(): array
{
return [
['ff6f8cb0-c57d-11e1-0b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-1b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-2b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-3b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-4b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-5b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-6b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-7b21-0800200c9a66', 0],
['ff6f8cb0-c57d-11e1-8b21-0800200c9a66', 2],
['ff6f8cb0-c57d-11e1-9b21-0800200c9a66', 2],
['ff6f8cb0-c57d-11e1-ab21-0800200c9a66', 2],
['ff6f8cb0-c57d-11e1-bb21-0800200c9a66', 2],
['ff6f8cb0-c57d-11e1-cb21-0800200c9a66', 6],
['ff6f8cb0-c57d-11e1-db21-0800200c9a66', 6],
['ff6f8cb0-c57d-11e1-eb21-0800200c9a66', 7],
['ff6f8cb0-c57d-11e1-fb21-0800200c9a66', 7],
// The following are the same UUIDs in GUID byte order. Dashes have
// been removed in the tests to distinguish these from string
// representations, which are never in GUID byte order.
['b08c6fff7dc5e1110b210800200c9a66', 0],
['b08c6fff7dc5e1111b210800200c9a66', 0],
['b08c6fff7dc5e1112b210800200c9a66', 0],
['b08c6fff7dc5e1113b210800200c9a66', 0],
['b08c6fff7dc5e1114b210800200c9a66', 0],
['b08c6fff7dc5e1115b210800200c9a66', 0],
['b08c6fff7dc5e1116b210800200c9a66', 0],
['b08c6fff7dc5e1117b210800200c9a66', 0],
['b08c6fff7dc5e1118b210800200c9a66', 2],
['b08c6fff7dc5e1119b210800200c9a66', 2],
['b08c6fff7dc5e111ab210800200c9a66', 2],
['b08c6fff7dc5e111bb210800200c9a66', 2],
['b08c6fff7dc5e111cb210800200c9a66', 6],
['b08c6fff7dc5e111db210800200c9a66', 6],
['b08c6fff7dc5e111eb210800200c9a66', 7],
['b08c6fff7dc5e111fb210800200c9a66', 7],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Rfc4122/UuidV7Test.php | tests/Rfc4122/UuidV7Test.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Rfc4122;
use DateTimeImmutable;
use Mockery;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV7;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
class UuidV7Test extends TestCase
{
/**
* @dataProvider provideTestVersions
*/
public function testConstructorThrowsExceptionWhenFieldsAreNotValidForType(int $version): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => $version,
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Fields used to create a UuidV7 must represent a '
. 'version 7 (Unix Epoch time) UUID'
);
new UuidV7($fields, $numberConverter, $codec, $timeConverter);
}
/**
* @return array<array{version: int}>
*/
public function provideTestVersions(): array
{
return [
['version' => 0],
['version' => 1],
['version' => 2],
['version' => 3],
['version' => 4],
['version' => 5],
['version' => 6],
['version' => 8],
['version' => 9],
];
}
/**
* @param non-empty-string $uuid
*
* @dataProvider provideUuidV7WithMicroseconds
*/
public function testGetDateTimeProperlyHandlesMicroseconds(string $uuid, string $expected): void
{
/** @var UuidV7 $object */
$object = Uuid::fromString($uuid);
$date = $object->getDateTime();
$this->assertInstanceOf(DateTimeImmutable::class, $date);
$this->assertSame($expected, $date->format('U.u'));
}
/**
* @return array<array{uuid: string, expected: numeric-string}>
*/
public function provideUuidV7WithMicroseconds(): array
{
return [
[
'uuid' => '00000000-0001-71b2-9669-00007ffffffe',
'expected' => '0.001000',
],
[
'uuid' => '00000000-000f-71b2-9669-00007ffffffe',
'expected' => '0.015000',
],
[
'uuid' => '00000000-0064-71b2-9669-00007ffffffe',
'expected' => '0.100000',
],
[
'uuid' => '00000000-03e7-71b2-9669-00007ffffffe',
'expected' => '0.999000',
],
[
'uuid' => '00000000-03e8-71b2-9669-00007ffffffe',
'expected' => '1.000000',
],
[
'uuid' => '00000000-03e9-71b2-9669-00007ffffffe',
'expected' => '1.001000',
],
];
}
public function testGetDateTimeThrowsException(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getVersion' => 7,
'getTimestamp' => new Hexadecimal('0'),
]);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$codec = Mockery::mock(CodecInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class, [
'convertTime' => new Time('0', '1234567'),
]);
$uuid = new UuidV7($fields, $numberConverter, $codec, $timeConverter);
$this->expectException(DateTimeException::class);
$uuid->getDateTime();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Codec/StringCodecTest.php | tests/Codec/StringCodecTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Codec;
use InvalidArgumentException;
use Mockery;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\UuidInterface;
use function hex2bin;
use function implode;
use function pack;
class StringCodecTest extends TestCase
{
/**
* @var UuidBuilderInterface & MockObject
*/
private $builder;
/**
* @var UuidInterface & MockObject
*/
private $uuid;
/**
* @var Fields
*/
private $fields;
/**
* @var string
*/
private $uuidString = '12345678-1234-4bcd-abef-1234abcd4321';
protected function setUp(): void
{
parent::setUp();
$this->builder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock();
$this->uuid = $this->getMockBuilder(UuidInterface::class)->getMock();
$this->fields = new Fields((string) hex2bin('1234567812344bcdabef1234abcd4321'));
}
protected function tearDown(): void
{
parent::tearDown();
unset($this->builder, $this->uuid, $this->fields);
}
public function testEncodeUsesFieldsArray(): void
{
$this->uuid->expects($this->once())
->method('getFields')
->willReturn($this->fields);
$codec = new StringCodec($this->builder);
$codec->encode($this->uuid);
}
public function testEncodeReturnsFormattedString(): void
{
$this->uuid->method('getFields')
->willReturn($this->fields);
$codec = new StringCodec($this->builder);
$result = $codec->encode($this->uuid);
$this->assertSame($this->uuidString, $result);
}
public function testEncodeBinaryReturnsBinaryString(): void
{
$expected = hex2bin('123456781234abcdabef1234abcd4321');
$fields = Mockery::mock(FieldsInterface::class, [
'getBytes' => hex2bin('123456781234abcdabef1234abcd4321'),
]);
$this->uuid->method('getFields')->willReturn($fields);
$codec = new StringCodec($this->builder);
$result = $codec->encodeBinary($this->uuid);
$this->assertSame($expected, $result);
}
public function testDecodeUsesBuilderOnFields(): void
{
$fields = [
'time_low' => $this->fields->getTimeLow()->toString(),
'time_mid' => $this->fields->getTimeMid()->toString(),
'time_hi_and_version' => $this->fields->getTimeHiAndVersion()->toString(),
'clock_seq_hi_and_reserved' => $this->fields->getClockSeqHiAndReserved()->toString(),
'clock_seq_low' => $this->fields->getClockSeqLow()->toString(),
'node' => $this->fields->getNode()->toString(),
];
$bytes = hex2bin(implode('', $fields));
$string = 'uuid:12345678-1234-4bcd-abef-1234abcd4321';
$this->builder->expects($this->once())
->method('build')
->with($this->isInstanceOf(StringCodec::class), $bytes);
$codec = new StringCodec($this->builder);
$codec->decode($string);
}
public function testDecodeThrowsExceptionOnInvalidUuid(): void
{
$string = 'invalid-uuid';
$codec = new StringCodec($this->builder);
$this->expectException(InvalidArgumentException::class);
$codec->decode($string);
}
public function testDecodeReturnsUuidFromBuilder(): void
{
$string = 'uuid:12345678-1234-abcd-abef-1234abcd4321';
$this->builder->method('build')
->willReturn($this->uuid);
$codec = new StringCodec($this->builder);
$result = $codec->decode($string);
$this->assertSame($this->uuid, $result);
}
public function testDecodeBytesThrowsExceptionWhenBytesStringNotSixteenCharacters(): void
{
$string = '61';
$bytes = pack('H*', $string);
$codec = new StringCodec($this->builder);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('$bytes string should contain 16 characters.');
$codec->decodeBytes($bytes);
}
public function testDecodeBytesReturnsUuid(): void
{
$string = '123456781234abcdabef1234abcd4321';
$bytes = pack('H*', $string);
$codec = new StringCodec($this->builder);
$this->builder->method('build')
->willReturn($this->uuid);
$result = $codec->decodeBytes($bytes);
$this->assertSame($this->uuid, $result);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Codec/OrderedTimeCodecTest.php | tests/Codec/OrderedTimeCodecTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Codec;
use Mockery;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\DefaultUuidBuilder;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\OrderedTimeCodec;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Nonstandard\Fields as NonstandardFields;
use Ramsey\Uuid\Nonstandard\UuidBuilder;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\UuidInterface;
use function hex2bin;
use function pack;
use function serialize;
use function str_replace;
use function unserialize;
class OrderedTimeCodecTest extends TestCase
{
/**
* @var UuidBuilderInterface & MockObject
*/
private $builder;
/**
* @var UuidInterface & MockObject
*/
private $uuid;
/**
* @var Fields
*/
private $fields;
/**
* @var string
*/
private $uuidString = '58e0a7d7-eebc-11d8-9669-0800200c9a66';
/**
* @var string
*/
private $optimizedHex = '11d8eebc58e0a7d796690800200c9a66';
protected function setUp(): void
{
parent::setUp();
$this->builder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock();
$this->uuid = $this->getMockBuilder(UuidInterface::class)->getMock();
$this->fields = new Fields((string) hex2bin('58e0a7d7eebc11d896690800200c9a66'));
}
protected function tearDown(): void
{
parent::tearDown();
unset($this->builder, $this->uuid, $this->fields);
}
public function testEncodeUsesFieldsArray(): void
{
$this->uuid->expects($this->once())
->method('getFields')
->willReturn($this->fields);
$codec = new OrderedTimeCodec($this->builder);
$codec->encode($this->uuid);
}
public function testEncodeReturnsFormattedString(): void
{
$this->uuid->method('getFields')
->willReturn($this->fields);
$codec = new OrderedTimeCodec($this->builder);
$result = $codec->encode($this->uuid);
$this->assertSame($this->uuidString, $result);
}
public function testEncodeBinary(): void
{
$expected = hex2bin($this->optimizedHex);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$builder = new DefaultUuidBuilder($numberConverter, $timeConverter);
$codec = new OrderedTimeCodec($builder);
$factory = new UuidFactory();
$factory->setCodec($codec);
$uuid = $factory->fromString($this->uuidString);
$this->assertSame($expected, $codec->encodeBinary($uuid));
}
public function testDecodeBytesThrowsExceptionWhenBytesStringNotSixteenCharacters(): void
{
$string = '61';
$bytes = pack('H*', $string);
$codec = new OrderedTimeCodec($this->builder);
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('$bytes string should contain 16 characters.');
$codec->decodeBytes($bytes);
}
public function testDecodeReturnsUuidFromBuilder(): void
{
$string = 'uuid:58e0a7d7-eebc-11d8-9669-0800200c9a66';
$this->builder->method('build')
->willReturn($this->uuid);
$codec = new OrderedTimeCodec($this->builder);
$result = $codec->decode($string);
$this->assertSame($this->uuid, $result);
}
public function testDecodeBytesRearrangesFields(): void
{
$bytes = (string) hex2bin($this->optimizedHex);
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$builder = new DefaultUuidBuilder($numberConverter, $timeConverter);
$codec = new OrderedTimeCodec($builder);
$factory = new UuidFactory();
$factory->setCodec($codec);
$expectedUuid = $factory->fromString($this->uuidString);
$uuidReturned = $codec->decodeBytes($bytes);
$this->assertTrue($uuidReturned->equals($expectedUuid));
}
public function testEncodeBinaryThrowsExceptionForNonRfc4122Uuid(): void
{
$nonRfc4122Uuid = '58e0a7d7-eebc-11d8-d669-0800200c9a66';
$fields = new NonstandardFields((string) hex2bin(str_replace('-', '', $nonRfc4122Uuid)));
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$builder = new DefaultUuidBuilder($numberConverter, $timeConverter);
$codec = new OrderedTimeCodec($builder);
$uuid = Mockery::mock(UuidInterface::class, [
'getVariant' => 0,
'toString' => $nonRfc4122Uuid,
'getFields' => $fields,
]);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected version 1 (time-based) UUID');
$codec->encodeBinary($uuid);
}
public function testEncodeBinaryThrowsExceptionForNonTimeBasedUuid(): void
{
$nonTimeBasedUuid = '58e0a7d7-eebc-41d8-9669-0800200c9a66';
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$builder = new DefaultUuidBuilder($numberConverter, $timeConverter);
$codec = new OrderedTimeCodec($builder);
$factory = new UuidFactory();
$factory->setCodec($codec);
$uuid = $factory->fromString($nonTimeBasedUuid);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Expected version 1 (time-based) UUID');
$codec->encodeBinary($uuid);
}
public function testDecodeBytesThrowsExceptionsForNonRfc4122Uuid(): void
{
$nonRfc4122OptimizedHex = '11d8eebc58e0a7d716690800200c9a66';
$bytes = (string) hex2bin($nonRfc4122OptimizedHex);
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = new GenericTimeConverter($calculator);
$builder = new UuidBuilder($numberConverter, $timeConverter);
$codec = new OrderedTimeCodec($builder);
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage(
'Attempting to decode a non-time-based UUID using OrderedTimeCodec'
);
$codec->decodeBytes($bytes);
}
public function testDecodeBytesThrowsExceptionsForNonTimeBasedUuid(): void
{
$nonTimeBasedOptimizedHex = '41d8eebc58e0a7d796690800200c9a66';
$bytes = (string) hex2bin($nonTimeBasedOptimizedHex);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$builder = new DefaultUuidBuilder($numberConverter, $timeConverter);
$codec = new OrderedTimeCodec($builder);
$factory = new UuidFactory();
$factory->setCodec($codec);
$this->expectException(UnsupportedOperationException::class);
$this->expectExceptionMessage(
'Attempting to decode a non-time-based UUID using OrderedTimeCodec'
);
$codec->decodeBytes($bytes);
}
public function testSerializationDoesNotUseOrderedTimeCodec(): void
{
$expected = '9ec692cc-67c8-11eb-ae93-0242ac130002';
$codec = new OrderedTimeCodec(
(new UuidFactory())->getUuidBuilder()
);
$decoded = $codec->decode($expected);
$serialized = serialize($decoded);
/** @var UuidInterface $unserializedUuid */
$unserializedUuid = unserialize($serialized);
$expectedUuid = Uuid::fromString($expected);
$this->assertSame($expectedUuid->getVersion(), $unserializedUuid->getVersion());
$this->assertTrue($expectedUuid->equals($unserializedUuid));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Codec/GuidStringCodecTest.php | tests/Codec/GuidStringCodecTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Codec;
use Mockery;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\GuidStringCodec;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Guid\Fields;
use Ramsey\Uuid\Guid\Guid;
use Ramsey\Uuid\Guid\GuidBuilder;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\UuidInterface;
use function hex2bin;
use function pack;
class GuidStringCodecTest extends TestCase
{
/**
* @var UuidBuilderInterface & MockObject
*/
private $builder;
/**
* @var UuidInterface & MockObject
*/
private $uuid;
/**
* @var Fields
*/
private $fields;
protected function setUp(): void
{
parent::setUp();
$this->builder = $this->getMockBuilder(UuidBuilderInterface::class)->getMock();
$this->uuid = $this->getMockBuilder(UuidInterface::class)->getMock();
$this->fields = new Fields((string) hex2bin('785634123412cd4babef1234abcd4321'));
}
protected function tearDown(): void
{
parent::tearDown();
unset($this->builder, $this->fields, $this->uuid);
}
public function testEncodeUsesFieldsArray(): void
{
$this->uuid->expects($this->once())
->method('getFields')
->willReturn($this->fields);
$codec = new GuidStringCodec($this->builder);
$codec->encode($this->uuid);
}
public function testEncodeReturnsFormattedString(): void
{
$this->uuid->method('getFields')
->willReturn($this->fields);
$codec = new GuidStringCodec($this->builder);
$result = $codec->encode($this->uuid);
$this->assertSame('12345678-1234-4bcd-abef-1234abcd4321', $result);
}
public function testEncodeBinary(): void
{
$expectedBytes = (string) hex2bin('785634123412cd4babef1234abcd4321');
$fields = new Fields($expectedBytes);
$codec = new GuidStringCodec($this->builder);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$uuid = new Guid($fields, $numberConverter, $codec, $timeConverter);
$bytes = $codec->encodeBinary($uuid);
$this->assertSame($expectedBytes, $bytes);
}
public function testDecodeReturnsGuid(): void
{
$string = 'uuid:12345678-1234-4bcd-abef-1234abcd4321';
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeConverter = Mockery::mock(TimeConverterInterface::class);
$builder = new GuidBuilder($numberConverter, $timeConverter);
$codec = new GuidStringCodec($builder);
$guid = $codec->decode($string);
$this->assertInstanceOf(Guid::class, $guid);
$this->assertSame('12345678-1234-4bcd-abef-1234abcd4321', $guid->toString());
}
public function testDecodeReturnsUuidFromBuilder(): void
{
$string = 'uuid:78563412-3412-cd4b-abef-1234abcd4321';
$this->builder->method('build')
->willReturn($this->uuid);
$codec = new GuidStringCodec($this->builder);
$result = $codec->decode($string);
$this->assertSame($this->uuid, $result);
}
public function testDecodeBytesReturnsUuid(): void
{
$string = '1234567812344bcd4bef1234abcd4321';
$bytes = pack('H*', $string);
$codec = new GuidStringCodec($this->builder);
$this->builder->method('build')
->willReturn($this->uuid);
$result = $codec->decodeBytes($bytes);
$this->assertSame($this->uuid, $result);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Encoder/TimestampFirstCombCodecTest.php | tests/Encoder/TimestampFirstCombCodecTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Encoder;
use Mockery;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\TimestampFirstCombCodec;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\UuidInterface;
use function hex2bin;
use function implode;
class TimestampFirstCombCodecTest extends TestCase
{
/**
* @var CodecInterface
*/
private $codec;
/**
* @var MockObject & UuidBuilderInterface
*/
private $builderMock;
protected function setUp(): void
{
$this->builderMock = $this->getMockBuilder(UuidBuilderInterface::class)->getMock();
$this->codec = new TimestampFirstCombCodec($this->builderMock);
}
public function testEncoding(): void
{
$fields = new Fields((string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66'));
$uuidMock = Mockery::mock(UuidInterface::class, [
'getFields' => $fields,
]);
$encodedUuid = $this->codec->encode($uuidMock);
$this->assertSame('0800200c-9a66-11e1-9b21-ff6f8cb0c57d', $encodedUuid);
}
public function testBinaryEncoding(): void
{
$fields = new Fields((string) hex2bin('ff6f8cb0c57d11e19b210800200c9a66'));
$uuidMock = Mockery::mock(UuidInterface::class, [
'getFields' => $fields,
]);
$encodedUuid = $this->codec->encodeBinary($uuidMock);
$this->assertSame(hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'), $encodedUuid);
}
public function testDecoding(): void
{
$this->builderMock->expects($this->exactly(1))
->method('build')
->with(
$this->codec,
hex2bin(implode('', [
'time_low' => 'ff6f8cb0',
'time_mid' => 'c57d',
'time_hi_and_version' => '11e1',
'clock_seq_hi_and_reserved' => '9b',
'clock_seq_low' => '21',
'node' => '0800200c9a66',
]))
);
$this->codec->decode('0800200c-9a66-11e1-9b21-ff6f8cb0c57d');
}
public function testBinaryDecoding(): void
{
$this->builderMock->expects($this->exactly(1))
->method('build')
->with(
$this->codec,
hex2bin(implode('', [
'time_low' => 'ff6f8cb0',
'time_mid' => 'c57d',
'time_hi_and_version' => '11e1',
'clock_seq_hi_and_reserved' => '9b',
'clock_seq_low' => '21',
'node' => '0800200c9a66',
]))
);
$this->codec->decodeBytes((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Encoder/TimestampLastCombCodecTest.php | tests/Encoder/TimestampLastCombCodecTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Encoder;
use Mockery;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\TimestampLastCombCodec;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\UuidInterface;
use function hex2bin;
use function implode;
class TimestampLastCombCodecTest extends TestCase
{
/**
* @var CodecInterface
*/
private $codec;
/**
* @var MockObject & UuidBuilderInterface
*/
private $builderMock;
protected function setUp(): void
{
$this->builderMock = $this->getMockBuilder(UuidBuilderInterface::class)->getMock();
$this->codec = new TimestampLastCombCodec($this->builderMock);
}
public function testEncoding(): void
{
$fields = new Fields((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'));
$uuidMock = Mockery::mock(UuidInterface::class, [
'getFields' => $fields,
]);
$encodedUuid = $this->codec->encode($uuidMock);
$this->assertSame('0800200c-9a66-11e1-9b21-ff6f8cb0c57d', $encodedUuid);
}
public function testBinaryEncoding(): void
{
$fields = Mockery::mock(FieldsInterface::class, [
'getBytes' => hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'),
]);
/** @var MockObject & UuidInterface $uuidMock */
$uuidMock = $this->getMockBuilder(UuidInterface::class)->getMock();
$uuidMock->expects($this->any())->method('getFields')->willReturn($fields);
$encodedUuid = $this->codec->encodeBinary($uuidMock);
$this->assertSame(hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'), $encodedUuid);
}
public function testDecoding(): void
{
$this->builderMock->expects($this->exactly(1))
->method('build')
->with(
$this->codec,
hex2bin(implode('', [
'time_low' => '0800200c',
'time_mid' => '9a66',
'time_hi_and_version' => '11e1',
'clock_seq_hi_and_reserved' => '9b',
'clock_seq_low' => '21',
'node' => 'ff6f8cb0c57d',
]))
);
$this->codec->decode('0800200c-9a66-11e1-9b21-ff6f8cb0c57d');
}
public function testBinaryDecoding(): void
{
$this->builderMock->expects($this->exactly(1))
->method('build')
->with(
$this->codec,
hex2bin(implode('', [
'time_low' => '0800200c',
'time_mid' => '9a66',
'time_hi_and_version' => '11e1',
'clock_seq_hi_and_reserved' => '9b',
'clock_seq_low' => '21',
'node' => 'ff6f8cb0c57d',
]))
);
$this->codec->decodeBytes((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Validator/GenericValidatorTest.php | tests/Validator/GenericValidatorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Validator;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Validator\GenericValidator;
use function array_merge;
use function strtoupper;
class GenericValidatorTest extends TestCase
{
/**
* @dataProvider provideValuesForValidation
*/
public function testValidate(string $value, bool $expected): void
{
$variations = [];
$variations[] = $value;
$variations[] = 'urn:uuid:' . $value;
$variations[] = '{' . $value . '}';
foreach ($variations as $variation) {
$variations[] = strtoupper($variation);
}
$validator = new GenericValidator();
foreach ($variations as $variation) {
$this->assertSame($expected, $validator->validate($variation));
}
}
/**
* @return array<array{value: string, expected: bool}>
*/
public function provideValuesForValidation(): array
{
$hexMutations = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f'];
$testValues = [];
foreach ($hexMutations as $version) {
foreach ($hexMutations as $variant) {
$testValues[] = [
'value' => "ff6f8cb0-c57d-{$version}1e1-{$variant}b21-0800200c9a66",
'expected' => true,
];
}
}
return array_merge($testValues, [
[
'value' => 'zf6f8cb0-c57d-11e1-9b21-0800200c9a66',
'expected' => false,
],
[
'value' => '3f6f8cb0-c57d-11e1-9b21-0800200c9a6',
'expected' => false,
],
[
'value' => 'af6f8cb-c57d-11e1-9b21-0800200c9a66',
'expected' => false,
],
[
'value' => 'af6f8cb0c57d11e19b210800200c9a66',
'expected' => false,
],
[
'value' => 'ff6f8cb0-c57da-51e1-9b21-0800200c9a66',
'expected' => false,
],
[
'value' => "ff6f8cb0-c57d-11e1-1b21-0800200c9a66\n",
'expected' => false,
],
[
'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66",
'expected' => false,
],
[
'value' => "\nff6f8cb0-c57d-11e1-1b21-0800200c9a66\n",
'expected' => false,
],
]);
}
public function testGetPattern(): void
{
$expectedPattern = '\A[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}\z';
$validator = new GenericValidator();
$this->assertSame($expectedPattern, $validator->getPattern());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Node/SystemNodeProviderTest.php | tests/Provider/Node/SystemNodeProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Node;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Exception\NodeException;
use Ramsey\Uuid\Provider\Node\SystemNodeProvider;
use Ramsey\Uuid\Test\TestCase;
use phpmock\spy\Spy;
use function array_shift;
use function array_walk;
use function gettype;
use function is_array;
use function strlen;
use function vsprintf;
use const GLOB_NOSORT;
/**
* Tests for the SystemNodeProvider class
*
* The class under test make use of various native functions who's output is
* dictated by which environment PHP runs on. Instead of having to run these
* tests on each of these environments, the related functions are mocked. The
* following functions are concerned:
*
* - glob
* - constant
* - passthru
* - file_get_contents
* - ini_get
*
* On Linux systems `glob` would normally provide one or more paths were mac
* address can be retrieved (using `file_get_contents`). On non-linux systems,
* or when the `glob` fails, `passthru` is used to read the mac address from the
* command for the relevant environment as provided by `constant('PHP_OS')`.
*
* Please note that, in order to have robust tests, (the output of) these
* functions should ALWAYS be mocked and the amount of times each function
* should be run should ALWAYS be specified.
*
* This will make the tests more verbose but also more bullet-proof.
*/
class SystemNodeProviderTest extends TestCase
{
private const MOCK_GLOB = 'glob';
private const MOCK_CONSTANT = 'constant';
private const MOCK_PASSTHRU = 'passthru';
private const MOCK_FILE_GET_CONTENTS = 'file_get_contents';
private const MOCK_INI_GET = 'ini_get';
private const MOCK_IS_READABLE = 'is_readable';
private const PROVIDER_NAMESPACE = 'Ramsey\\Uuid\\Provider\\Node';
/**
* @var Spy[]
*/
private $functionProxies = [];
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideValidNetStatOutput
*/
public function testGetNodeReturnsSystemNodeFromMacAddress(string $netstatOutput, string $expected): void
{
/* Arrange mocks for native functions */
$this->arrangeMockFunctions(
null,
null,
function () use ($netstatOutput): void {
echo $netstatOutput;
},
'NOT LINUX',
'nothing disabled'
);
/* Act upon the system under test */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert the result match expectations */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertSame($expected, $node->toString());
$message = vsprintf(
'Node should be a hexadecimal string of 12 characters. Actual node: %s (length: %s)',
[$node->toString(), strlen($node->toString()),]
);
$this->assertMatchesRegularExpression('/^[A-Fa-f0-9]{12}$/', $node->toString(), $message);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideInvalidNetStatOutput
*/
public function testGetNodeShouldNotReturnsSystemNodeForInvalidMacAddress(string $netstatOutput): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function () use ($netstatOutput): void {
echo $netstatOutput;
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$exception = null;
$provider = new SystemNodeProvider();
try {
$provider->getNode();
} catch (NodeException $exception) {
// do nothing
}
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertInstanceOf(NodeException::class, $exception);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideNotationalFormats
*/
public function testGetNodeReturnsNodeStrippedOfNotationalFormatting(string $formatted, string $expected): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function () use ($formatted): void {
echo "\n{$formatted}\n";
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertSame($expected, $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideInvalidNotationalFormats
*/
public function testGetNodeDoesNotAcceptIncorrectNotationalFormatting(string $formatted): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function () use ($formatted): void {
echo "\n{$formatted}\n";
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$exception = null;
$provider = new SystemNodeProvider();
try {
$provider->getNode();
} catch (NodeException $exception) {
// do nothing
}
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertInstanceOf(NodeException::class, $exception);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeReturnsFirstMacAddressFound(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function (): void {
echo "\nAA-BB-CC-DD-EE-FF\n00-11-22-33-44-55\nFF-11-EE-22-DD-33\n";
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertSame('aabbccddeeff', $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeReturnsFalseWhenNodeIsNotFound(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function (): void {
echo 'some string that does not match the mac address';
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$exception = null;
$provider = new SystemNodeProvider();
try {
$provider->getNode();
} catch (NodeException $exception) {
// do nothing
}
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertInstanceOf(NodeException::class, $exception);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeWillNotExecuteSystemCallIfFailedFirstTime(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function (): void {
echo 'some string that does not match the mac address';
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$exception1 = null;
$exception2 = null;
$provider = new SystemNodeProvider();
try {
$provider->getNode();
} catch (NodeException $exception1) {
// do nothing
}
try {
$provider->getNode();
} catch (NodeException $exception2) {
// do nothing
}
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertInstanceOf(NodeException::class, $exception1);
$this->assertInstanceOf(NodeException::class, $exception2);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideCommandPerOs
*/
public function testGetNodeGetsNetworkInterfaceConfig(string $os, string $command): void
{
/* Arrange */
$this->arrangeMockFunctions(
'whatever',
['mock address path'],
'whatever',
$os,
'nothing disabled',
true
);
/* Act */
$exception = null;
$provider = new SystemNodeProvider();
try {
$provider->getNode();
} catch (NodeException $exception) {
// do nothing
}
/* Assert */
$globBodyAssert = null;
$fileGetContentsAssert = null;
$isReadableAssert = null;
if ($os === 'Linux') {
$globBodyAssert = [['/sys/class/net/*/address', GLOB_NOSORT]];
$fileGetContentsAssert = ['mock address path'];
$isReadableAssert = $fileGetContentsAssert;
}
$this->assertMockFunctions(
$fileGetContentsAssert,
$globBodyAssert,
[$command],
['PHP_OS'],
['disable_functions'],
$isReadableAssert
);
$this->assertInstanceOf(NodeException::class, $exception);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeReturnsSameNodeUponSubsequentCalls(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function (): void {
echo "\nAA-BB-CC-DD-EE-FF\n";
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
$node2 = $provider->getNode();
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertSame($node->toString(), $node2->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testSubsequentCallsToGetNodeDoNotRecallIfconfig(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
function (): void {
echo "\nAA-BB-CC-DD-EE-FF\n";
},
'NOT LINUX',
'nothing disabled'
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
$node2 = $provider->getNode();
/* Assert */
$this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']);
$this->assertSame($node->toString(), $node2->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideCommandPerOs
*/
public function testCallGetsysfsOnLinux(string $os, string $command): void
{
/* Arrange */
$this->arrangeMockFunctions(
function () {
/** @var non-empty-list<string> $macs */
static $macs = ["00:00:00:00:00:00\n", "01:02:03:04:05:06\n"];
return array_shift($macs);
},
['mock address path 1', 'mock address path 2'],
function (): void {
echo "\n01-02-03-04-05-06\n";
},
$os,
'nothing disabled',
true
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert */
$fileGetContentsAssert = null;
$globBodyAssert = null;
$passthruBodyAssert = [$command];
$constantBodyAssert = ['PHP_OS'];
$iniGetDisableFunctionsAssert = ['disable_functions'];
$isReadableAssert = null;
if ($os === 'Linux') {
$fileGetContentsAssert = [['mock address path 1'], ['mock address path 2']];
$globBodyAssert = [['/sys/class/net/*/address', GLOB_NOSORT]];
$passthruBodyAssert = null;
$constantBodyAssert = ['PHP_OS'];
$iniGetDisableFunctionsAssert = null;
$isReadableAssert = $fileGetContentsAssert;
}
$this->assertMockFunctions(
$fileGetContentsAssert,
$globBodyAssert,
$passthruBodyAssert,
$constantBodyAssert,
$iniGetDisableFunctionsAssert,
$isReadableAssert
);
$this->assertSame('010203040506', $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testCallGetsysfsOnLinuxWhenGlobReturnsFalse(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
false,
function (): void {
echo "\n01-02-03-04-05-06\n";
},
'Linux',
'nothing disabled'
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert */
$this->assertMockFunctions(
null,
[['/sys/class/net/*/address', GLOB_NOSORT]],
['netstat -ie 2>&1'],
['PHP_OS'],
['disable_functions']
);
$this->assertSame('010203040506', $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testCallGetsysfsOnLinuxWhenGlobReturnsEmptyArray(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
[],
function (): void {
echo "\n01-02-03-04-05-06\n";
},
'Linux',
'nothing disabled'
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert */
$this->assertMockFunctions(
null,
[['/sys/class/net/*/address', GLOB_NOSORT]],
['netstat -ie 2>&1'],
['PHP_OS'],
['disable_functions']
);
$this->assertSame('010203040506', $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testCallGetsysfsOnLinuxWhenGlobFilesAreNotReadable(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
['mock address path 1', 'mock address path 2'],
function (): void {
echo "\n01-02-03-04-05-06\n";
},
'Linux',
'nothing disabled',
false
);
/* Act */
$provider = new SystemNodeProvider();
$node = $provider->getNode();
/* Assert */
$this->assertMockFunctions(
null,
[['/sys/class/net/*/address', GLOB_NOSORT]],
['netstat -ie 2>&1'],
['PHP_OS'],
['disable_functions'],
['mock address path 1', 'mock address path 2']
);
$this->assertSame('010203040506', $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeReturnsFalseWhenPassthruIsDisabled(): void
{
/* Arrange */
$this->arrangeMockFunctions(
null,
null,
null,
'NOT LINUX',
'PASSTHRU,some_other_function'
);
/* Act */
$exception = null;
$provider = new SystemNodeProvider();
try {
$provider->getNode();
} catch (NodeException $exception) {
// do nothing
}
/* Assert */
$this->assertMockFunctions(
null,
null,
null,
['PHP_OS'],
['disable_functions']
);
$this->assertInstanceOf(NodeException::class, $exception);
}
/**
* Replaces the return value for functions with the given value or callback.
*
* @param callback|mixed|null $fileGetContentsBody
* @param callback|mixed|null $globBody
* @param callback|mixed|null $passthruBody
* @param callback|mixed|null $constantBody
* @param callback|mixed|null $iniGetDisableFunctionsBody
* @param callback|mixed|null $isReadableBody
*/
private function arrangeMockFunctions(
$fileGetContentsBody,
$globBody,
$passthruBody,
$constantBody,
$iniGetDisableFunctionsBody,
$isReadableBody = true
): void {
$mockFunction = [
self::MOCK_FILE_GET_CONTENTS => $fileGetContentsBody,
self::MOCK_GLOB => $globBody,
self::MOCK_PASSTHRU => $passthruBody,
self::MOCK_CONSTANT => $constantBody,
self::MOCK_INI_GET => $iniGetDisableFunctionsBody,
self::MOCK_IS_READABLE => $isReadableBody,
];
array_walk($mockFunction, function ($body, $key): void {
if (!is_callable($body)) {
$body = function () use ($body) {
return $body;
};
}
$spy = new Spy(self::PROVIDER_NAMESPACE, $key, $body);
$spy->enable();
$this->functionProxies[$key] = $spy;
});
}
/**
* Verifies that each function was called exactly once for each assert given.
*
* Provide a NULL to assert a function is never called.
*
* @param array<int, string>|array<int, array<int,string>>|null $fileGetContentsAssert
* @param array<int, array<int, int|string>>|null $globBodyAssert
* @param array<int, string>|array<int, array<int,string>>|null $passthruBodyAssert
* @param array<int, string>|array<int, array<int,string>>|null $constantBodyAssert
* @param array<int, string>|array<int, array<int,string>>|null $iniGetDisableFunctionsAssert
* @param array<int, string>|array<int, array<int,string>>|null $isReadableAssert
*/
private function assertMockFunctions(
?array $fileGetContentsAssert,
?array $globBodyAssert,
?array $passthruBodyAssert,
?array $constantBodyAssert,
?array $iniGetDisableFunctionsAssert,
?array $isReadableAssert = null
): void {
$mockFunctionAsserts = [
self::MOCK_FILE_GET_CONTENTS => $fileGetContentsAssert,
self::MOCK_GLOB => $globBodyAssert,
self::MOCK_PASSTHRU => $passthruBodyAssert,
self::MOCK_CONSTANT => $constantBodyAssert,
self::MOCK_INI_GET => $iniGetDisableFunctionsAssert,
self::MOCK_IS_READABLE => $isReadableAssert,
];
array_walk($mockFunctionAsserts, function (mixed $asserts, string $key): void {
if ($asserts === null) {
// Assert the function was never invoked.
$this->assertEmpty($this->functionProxies[$key]->getInvocations());
} elseif (is_array($asserts)) { /** @phpstan-ignore function.alreadyNarrowedType */
// Assert there was at least one invocation for this function.
$this->assertNotEmpty($this->functionProxies[$key]->getInvocations());
$invokedArgs = [];
foreach ($this->functionProxies[$key]->getInvocations() as $invocation) {
$invokedArgs[] = $invocation->getArguments();
}
foreach ($asserts as $assert) {
// Assert these args were used to invoke the function.
$assert = is_array($assert) ? $assert : [$assert];
$this->assertContains($assert, $invokedArgs);
}
} else {
$error = vsprintf(
'Given parameter for %s must be an array or NULL, "%s" given.',
[$key, gettype($asserts)]
);
throw new InvalidArgumentException($error);
}
});
}
/**
* Provides the command that should be executed per supported OS
*
* @return array<string, array{0: non-empty-string, 1: non-empty-string}>
*/
public function provideCommandPerOs(): array
{
return [
'windows' => ['Windows', 'ipconfig /all 2>&1'],
'mac' => ['Darwhat', 'ifconfig 2>&1'],
'linux' => ['Linux', 'netstat -ie 2>&1'],
'freebsd' => ['FreeBSD', 'netstat -i -f link 2>&1'],
'anything_else' => ['someotherxyz', 'netstat -ie 2>&1'],
'Linux when `glob` fails' => ['LIN', 'netstat -ie 2>&1'],
];
}
/**
* Values that are NOT parsed to a mac address by the class under test
*
* @return array<string, array{0: non-empty-string}>
*/
public function provideInvalidNetStatOutput(): array
{
return [
'Not an octal value' => [
"The program 'netstat' is currently not installed. " .
"You can install it by typing:\nsudo apt install net-tools\n",
],
'One character too short' => ["\nA-BB-CC-DD-EE-FF\n"],
'One tuple too short' => ["\nBB-CC-DD-EE-FF\n"],
'With colon, with linebreak, without space' => ["\n:AA-BB-CC-DD-EE-FF\n"],
'With colon, without linebreak, with space' => [' : AA-BB-CC-DD-EE-FF'],
'With colon, without linebreak, without space' => [':AA-BB-CC-DD-EE-FF'],
'Without colon, without linebreak, without space' => ['AA-BB-CC-DD-EE-FF'],
'Without leading linebreak' => ["AA-BB-CC-DD-EE-FF\n"],
'Without leading whitespace' => ['AA-BB-CC-DD-EE-FF '],
'Without trailing linebreak' => ["\nAA-BB-CC-DD-EE-FF"],
'Without trailing whitespace' => [' AA-BB-CC-DD-EE-FF'],
'All zero MAC address' => ['00-00-00-00-00-00'],
];
}
/**
* Provides notations that the class under test should NOT attempt to strip
*
* @return array<array{0: non-empty-string}>
*/
public function provideInvalidNotationalFormats(): array
{
return [
['01:23-45-67-89-ab'],
['01:23:45-67-89-ab'],
['01:23:45:67-89-ab'],
['01:23:45:67:89-ab'],
['01-23:45:67:89:ab'],
['01-23-45:67:89:ab'],
['01-23-45-67:89:ab'],
['01-23-45-67-89:ab'],
['00:00:00:00:00:00'],
];
}
/**
* Provides mac addresses that the class under test should strip notational format from
*
* @return array<array{0: non-empty-string, 1: non-empty-string}>
*/
public function provideNotationalFormats(): array
{
return [
['01-23-45-67-89-ab', '0123456789ab'],
['01:23:45:67:89:ab', '0123456789ab'],
];
}
/**
* Values that are parsed to a mac address by the class under test
*
* @return array<string, array{0: non-empty-string, 1: non-empty-string}>
*/
public function provideValidNetStatOutput(): array
{
return [
/* Full output of related command */
'Full output - Linux' => [
<<<'TXT'
Kernel Interface table
docker0 Link encap:Ethernet HWaddr 01:23:45:67:89:ab
inet addr:172.17.0.1 Bcast:0.0.0.0 Mask:255.255.0.0
UP BROADCAST MULTICAST MTU:1500 Metric:1
RX packets:0 errors:0 dropped:0 overruns:0 frame:0
TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:0 (0.0 B) TX bytes:0 (0.0 B)
enp3s0 Link encap:Ethernet HWaddr fe:dc:ba:98:76:54
inet addr:10.0.0.1 Bcast:10.0.0.255 Mask:255.255.255.0
inet6 addr: ffee::ddcc:bbaa:9988:7766/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:943077 errors:0 dropped:0 overruns:0 frame:0
TX packets:2168039 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:748596414 (748.5 MB) TX bytes:2930448282 (2.9 GB)
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:8302 errors:0 dropped:0 overruns:0 frame:0
TX packets:8302 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:1094983 (1.0 MB) TX bytes:1094983 (1.0 MB)
TXT,
'0123456789ab',
],
'Full output - MacOS' => [
<<<'TXT'
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
options=1203<RXCSUM,TXCSUM,TXSTATUS,SW_TIMESTAMP>
inet 127.0.0.1 netmask 0xff000000
inet6 ::1 prefixlen 128
inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
nd6 options=201<PERFORMNUD,DAD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
EHC29: flags=0<> mtu 0
XHC20: flags=0<> mtu 0
EHC26: flags=0<> mtu 0
aa0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=10b<RXCSUM,TXCSUM,VLAN_HWTAGGING,AV>
ether 00:00:00:00:00:00
status: active
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
options=10b<RXCSUM,TXCSUM,VLAN_HWTAGGING,AV>
ether 10:dd:b1:b4:e4:8e
inet6 fe80::c70:76f5:aa1:5db1%en0 prefixlen 64 secured scopeid 0x7
inet 10.53.8.112 netmask 0xfffffc00 broadcast 10.53.11.255
nd6 options=201<PERFORMNUD,DAD>
media: autoselect (1000baseT <full-duplex>)
status: active
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
ether ec:35:86:38:c8:c2
inet6 fe80::aa:d44f:5f5f:7fd4%en1 prefixlen 64 secured scopeid 0x8
inet 10.53.17.196 netmask 0xfffffc00 broadcast 10.53.19.255
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
ether 0e:35:86:38:c8:c2
media: autoselect
status: inactive
awdl0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1484
ether ea:ab:ae:25:f5:d0
inet6 fe80::e8ab:aeff:fe25:f5d0%awdl0 prefixlen 64 scopeid 0xa
nd6 options=201<PERFORMNUD,DAD>
media: autoselect
status: active
en2: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 32:00:18:9b:dc:60
media: autoselect <full-duplex>
status: inactive
en3: flags=8963<UP,BROADCAST,SMART,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
options=60<TSO4,TSO6>
ether 32:00:18:9b:dc:61
media: autoselect <full-duplex>
status: inactive
bridge0: flags=8822<BROADCAST,SMART,SIMPLEX,MULTICAST> mtu 1500
options=63<RXCSUM,TXCSUM,TSO4,TSO6>
ether 32:00:18:9b:dc:60
Configuration:
id 0:0:0:0:0:0 priority 0 hellotime 0 fwddelay 0
maxage 0 holdcnt 0 proto stp maxaddr 100 timeout 1200
root id 0:0:0:0:0:0 priority 0 ifcost 0 port 0
ipfilter disabled flags 0x2
member: en2 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 11 priority 0 path cost 0
member: en3 flags=3<LEARNING,DISCOVER>
ifmaxaddr 0 port 12 priority 0 path cost 0
media: <unknown type>
status: inactive
utun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 2000
options=6403<RXCSUM,TXCSUM,CHANNEL_IO,PARTIAL_CSUM,ZEROINVERT_CSUM>
inet6 fe80::57c6:d692:9d41:d28f%utun0 prefixlen 64 scopeid 0xe
nd6 options=201<PERFORMNUD,DAD>
TXT,
'10ddb1b4e48e',
],
'Full output - Window' => [
<<<'TXT'
Windows IP Configuration
Host Name . . . . . . . . . . . . : MSEDGEWIN10
Primary Dns Suffix . . . . . . . :
Node Type . . . . . . . . . . . . : Hybrid
IP Routing Enabled. . . . . . . . : No
WINS Proxy Enabled. . . . . . . . : No
DNS Suffix Search List. . . . . . : network.lan
Some kind of adapter:
Connection-specific DNS Suffix . : network.foo
Description . . . . . . . . . . . : Some Adapter
Physical Address. . . . . . . . . : 00-00-00-00-00-00
Ethernet adapter Ethernet:
Connection-specific DNS Suffix . : network.lan
Description . . . . . . . . . . . : Intel(R) PRO/1000 MT Desktop Adapter
Physical Address. . . . . . . . . : 08-00-27-B8-42-C6
DHCP Enabled. . . . . . . . . . . : Yes
Autoconfiguration Enabled . . . . : Yes
Link-local IPv6 Address . . . . . : fe80::606a:ae33:7ce1:b5e9%3(Preferred)
IPv4 Address. . . . . . . . . . . : 10.0.2.15(Preferred)
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Lease Obtained. . . . . . . . . . : Tuesday, January 30, 2018 11:25:31 PM
Lease Expires . . . . . . . . . . : Wednesday, January 31, 2018 11:25:27 PM
Default Gateway . . . . . . . . . : 10.0.2.2
DHCP Server . . . . . . . . . . . : 10.0.2.2
DHCPv6 IAID . . . . . . . . . . . : 34078759
DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-21-40-72-3F-08-00-27-B8-42-C6
DNS Servers . . . . . . . . . . . : 10.0.2.3
NetBIOS over Tcpip. . . . . . . . : Enabled
Tunnel adapter isatap.network.lan:
Media State . . . . . . . . . . . : Media disconnected
Connection-specific DNS Suffix . : network.lan
Description . . . . . . . . . . . : Microsoft ISATAP Adapter
Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
DHCP Enabled. . . . . . . . . . . : No
Autoconfiguration Enabled . . . . : Yes
TXT,
'080027b842c6',
],
'Full output - FreeBSD' => [
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | true |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Node/RandomNodeProviderTest.php | tests/Provider/Node/RandomNodeProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Node;
use Exception;
use Ramsey\Uuid\Exception\RandomSourceException;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Test\TestCase;
use phpmock\mockery\PHPMockery;
use function bin2hex;
use function hex2bin;
use function hexdec;
use function sprintf;
use function substr;
class RandomNodeProviderTest extends TestCase
{
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeUsesRandomBytes(): void
{
$bytes = hex2bin('38a675685d50');
$expectedNode = '39a675685d50';
PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes')
->once()
->with(6)
->andReturn($bytes);
$provider = new RandomNodeProvider();
$node = $provider->getNode();
$this->assertSame($expectedNode, $node->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeAlreadyHasMulticastBit(): void
{
$bytesHex = '4161a1ff5d50';
$bytes = hex2bin($bytesHex);
// We expect the same hex value for the node.
$expectedNode = $bytesHex;
PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes')
->once()
->with(6)
->andReturn($bytes);
$provider = new RandomNodeProvider();
$this->assertSame($expectedNode, $provider->getNode()->toString());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeSetsMulticastBitForLowNodeValue(): void
{
$bytes = hex2bin('100000000001');
$expectedNode = '110000000001';
PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes')
->once()
->with(6)
->andReturn($bytes);
$provider = new RandomNodeProvider();
$this->assertSame($expectedNode, $provider->getNode()->toString());
}
public function testGetNodeAlwaysSetsMulticastBit(): void
{
$provider = new RandomNodeProvider();
$nodeHex = $provider->getNode();
// Convert what we got into bytes so that we can mask out everything
// except the multicast bit. If the multicast bit doesn't exist, this
// test will fail appropriately.
$nodeBytes = (string) hex2bin((string) $nodeHex);
// Split the node bytes for math on 32-bit systems.
$nodeMsb = substr($nodeBytes, 0, 3);
$nodeLsb = substr($nodeBytes, 3);
// Only set bits that match the mask so we can see that the multicast
// bit is always set.
$nodeMsb = sprintf('%06x', hexdec(bin2hex($nodeMsb)) & 0x010000);
$nodeLsb = sprintf('%06x', hexdec(bin2hex($nodeLsb)) & 0x000000);
// Recombine the node bytes.
$node = $nodeMsb . $nodeLsb;
$this->assertSame('010000000000', $node);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetNodeThrowsExceptionWhenExceptionThrownByRandombytes(): void
{
PHPMockery::mock('Ramsey\Uuid\Provider\Node', 'random_bytes')
->once()
->andThrow(new Exception('Could not gather sufficient random data'));
$provider = new RandomNodeProvider();
$this->expectException(RandomSourceException::class);
$this->expectExceptionMessage('Could not gather sufficient random data');
$provider->getNode();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Node/FallbackNodeProviderTest.php | tests/Provider/Node/FallbackNodeProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Node;
use Ramsey\Uuid\Exception\NodeException;
use Ramsey\Uuid\Provider\Node\FallbackNodeProvider;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Provider\Node\StaticNodeProvider;
use Ramsey\Uuid\Provider\Node\SystemNodeProvider;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
class FallbackNodeProviderTest extends TestCase
{
public function testGetNodeCallsGetNodeOnEachProviderUntilNodeFound(): void
{
$providerWithNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$providerWithNode->expects($this->once())
->method('getNode')
->willReturn(new Hexadecimal('57764a07f756'));
$providerWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$providerWithoutNode->expects($this->once())
->method('getNode')
->willThrowException(new NodeException());
$provider = new FallbackNodeProvider([$providerWithoutNode, $providerWithNode]);
$provider->getNode();
}
public function testGetNodeReturnsNodeFromFirstProviderWithNode(): void
{
$providerWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$providerWithoutNode->expects($this->once())
->method('getNode')
->willThrowException(new NodeException());
$providerWithNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$providerWithNode->expects($this->once())
->method('getNode')
->willReturn(new Hexadecimal('57764a07f756'));
$anotherProviderWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$anotherProviderWithoutNode->expects($this->never())
->method('getNode');
$provider = new FallbackNodeProvider([$providerWithoutNode, $providerWithNode, $anotherProviderWithoutNode]);
$node = $provider->getNode();
$this->assertSame('57764a07f756', $node->toString());
}
public function testGetNodeThrowsExceptionWhenNoNodesFound(): void
{
$providerWithoutNode = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$providerWithoutNode->method('getNode')
->willThrowException(new NodeException());
$provider = new FallbackNodeProvider([$providerWithoutNode]);
$this->expectException(NodeException::class);
$this->expectExceptionMessage(
'Unable to find a suitable node provider'
);
$provider->getNode();
}
public function testSerializationOfNodeProviderCollection(): void
{
$staticNodeProvider = new StaticNodeProvider(new Hexadecimal('aabbccddeeff'));
$randomNodeProvider = new RandomNodeProvider();
$systemNodeProvider = new SystemNodeProvider();
/** @var list<NodeProviderInterface> $unserializedNodeProviderCollection */
$unserializedNodeProviderCollection = unserialize(serialize([
$staticNodeProvider,
$randomNodeProvider,
$systemNodeProvider,
]));
foreach ($unserializedNodeProviderCollection as $nodeProvider) {
$this->assertInstanceOf(NodeProviderInterface::class, $nodeProvider);
}
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Node/StaticNodeProviderTest.php | tests/Provider/Node/StaticNodeProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Node;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Provider\Node\StaticNodeProvider;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
class StaticNodeProviderTest extends TestCase
{
/**
* @param non-empty-string $expectedNode
*
* @dataProvider provideNodeForTest
*/
public function testStaticNode(Hexadecimal $node, string $expectedNode): void
{
$staticNode = new StaticNodeProvider($node);
$this->assertSame($expectedNode, $staticNode->getNode()->toString());
}
/**
* @return array<array{node: Hexadecimal, expectedNode: non-empty-string}>
*/
public function provideNodeForTest(): array
{
return [
[
'node' => new Hexadecimal('0'),
'expectedNode' => '010000000000',
],
[
'node' => new Hexadecimal('1'),
'expectedNode' => '010000000001',
],
[
'node' => new Hexadecimal('f2ffffffffff'),
'expectedNode' => 'f3ffffffffff',
],
[
'node' => new Hexadecimal('ffffffffffff'),
'expectedNode' => 'ffffffffffff',
],
];
}
public function testStaticNodeThrowsExceptionForTooLongNode(): void
{
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Static node value cannot be greater than 12 hexadecimal characters'
);
new StaticNodeProvider(new Hexadecimal('1000000000000'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Time/SystemTimeProviderTest.php | tests/Provider/Time/SystemTimeProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Time;
use Ramsey\Uuid\Provider\Time\SystemTimeProvider;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Time;
class SystemTimeProviderTest extends TestCase
{
public function testGetTimeUses(): void
{
$provider = new SystemTimeProvider();
$time = $provider->getTime();
/** @phpstan-ignore method.alreadyNarrowedType */
$this->assertInstanceOf(Time::class, $time);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Time/FixedTimeProviderTest.php | tests/Provider/Time/FixedTimeProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Time;
use Ramsey\Uuid\Provider\Time\FixedTimeProvider;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Time;
class FixedTimeProviderTest extends TestCase
{
public function testGetTimeReturnsTime(): void
{
$time = new Time(1458844556, 200997);
$provider = new FixedTimeProvider($time);
$this->assertSame($time, $provider->getTime());
}
public function testGetTimeReturnsTimeAfterChange(): void
{
$time = new Time(1458844556, 200997);
$provider = new FixedTimeProvider($time);
$this->assertSame('1458844556', $provider->getTime()->getSeconds()->toString());
$this->assertSame('200997', $provider->getTime()->getMicroseconds()->toString());
$provider->setSec(1050804050);
$this->assertSame('1050804050', $provider->getTime()->getSeconds()->toString());
$this->assertSame('200997', $provider->getTime()->getMicroseconds()->toString());
$provider->setUsec(30192);
$this->assertSame('1050804050', $provider->getTime()->getSeconds()->toString());
$this->assertSame('30192', $provider->getTime()->getMicroseconds()->toString());
$this->assertNotSame($time, $provider->getTime());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Provider/Dce/SystemDceSecurityProviderTest.php | tests/Provider/Dce/SystemDceSecurityProviderTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Provider\Dce;
use Mockery;
use Ramsey\Uuid\Exception\DceSecurityException;
use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider;
use Ramsey\Uuid\Test\TestCase;
use phpmock\mockery\PHPMockery;
use function array_merge;
class SystemDceSecurityProviderTest extends TestCase
{
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetUidThrowsExceptionIfShellExecDisabled(): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('foo bar shell_exec baz');
$provider = new SystemDceSecurityProvider();
// Test that we catch the exception multiple times, but the ini_get()
// function is called only once.
$caughtException = 0;
for ($i = 1; $i <= 5; $i++) {
try {
$provider->getUid();
} catch (DceSecurityException $e) {
$caughtException++;
$this->assertSame(
'Unable to get a user identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider',
$e->getMessage()
);
}
}
$this->assertSame(5, $caughtException);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetUidForPosixThrowsExceptionIfShellExecReturnsNull(): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Linux');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('id -u')->once()->andReturnNull();
$provider = new SystemDceSecurityProvider();
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Unable to get a user identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider'
);
$provider->getUid();
}
/**
* @param mixed $value
*
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideWindowsBadValues
*/
public function testGetUidForWindowsThrowsExceptionIfShellExecForWhoAmIReturnsBadValues($value): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Windows_NT');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('whoami /user /fo csv /nh')->once()->andReturn($value);
$provider = new SystemDceSecurityProvider();
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Unable to get a user identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider'
);
$provider->getUid();
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideWindowsGoodWhoAmIValues
*/
public function testGetUidForWindowsWhenShellExecForWhoAmIReturnsGoodValues(
string $value,
string $expectedId
): void {
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Windows_NT');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('whoami /user /fo csv /nh')->once()->andReturn($value);
$provider = new SystemDceSecurityProvider();
$uid = $provider->getUid();
$this->assertSame($expectedId, $uid->toString());
$this->assertSame($uid, $provider->getUid());
}
/**
* @return array<array{value: non-empty-string, expectedId: non-empty-string}>
*/
public function provideWindowsGoodWhoAmIValues(): array
{
return [
[
'value' => '"Melilot Sackville","S-1-5-21-7375663-6890924511-1272660413-2944159"',
'expectedId' => '2944159',
],
[
'value' => '"Brutus Sandheaver","S-1-3-12-1234525106-3567804255-30012867-1437"',
'expectedId' => '1437',
],
[
'value' => '"Cora Rumble","S-345"',
'expectedId' => '345',
],
];
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider providePosixTestValues
*/
public function testGetUidForPosixSystems(string $os, string $id): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn($os);
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('id -u')->once()->andReturn($id);
$provider = new SystemDceSecurityProvider();
$uid = $provider->getUid();
$this->assertSame($id, $uid->toString());
$this->assertSame($uid, $provider->getUid());
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetGidThrowsExceptionIfShellExecDisabled(): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('foo bar shell_exec baz');
$provider = new SystemDceSecurityProvider();
// Test that we catch the exception multiple times, but the ini_get()
// function is called only once.
$caughtException = 0;
for ($i = 1; $i <= 5; $i++) {
try {
$provider->getGid();
} catch (DceSecurityException $e) {
$caughtException++;
$this->assertSame(
'Unable to get a group identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider',
$e->getMessage()
);
}
}
$this->assertSame(5, $caughtException);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGetGidForPosixThrowsExceptionIfShellExecReturnsNull(): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Linux');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('id -g')->once()->andReturnNull();
$provider = new SystemDceSecurityProvider();
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Unable to get a group identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider'
);
$provider->getGid();
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider providePosixTestValues
*/
public function testGetGidForPosixSystems(string $os, string $id): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn($os);
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('id -g')->once()->andReturn($id);
$provider = new SystemDceSecurityProvider();
$gid = $provider->getGid();
$this->assertSame($id, $gid->toString());
$this->assertSame($gid, $provider->getGid());
}
/**
* @param mixed $value
*
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideWindowsBadValues
*/
public function testGetGidForWindowsThrowsExceptionWhenShellExecForNetUserReturnsBadValues($value): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Windows_NT');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'shell_exec'
)->with('net user %username% | findstr /b /i "Local Group Memberships"')->once()->andReturn($value);
$provider = new SystemDceSecurityProvider();
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Unable to get a group identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider'
);
$provider->getGid();
}
/**
* @param mixed $value
*
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideWindowsBadGroupValues
*/
public function testGetGidForWindowsThrowsExceptionWhenShellExecForWmicGroupGetReturnsBadValues($value): void
{
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Windows_NT');
$shellExec = PHPMockery::mock('Ramsey\Uuid\Provider\Dce', 'shell_exec');
$shellExec
->with('net user %username% | findstr /b /i "Local Group Memberships"')
->once()
->andReturn('Local Group Memberships *Users');
$shellExec
->with(Mockery::pattern("/^wmic group get name,sid \| findstr \/b \/i (\"|\')Users(\"|\')$/"))
->once()
->andReturn($value);
$provider = new SystemDceSecurityProvider();
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Unable to get a group identifier using the system DCE '
. 'Security provider; please provide a custom identifier or '
. 'use a different provider'
);
$provider->getGid();
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
* @dataProvider provideWindowsGoodNetUserAndWmicGroupValues
*/
public function testGetGidForWindowsSucceeds(
string $netUserResponse,
string $wmicGroupResponse,
string $expectedGroup,
string $expectedId
): void {
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'ini_get'
)->with('disable_functions')->once()->andReturn('nothing');
PHPMockery::mock(
'Ramsey\Uuid\Provider\Dce',
'constant'
)->with('PHP_OS')->once()->andReturn('Windows_NT');
$shellExec = PHPMockery::mock('Ramsey\Uuid\Provider\Dce', 'shell_exec');
$shellExec
->with('net user %username% | findstr /b /i "Local Group Memberships"')
->once()
->andReturn($netUserResponse);
$shellExec
->with(Mockery::pattern("/^wmic group get name,sid \| findstr \/b \/i (\"|\'){$expectedGroup}(\"|\')$/"))
->once()
->andReturn($wmicGroupResponse);
$provider = new SystemDceSecurityProvider();
$gid = $provider->getGid();
$this->assertSame($expectedId, $gid->toString());
$this->assertSame($gid, $provider->getGid());
}
/**
* @return array<array{
* netUserResponse: non-empty-string,
* wmicGroupResponse: non-empty-string,
* expectedGroup: non-empty-string,
* expectedId: non-empty-string,
* }>
*/
public function provideWindowsGoodNetUserAndWmicGroupValues(): array
{
return [
[
'netUserResponse' => 'Local Group Memberships *Administrators *Users',
'wmicGroupResponse' => 'Administrators S-1-5-32-544',
'expectedGroup' => 'Administrators',
'expectedId' => '544',
],
[
'netUserResponse' => 'Local Group Memberships Users',
'wmicGroupResponse' => 'Users S-1-5-32-545',
'expectedGroup' => 'Users',
'expectedId' => '545',
],
[
'netUserResponse' => 'Local Group Memberships Guests Nobody',
'wmicGroupResponse' => 'Guests S-1-5-32-546',
'expectedGroup' => 'Guests',
'expectedId' => '546',
],
[
'netUserResponse' => 'Local Group Memberships Some Group Another Group',
'wmicGroupResponse' => 'Some Group S-1-5-80-19088743-1985229328-4294967295-1324',
'expectedGroup' => 'Some Group',
'expectedId' => '1324',
],
];
}
/**
* @return array<array{os: non-empty-string, id: non-empty-string}>
*/
public function providePosixTestValues(): array
{
return [
['os' => 'Darwin', 'id' => '1042'],
['os' => 'FreeBSD', 'id' => '672'],
['os' => 'GNU', 'id' => '1008'],
['os' => 'Linux', 'id' => '567'],
['os' => 'NetBSD', 'id' => '7234'],
['os' => 'OpenBSD', 'id' => '2347'],
['os' => 'OS400', 'id' => '1234'],
];
}
/**
* @return array<array{value: string | null}>
*/
public function provideWindowsBadValues(): array
{
return [
['value' => null],
['value' => 'foobar'],
['value' => 'foo,bar,baz'],
['value' => ''],
['value' => '1234'],
['value' => 'Local Group Memberships'],
['value' => 'Local Group Memberships **** Foo'],
];
}
/**
* @return array<array{value: string | null}>
*/
public function provideWindowsBadGroupValues(): array
{
return array_merge(
$this->provideWindowsBadValues(),
[
['value' => 'Users Not a valid SID string'],
['value' => 'Users 344aab9758bb0d018b93739e7893fb3a'],
]
);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Converter/Number/GenericNumberConverterTest.php | tests/Converter/Number/GenericNumberConverterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Converter\Number;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Test\TestCase;
class GenericNumberConverterTest extends TestCase
{
public function testFromHex(): void
{
$calculator = new BrickMathCalculator();
$converter = new GenericNumberConverter($calculator);
$this->assertSame('65535', $converter->fromHex('ffff'));
}
public function testToHex(): void
{
$calculator = new BrickMathCalculator();
$converter = new GenericNumberConverter($calculator);
$this->assertSame('ffff', $converter->toHex('65535'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Converter/Number/BigNumberConverterTest.php | tests/Converter/Number/BigNumberConverterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Converter\Number;
use Ramsey\Uuid\Converter\Number\BigNumberConverter;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Test\TestCase;
class BigNumberConverterTest extends TestCase
{
public function testFromHexThrowsExceptionWhenStringDoesNotContainOnlyHexadecimalCharacters(): void
{
$converter = new BigNumberConverter();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('"." is not a valid character in base 16');
$converter->fromHex('123.34');
}
public function testToHexThrowsExceptionWhenStringDoesNotContainOnlyDigits(): void
{
$converter = new BigNumberConverter();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed integer or a string containing only digits '
. '0-9 and, optionally, a sign (+ or -)'
);
$converter->toHex('123.34');
}
public function testFromHex(): void
{
$converter = new BigNumberConverter();
$this->assertSame('65535', $converter->fromHex('ffff'));
}
public function testToHex(): void
{
$converter = new BigNumberConverter();
$this->assertSame('ffff', $converter->toHex('65535'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Converter/Time/GenericTimeConverterTest.php | tests/Converter/Time/GenericTimeConverterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Converter\Time;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
class GenericTimeConverterTest extends TestCase
{
/**
* @param numeric-string $seconds
* @param numeric-string $microseconds
* @param non-empty-string $expected
*
* @dataProvider provideCalculateTime
*/
public function testCalculateTime(string $seconds, string $microseconds, string $expected): void
{
$calculator = new BrickMathCalculator();
$converter = new GenericTimeConverter($calculator);
$result = $converter->calculateTime($seconds, $microseconds);
$this->assertSame($expected, $result->toString());
}
/**
* @return array<array{seconds: numeric-string, microseconds: numeric-string, expected: non-empty-string}>
*/
public function provideCalculateTime(): array
{
return [
[
'seconds' => '-12219146756',
'microseconds' => '0',
'expected' => '000001540901e600',
],
[
'seconds' => '103072857659',
'microseconds' => '999999',
'expected' => '0fffffffff9785f6',
],
[
'seconds' => '1578612359',
'microseconds' => '521023',
'expected' => '01ea333764c71df6',
],
// This is the earliest possible date supported by v1 UUIDs:
// 1582-10-15 00:00:00.000000
[
'seconds' => '-12219292800',
'microseconds' => '0',
'expected' => '0000000000000000',
],
// This is the last possible time supported by the GenericTimeConverter:
// 60038-03-11 05:36:10.955161
// When a UUID is created from this time, however, the highest 4 bits
// are replaced with the version (1), so we lose fidelity and cannot
// accurately decompose the date from the UUID.
[
'seconds' => '1832455114570',
'microseconds' => '955161',
'expected' => 'fffffffffffffffa',
],
// This is technically the last possible time supported by v1 UUIDs:
// 5236-03-31 21:21:00.684697
// All dates above this will lose fidelity, since the highest 4 bits
// are replaced with the UUID version (1). As a result, we cannot
// accurately decompose the date from UUIDs created from dates
// greater than this one.
[
'seconds' => '103072857660',
'microseconds' => '684697',
'expected' => '0ffffffffffffffa',
],
];
}
/**
* @param numeric-string $unixTimestamp
* @param numeric-string $microseconds
*
* @dataProvider provideConvertTime
*/
public function testConvertTime(Hexadecimal $uuidTimestamp, string $unixTimestamp, string $microseconds): void
{
$calculator = new BrickMathCalculator();
$converter = new GenericTimeConverter($calculator);
$result = $converter->convertTime($uuidTimestamp);
$this->assertSame($unixTimestamp, $result->getSeconds()->toString());
$this->assertSame($microseconds, $result->getMicroseconds()->toString());
}
/**
* @return array<array{uuidTimestamp: Hexadecimal, unixTimestamp: numeric-string, microseconds: numeric-string}>
*/
public function provideConvertTime(): array
{
return [
[
'uuidTimestamp' => new Hexadecimal('1e1c57dff6f8cb0'),
'unixTimestamp' => '1341368074',
'microseconds' => '491000',
],
[
'uuidTimestamp' => new Hexadecimal('1ea333764c71df6'),
'unixTimestamp' => '1578612359',
'microseconds' => '521023',
],
[
'uuidTimestamp' => new Hexadecimal('fffffffff9785f6'),
'unixTimestamp' => '103072857659',
'microseconds' => '999999',
],
// This is the last possible time supported by v1 UUIDs. When
// converted to a Unix timestamp, the microseconds are lost.
// 60038-03-11 05:36:10.955161
[
'uuidTimestamp' => new Hexadecimal('fffffffffffffffa'),
'unixTimestamp' => '1832455114570',
'microseconds' => '955161',
],
// This is the earliest possible date supported by v1 UUIDs:
// 1582-10-15 00:00:00.000000
[
'uuidTimestamp' => new Hexadecimal('000000000000'),
'unixTimestamp' => '-12219292800',
'microseconds' => '0',
],
// This is the Unix epoch:
// 1970-01-01 00:00:00.000000
[
'uuidTimestamp' => new Hexadecimal('1b21dd213814000'),
'unixTimestamp' => '0',
'microseconds' => '0',
],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Converter/Time/PhpTimeConverterTest.php | tests/Converter/Time/PhpTimeConverterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Converter\Time;
use Brick\Math\BigInteger;
use Mockery;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\Time\PhpTimeConverter;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use function sprintf;
class PhpTimeConverterTest extends TestCase
{
public function testCalculateTimeReturnsArrayOfTimeSegments(): void
{
$seconds = BigInteger::of(5);
$microseconds = BigInteger::of(3);
$calculatedTime = BigInteger::zero()
->plus($seconds->multipliedBy(10000000))
->plus($microseconds->multipliedBy(10))
->plus(BigInteger::fromBase('01b21dd213814000', 16));
$maskLow = BigInteger::fromBase('ffffffff', 16);
$maskMid = BigInteger::fromBase('ffff', 16);
$maskHi = BigInteger::fromBase('0fff', 16);
$expected = sprintf('%04s', $calculatedTime->shiftedRight(48)->and($maskHi)->toBase(16));
$expected .= sprintf('%04s', $calculatedTime->shiftedRight(32)->and($maskMid)->toBase(16));
$expected .= sprintf('%08s', $calculatedTime->and($maskLow)->toBase(16));
$converter = new PhpTimeConverter();
$returned = $converter->calculateTime((string) $seconds, (string) $microseconds);
$this->assertSame($expected, $returned->toString());
}
public function testCalculateTimeThrowsExceptionWhenSecondsIsNotOnlyDigits(): void
{
/** @var Mockery\MockInterface & PhpTimeConverter $converter */
$converter = Mockery::mock(PhpTimeConverter::class)->makePartial();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed integer or a string containing only digits '
. '0-9 and, optionally, a sign (+ or -)'
);
$converter->calculateTime('12.34', '5678');
}
public function testCalculateTimeThrowsExceptionWhenMicrosecondsIsNotOnlyDigits(): void
{
/** @var Mockery\MockInterface & PhpTimeConverter $converter */
$converter = Mockery::mock(PhpTimeConverter::class)->makePartial();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed integer or a string containing only digits '
. '0-9 and, optionally, a sign (+ or -)'
);
$converter->calculateTime('1234', '56.78');
}
/**
* @param numeric-string $unixTimestamp
* @param numeric-string $microseconds
*
* @dataProvider provideConvertTime
*/
public function testConvertTime(Hexadecimal $uuidTimestamp, string $unixTimestamp, string $microseconds): void
{
$calculator = new BrickMathCalculator();
$fallbackConverter = new GenericTimeConverter($calculator);
$converter = new PhpTimeConverter($calculator, $fallbackConverter);
$result = $converter->convertTime($uuidTimestamp);
$this->assertSame($unixTimestamp, $result->getSeconds()->toString());
$this->assertSame($microseconds, $result->getMicroseconds()->toString());
}
/**
* @return array<array{uuidTimestamp: Hexadecimal, unixTimestamp: numeric-string, microseconds: numeric-string}>
*/
public function provideConvertTime(): array
{
return [
[
'uuidTimestamp' => new Hexadecimal('1e1c57dff6f8cb0'),
'unixTimestamp' => '1341368074',
'microseconds' => '491000',
],
[
'uuidTimestamp' => new Hexadecimal('1ea333764c71df6'),
'unixTimestamp' => '1578612359',
'microseconds' => '521023',
],
[
'uuidTimestamp' => new Hexadecimal('fffffffff9785f6'),
'unixTimestamp' => '103072857659',
'microseconds' => '999999',
],
// This is the last possible time supported by v1 UUIDs. When
// converted to a Unix timestamp, the microseconds are lost.
// 60038-03-11 05:36:10.955161
[
'uuidTimestamp' => new Hexadecimal('fffffffffffffffa'),
'unixTimestamp' => '1832455114570',
'microseconds' => '955161',
],
// This is the earliest possible date supported by v1 UUIDs:
// 1582-10-15 00:00:00.000000
[
'uuidTimestamp' => new Hexadecimal('000000000000'),
'unixTimestamp' => '-12219292800',
'microseconds' => '0',
],
// This is the Unix epoch:
// 1970-01-01 00:00:00.000000
[
'uuidTimestamp' => new Hexadecimal('1b21dd213814000'),
'unixTimestamp' => '0',
'microseconds' => '0',
],
];
}
/**
* @param non-empty-string $seconds
* @param non-empty-string $microseconds
* @param non-empty-string $expected
*
* @dataProvider provideCalculateTime
*/
public function testCalculateTime(string $seconds, string $microseconds, string $expected): void
{
$calculator = new BrickMathCalculator();
$fallbackConverter = new GenericTimeConverter($calculator);
$converter = new PhpTimeConverter($calculator, $fallbackConverter);
$result = $converter->calculateTime($seconds, $microseconds);
$this->assertSame($expected, $result->toString());
}
/**
* @return array<array{seconds: non-empty-string, microseconds: non-empty-string, expected: non-empty-string}>
*/
public function provideCalculateTime(): array
{
return [
[
'seconds' => '-12219146756',
'microseconds' => '0',
'expected' => '000001540901e600',
],
[
'seconds' => '103072857659',
'microseconds' => '999999',
'expected' => '0fffffffff9785f6',
],
[
'seconds' => '1578612359',
'microseconds' => '521023',
'expected' => '01ea333764c71df6',
],
// This is the earliest possible date supported by v1 UUIDs:
// 1582-10-15 00:00:00.000000
[
'seconds' => '-12219292800',
'microseconds' => '0',
'expected' => '0000000000000000',
],
// This is the last possible time supported by v1 UUIDs:
// 60038-03-11 05:36:10.955161
[
'seconds' => '1832455114570',
'microseconds' => '955161',
'expected' => 'fffffffffffffffa',
],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Converter/Time/UnixTimeConverterTest.php | tests/Converter/Time/UnixTimeConverterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Converter\Time;
use Ramsey\Uuid\Converter\Time\UnixTimeConverter;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
class UnixTimeConverterTest extends TestCase
{
/**
* @dataProvider provideConvertTime
*/
public function testConvertTime(Hexadecimal $uuidTimestamp, string $unixTimestamp, string $microseconds): void
{
$calculator = new BrickMathCalculator();
$converter = new UnixTimeConverter($calculator);
$result = $converter->convertTime($uuidTimestamp);
$this->assertSame($unixTimestamp, $result->getSeconds()->toString());
$this->assertSame($microseconds, $result->getMicroseconds()->toString());
}
/**
* @return array<array{uuidTimestamp: Hexadecimal, unixTimestamp: string, microseconds: string}>
*/
public function provideConvertTime(): array
{
return [
[
'uuidTimestamp' => new Hexadecimal('017F22E279B0'),
'unixTimestamp' => '1645557742',
'microseconds' => '0',
],
[
'uuidTimestamp' => new Hexadecimal('01384fc480fb'),
'unixTimestamp' => '1341368074',
'microseconds' => '491000',
],
[
'uuidTimestamp' => new Hexadecimal('016f8ca10161'),
'unixTimestamp' => '1578612359',
'microseconds' => '521000',
],
[
'uuidTimestamp' => new Hexadecimal('5dbe85111a5f'),
'unixTimestamp' => '103072857659',
'microseconds' => '999000',
],
// This is the last possible time supported by v7 UUIDs (2 ^ 48 - 1).
// 10889-08-02 05:31:50.655 +00:00
[
'uuidTimestamp' => new Hexadecimal('ffffffffffff'),
'unixTimestamp' => '281474976710',
'microseconds' => '655000',
],
// This is the earliest possible date supported by v7 UUIDs.
// It is the Unix Epoch (big surprise!).
// 1970-01-01 00:00:00.0 +00:00
[
'uuidTimestamp' => new Hexadecimal('000000000000'),
'unixTimestamp' => '0',
'microseconds' => '0',
],
[
'uuidTimestamp' => new Hexadecimal('000000000001'),
'unixTimestamp' => '0',
'microseconds' => '1000',
],
[
'uuidTimestamp' => new Hexadecimal('00000000000f'),
'unixTimestamp' => '0',
'microseconds' => '15000',
],
[
'uuidTimestamp' => new Hexadecimal('000000000064'),
'unixTimestamp' => '0',
'microseconds' => '100000',
],
[
'uuidTimestamp' => new Hexadecimal('0000000003e7'),
'unixTimestamp' => '0',
'microseconds' => '999000',
],
[
'uuidTimestamp' => new Hexadecimal('0000000003e8'),
'unixTimestamp' => '1',
'microseconds' => '0',
],
[
'uuidTimestamp' => new Hexadecimal('0000000003e9'),
'unixTimestamp' => '1',
'microseconds' => '1000',
],
];
}
/**
* @dataProvider provideCalculateTime
*/
public function testCalculateTime(string $seconds, string $microseconds, string $expected): void
{
$calculator = new BrickMathCalculator();
$converter = new UnixTimeConverter($calculator);
$result = $converter->calculateTime($seconds, $microseconds);
$this->assertSame($expected, $result->toString());
}
/**
* @return array<array{seconds: string, microseconds: string, expected: string}>
*/
public function provideCalculateTime(): array
{
return [
[
'seconds' => '1645557742',
'microseconds' => '0',
'expected' => '017f22e279b0',
],
[
'seconds' => '1341368074',
'microseconds' => '491000',
'expected' => '01384fc480fb',
],
[
'seconds' => '1578612359',
'microseconds' => '521023',
'expected' => '016f8ca10161',
],
[
'seconds' => '103072857659',
'microseconds' => '999499',
'expected' => '5dbe85111a5f',
],
[
'seconds' => '103072857659',
'microseconds' => '999999',
'expected' => '5dbe85111a5f',
],
// This is the earliest possible date supported by v7 UUIDs.
// It is the Unix Epoch (big surprise!): 1970-01-01 00:00:00.0 +00:00
[
'seconds' => '0',
'microseconds' => '0',
'expected' => '000000000000',
],
// This is the last possible time supported by v7 UUIDs (2 ^ 48 - 1):
// 10889-08-02 05:31:50.655 +00:00
[
'seconds' => '281474976710',
'microseconds' => '655000',
'expected' => 'ffffffffffff',
],
[
'seconds' => '0',
'microseconds' => '1000',
'expected' => '000000000001',
],
[
'seconds' => '0',
'microseconds' => '15000',
'expected' => '00000000000f',
],
[
'seconds' => '0',
'microseconds' => '100000',
'expected' => '000000000064',
],
[
'seconds' => '0',
'microseconds' => '999000',
'expected' => '0000000003e7',
],
[
'seconds' => '1',
'microseconds' => '0',
'expected' => '0000000003e8',
],
[
'seconds' => '1',
'microseconds' => '1000',
'expected' => '0000000003e9',
],
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Converter/Time/BigNumberTimeConverterTest.php | tests/Converter/Time/BigNumberTimeConverterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Converter\Time;
use Brick\Math\BigInteger;
use Ramsey\Uuid\Converter\Time\BigNumberTimeConverter;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use function sprintf;
class BigNumberTimeConverterTest extends TestCase
{
public function testCalculateTimeReturnsArrayOfTimeSegments(): void
{
$seconds = BigInteger::of(5);
$microseconds = BigInteger::of(3);
$calculatedTime = BigInteger::zero()
->plus($seconds->multipliedBy(10000000))
->plus($microseconds->multipliedBy(10))
->plus(BigInteger::fromBase('01b21dd213814000', 16));
$maskLow = BigInteger::fromBase('ffffffff', 16);
$maskMid = BigInteger::fromBase('ffff', 16);
$maskHi = BigInteger::fromBase('0fff', 16);
$expected = sprintf('%04s', $calculatedTime->shiftedRight(48)->and($maskHi)->toBase(16));
$expected .= sprintf('%04s', $calculatedTime->shiftedRight(32)->and($maskMid)->toBase(16));
$expected .= sprintf('%08s', $calculatedTime->and($maskLow)->toBase(16));
$converter = new BigNumberTimeConverter();
$returned = $converter->calculateTime((string) $seconds, (string) $microseconds);
$this->assertSame($expected, $returned->toString());
}
public function testConvertTime(): void
{
$converter = new BigNumberTimeConverter();
$returned = $converter->convertTime(new Hexadecimal('1e1c57dff6f8cb0'));
$this->assertSame('1341368074', $returned->getSeconds()->toString());
}
public function testCalculateTimeThrowsExceptionWhenSecondsIsNotOnlyDigits(): void
{
$converter = new BigNumberTimeConverter();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed integer or a string containing only digits '
. '0-9 and, optionally, a sign (+ or -)'
);
$converter->calculateTime('12.34', '5678');
}
public function testCalculateTimeThrowsExceptionWhenMicrosecondsIsNotOnlyDigits(): void
{
$converter = new BigNumberTimeConverter();
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage(
'Value must be a signed integer or a string containing only digits '
. '0-9 and, optionally, a sign (+ or -)'
);
$converter->calculateTime('1234', '56.78');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/static-analysis/UuidIsNeverEmpty.php | tests/static-analysis/UuidIsNeverEmpty.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\StaticAnalysis;
use Ramsey\Uuid\UuidInterface;
/**
* This is a static analysis fixture to verify that the API signature
* of a UUID does not return empty strings for methods that never will do so.
*/
final class UuidIsNeverEmpty
{
/** @return non-empty-string */
public function bytesAreNeverEmpty(UuidInterface $uuid): string
{
return $uuid->getBytes();
}
/** @return non-empty-string */
public function stringIsNeverEmpty(UuidInterface $uuid): string
{
return $uuid->toString();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/static-analysis/stubs.php | tests/static-analysis/stubs.php | <?php
/**
* Stubs for static analysis
*
* @codingStandardsIgnoreFile
*/
if (!defined('UUID_TYPE_DEFAULT')) {
define('UUID_TYPE_DEFAULT', 0);
}
if (!defined('UUID_TYPE_TIME')) {
define('UUID_TYPE_TIME', 1);
}
if (!defined('UUID_TYPE_RANDOM')) {
define('UUID_TYPE_RANDOM', 4);
}
if (!function_exists('uuid_create')) {
function uuid_create(int $uuid_type=UUID_TYPE_DEFAULT): string {} // @phpstan-ignore-line
}
if (!function_exists('uuid_generate_md5')) {
function uuid_generate_md5(string $uuid_ns, string $name): string {} // @phpstan-ignore-line
}
if (!function_exists('uuid_generate_sha1')) {
function uuid_generate_sha1(string $uuid_ns, string $name): string {} // @phpstan-ignore-line
}
if (!function_exists('uuid_parse')) {
function uuid_parse(string $uuid): string {} // @phpstan-ignore-line
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/static-analysis/UuidIsImmutable.php | tests/static-analysis/UuidIsImmutable.php | <?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
declare(strict_types=1);
namespace Ramsey\Uuid\StaticAnalysis;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
/**
* This is a static analysis fixture to verify that the API signature
* of a UUID allows for pure operations. Almost all methods will seem to be
* redundant or trivial: that's normal, we're just verifying the
* transitivity of immutable type signatures.
*
* Please note that this does not guarantee that the internals of the UUID
* library are pure/safe, but just that the declared API to the outside world
* is seen as immutable.
*/
final class UuidIsImmutable
{
public static function pureCompareTo(UuidInterface $a, UuidInterface $b): int
{
return $a->compareTo($b);
}
public static function pureEquals(UuidInterface $a, ?object $b): bool
{
return $a->equals($b);
}
/**
* @return mixed[]
*/
public static function pureGetters(UuidInterface $a): array
{
return [
$a->getBytes(),
$a->getNumberConverter(),
$a->getHex(),
$a->getFieldsHex(),
$a->getClockSeqHiAndReservedHex(),
$a->getClockSeqLowHex(),
$a->getClockSequenceHex(),
$a->getDateTime(),
$a->getInteger(),
$a->getLeastSignificantBitsHex(),
$a->getMostSignificantBitsHex(),
$a->getNodeHex(),
$a->getTimeHiAndVersionHex(),
$a->getTimeLowHex(),
$a->getTimeMidHex(),
$a->getTimestampHex(),
$a->getUrn(),
$a->getVariant(),
$a->getVersion(),
$a->toString(),
$a->__toString(),
];
}
/**
* @return UuidInterface[]|bool[]
*/
public static function pureStaticUuidApi(): array
{
$id = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66');
return [
Uuid::fromBytes($id->getBytes()),
Uuid::fromInteger($id->getInteger()->toString()),
Uuid::isValid('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'),
];
}
public static function uuid3IsPure(): UuidInterface
{
return Uuid::uuid3(
Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'),
'Look ma! I am a pure function!'
);
}
public static function uuid5IsPure(): UuidInterface
{
return Uuid::uuid5(
Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'),
'Look ma! I am a pure function!'
);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/static-analysis/ValidUuidIsNonEmpty.php | tests/static-analysis/ValidUuidIsNonEmpty.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\StaticAnalysis;
use InvalidArgumentException;
use Ramsey\Uuid\Uuid;
final class ValidUuidIsNonEmpty
{
/** @return non-empty-string */
public function validUuidsAreNotEmpty(string $input): string
{
if (Uuid::isValid($input)) {
return $input;
}
throw new InvalidArgumentException('Not a UUID');
}
/**
* @param non-empty-string $input
*
* @return non-empty-string
*/
public function givenNonEmptyInputAssertionRemainsValid(string $input): string
{
if (Uuid::isValid($input)) {
return $input;
}
throw new InvalidArgumentException('Not a UUID');
}
public function givenInvalidInputValueRemainsAString(string $input): string
{
if (Uuid::isValid($input)) {
return 'It Worked!';
}
return $input;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/DefaultNameGeneratorTest.php | tests/Generator/DefaultNameGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Ramsey\Uuid\Exception\NameException;
use Ramsey\Uuid\Generator\DefaultNameGenerator;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Uuid;
use function hash;
class DefaultNameGeneratorTest extends TestCase
{
/**
* @param non-empty-string $ns
* @param non-empty-string $name
* @param non-empty-string $algorithm
*
* @dataProvider provideNamesForHashingTest
*/
public function testDefaultNameGeneratorHashesName(string $ns, string $name, string $algorithm): void
{
$namespace = Uuid::fromString($ns);
$expectedBytes = hash($algorithm, $namespace->getBytes() . $name, true);
$generator = new DefaultNameGenerator();
$this->assertSame($expectedBytes, $generator->generate($namespace, $name, $algorithm));
}
/**
* @return array<array{ns: non-empty-string, name: non-empty-string, algorithm: non-empty-string}>
*/
public function provideNamesForHashingTest(): array
{
return [
[
'ns' => Uuid::NAMESPACE_URL,
'name' => 'https://example.com/foobar',
'algorithm' => 'md5',
],
[
'ns' => Uuid::NAMESPACE_URL,
'name' => 'https://example.com/foobar',
'algorithm' => 'sha1',
],
[
'ns' => Uuid::NAMESPACE_URL,
'name' => 'https://example.com/foobar',
'algorithm' => 'sha256',
],
[
'ns' => Uuid::NAMESPACE_OID,
'name' => '1.3.6.1.4.1.343',
'algorithm' => 'sha1',
],
[
'ns' => Uuid::NAMESPACE_OID,
'name' => '1.3.6.1.4.1.52627',
'algorithm' => 'md5',
],
[
'ns' => 'd988ae29-674e-48e7-b93c-2825e2a96fbe',
'name' => 'foobar',
'algorithm' => 'sha1',
],
];
}
public function testGenerateThrowsException(): void
{
$namespace = Uuid::fromString('cd998804-c661-4264-822c-00cada75a87b');
$generator = new DefaultNameGenerator();
$this->expectException(NameException::class);
$this->expectExceptionMessage(
'Unable to hash namespace and name with algorithm \'aBadAlgorithm\''
);
$generator->generate($namespace, 'a test name', 'aBadAlgorithm');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/DefaultTimeGeneratorTest.php | tests/Generator/DefaultTimeGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Exception;
use Mockery;
use Mockery\MockInterface;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\BinaryUtils;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\RandomSourceException;
use Ramsey\Uuid\Exception\TimeSourceException;
use Ramsey\Uuid\FeatureSet;
use Ramsey\Uuid\Generator\DefaultTimeGenerator;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\Time\FixedTimeProvider;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
use phpmock\mockery\PHPMockery;
use function hex2bin;
class DefaultTimeGeneratorTest extends TestCase
{
/**
* @var TimeProviderInterface & MockInterface
*/
private $timeProvider;
/**
* @var NodeProviderInterface & MockObject
*/
private $nodeProvider;
/**
* @var TimeConverterInterface & MockObject
*/
private $timeConverter;
/**
* @var string
*/
private $nodeId = '122f80ca9e06';
/**
* @var int[]
*/
private $currentTime;
/**
* @var Hexadecimal
*/
private $calculatedTime;
/**
* @var int
*/
private $clockSeq = 4066;
protected function setUp(): void
{
parent::setUp();
$this->nodeProvider = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
$this->timeConverter = $this->getMockBuilder(TimeConverterInterface::class)->getMock();
$this->currentTime = ['sec' => 1458733431, 'usec' => 877449];
$this->calculatedTime = new Hexadecimal('03cb98e083cb98e0');
$time = new Time($this->currentTime['sec'], $this->currentTime['usec']);
$this->timeProvider = Mockery::mock(TimeProviderInterface::class, [
'getTime' => $time,
]);
}
protected function tearDown(): void
{
parent::tearDown();
unset($this->timeProvider, $this->nodeProvider, $this->timeConverter);
Mockery::close();
}
public function testGenerateUsesNodeProviderWhenNodeIsNull(): void
{
$this->nodeProvider->expects($this->once())
->method('getNode')
->willReturn(new Hexadecimal('122f80ca9e06'));
$this->timeConverter->expects($this->once())
->method('calculateTime')
->with($this->currentTime['sec'], $this->currentTime['usec'])
->willReturn($this->calculatedTime);
$defaultTimeGenerator = new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
$defaultTimeGenerator->generate(null, $this->clockSeq);
}
public function testGenerateUsesTimeProvidersCurrentTime(): void
{
$this->timeConverter->expects($this->once())
->method('calculateTime')
->with($this->currentTime['sec'], $this->currentTime['usec'])
->willReturn($this->calculatedTime);
$defaultTimeGenerator = new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
$defaultTimeGenerator->generate($this->nodeId, $this->clockSeq);
}
public function testGenerateCalculatesTimeWithConverter(): void
{
$this->timeConverter->expects($this->once())
->method('calculateTime')
->with($this->currentTime['sec'], $this->currentTime['usec'])
->willReturn($this->calculatedTime);
$defaultTimeGenerator = new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
$defaultTimeGenerator->generate($this->nodeId, $this->clockSeq);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateDoesNotApplyVersionAndVariant(): void
{
$expectedBytes = hex2bin('83cb98e098e003cb0fe2122f80ca9e06');
$this->timeConverter->method('calculateTime')
->with($this->currentTime['sec'], $this->currentTime['usec'])
->willReturn($this->calculatedTime);
$binaryUtils = Mockery::mock('alias:' . BinaryUtils::class);
$binaryUtils->shouldNotReceive('applyVersion');
$binaryUtils->shouldNotReceive('applyVariant');
$defaultTimeGenerator = new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
$this->assertSame($expectedBytes, $defaultTimeGenerator->generate($this->nodeId, $this->clockSeq));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateUsesRandomSequenceWhenClockSeqNull(): void
{
PHPMockery::mock('Ramsey\Uuid\Generator', 'random_int')
->once()
->with(0, 0x3fff)
->andReturn(9622);
$this->timeConverter->expects($this->once())
->method('calculateTime')
->with($this->currentTime['sec'], $this->currentTime['usec'])
->willReturn($this->calculatedTime);
$defaultTimeGenerator = new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
$defaultTimeGenerator->generate($this->nodeId);
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateThrowsExceptionWhenExceptionThrownByRandomint(): void
{
PHPMockery::mock('Ramsey\Uuid\Generator', 'random_int')
->once()
->andThrow(new Exception('Could not gather sufficient random data'));
$defaultTimeGenerator = new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
$this->expectException(RandomSourceException::class);
$this->expectExceptionMessage('Could not gather sufficient random data');
$defaultTimeGenerator->generate($this->nodeId);
}
public function testDefaultTimeGeneratorThrowsExceptionForLargeGeneratedValue(): void
{
$timeProvider = new FixedTimeProvider(new Time('1832455114570', '955162'));
$featureSet = new FeatureSet();
$timeGenerator = new DefaultTimeGenerator(
$featureSet->getNodeProvider(),
$featureSet->getTimeConverter(),
$timeProvider
);
$this->expectException(TimeSourceException::class);
$this->expectExceptionMessage(
'The generated time of \'10000000000000004\' is larger than expected'
);
$timeGenerator->generate();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/RandomBytesGeneratorTest.php | tests/Generator/RandomBytesGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Exception;
use Ramsey\Uuid\Exception\RandomSourceException;
use Ramsey\Uuid\Generator\RandomBytesGenerator;
use Ramsey\Uuid\Test\TestCase;
use phpmock\mockery\PHPMockery;
use function hex2bin;
class RandomBytesGeneratorTest extends TestCase
{
/**
* @return array<array{0: positive-int, 1: non-empty-string}>
*/
public function lengthAndHexDataProvider(): array
{
return [
[6, '4f17dd046fb8'],
[10, '4d25f6fe5327cb04267a'],
[12, '1ea89f83bd49cacfdf119e24'],
];
}
/**
* @param positive-int $length
* @param non-empty-string $hex
*
* @throws Exception
*
* @dataProvider lengthAndHexDataProvider
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateReturnsRandomBytes(int $length, string $hex): void
{
$bytes = hex2bin($hex);
PHPMockery::mock('Ramsey\Uuid\Generator', 'random_bytes')
->once()
->with($length)
->andReturn($bytes);
$generator = new RandomBytesGenerator();
$this->assertSame($bytes, $generator->generate($length));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testGenerateThrowsExceptionWhenExceptionThrownByRandomBytes(): void
{
PHPMockery::mock('Ramsey\Uuid\Generator', 'random_bytes')
->once()
->with(16)
->andThrow(new Exception('Could not gather sufficient random data'));
$generator = new RandomBytesGenerator();
$this->expectException(RandomSourceException::class);
$this->expectExceptionMessage('Could not gather sufficient random data');
$generator->generate(16);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/RandomGeneratorFactoryTest.php | tests/Generator/RandomGeneratorFactoryTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Ramsey\Uuid\Generator\RandomBytesGenerator;
use Ramsey\Uuid\Generator\RandomGeneratorFactory;
use Ramsey\Uuid\Test\TestCase;
class RandomGeneratorFactoryTest extends TestCase
{
public function testFactoryReturnsRandomBytesGenerator(): void
{
$generator = (new RandomGeneratorFactory())->getGenerator();
$this->assertInstanceOf(RandomBytesGenerator::class, $generator);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/PeclUuidRandomGeneratorTest.php | tests/Generator/PeclUuidRandomGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Ramsey\Uuid\Generator\PeclUuidRandomGenerator;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Uuid;
class PeclUuidRandomGeneratorTest extends TestCase
{
/**
* @requires extension uuid
*/
public function testGenerateCreatesUuidUsingPeclUuidMethods(): void
{
$generator = new PeclUuidRandomGenerator();
$bytes = $generator->generate(10);
$uuid = Uuid::fromBytes($bytes);
/** @var Fields $fields */
$fields = $uuid->getFields();
$this->assertSame(16, strlen($bytes));
$this->assertSame(Uuid::UUID_TYPE_RANDOM, $fields->getVersion());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/TimeGeneratorFactoryTest.php | tests/Generator/TimeGeneratorFactoryTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Generator\TimeGeneratorFactory;
use Ramsey\Uuid\Generator\TimeGeneratorInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Test\TestCase;
class TimeGeneratorFactoryTest extends TestCase
{
public function testGeneratorReturnsNewGenerator(): void
{
/** @var MockObject & TimeProviderInterface $timeProvider */
$timeProvider = $this->getMockBuilder(TimeProviderInterface::class)->getMock();
/** @var MockObject & NodeProviderInterface $nodeProvider */
$nodeProvider = $this->getMockBuilder(NodeProviderInterface::class)->getMock();
/** @var MockObject & TimeConverterInterface $timeConverter */
$timeConverter = $this->getMockBuilder(TimeConverterInterface::class)->getMock();
$factory = new TimeGeneratorFactory($nodeProvider, $timeConverter, $timeProvider);
$generator = $factory->getGenerator();
/** @phpstan-ignore method.alreadyNarrowedType */
$this->assertInstanceOf(TimeGeneratorInterface::class, $generator);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/PeclUuidNameGeneratorTest.php | tests/Generator/PeclUuidNameGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Ramsey\Uuid\BinaryUtils;
use Ramsey\Uuid\Exception\NameException;
use Ramsey\Uuid\Generator\PeclUuidNameGenerator;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Uuid;
use function hash;
use function pack;
use function substr;
use function substr_replace;
use function unpack;
class PeclUuidNameGeneratorTest extends TestCase
{
/**
* @param non-empty-string $ns
*
* @dataProvider provideNamesForHashingTest
* @requires extension uuid
*/
public function testPeclUuidNameGeneratorHashesName(string $ns, string $name, string $algorithm): void
{
$namespace = Uuid::fromString($ns);
$version = $algorithm === 'md5' ? 3 : 5;
$expectedBytes = substr(hash($algorithm, $namespace->getBytes() . $name, true), 0, 16);
// Need to add the version and variant, since ext-uuid already includes
// these in the values returned.
/** @var int[] $unpackedTime */
$unpackedTime = unpack('n*', substr($expectedBytes, 6, 2));
$timeHi = $unpackedTime[1];
$timeHiAndVersion = pack('n*', BinaryUtils::applyVersion($timeHi, $version));
/** @var int[] $unpackedClockSeq */
$unpackedClockSeq = unpack('n*', substr($expectedBytes, 8, 2));
$clockSeqHi = $unpackedClockSeq[1];
$clockSeqHiAndReserved = pack('n*', BinaryUtils::applyVariant($clockSeqHi));
$expectedBytes = substr_replace($expectedBytes, $timeHiAndVersion, 6, 2);
$expectedBytes = substr_replace($expectedBytes, $clockSeqHiAndReserved, 8, 2);
$generator = new PeclUuidNameGenerator();
$generatedBytes = $generator->generate($namespace, $name, $algorithm);
$this->assertSame(
$expectedBytes,
$generatedBytes,
'Expected: ' . bin2hex($expectedBytes) . '; Received: ' . bin2hex($generatedBytes)
);
}
/**
* @return array<array{ns: string, name: string, algorithm: string}>
*/
public function provideNamesForHashingTest(): array
{
return [
[
'ns' => Uuid::NAMESPACE_URL,
'name' => 'https://example.com/foobar',
'algorithm' => 'md5',
],
[
'ns' => Uuid::NAMESPACE_URL,
'name' => 'https://example.com/foobar',
'algorithm' => 'sha1',
],
[
'ns' => Uuid::NAMESPACE_OID,
'name' => '1.3.6.1.4.1.343',
'algorithm' => 'sha1',
],
[
'ns' => Uuid::NAMESPACE_OID,
'name' => '1.3.6.1.4.1.52627',
'algorithm' => 'md5',
],
[
'ns' => 'd988ae29-674e-48e7-b93c-2825e2a96fbe',
'name' => 'foobar',
'algorithm' => 'sha1',
],
];
}
public function testGenerateThrowsException(): void
{
$namespace = Uuid::fromString('cd998804-c661-4264-822c-00cada75a87b');
$generator = new PeclUuidNameGenerator();
$this->expectException(NameException::class);
$this->expectExceptionMessage(
'Unable to hash namespace and name with algorithm \'aBadAlgorithm\''
);
$generator->generate($namespace, 'a test name', 'aBadAlgorithm');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/UnixTimeGeneratorTest.php | tests/Generator/UnixTimeGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use DateTimeImmutable;
use Mockery;
use Mockery\MockInterface;
use Ramsey\Uuid\Generator\RandomBytesGenerator;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Generator\UnixTimeGenerator;
use Ramsey\Uuid\Test\TestCase;
class UnixTimeGeneratorTest extends TestCase
{
private const ITERATIONS = 2000;
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerate(): void
{
$dateTime = new DateTimeImmutable('@1578612359.521023');
$expectedBytes = "\x01\x6f\x8c\xa1\x01\x61\x03\x00\xff\x00\xff\x00\xff\x00\xff\x00";
/** @var RandomGeneratorInterface&MockInterface $randomGenerator */
$randomGenerator = Mockery::mock(RandomGeneratorInterface::class);
$randomGenerator->expects()->generate(16)->andReturns(
"\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00\xff\x00",
);
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator);
$bytes = $unixTimeGenerator->generate(null, null, $dateTime);
$this->assertSame(
$expectedBytes,
$bytes,
'Failed asserting that "' . bin2hex($bytes) . '" is equal to "' . bin2hex($expectedBytes) . '"',
);
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateProducesMonotonicResults(): void
{
$randomGenerator = new RandomBytesGenerator();
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator);
$previous = '';
for ($i = 0; $i < self::ITERATIONS; $i++) {
$bytes = $unixTimeGenerator->generate();
$this->assertTrue(
$bytes > $previous,
'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous),
);
$previous = $bytes;
}
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateProducesMonotonicResultsWithSameDate(): void
{
$dateTime = new DateTimeImmutable('now');
$randomGenerator = new RandomBytesGenerator();
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator);
$previous = '';
for ($i = 0; $i < self::ITERATIONS; $i++) {
$bytes = $unixTimeGenerator->generate(null, null, $dateTime);
$this->assertTrue(
$bytes > $previous,
'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous),
);
$previous = $bytes;
}
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateProducesMonotonicResultsFor32BitPath(): void
{
$randomGenerator = new RandomBytesGenerator();
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4);
$previous = '';
for ($i = 0; $i < self::ITERATIONS; $i++) {
$bytes = $unixTimeGenerator->generate();
$this->assertTrue(
$bytes > $previous,
'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous),
);
$previous = $bytes;
}
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateProducesMonotonicResultsWithSameDateFor32BitPath(): void
{
$dateTime = new DateTimeImmutable('now');
$randomGenerator = new RandomBytesGenerator();
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4);
$previous = '';
for ($i = 0; $i < self::ITERATIONS; $i++) {
$bytes = $unixTimeGenerator->generate(null, null, $dateTime);
$this->assertTrue(
$bytes > $previous,
'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous),
);
$previous = $bytes;
}
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateProducesMonotonicResultsStartingWithAllBitsSet(): void
{
/** @var RandomGeneratorInterface&MockInterface $randomGenerator */
$randomGenerator = Mockery::mock(RandomGeneratorInterface::class);
$randomGenerator->expects()->generate(16)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$randomGenerator->allows()->generate(10)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator);
$previous = '';
for ($i = 0; $i < self::ITERATIONS; $i++) {
$bytes = $unixTimeGenerator->generate();
$this->assertTrue(
$bytes > $previous,
'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous),
);
$previous = $bytes;
}
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateRollsOverWithAllBitsSetWithSameDate(): void
{
$dateTime = new DateTimeImmutable('now');
/** @var RandomGeneratorInterface&MockInterface $randomGenerator */
$randomGenerator = Mockery::mock(RandomGeneratorInterface::class);
$randomGenerator->expects()->generate(16)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$randomGenerator->allows()->generate(10)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator);
// We can only call this twice before the overflow kicks in, "randomizing" all the bits back to 1's, according to
// our mocked random generator. As a result, we can't run this in a loop like with the other monotonicity tests
// in this class; it starts failing at the third loop. This is okay, since our goal is to test the overflow.
$first = $unixTimeGenerator->generate(null, null, $dateTime);
$second = $unixTimeGenerator->generate(null, null, $dateTime);
$this->assertTrue($second > $first);
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateProducesMonotonicResultsStartingWithAllBitsSetFor32BitPath(): void
{
/** @var RandomGeneratorInterface&MockInterface $randomGenerator */
$randomGenerator = Mockery::mock(RandomGeneratorInterface::class);
$randomGenerator->expects()->generate(16)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$randomGenerator->allows()->generate(10)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4);
$previous = '';
for ($i = 0; $i < self::ITERATIONS; $i++) {
$bytes = $unixTimeGenerator->generate();
$this->assertTrue(
$bytes > $previous,
'Failed on iteration ' . $i . ' when evaluating ' . bin2hex($bytes) . ' > ' . bin2hex($previous),
);
$previous = $bytes;
}
}
/**
* @runInSeparateProcess since values are stored statically on the class
* @preserveGlobalState disabled
*/
public function testGenerateRollsOverWithAllBitsSetWithSameDateFor32BitPath(): void
{
$dateTime = new DateTimeImmutable('now');
/** @var RandomGeneratorInterface&MockInterface $randomGenerator */
$randomGenerator = Mockery::mock(RandomGeneratorInterface::class);
$randomGenerator->expects()->generate(16)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$randomGenerator->allows()->generate(10)->andReturns(
"\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff",
);
$unixTimeGenerator = new UnixTimeGenerator($randomGenerator, 4);
// We can only call this twice before the overflow kicks in, "randomizing" all the bits back to 1's, according to
// our mocked random generator. As a result, we can't run this in a loop like with the other monotonicity tests
// in this class; it starts failing at the third loop. This is okay, since our goal is to test the overflow.
$first = $unixTimeGenerator->generate(null, null, $dateTime);
$second = $unixTimeGenerator->generate(null, null, $dateTime);
$this->assertTrue($second > $first);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/PeclUuidTimeGeneratorTest.php | tests/Generator/PeclUuidTimeGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Ramsey\Uuid\Generator\PeclUuidTimeGenerator;
use Ramsey\Uuid\Rfc4122\Fields;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Uuid;
class PeclUuidTimeGeneratorTest extends TestCase
{
/**
* @requires extension uuid
*/
public function testGenerateCreatesUuidUsingPeclUuidMethods(): void
{
$generator = new PeclUuidTimeGenerator();
$bytes = $generator->generate();
$uuid = Uuid::fromBytes($bytes);
/** @var Fields $fields */
$fields = $uuid->getFields();
$this->assertSame(16, strlen($bytes));
$this->assertSame(Uuid::UUID_TYPE_TIME, $fields->getVersion());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/CombGeneratorTest.php | tests/Generator/CombGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use PHPUnit\Framework\MockObject\MockObject;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Generator\CombGenerator;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Test\TestCase;
use function bin2hex;
use function dechex;
use function hex2bin;
use function str_pad;
use const STR_PAD_LEFT;
class CombGeneratorTest extends TestCase
{
private int $timestampBytes = 6;
public function testGenerateUsesRandomGeneratorWithLengthMinusTimestampBytes(): void
{
$length = 10;
$expectedLength = $length - $this->timestampBytes;
/** @var MockObject & RandomGeneratorInterface $randomGenerator */
$randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock();
$randomGenerator->expects($this->once())
->method('generate')
->with($expectedLength);
/** @var MockObject & NumberConverterInterface $converter */
$converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock();
$generator = new CombGenerator($randomGenerator, $converter);
$generator->generate($length);
}
public function testGenerateCalculatesPaddedHexStringFromCurrentTimestamp(): void
{
/** @var MockObject & RandomGeneratorInterface $randomGenerator */
$randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock();
/** @var MockObject & NumberConverterInterface $converter */
$converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock();
$converter->expects($this->once())
->method('toHex')
->with($this->isType('string'));
$generator = new CombGenerator($randomGenerator, $converter);
$generator->generate(10);
}
public function testGenerateReturnsBinaryStringCreatedFromGeneratorAndConverter(): void
{
$length = 20;
$hash = dechex(1234567891);
$timeHash = dechex(1458147405);
/** @var MockObject & RandomGeneratorInterface $randomGenerator */
$randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock();
$randomGenerator->method('generate')
->with($length - $this->timestampBytes)
->willReturn($hash);
/** @var MockObject & NumberConverterInterface $converter */
$converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock();
$converter->method('toHex')
->with($this->isType('string'))
->willReturn($timeHash);
$time = str_pad($timeHash, 12, '0', STR_PAD_LEFT);
$expected = hex2bin(str_pad(bin2hex($hash), $length - $this->timestampBytes, '0')) . hex2bin($time);
$generator = new CombGenerator($randomGenerator, $converter);
$returned = $generator->generate($length);
$this->assertIsString($returned);
$this->assertSame($expected, $returned);
}
/**
* @return array<array{0: int}>
*/
public function lengthLessThanSix(): array
{
return [[0], [1], [2], [3], [4], [5]];
}
/**
* @param int<1, max> $length
*
* @dataProvider lengthLessThanSix
*/
public function testGenerateWithLessThanTimestampBytesThrowsException(int $length): void
{
/** @var MockObject & RandomGeneratorInterface $randomGenerator */
$randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock();
/** @var MockObject & NumberConverterInterface $converter */
$converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock();
$generator = new CombGenerator($randomGenerator, $converter);
$this->expectException(InvalidArgumentException::class);
$generator->generate($length);
}
public function testGenerateWithOddNumberOverTimestampBytesCausesError(): void
{
/** @var MockObject & RandomGeneratorInterface $randomGenerator */
$randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock();
/** @var MockObject & NumberConverterInterface $converter */
$converter = $this->getMockBuilder(NumberConverterInterface::class)->getMock();
$generator = new CombGenerator($randomGenerator, $converter);
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessage('Length must be an even number');
$generator->generate(7);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/RandomLibAdapterTest.php | tests/Generator/RandomLibAdapterTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Mockery;
use Mockery\MockInterface;
use Ramsey\Uuid\Generator\RandomLibAdapter;
use Ramsey\Uuid\Test\TestCase;
use RandomLib\Factory as RandomLibFactory;
use RandomLib\Generator;
class RandomLibAdapterTest extends TestCase
{
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testAdapterWithGeneratorDoesNotCreateGenerator(): void
{
$factory = Mockery::mock('overload:' . RandomLibFactory::class);
$factory->shouldNotReceive('getHighStrengthGenerator');
$generator = $this->getMockBuilder(Generator::class)
->disableOriginalConstructor()
->getMock();
/** @phpstan-ignore method.alreadyNarrowedType */
$this->assertInstanceOf(RandomLibAdapter::class, new RandomLibAdapter($generator));
}
/**
* @runInSeparateProcess
* @preserveGlobalState disabled
*/
public function testAdapterWithoutGeneratorCreatesGenerator(): void
{
$generator = Mockery::mock(Generator::class);
/** @var RandomLibFactory&MockInterface $factory */
$factory = Mockery::mock('overload:' . RandomLibFactory::class);
$factory->expects()->getHighStrengthGenerator()->andReturns($generator);
/** @phpstan-ignore method.alreadyNarrowedType */
$this->assertInstanceOf(RandomLibAdapter::class, new RandomLibAdapter());
}
public function testGenerateUsesGenerator(): void
{
$length = 10;
$generator = $this->getMockBuilder(Generator::class)
->disableOriginalConstructor()
->getMock();
$generator->expects($this->once())
->method('generate')
->with($length)
->willReturn('foo');
$adapter = new RandomLibAdapter($generator);
$adapter->generate($length);
}
public function testGenerateReturnsString(): void
{
$generator = $this->getMockBuilder(Generator::class)
->disableOriginalConstructor()
->getMock();
$generator->expects($this->once())
->method('generate')
->willReturn('random-string');
$adapter = new RandomLibAdapter($generator);
$result = $adapter->generate(1);
$this->assertSame('random-string', $result);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/NameGeneratorFactoryTest.php | tests/Generator/NameGeneratorFactoryTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Ramsey\Uuid\Generator\DefaultNameGenerator;
use Ramsey\Uuid\Generator\NameGeneratorFactory;
use Ramsey\Uuid\Test\TestCase;
class NameGeneratorFactoryTest extends TestCase
{
public function testGetGenerator(): void
{
$factory = new NameGeneratorFactory();
$this->assertInstanceOf(DefaultNameGenerator::class, $factory->getGenerator());
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/tests/Generator/DceSecurityGeneratorTest.php | tests/Generator/DceSecurityGeneratorTest.php | <?php
declare(strict_types=1);
namespace Ramsey\Uuid\Test\Generator;
use Mockery;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Exception\DceSecurityException;
use Ramsey\Uuid\Generator\DceSecurityGenerator;
use Ramsey\Uuid\Generator\DefaultTimeGenerator;
use Ramsey\Uuid\Generator\TimeGeneratorInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Provider\DceSecurityProviderInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\Time\FixedTimeProvider;
use Ramsey\Uuid\Test\TestCase;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
use Ramsey\Uuid\Uuid;
use function bin2hex;
use function substr;
class DceSecurityGeneratorTest extends TestCase
{
/**
* @param int|string $uid
* @param int|string $gid
* @param int|string $seconds
* @param int|string $microseconds
*
* @dataProvider provideValuesForDceSecurityGenerator
*/
public function testGenerateBytesReplacesBytesWithDceValues(
$uid,
$gid,
string $node,
$seconds,
$microseconds,
int $providedDomain,
?IntegerObject $providedId,
?Hexadecimal $providedNode,
string $expectedId,
string $expectedDomain,
string $expectedNode,
string $expectedTimeMidHi
): void {
/** @var DceSecurityProviderInterface $dceSecurityProvider */
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class, [
'getUid' => new IntegerObject($uid),
'getGid' => new IntegerObject($gid),
]);
/** @var NodeProviderInterface $nodeProvider */
$nodeProvider = Mockery::mock(NodeProviderInterface::class, [
'getNode' => new Hexadecimal($node),
]);
$timeProvider = new FixedTimeProvider(new Time($seconds, $microseconds));
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = new GenericTimeConverter($calculator);
$timeGenerator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$bytes = $dceSecurityGenerator->generate($providedDomain, $providedId, $providedNode);
$this->assertSame($expectedId, bin2hex(substr($bytes, 0, 4)));
$this->assertSame($expectedDomain, bin2hex(substr($bytes, 9, 1)));
$this->assertSame($expectedNode, bin2hex(substr($bytes, 10)));
$this->assertSame($expectedTimeMidHi, bin2hex(substr($bytes, 4, 4)));
}
/**
* @return array<array{uid: int|string, node: string, seconds: int, microseconds: int, providedDomain: int, providedId: IntegerObject|null, providedNode: null, expectedId: string, expectedDomain: string, expectedNode: string, expectedTimeMidHi: string}>
*/
public function provideValuesForDceSecurityGenerator(): array
{
return [
[
'uid' => '1001',
'gid' => '2001',
'node' => '001122334455',
'seconds' => 1579132397,
'microseconds' => 500000,
'providedDomain' => Uuid::DCE_DOMAIN_PERSON,
'providedId' => null,
'providedNode' => null,
'expectedId' => '000003e9',
'expectedDomain' => '00',
'expectedNode' => '001122334455',
'expectedTimeMidHi' => '37f201ea',
],
[
'uid' => '1001',
'gid' => '2001',
'node' => '001122334455',
'seconds' => 1579132397,
'microseconds' => 500000,
'providedDomain' => Uuid::DCE_DOMAIN_GROUP,
'providedId' => null,
'providedNode' => null,
'expectedId' => '000007d1',
'expectedDomain' => '01',
'expectedNode' => '001122334455',
'expectedTimeMidHi' => '37f201ea',
],
[
'uid' => 0,
'gid' => 0,
'node' => '001122334455',
'seconds' => 1579132397,
'microseconds' => 500000,
'providedDomain' => Uuid::DCE_DOMAIN_ORG,
'providedId' => new IntegerObject('4294967295'),
'providedNode' => null,
'expectedId' => 'ffffffff',
'expectedDomain' => '02',
'expectedNode' => '001122334455',
'expectedTimeMidHi' => '37f201ea',
],
];
}
public function testGenerateThrowsExceptionForInvalidDomain(): void
{
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$generator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage('Local domain must be a valid DCE Security domain');
$generator->generate(42);
}
public function testGenerateThrowsExceptionForOrgWithoutIdentifier(): void
{
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$generator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage('A local identifier must be provided for the org domain');
$generator->generate(Uuid::DCE_DOMAIN_ORG);
}
public function testClockSequenceLowerBounds(): void
{
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$nodeProvider = Mockery::mock(NodeProviderInterface::class);
$timeProvider = new FixedTimeProvider(new Time(1583527677, 111984));
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = new GenericTimeConverter($calculator);
$timeGenerator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$bytes = $dceSecurityGenerator->generate(
Uuid::DCE_DOMAIN_ORG,
new IntegerObject(1001),
new Hexadecimal('0123456789ab'),
0
);
$hex = bin2hex($bytes);
$this->assertSame('000003e9', substr($hex, 0, 8));
$this->assertSame('5feb01ea', substr($hex, 8, 8));
$this->assertSame('00', substr($hex, 16, 2));
$this->assertSame('02', substr($hex, 18, 2));
$this->assertSame('0123456789ab', substr($hex, 20));
}
public function testClockSequenceUpperBounds(): void
{
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$nodeProvider = Mockery::mock(NodeProviderInterface::class);
$timeProvider = new FixedTimeProvider(new Time(1583527677, 111984));
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$timeConverter = new GenericTimeConverter($calculator);
$timeGenerator = new DefaultTimeGenerator($nodeProvider, $timeConverter, $timeProvider);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$bytes = $dceSecurityGenerator->generate(
Uuid::DCE_DOMAIN_ORG,
new IntegerObject(1001),
new Hexadecimal('0123456789ab'),
63
);
$hex = bin2hex($bytes);
$this->assertSame('000003e9', substr($hex, 0, 8));
$this->assertSame('5feb01ea', substr($hex, 8, 8));
$this->assertSame('3f', substr($hex, 16, 2));
$this->assertSame('02', substr($hex, 18, 2));
$this->assertSame('0123456789ab', substr($hex, 20));
}
public function testExceptionThrownWhenClockSequenceTooLow(): void
{
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Clock sequence out of bounds; it must be a value between 0 and 63'
);
$dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, null, null, -1);
}
public function testExceptionThrownWhenClockSequenceTooHigh(): void
{
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Clock sequence out of bounds; it must be a value between 0 and 63'
);
$dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, null, null, 64);
}
public function testExceptionThrownWhenLocalIdTooLow(): void
{
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$numberConverter = Mockery::mock(NumberConverterInterface::class);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Local identifier out of bounds; it must be a value between 0 and 4294967295'
);
$dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, new IntegerObject(-1));
}
public function testExceptionThrownWhenLocalIdTooHigh(): void
{
$dceSecurityProvider = Mockery::mock(DceSecurityProviderInterface::class);
$timeGenerator = Mockery::mock(TimeGeneratorInterface::class);
$calculator = new BrickMathCalculator();
$numberConverter = new GenericNumberConverter($calculator);
$dceSecurityGenerator = new DceSecurityGenerator($numberConverter, $timeGenerator, $dceSecurityProvider);
$this->expectException(DceSecurityException::class);
$this->expectExceptionMessage(
'Local identifier out of bounds; it must be a value between 0 and 4294967295'
);
$dceSecurityGenerator->generate(Uuid::DCE_DOMAIN_ORG, new IntegerObject('4294967296'));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
piotrplenik/clean-code-php | https://github.com/piotrplenik/clean-code-php/blob/8d9013251a674da30a0e25fb950438f2d7cfdf64/ecs.php | ecs.php | <?php
declare(strict_types=1);
use PhpCsFixer\Fixer\PhpTag\BlankLineAfterOpeningTagFixer;
use PhpCsFixer\Fixer\Strict\DeclareStrictTypesFixer;
use PhpCsFixer\Fixer\Strict\StrictComparisonFixer;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
use Symplify\EasyCodingStandard\ValueObject\Option;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;
return static function (ContainerConfigurator $containerConfigurator): void
{
$containerConfigurator->import(SetList::COMMON);
$containerConfigurator->import(SetList::CLEAN_CODE);
$containerConfigurator->import(SetList::PSR_12);
$containerConfigurator->import(SetList::SYMPLIFY);
$parameters = $containerConfigurator->parameters();
$parameters->set(Option::PATHS, [__DIR__ . '/src', __DIR__ . '/config', __DIR__ . '/ecs.php']);
$parameters->set(Option::SKIP, [
BlankLineAfterOpeningTagFixer::class => null,
StrictComparisonFixer::class => null,
DeclareStrictTypesFixer::class => null,
]);
};
| php | MIT | 8d9013251a674da30a0e25fb950438f2d7cfdf64 | 2026-01-04T15:03:18.329539Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/autoload.php | src/autoload.php | <?php
/**
* Simple autoloader that follow the PHP Standards Recommendation #0 (PSR-0)
* @see https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md for more informations.
*
* Code inspired from the SplClassLoader RFC
* @see https://wiki.php.net/rfc/splclassloader#example_implementation
*/
spl_autoload_register(function ($className) {
$className = ltrim($className, '\\');
$fileName = '';
if ($lastNsPos = strripos($className, '\\')) {
$namespace = substr($className, 0, $lastNsPos);
$className = substr($className, $lastNsPos + 1);
$fileName = str_replace('\\', DIRECTORY_SEPARATOR, $namespace) . DIRECTORY_SEPARATOR;
}
$fileName = __DIR__ . DIRECTORY_SEPARATOR . $fileName . $className . '.php';
if (file_exists($fileName)) {
require $fileName;
return true;
}
return false;
});
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/UniqueGenerator.php | src/Faker/UniqueGenerator.php | <?php
namespace Faker;
/**
* Proxy for other generators, to return only unique values. Works with
* Faker\Generator\Base->unique()
*/
class UniqueGenerator
{
protected $generator;
protected $maxRetries;
protected $uniques = array();
/**
* @param Generator $generator
* @param integer $maxRetries
*/
public function __construct(Generator $generator, $maxRetries = 10000)
{
$this->generator = $generator;
$this->maxRetries = $maxRetries;
}
/**
* Catch and proxy all generator calls but return only unique values
* @param string $attribute
* @return mixed
*/
public function __get($attribute)
{
return $this->__call($attribute, array());
}
/**
* Catch and proxy all generator calls with arguments but return only unique values
* @param string $name
* @param array $arguments
* @return mixed
*/
public function __call($name, $arguments)
{
if (!isset($this->uniques[$name])) {
$this->uniques[$name] = array();
}
$i = 0;
do {
$res = call_user_func_array(array($this->generator, $name), $arguments);
$i++;
if ($i > $this->maxRetries) {
throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a unique value', $this->maxRetries));
}
} while (array_key_exists(serialize($res), $this->uniques[$name]));
$this->uniques[$name][serialize($res)]= null;
return $res;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/Documentor.php | src/Faker/Documentor.php | <?php
namespace Faker;
class Documentor
{
protected $generator;
/**
* @param Generator $generator
*/
public function __construct(Generator $generator)
{
$this->generator = $generator;
}
/**
* @return array
*/
public function getFormatters()
{
$formatters = array();
$providers = array_reverse($this->generator->getProviders());
$providers[]= new Provider\Base($this->generator);
foreach ($providers as $provider) {
$providerClass = get_class($provider);
$formatters[$providerClass] = array();
$refl = new \ReflectionObject($provider);
foreach ($refl->getMethods(\ReflectionMethod::IS_PUBLIC) as $reflmethod) {
if ($reflmethod->getDeclaringClass()->getName() == 'Faker\Provider\Base' && $providerClass != 'Faker\Provider\Base') {
continue;
}
$methodName = $reflmethod->name;
if ($reflmethod->isConstructor()) {
continue;
}
$parameters = array();
foreach ($reflmethod->getParameters() as $reflparameter) {
$parameter = '$'. $reflparameter->getName();
if ($reflparameter->isDefaultValueAvailable()) {
$parameter .= ' = ' . var_export($reflparameter->getDefaultValue(), true);
}
$parameters []= $parameter;
}
$parameters = $parameters ? '('. join(', ', $parameters) . ')' : '';
try {
$example = $this->generator->format($methodName);
} catch (\InvalidArgumentException $e) {
$example = '';
}
if (is_array($example)) {
$example = "array('". join("', '", $example) . "')";
} elseif ($example instanceof \DateTime) {
$example = "DateTime('" . $example->format('Y-m-d H:i:s') . "')";
} elseif ($example instanceof Generator || $example instanceof UniqueGenerator) { // modifier
$example = '';
} else {
$example = var_export($example, true);
}
$formatters[$providerClass][$methodName . $parameters] = $example;
}
}
return $formatters;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/DefaultGenerator.php | src/Faker/DefaultGenerator.php | <?php
namespace Faker;
/**
* This generator returns a default value for all called properties
* and methods. It works with Faker\Generator\Base->optional().
*/
class DefaultGenerator
{
protected $default;
public function __construct($default = null)
{
$this->default = $default;
}
/**
* @param string $attribute
*
* @return mixed
*/
public function __get($attribute)
{
return $this->default;
}
/**
* @param string $method
* @param array $attributes
*
* @return mixed
*/
public function __call($method, $attributes)
{
return $this->default;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ValidGenerator.php | src/Faker/ValidGenerator.php | <?php
namespace Faker;
/**
* Proxy for other generators, to return only valid values. Works with
* Faker\Generator\Base->valid()
*/
class ValidGenerator
{
protected $generator;
protected $validator;
protected $maxRetries;
/**
* @param Generator $generator
* @param callable|null $validator
* @param integer $maxRetries
*/
public function __construct(Generator $generator, $validator = null, $maxRetries = 10000)
{
if (is_null($validator)) {
$validator = function () {
return true;
};
} elseif (!is_callable($validator)) {
throw new \InvalidArgumentException('valid() only accepts callables as first argument');
}
$this->generator = $generator;
$this->validator = $validator;
$this->maxRetries = $maxRetries;
}
/**
* Catch and proxy all generator calls but return only valid values
* @param string $attribute
*
* @return mixed
*/
public function __get($attribute)
{
return $this->__call($attribute, array());
}
/**
* Catch and proxy all generator calls with arguments but return only valid values
* @param string $name
* @param array $arguments
*
* @return mixed
*/
public function __call($name, $arguments)
{
$i = 0;
do {
$res = call_user_func_array(array($this->generator, $name), $arguments);
$i++;
if ($i > $this->maxRetries) {
throw new \OverflowException(sprintf('Maximum retries of %d reached without finding a valid value', $this->maxRetries));
}
} while (!call_user_func($this->validator, $res));
return $res;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/Factory.php | src/Faker/Factory.php | <?php
namespace Faker;
class Factory
{
const DEFAULT_LOCALE = 'en_US';
protected static $defaultProviders = array('Address', 'Barcode', 'Biased', 'Color', 'Company', 'DateTime', 'File', 'HtmlLorem', 'Image', 'Internet', 'Lorem', 'Miscellaneous', 'Payment', 'Person', 'PhoneNumber', 'Text', 'UserAgent', 'Uuid');
/**
* Create a new generator
*
* @param string $locale
* @return Generator
*/
public static function create($locale = self::DEFAULT_LOCALE)
{
$generator = new Generator();
foreach (static::$defaultProviders as $provider) {
$providerClassName = self::getProviderClassname($provider, $locale);
$generator->addProvider(new $providerClassName($generator));
}
return $generator;
}
/**
* @param string $provider
* @param string $locale
* @return string
*/
protected static function getProviderClassname($provider, $locale = '')
{
if ($providerClass = self::findProviderClassname($provider, $locale)) {
return $providerClass;
}
// fallback to default locale
if ($providerClass = self::findProviderClassname($provider, static::DEFAULT_LOCALE)) {
return $providerClass;
}
// fallback to no locale
if ($providerClass = self::findProviderClassname($provider)) {
return $providerClass;
}
throw new \InvalidArgumentException(sprintf('Unable to find provider "%s" with locale "%s"', $provider, $locale));
}
/**
* @param string $provider
* @param string $locale
* @return string
*/
protected static function findProviderClassname($provider, $locale = '')
{
$providerClass = 'Faker\\' . ($locale ? sprintf('Provider\%s\%s', $locale, $provider) : sprintf('Provider\%s', $provider));
if (class_exists($providerClass, true)) {
return $providerClass;
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/Generator.php | src/Faker/Generator.php | <?php
namespace Faker;
/**
* @property string $name
* @method string name(string $gender = null)
* @property string $firstName
* @method string firstName(string $gender = null)
* @property string $firstNameMale
* @property string $firstNameFemale
* @property string $lastName
* @property string $title
* @method string title(string $gender = null)
* @property string $titleMale
* @property string $titleFemale
*
* @property string $citySuffix
* @property string $streetSuffix
* @property string $buildingNumber
* @property string $city
* @property string $streetName
* @property string $streetAddress
* @property string $secondaryAddress
* @property string $postcode
* @property string $address
* @property string $state
* @property string $country
* @property float $latitude
* @property float $longitude
*
* @property string $ean13
* @property string $ean8
* @property string $isbn13
* @property string $isbn10
*
* @property string $phoneNumber
* @property string $e164PhoneNumber
*
* @property string $catchPhrase
* @property string $bs
* @property string $company
* @property string $companySuffix
* @property string $jobTitle
*
* @property string $creditCardType
* @property string $creditCardNumber
* @method string creditCardNumber($type = null, $formatted = false, $separator = '-')
* @property \DateTime $creditCardExpirationDate
* @property string $creditCardExpirationDateString
* @property array $creditCardDetails
* @property string $bankAccountNumber
* @method string iban($countryCode = null, $prefix = '', $length = null)
* @property string $swiftBicNumber
* @property string $vat
*
* @property string $word
* @property string|array $words
* @method string|array words($nb = 3, $asText = false)
* @method string word()
* @property string $sentence
* @method string sentence($nbWords = 6, $variableNbWords = true)
* @property string|array $sentences
* @method string|array sentences($nb = 3, $asText = false)
* @property string $paragraph
* @method string paragraph($nbSentences = 3, $variableNbSentences = true)
* @property string|array $paragraphs
* @method string|array paragraphs($nb = 3, $asText = false)
* @property string $text
* @method string text($maxNbChars = 200)
*
* @method string realText($maxNbChars = 200, $indexSize = 2)
*
* @property string $email
* @property string $safeEmail
* @property string $freeEmail
* @property string $companyEmail
* @property string $freeEmailDomain
* @property string $safeEmailDomain
* @property string $userName
* @property string $password
* @method string password($minLength = 6, $maxLength = 20)
* @property string $domainName
* @property string $domainWord
* @property string $tld
* @property string $url
* @property string $slug
* @method string slug($nbWords = 6, $variableNbWords = true)
* @property string $ipv4
* @property string $ipv6
* @property string $localIpv4
* @property string $macAddress
*
* @property int $unixTime
* @property \DateTime $dateTime
* @property \DateTime $dateTimeAD
* @property string $iso8601
* @property \DateTime $dateTimeThisCentury
* @property \DateTime $dateTimeThisDecade
* @property \DateTime $dateTimeThisYear
* @property \DateTime $dateTimeThisMonth
* @property string $amPm
* @property string $dayOfMonth
* @property string $dayOfWeek
* @property string $month
* @property string $monthName
* @property string $year
* @property string $century
* @property string $timezone
* @method string amPm($max = 'now')
* @method string date($format = 'Y-m-d', $max = 'now')
* @method string dayOfMonth($max = 'now')
* @method string dayOfWeek($max = 'now')
* @method string iso8601($max = 'now')
* @method string month($max = 'now')
* @method string monthName($max = 'now')
* @method string time($format = 'H:i:s', $max = 'now')
* @method int unixTime($max = 'now')
* @method string year($max = 'now')
* @method \DateTime dateTime($max = 'now', $timezone = null)
* @method \DateTime dateTimeAd($max = 'now', $timezone = null)
* @method \DateTime dateTimeBetween($startDate = '-30 years', $endDate = 'now', $timezone = null)
* @method \DateTime dateTimeInInterval($date = '-30 years', $interval = '+5 days', $timezone = null)
* @method \DateTime dateTimeThisCentury($max = 'now', $timezone = null)
* @method \DateTime dateTimeThisDecade($max = 'now', $timezone = null)
* @method \DateTime dateTimeThisYear($max = 'now', $timezone = null)
* @method \DateTime dateTimeThisMonth($max = 'now', $timezone = null)
*
* @property string $md5
* @property string $sha1
* @property string $sha256
* @property string $locale
* @property string $countryCode
* @property string $countryISOAlpha3
* @property string $languageCode
* @property string $currencyCode
* @property boolean $boolean
* @method boolean boolean($chanceOfGettingTrue = 50)
*
* @property int $randomDigit
* @property int $randomDigitNot
* @property int $randomDigitNotNull
* @property string $randomLetter
* @property string $randomAscii
* @method int randomNumber($nbDigits = null, $strict = false)
* @method int|string|null randomKey(array $array = array())
* @method int numberBetween($min = 0, $max = 2147483647)
* @method float randomFloat($nbMaxDecimals = null, $min = 0, $max = null)
* @method mixed randomElement(array $array = array('a', 'b', 'c'))
* @method array randomElements(array $array = array('a', 'b', 'c'), $count = 1, $allowDuplicates = false)
* @method array|string shuffle($arg = '')
* @method array shuffleArray(array $array = array())
* @method string shuffleString($string = '', $encoding = 'UTF-8')
* @method string numerify($string = '###')
* @method string lexify($string = '????')
* @method string bothify($string = '## ??')
* @method string asciify($string = '****')
* @method string regexify($regex = '')
* @method string toLower($string = '')
* @method string toUpper($string = '')
* @method Generator optional($weight = 0.5, $default = null)
* @method Generator unique($reset = false, $maxRetries = 10000)
* @method Generator valid($validator = null, $maxRetries = 10000)
* @method mixed passthrough($passthrough)
*
* @method integer biasedNumberBetween($min = 0, $max = 100, $function = 'sqrt')
*
* @property string $macProcessor
* @property string $linuxProcessor
* @property string $userAgent
* @property string $chrome
* @property string $firefox
* @property string $safari
* @property string $opera
* @property string $internetExplorer
* @property string $windowsPlatformToken
* @property string $macPlatformToken
* @property string $linuxPlatformToken
*
* @property string $uuid
*
* @property string $mimeType
* @property string $fileExtension
* @method string file($sourceDirectory = '/tmp', $targetDirectory = '/tmp', $fullPath = true)
*
* @method string imageUrl($width = 640, $height = 480, $category = null, $randomize = true, $word = null, $gray = false)
* @method string image($dir = null, $width = 640, $height = 480, $category = null, $fullPath = true, $randomize = true, $word = null)
*
* @property string $hexColor
* @property string $safeHexColor
* @property string $rgbColor
* @property array $rgbColorAsArray
* @property string $rgbCssColor
* @property string $safeColorName
* @property string $colorName
*
* @method string randomHtml($maxDepth = 4, $maxWidth = 4)
*
*/
class Generator
{
protected $providers = array();
protected $formatters = array();
public function addProvider($provider)
{
array_unshift($this->providers, $provider);
}
public function getProviders()
{
return $this->providers;
}
public function seed($seed = null)
{
if ($seed === null) {
mt_srand();
} else {
if (PHP_VERSION_ID < 70100) {
mt_srand((int) $seed);
} else {
mt_srand((int) $seed, MT_RAND_PHP);
}
}
}
public function format($formatter, $arguments = array())
{
return call_user_func_array($this->getFormatter($formatter), $arguments);
}
/**
* @param string $formatter
*
* @return Callable
*/
public function getFormatter($formatter)
{
if (isset($this->formatters[$formatter])) {
return $this->formatters[$formatter];
}
foreach ($this->providers as $provider) {
if (method_exists($provider, $formatter)) {
$this->formatters[$formatter] = array($provider, $formatter);
return $this->formatters[$formatter];
}
}
throw new \InvalidArgumentException(sprintf('Unknown formatter "%s"', $formatter));
}
/**
* Replaces tokens ('{{ tokenName }}') with the result from the token method call
*
* @param string $string String that needs to bet parsed
* @return string
*/
public function parse($string)
{
return preg_replace_callback('/\{\{\s?(\w+)\s?\}\}/u', array($this, 'callFormatWithMatches'), $string);
}
protected function callFormatWithMatches($matches)
{
return $this->format($matches[1]);
}
/**
* @param string $attribute
*
* @return mixed
*/
public function __get($attribute)
{
return $this->format($attribute);
}
/**
* @param string $method
* @param array $attributes
*
* @return mixed
*/
public function __call($method, $attributes)
{
return $this->format($method, $attributes);
}
public function __destruct()
{
$this->seed();
}
public function __wakeup()
{
$this->formatters = [];
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Doctrine/Populator.php | src/Faker/ORM/Doctrine/Populator.php | <?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\ObjectManager;
use Faker\Generator;
/**
* Service class for populating a database using the Doctrine ORM or ODM.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
/** @var int */
protected $batchSize;
/** @var Generator */
protected $generator;
/** @var ObjectManager|null */
protected $manager;
/** @var array */
protected $entities = array();
/** @var array */
protected $quantities = array();
/** @var array */
protected $generateId = array();
/**
* Populator constructor.
* @param Generator $generator
* @param ObjectManager|null $manager
* @param int $batchSize
*/
public function __construct(Generator $generator, ObjectManager $manager = null, $batchSize = 1000)
{
$this->generator = $generator;
$this->manager = $manager;
$this->batchSize = $batchSize;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Doctrine classname, or a \Faker\ORM\Doctrine\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array(), $customModifiers = array(), $generateId = false)
{
if (!$entity instanceof \Faker\ORM\Doctrine\EntityPopulator) {
if (null === $this->manager) {
throw new \InvalidArgumentException("No entity manager passed to Doctrine Populator.");
}
$entity = new \Faker\ORM\Doctrine\EntityPopulator($this->manager->getClassMetadata($entity));
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->mergeModifiersWith($customModifiers);
$this->generateId[$entity->getClass()] = $generateId;
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* Please note that large amounts of data will result in more memory usage since the the Populator will return
* all newly created primary keys after executing.
*
* @param null|EntityManager $entityManager A Doctrine connection object
*
* @return array A list of the inserted PKs
*/
public function execute($entityManager = null)
{
if (null === $entityManager) {
$entityManager = $this->manager;
}
if (null === $entityManager) {
throw new \InvalidArgumentException("No entity manager passed to Doctrine Populator.");
}
$insertedEntities = array();
foreach ($this->quantities as $class => $number) {
$generateId = $this->generateId[$class];
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute(
$entityManager,
$insertedEntities,
$generateId
);
if (count($insertedEntities) % $this->batchSize === 0) {
$entityManager->flush();
}
}
$entityManager->flush();
}
return $insertedEntities;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Doctrine/EntityPopulator.php | src/Faker/ORM/Doctrine/EntityPopulator.php | <?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
/**
* Service class for populating a table through a Doctrine Entity class.
*/
class EntityPopulator
{
/**
* @var ClassMetadata
*/
protected $class;
/**
* @var array
*/
protected $columnFormatters = array();
/**
* @var array
*/
protected $modifiers = array();
/**
* Class constructor.
*
* @param ClassMetadata $class
*/
public function __construct(ClassMetadata $class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class->getName();
}
/**
* @param $columnFormatters
*/
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param array $modifiers
*/
public function setModifiers(array $modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
/**
* @param array $modifiers
*/
public function mergeModifiersWith(array $modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator)
{
$formatters = array();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new ColumnTypeGuesser($generator);
foreach ($this->class->getFieldNames() as $fieldName) {
if ($this->class->isIdentifier($fieldName) || !$this->class->hasField($fieldName)) {
continue;
}
$size = isset($this->class->fieldMappings[$fieldName]['length']) ? $this->class->fieldMappings[$fieldName]['length'] : null;
if ($formatter = $nameGuesser->guessFormat($fieldName, $size)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($fieldName, $this->class)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
foreach ($this->class->getAssociationNames() as $assocName) {
if ($this->class->isCollectionValuedAssociation($assocName)) {
continue;
}
$relatedClass = $this->class->getAssociationTargetClass($assocName);
$unique = $optional = false;
if ($this->class instanceof \Doctrine\ORM\Mapping\ClassMetadata) {
$mappings = $this->class->getAssociationMappings();
foreach ($mappings as $mapping) {
if ($mapping['targetEntity'] == $relatedClass) {
if ($mapping['type'] == \Doctrine\ORM\Mapping\ClassMetadata::ONE_TO_ONE) {
$unique = true;
$optional = isset($mapping['joinColumns'][0]['nullable']) ? $mapping['joinColumns'][0]['nullable'] : false;
break;
}
}
}
} elseif ($this->class instanceof \Doctrine\ODM\MongoDB\Mapping\ClassMetadata) {
$mappings = $this->class->associationMappings;
foreach ($mappings as $mapping) {
if ($mapping['targetDocument'] == $relatedClass) {
if ($mapping['type'] == \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::ONE && $mapping['association'] == \Doctrine\ODM\MongoDB\Mapping\ClassMetadata::REFERENCE_ONE) {
$unique = true;
$optional = isset($mapping['nullable']) ? $mapping['nullable'] : false;
break;
}
}
}
}
$index = 0;
$formatters[$assocName] = function ($inserted) use ($relatedClass, &$index, $unique, $optional) {
if (isset($inserted[$relatedClass])) {
if ($unique) {
$related = null;
if (isset($inserted[$relatedClass][$index]) || !$optional) {
$related = $inserted[$relatedClass][$index];
}
$index++;
return $related;
}
return $inserted[$relatedClass][mt_rand(0, count($inserted[$relatedClass]) - 1)];
}
return null;
};
}
return $formatters;
}
/**
* Insert one new record using the Entity class.
* @param ObjectManager $manager
* @param bool $generateId
* @return EntityPopulator
*/
public function execute(ObjectManager $manager, $insertedEntities, $generateId = false)
{
$obj = $this->class->newInstance();
$this->fillColumns($obj, $insertedEntities);
$this->callMethods($obj, $insertedEntities);
if ($generateId) {
$idsName = $this->class->getIdentifier();
foreach ($idsName as $idName) {
$id = $this->generateId($obj, $idName, $manager);
$this->class->reflFields[$idName]->setValue($obj, $id);
}
}
$manager->persist($obj);
return $obj;
}
private function fillColumns($obj, $insertedEntities)
{
foreach ($this->columnFormatters as $field => $format) {
if (null !== $format) {
// Add some extended debugging information to any errors thrown by the formatter
try {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
} catch (\InvalidArgumentException $ex) {
throw new \InvalidArgumentException(sprintf(
"Failed to generate a value for %s::%s: %s",
get_class($obj),
$field,
$ex->getMessage()
));
}
// Try a standard setter if it's available, otherwise fall back on reflection
$setter = sprintf("set%s", ucfirst($field));
if (is_callable(array($obj, $setter))) {
$obj->$setter($value);
} else {
$this->class->reflFields[$field]->setValue($obj, $value);
}
}
}
}
private function callMethods($obj, $insertedEntities)
{
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
}
/**
* @param ObjectManager $manager
* @return int|null
*/
private function generateId($obj, $column, ObjectManager $manager)
{
/* @var $repository \Doctrine\Common\Persistence\ObjectRepository */
$repository = $manager->getRepository(get_class($obj));
$result = $repository->createQueryBuilder('e')
->select(sprintf('e.%s', $column))
->getQuery()
->execute();
$ids = array_map('current', $result->toArray());
$id = null;
do {
$id = mt_rand();
} while (in_array($id, $ids));
return $id;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Doctrine/ColumnTypeGuesser.php | src/Faker/ORM/Doctrine/ColumnTypeGuesser.php | <?php
namespace Faker\ORM\Doctrine;
use Doctrine\Common\Persistence\Mapping\ClassMetadata;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @param ClassMetadata $class
* @return \Closure|null
*/
public function guessFormat($fieldName, ClassMetadata $class)
{
$generator = $this->generator;
$type = $class->getTypeOfField($fieldName);
switch ($type) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'decimal':
$size = isset($class->fieldMappings[$fieldName]['precision']) ? $class->fieldMappings[$fieldName]['precision'] : 2;
return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case 'smallint':
return function () {
return mt_rand(0, 65535);
};
case 'integer':
return function () {
return mt_rand(0, intval('2147483647'));
};
case 'bigint':
return function () {
return mt_rand(0, intval('18446744073709551615'));
};
case 'float':
return function () {
return mt_rand(0, intval('4294967295'))/mt_rand(1, intval('4294967295'));
};
case 'string':
$size = isset($class->fieldMappings[$fieldName]['length']) ? $class->fieldMappings[$fieldName]['length'] : 255;
return function () use ($generator, $size) {
return $generator->text($size);
};
case 'text':
return function () use ($generator) {
return $generator->text;
};
case 'datetime':
case 'date':
case 'time':
return function () use ($generator) {
return $generator->datetime;
};
case 'datetime_immutable':
case 'date_immutable':
case 'time_immutable':
return function () use ($generator) {
return \DateTimeImmutable::createFromMutable($generator->datetime);
};
default:
// no smart way to guess what the user expects here
return null;
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Mandango/Populator.php | src/Faker/ORM/Mandango/Populator.php | <?php
namespace Faker\ORM\Mandango;
use Mandango\Mandango;
/**
* Service class for populating a database using Mandango.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
protected $generator;
protected $mandango;
protected $entities = array();
protected $quantities = array();
/**
* @param \Faker\Generator $generator
* @param Mandango $mandango
*/
public function __construct(\Faker\Generator $generator, Mandango $mandango)
{
$this->generator = $generator;
$this->mandango = $mandango;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Propel ActiveRecord classname, or a \Faker\ORM\Propel\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array())
{
if (!$entity instanceof \Faker\ORM\Mandango\EntityPopulator) {
$entity = new \Faker\ORM\Mandango\EntityPopulator($entity);
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator, $this->mandango));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @return array A list of the inserted entities.
*/
public function execute()
{
$insertedEntities = array();
foreach ($this->quantities as $class => $number) {
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute($this->mandango, $insertedEntities);
}
}
$this->mandango->flush();
return $insertedEntities;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Mandango/EntityPopulator.php | src/Faker/ORM/Mandango/EntityPopulator.php | <?php
namespace Faker\ORM\Mandango;
use Mandango\Mandango;
use Faker\Provider\Base;
/**
* Service class for populating a table through a Mandango ActiveRecord class.
*/
class EntityPopulator
{
protected $class;
protected $columnFormatters = array();
/**
* Class constructor.
*
* @param string $class A Mandango ActiveRecord classname
*/
public function __construct($class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class;
}
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param \Faker\Generator $generator
* @param Mandango $mandango
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator, Mandango $mandango)
{
$formatters = array();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new \Faker\ORM\Mandango\ColumnTypeGuesser($generator);
$metadata = $mandango->getMetadata($this->class);
// fields
foreach ($metadata['fields'] as $fieldName => $field) {
if ($formatter = $nameGuesser->guessFormat($fieldName)) {
$formatters[$fieldName] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($field)) {
$formatters[$fieldName] = $formatter;
continue;
}
}
// references
foreach (array_merge($metadata['referencesOne'], $metadata['referencesMany']) as $referenceName => $reference) {
if (!isset($reference['class'])) {
continue;
}
$referenceClass = $reference['class'];
$formatters[$referenceName] = function ($insertedEntities) use ($referenceClass) {
if (isset($insertedEntities[$referenceClass])) {
return Base::randomElement($insertedEntities[$referenceClass]);
}
};
}
return $formatters;
}
/**
* Insert one new record using the Entity class.
* @param Mandango $mandango
*/
public function execute(Mandango $mandango, $insertedEntities)
{
$metadata = $mandango->getMetadata($this->class);
$obj = $mandango->create($this->class);
foreach ($this->columnFormatters as $column => $format) {
if (null !== $format) {
$value = is_callable($format) ? $format($insertedEntities, $obj) : $format;
if (isset($metadata['fields'][$column]) ||
isset($metadata['referencesOne'][$column])) {
$obj->set($column, $value);
}
if (isset($metadata['referencesMany'][$column])) {
$adder = 'add'.ucfirst($column);
$obj->$adder($value);
}
}
}
$mandango->persist($obj);
return $obj;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Mandango/ColumnTypeGuesser.php | src/Faker/ORM/Mandango/ColumnTypeGuesser.php | <?php
namespace Faker\ORM\Mandango;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @return \Closure|null
*/
public function guessFormat($field)
{
$generator = $this->generator;
switch ($field['type']) {
case 'boolean':
return function () use ($generator) {
return $generator->boolean;
};
case 'integer':
return function () {
return mt_rand(0, intval('4294967295'));
};
case 'float':
return function () {
return mt_rand(0, intval('4294967295'))/mt_rand(1, intval('4294967295'));
};
case 'string':
return function () use ($generator) {
return $generator->text(255);
};
case 'date':
return function () use ($generator) {
return $generator->datetime;
};
default:
// no smart way to guess what the user expects here
return null;
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Propel2/Populator.php | src/Faker/ORM/Propel2/Populator.php | <?php
namespace Faker\ORM\Propel2;
use Propel\Runtime\Propel;
use Propel\Runtime\ServiceContainer\ServiceContainerInterface;
/**
* Service class for populating a database using the Propel ORM.
* A Populator can populate several tables using ActiveRecord classes.
*/
class Populator
{
protected $generator;
protected $entities = array();
protected $quantities = array();
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param mixed $entity A Propel ActiveRecord classname, or a \Faker\ORM\Propel2\EntityPopulator instance
* @param int $number The number of entities to populate
*/
public function addEntity($entity, $number, $customColumnFormatters = array(), $customModifiers = array())
{
if (!$entity instanceof \Faker\ORM\Propel2\EntityPopulator) {
$entity = new \Faker\ORM\Propel2\EntityPopulator($entity);
}
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->setModifiers($entity->guessModifiers($this->generator));
if ($customModifiers) {
$entity->mergeModifiersWith($customModifiers);
}
$class = $entity->getClass();
$this->entities[$class] = $entity;
$this->quantities[$class] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @param PropelPDO $con A Propel connection object
*
* @return array A list of the inserted PKs
*/
public function execute($con = null)
{
if (null === $con) {
$con = $this->getConnection();
}
$isInstancePoolingEnabled = Propel::isInstancePoolingEnabled();
Propel::disableInstancePooling();
$insertedEntities = array();
$con->beginTransaction();
foreach ($this->quantities as $class => $number) {
for ($i=0; $i < $number; $i++) {
$insertedEntities[$class][]= $this->entities[$class]->execute($con, $insertedEntities);
}
}
$con->commit();
if ($isInstancePoolingEnabled) {
Propel::enableInstancePooling();
}
return $insertedEntities;
}
protected function getConnection()
{
// use the first connection available
$class = key($this->entities);
if (!$class) {
throw new \RuntimeException('No class found from entities. Did you add entities to the Populator ?');
}
$peer = $class::TABLE_MAP;
return Propel::getConnection($peer::DATABASE_NAME, ServiceContainerInterface::CONNECTION_WRITE);
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Propel2/EntityPopulator.php | src/Faker/ORM/Propel2/EntityPopulator.php | <?php
namespace Faker\ORM\Propel2;
use \Faker\Provider\Base;
use \Propel\Runtime\Map\ColumnMap;
/**
* Service class for populating a table through a Propel ActiveRecord class.
*/
class EntityPopulator
{
protected $class;
protected $columnFormatters = array();
protected $modifiers = array();
/**
* Class constructor.
*
* @param string $class A Propel ActiveRecord classname
*/
public function __construct($class)
{
$this->class = $class;
}
/**
* @return string
*/
public function getClass()
{
return $this->class;
}
public function setColumnFormatters($columnFormatters)
{
$this->columnFormatters = $columnFormatters;
}
/**
* @return array
*/
public function getColumnFormatters()
{
return $this->columnFormatters;
}
public function mergeColumnFormattersWith($columnFormatters)
{
$this->columnFormatters = array_merge($this->columnFormatters, $columnFormatters);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessColumnFormatters(\Faker\Generator $generator)
{
$formatters = array();
$class = $this->class;
$peerClass = $class::TABLE_MAP;
$tableMap = $peerClass::getTableMap();
$nameGuesser = new \Faker\Guesser\Name($generator);
$columnTypeGuesser = new \Faker\ORM\Propel2\ColumnTypeGuesser($generator);
foreach ($tableMap->getColumns() as $columnMap) {
// skip behavior columns, handled by modifiers
if ($this->isColumnBehavior($columnMap)) {
continue;
}
if ($columnMap->isForeignKey()) {
$relatedClass = $columnMap->getRelation()->getForeignTable()->getClassname();
$formatters[$columnMap->getPhpName()] = function ($inserted) use ($relatedClass) {
$relatedClass = trim($relatedClass, "\\");
return isset($inserted[$relatedClass]) ? $inserted[$relatedClass][mt_rand(0, count($inserted[$relatedClass]) - 1)] : null;
};
continue;
}
if ($columnMap->isPrimaryKey()) {
continue;
}
if ($formatter = $nameGuesser->guessFormat($columnMap->getPhpName(), $columnMap->getSize())) {
$formatters[$columnMap->getPhpName()] = $formatter;
continue;
}
if ($formatter = $columnTypeGuesser->guessFormat($columnMap)) {
$formatters[$columnMap->getPhpName()] = $formatter;
continue;
}
}
return $formatters;
}
/**
* @param ColumnMap $columnMap
* @return bool
*/
protected function isColumnBehavior(ColumnMap $columnMap)
{
foreach ($columnMap->getTable()->getBehaviors() as $name => $params) {
$columnName = Base::toLower($columnMap->getName());
switch ($name) {
case 'nested_set':
$columnNames = array($params['left_column'], $params['right_column'], $params['level_column']);
if (in_array($columnName, $columnNames)) {
return true;
}
break;
case 'timestampable':
$columnNames = array($params['create_column'], $params['update_column']);
if (in_array($columnName, $columnNames)) {
return true;
}
break;
}
}
return false;
}
public function setModifiers($modifiers)
{
$this->modifiers = $modifiers;
}
/**
* @return array
*/
public function getModifiers()
{
return $this->modifiers;
}
public function mergeModifiersWith($modifiers)
{
$this->modifiers = array_merge($this->modifiers, $modifiers);
}
/**
* @param \Faker\Generator $generator
* @return array
*/
public function guessModifiers(\Faker\Generator $generator)
{
$modifiers = array();
$class = $this->class;
$peerClass = $class::TABLE_MAP;
$tableMap = $peerClass::getTableMap();
foreach ($tableMap->getBehaviors() as $name => $params) {
switch ($name) {
case 'nested_set':
$modifiers['nested_set'] = function ($obj, $inserted) use ($class, $generator) {
if (isset($inserted[$class])) {
$queryClass = $class . 'Query';
$parent = $queryClass::create()->findPk($generator->randomElement($inserted[$class]));
$obj->insertAsLastChildOf($parent);
} else {
$obj->makeRoot();
}
};
break;
case 'sortable':
$modifiers['sortable'] = function ($obj, $inserted) use ($class) {
$maxRank = isset($inserted[$class]) ? count($inserted[$class]) : 0;
$obj->insertAtRank(mt_rand(1, $maxRank + 1));
};
break;
}
}
return $modifiers;
}
/**
* Insert one new record using the Entity class.
*/
public function execute($con, $insertedEntities)
{
$obj = new $this->class();
foreach ($this->getColumnFormatters() as $column => $format) {
if (null !== $format) {
$obj->setByName($column, is_callable($format) ? $format($insertedEntities, $obj) : $format);
}
}
foreach ($this->getModifiers() as $modifier) {
$modifier($obj, $insertedEntities);
}
$obj->save($con);
return $obj->getPrimaryKey();
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Propel2/ColumnTypeGuesser.php | src/Faker/ORM/Propel2/ColumnTypeGuesser.php | <?php
namespace Faker\ORM\Propel2;
use \Propel\Generator\Model\PropelTypes;
use \Propel\Runtime\Map\ColumnMap;
class ColumnTypeGuesser
{
protected $generator;
/**
* @param \Faker\Generator $generator
*/
public function __construct(\Faker\Generator $generator)
{
$this->generator = $generator;
}
/**
* @param ColumnMap $column
* @return \Closure|null
*/
public function guessFormat(ColumnMap $column)
{
$generator = $this->generator;
if ($column->isTemporal()) {
if ($column->getType() == PropelTypes::BU_DATE || $column->getType() == PropelTypes::BU_TIMESTAMP) {
return function () use ($generator) {
return $generator->dateTime;
};
}
return function () use ($generator) {
return $generator->dateTimeAD;
};
}
$type = $column->getType();
switch ($type) {
case PropelTypes::BOOLEAN:
case PropelTypes::BOOLEAN_EMU:
return function () use ($generator) {
return $generator->boolean;
};
case PropelTypes::NUMERIC:
case PropelTypes::DECIMAL:
$size = $column->getSize();
return function () use ($generator, $size) {
return $generator->randomNumber($size + 2) / 100;
};
case PropelTypes::TINYINT:
return function () {
return mt_rand(0, 127);
};
case PropelTypes::SMALLINT:
return function () {
return mt_rand(0, 32767);
};
case PropelTypes::INTEGER:
return function () {
return mt_rand(0, intval('2147483647'));
};
case PropelTypes::BIGINT:
return function () {
return mt_rand(0, intval('9223372036854775807'));
};
case PropelTypes::FLOAT:
return function () {
return mt_rand(0, intval('2147483647'))/mt_rand(1, intval('2147483647'));
};
case PropelTypes::DOUBLE:
case PropelTypes::REAL:
return function () {
return mt_rand(0, intval('9223372036854775807'))/mt_rand(1, intval('9223372036854775807'));
};
case PropelTypes::CHAR:
case PropelTypes::VARCHAR:
case PropelTypes::BINARY:
case PropelTypes::VARBINARY:
$size = $column->getSize();
return function () use ($generator, $size) {
return $generator->text($size);
};
case PropelTypes::LONGVARCHAR:
case PropelTypes::LONGVARBINARY:
case PropelTypes::CLOB:
case PropelTypes::CLOB_EMU:
case PropelTypes::BLOB:
return function () use ($generator) {
return $generator->text;
};
case PropelTypes::ENUM:
$valueSet = $column->getValueSet();
return function () use ($generator, $valueSet) {
return $generator->randomElement($valueSet);
};
case PropelTypes::OBJECT:
case PropelTypes::PHP_ARRAY:
default:
// no smart way to guess what the user expects here
return null;
}
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
fzaninotto/Faker | https://github.com/fzaninotto/Faker/blob/5ffe7db6c80f441f150fc88008d64e64af66634b/src/Faker/ORM/Spot/Populator.php | src/Faker/ORM/Spot/Populator.php | <?php
namespace Faker\ORM\Spot;
use Spot\Locator;
/**
* Service class for populating a database using the Spot ORM.
*/
class Populator
{
protected $generator;
protected $locator;
protected $entities = array();
protected $quantities = array();
/**
* Populator constructor.
* @param \Faker\Generator $generator
* @param Locator|null $locator
*/
public function __construct(\Faker\Generator $generator, Locator $locator = null)
{
$this->generator = $generator;
$this->locator = $locator;
}
/**
* Add an order for the generation of $number records for $entity.
*
* @param $entityName string Name of Entity object to generate
* @param $number int The number of entities to populate
* @param $customColumnFormatters array
* @param $customModifiers array
* @param $useExistingData bool Should we use existing rows (e.g. roles) to populate relations?
*/
public function addEntity(
$entityName,
$number,
$customColumnFormatters = array(),
$customModifiers = array(),
$useExistingData = false
) {
$mapper = $this->locator->mapper($entityName);
if (null === $mapper) {
throw new \InvalidArgumentException("No mapper can be found for entity " . $entityName);
}
$entity = new EntityPopulator($mapper, $this->locator, $useExistingData);
$entity->setColumnFormatters($entity->guessColumnFormatters($this->generator));
if ($customColumnFormatters) {
$entity->mergeColumnFormattersWith($customColumnFormatters);
}
$entity->mergeModifiersWith($customModifiers);
$this->entities[$entityName] = $entity;
$this->quantities[$entityName] = $number;
}
/**
* Populate the database using all the Entity classes previously added.
*
* @param Locator $locator A Spot locator
*
* @return array A list of the inserted PKs
*/
public function execute($locator = null)
{
if (null === $locator) {
$locator = $this->locator;
}
if (null === $locator) {
throw new \InvalidArgumentException("No entity manager passed to Spot Populator.");
}
$insertedEntities = array();
foreach ($this->quantities as $entityName => $number) {
for ($i = 0; $i < $number; $i++) {
$insertedEntities[$entityName][] = $this->entities[$entityName]->execute(
$insertedEntities
);
}
}
return $insertedEntities;
}
}
| php | MIT | 5ffe7db6c80f441f150fc88008d64e64af66634b | 2026-01-04T15:02:34.268161Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.