Upgrade framework

This commit is contained in:
2023-11-14 16:54:35 +01:00
parent 1648a5cd42
commit 4fcf6fffcc
10548 changed files with 693138 additions and 466698 deletions

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,76 +8,105 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
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 provides functionality to generate COMB (combined GUID/timestamp)
* sequential UUIDs
* CombGenerator generates COMBs (combined UUID/timestamp)
*
* @link https://en.wikipedia.org/wiki/Globally_unique_identifier#Sequential_algorithms
* 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.
*
* ``` php
* $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.
*
* ``` php
* $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder()));
* ```
*
* @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys
*/
class CombGenerator implements RandomGeneratorInterface
{
const TIMESTAMP_BYTES = 6;
public const TIMESTAMP_BYTES = 6;
/**
* @var RandomGeneratorInterface
*/
private $randomGenerator;
/**
* @var NumberConverterInterface
*/
private $converter;
/**
* Constructs a `CombGenerator` using a random-number generator and a number converter
*
* @param RandomGeneratorInterface $generator Random-number generator for the non-time part.
* @param NumberConverterInterface $numberConverter Instance of number converter.
*/
public function __construct(RandomGeneratorInterface $generator, NumberConverterInterface $numberConverter)
{
$this->converter = $numberConverter;
$this->randomGenerator = $generator;
public function __construct(
private RandomGeneratorInterface $generator,
private NumberConverterInterface $numberConverter
) {
}
/**
* Generates a string of binary data of the specified length
* @throws InvalidArgumentException if $length is not a positive integer
* greater than or equal to CombGenerator::TIMESTAMP_BYTES
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
* @inheritDoc
*/
public function generate($length)
public function generate(int $length): string
{
if ($length < self::TIMESTAMP_BYTES || $length < 0) {
throw new \InvalidArgumentException('Length must be a positive integer.');
if ($length < self::TIMESTAMP_BYTES) {
throw new InvalidArgumentException(
'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES
);
}
$hash = '';
if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) {
$hash = $this->randomGenerator->generate($length - self::TIMESTAMP_BYTES);
$hash = $this->generator->generate($length - self::TIMESTAMP_BYTES);
}
$lsbTime = str_pad($this->converter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT);
$lsbTime = str_pad(
$this->numberConverter->toHex($this->timestamp()),
self::TIMESTAMP_BYTES * 2,
'0',
STR_PAD_LEFT
);
return hex2bin(str_pad(bin2hex($hash), $length - self::TIMESTAMP_BYTES, '0') . $lsbTime);
return (string) hex2bin(
str_pad(
bin2hex($hash),
$length - self::TIMESTAMP_BYTES,
'0'
)
. $lsbTime
);
}
/**
* Returns current timestamp as integer, precise to 0.00001 seconds
*
* @return string
* Returns current timestamp a string integer, precise to 0.00001 seconds
*/
private function timestamp()
private function timestamp(): string
{
$time = explode(' ', microtime(false));

View File

@@ -0,0 +1,141 @@
<?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
// 4294967295. 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);
}
}

View File

@@ -0,0 +1,53 @@
<?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;
}

View File

@@ -0,0 +1,48 @@
<?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\Exception\NameException;
use Ramsey\Uuid\UuidInterface;
use ValueError;
use function hash;
/**
* DefaultNameGenerator generates strings of binary data based on a namespace,
* name, and hashing algorithm
*/
class DefaultNameGenerator implements NameGeneratorInterface
{
/** @psalm-pure */
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string
{
try {
/** @var string|bool $bytes */
$bytes = @hash($hashAlgorithm, $ns->getBytes() . $name, true);
} catch (ValueError $e) {
$bytes = false; // keep same behavior than PHP 7
}
if ($bytes === false) {
throw new NameException(sprintf(
'Unable to hash namespace and name with algorithm \'%s\'',
$hashAlgorithm
));
}
return (string) $bytes;
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,126 +8,122 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\BinaryUtils;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Exception\RandomSourceException;
use Ramsey\Uuid\Exception\TimeSourceException;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Throwable;
use function dechex;
use function hex2bin;
use function is_int;
use function pack;
use function preg_match;
use function sprintf;
use function str_pad;
use function strlen;
use const STR_PAD_LEFT;
/**
* DefaultTimeGenerator provides functionality to generate strings of binary
* data for version 1 UUIDs based on a host ID, sequence number, and the current
* time
* DefaultTimeGenerator generates strings of binary data based on a node ID,
* clock sequence, and the current time
*/
class DefaultTimeGenerator implements TimeGeneratorInterface
{
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var TimeConverterInterface
*/
private $timeConverter;
/**
* @var TimeProviderInterface
*/
private $timeProvider;
/**
* Constructs a `DefaultTimeGenerator` using a node provider, time converter,
* and time provider
*
* @param NodeProviderInterface $nodeProvider
* @param TimeConverterInterface $timeConverter
* @param TimeProviderInterface $timeProvider
*/
public function __construct(
NodeProviderInterface $nodeProvider,
TimeConverterInterface $timeConverter,
TimeProviderInterface $timeProvider
private NodeProviderInterface $nodeProvider,
private TimeConverterInterface $timeConverter,
private TimeProviderInterface $timeProvider
) {
$this->nodeProvider = $nodeProvider;
$this->timeConverter = $timeConverter;
$this->timeProvider = $timeProvider;
}
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time
* @throws InvalidArgumentException if the parameters contain invalid values
* @throws RandomSourceException if random_int() throws an exception/error
*
* If $node is not given, we will attempt to obtain the local hardware
* address. If $clockSeq is given, it is used as the sequence number;
* otherwise a random 14-bit sequence number is chosen.
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $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
* @inheritDoc
*/
public function generate($node = null, $clockSeq = null)
public function generate($node = null, ?int $clockSeq = null): string
{
if ($node instanceof Hexadecimal) {
$node = $node->toString();
}
$node = $this->getValidNode($node);
if ($clockSeq === null) {
// Not using "stable storage"; see RFC 4122, Section 4.2.1.1
$clockSeq = mt_rand(0, 1 << 14);
try {
// This does not use "stable storage"; see RFC 4122, Section 4.2.1.1.
$clockSeq = random_int(0, 0x3fff);
} catch (Throwable $exception) {
throw new RandomSourceException(
$exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
}
// Create a 60-bit time value as a count of 100-nanosecond intervals
// since 00:00:00.00, 15 October 1582
$timeOfDay = $this->timeProvider->currentTime();
$uuidTime = $this->timeConverter->calculateTime($timeOfDay['sec'], $timeOfDay['usec']);
$time = $this->timeProvider->getTime();
$timeHi = BinaryUtils::applyVersion($uuidTime['hi'], 1);
$clockSeqHi = BinaryUtils::applyVariant($clockSeq >> 8);
$hex = vsprintf(
'%08s%04s%04s%02s%02s%012s',
array(
$uuidTime['low'],
$uuidTime['mid'],
sprintf('%04x', $timeHi),
sprintf('%02x', $clockSeqHi),
sprintf('%02x', $clockSeq & 0xff),
$node,
)
$uuidTime = $this->timeConverter->calculateTime(
$time->getSeconds()->toString(),
$time->getMicroseconds()->toString()
);
return hex2bin($hex);
$timeHex = str_pad($uuidTime->toString(), 16, '0', STR_PAD_LEFT);
if (strlen($timeHex) !== 16) {
throw new TimeSourceException(sprintf(
'The generated time of \'%s\' is larger than expected',
$timeHex
));
}
$timeBytes = (string) hex2bin($timeHex);
return $timeBytes[4] . $timeBytes[5] . $timeBytes[6] . $timeBytes[7]
. $timeBytes[2] . $timeBytes[3]
. $timeBytes[0] . $timeBytes[1]
. pack('n*', $clockSeq)
. $node;
}
/**
* Uses the node provider given when constructing this instance to get
* the node ID (usually a MAC address)
*
* @param string|int $node A node value that may be used to override the node provider
* @return string Hexadecimal representation of the node ID
* @param int|string|null $node A node value that may be used to override the node provider
*
* @return string 6-byte binary string representation of the node
*
* @throws InvalidArgumentException
*/
protected function getValidNode($node)
private function getValidNode(int | string | null $node): string
{
if ($node === null) {
$node = $this->nodeProvider->getNode();
}
// Convert the node to hex, if it is still an integer
// Convert the node to hex, if it is still an integer.
if (is_int($node)) {
$node = sprintf('%012x', $node);
$node = dechex($node);
}
if (!ctype_xdigit($node) || strlen($node) > 12) {
throw new \InvalidArgumentException('Invalid node value');
if (!preg_match('/^[A-Fa-f0-9]+$/', (string) $node) || strlen((string) $node) > 12) {
throw new InvalidArgumentException('Invalid node value');
}
return strtolower(sprintf('%012s', $node));
return (string) hex2bin(str_pad((string) $node, 12, '0', STR_PAD_LEFT));
}
}

View File

@@ -1,41 +0,0 @@
<?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
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* MtRandRandomGenerator provides functionality to generate strings of random
* binary data using the `mt_rand()` PHP function
*
* @link http://php.net/mt_rand
*/
class MtRandGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
$bytes = '';
for ($i = 1; $i <= $length; $i++) {
$bytes = chr(mt_rand(0, 255)) . $bytes;
}
return $bytes;
}
}

View File

@@ -0,0 +1,30 @@
<?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();
}
}

View File

@@ -0,0 +1,38 @@
<?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\UuidInterface;
/**
* A name generator generates strings of binary data created by hashing together
* a namespace with a name, according to a hashing algorithm
*/
interface NameGeneratorInterface
{
/**
* Generate a binary string from a namespace and name hashed together with
* the specified hashing algorithm
*
* @param UuidInterface $ns The namespace
* @param string $name The name to use for creating a UUID
* @param string $hashAlgorithm The hashing algorithm to use
*
* @return string A binary string
*
* @psalm-pure
*/
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string;
}

View File

@@ -1,38 +0,0 @@
<?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
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* OpenSslRandomGenerator provides functionality to generate strings of random
* binary data using the `openssl_random_pseudo_bytes()` PHP function
*
* The use of this generator requires PHP to be compiled using the
* `--with-openssl` option.
*
* @link http://php.net/openssl_random_pseudo_bytes
*/
class OpenSslGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return openssl_random_pseudo_bytes($length);
}
}

View File

@@ -0,0 +1,49 @@
<?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\Exception\NameException;
use Ramsey\Uuid\UuidInterface;
use function sprintf;
use function uuid_generate_md5;
use function uuid_generate_sha1;
use function uuid_parse;
/**
* PeclUuidNameGenerator generates strings of binary data from a namespace and a
* name, using ext-uuid
*
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidNameGenerator implements NameGeneratorInterface
{
/** @psalm-pure */
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string
{
$uuid = match ($hashAlgorithm) {
'md5' => uuid_generate_md5($ns->toString(), $name),
'sha1' => uuid_generate_sha1($ns->toString(), $name),
default => throw new NameException(
sprintf(
'Unable to hash namespace and name with algorithm \'%s\'',
$hashAlgorithm
)
),
};
return uuid_parse($uuid);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,28 +8,25 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use function uuid_create;
use function uuid_parse;
use const UUID_TYPE_RANDOM;
/**
* PeclUuidRandomGenerator provides functionality to generate strings of random
* binary data using the PECL UUID PHP extension
* PeclUuidRandomGenerator generates strings of random binary data using ext-uuid
*
* @link https://pecl.php.net/package/uuid
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidRandomGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
public function generate(int $length): string
{
$uuid = uuid_create(UUID_TYPE_RANDOM);

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,29 +8,29 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use function uuid_create;
use function uuid_parse;
use const UUID_TYPE_TIME;
/**
* PeclUuidTimeGenerator provides functionality to generate strings of binary
* data for version 1 UUIDs using the PECL UUID PHP extension
* PeclUuidTimeGenerator generates strings of binary data for time-base UUIDs,
* using ext-uuid
*
* @link https://pecl.php.net/package/uuid
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidTimeGenerator implements TimeGeneratorInterface
{
/**
* Generate a version 1 UUID using the PECL UUID extension
*
* @param int|string $node Not used in this context
* @param int $clockSeq Not used in this context
* @return string A binary string
* @inheritDoc
*/
public function generate($node = null, $clockSeq = null)
public function generate($node = null, ?int $clockSeq = null): string
{
$uuid = uuid_create(UUID_TYPE_TIME);

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,30 +8,38 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Exception\RandomSourceException;
use Throwable;
/**
* RandomBytesGenerator provides functionality to generate strings of random
* binary data using `random_bytes()` function in PHP 7+ or paragonie/random_compat
* RandomBytesGenerator generates strings of random binary data using the
* built-in `random_bytes()` PHP function
*
* @link http://php.net/random_bytes
* @link https://github.com/paragonie/random_compat
* @link http://php.net/random_bytes random_bytes()
*/
class RandomBytesGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
* @throws RandomSourceException if random_bytes() throws an exception/error
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
* @inheritDoc
*/
public function generate($length)
public function generate(int $length): string
{
return random_bytes($length);
try {
return random_bytes($length);
} catch (Throwable $exception) {
throw new RandomSourceException(
$exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,24 +8,22 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
/**
* A factory for retrieving a random generator, based on the environment
* RandomGeneratorFactory retrieves a default random generator, based on the
* environment
*/
class RandomGeneratorFactory
{
/**
* Returns a default random generator, based on the current environment
*
* @return RandomGeneratorInterface
*/
public static function getGenerator()
public function getGenerator(): RandomGeneratorInterface
{
return new RandomBytesGenerator();
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,24 +8,23 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
/**
* RandomGeneratorInterface provides functionality to generate strings of random
* binary data
* A random generator generates strings of random binary data
*/
interface RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
* Generates a string of randomized binary data
*
* @param int<1, max> $length The number of bytes of random binary data to generate
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length);
public function generate(int $length): string;
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,55 +8,48 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use RandomLib\Generator;
use RandomLib\Factory;
use RandomLib\Generator;
/**
* RandomLibAdapter provides functionality to generate strings of random
* binary data using the ircmaxell/random-lib library
* RandomLibAdapter generates strings of random binary data using the
* paragonie/random-lib library
*
* @link https://packagist.org/packages/ircmaxell/random-lib
* @deprecated This class will be removed in 5.0.0. Use the default
* RandomBytesGenerator or implement your own generator that implements
* RandomGeneratorInterface.
*
* @link https://packagist.org/packages/paragonie/random-lib paragonie/random-lib
*/
class RandomLibAdapter implements RandomGeneratorInterface
{
/**
* @var Generator
*/
private $generator;
private Generator $generator;
/**
* Constructs a `RandomLibAdapter` using a `RandomLib\Generator`
* Constructs a RandomLibAdapter
*
* By default, if no `Generator` is passed in, this creates a medium-strength
* By default, if no Generator is passed in, this creates a high-strength
* generator to use when generating random binary data.
*
* @param Generator $generator An ircmaxell/random-lib `Generator`
* @param Generator|null $generator The generator to use when generating binary data
*/
public function __construct(Generator $generator = null)
public function __construct(?Generator $generator = null)
{
$this->generator = $generator;
if ($this->generator === null) {
if ($generator === null) {
$factory = new Factory();
$this->generator = $factory->getMediumStrengthGenerator();
$generator = $factory->getHighStrengthGenerator();
}
$this->generator = $generator;
}
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
public function generate(int $length): string
{
return $this->generator->generate($length);
}

View File

@@ -1,36 +0,0 @@
<?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
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* SodiumRandomGenerator provides functionality to generate strings of random
* binary data using the PECL libsodium extension
*
* @link http://pecl.php.net/package/libsodium
* @link https://paragonie.com/book/pecl-libsodium
*/
class SodiumRandomGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return \Sodium\randombytes_buf($length);
}
}

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,11 +8,10 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Converter\TimeConverterInterface;
@@ -19,49 +19,22 @@ use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* A factory for retrieving a time generator, based on the environment
* TimeGeneratorFactory retrieves a default time generator, based on the
* environment
*/
class TimeGeneratorFactory
{
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var TimeConverterInterface
*/
private $timeConverter;
/**
* @var TimeProviderInterface
*/
private $timeProvider;
/**
* Constructs a `TimeGeneratorFactory` using a node provider, time converter,
* and time provider
*
* @param NodeProviderInterface $nodeProvider
* @param TimeConverterInterface $timeConverter
* @param TimeProviderInterface $timeProvider
*/
public function __construct(
NodeProviderInterface $nodeProvider,
TimeConverterInterface $timeConverter,
TimeProviderInterface $timeProvider
private NodeProviderInterface $nodeProvider,
private TimeConverterInterface $timeConverter,
private TimeProviderInterface $timeProvider
) {
$this->nodeProvider = $nodeProvider;
$this->timeConverter = $timeConverter;
$this->timeProvider = $timeProvider;
}
/**
* Returns a default time generator, based on the current environment
*
* @return TimeGeneratorInterface
*/
public function getGenerator()
public function getGenerator(): TimeGeneratorInterface
{
return new DefaultTimeGenerator(
$this->nodeProvider,

View File

@@ -1,4 +1,5 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
@@ -7,29 +8,31 @@
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* TimeGeneratorInterface provides functionality to generate strings of binary
* data for version 1 UUIDs based on a host ID, sequence number, and the current
* time
* A time generator generates strings of binary data based on a node ID,
* clock sequence, and the current time
*/
interface TimeGeneratorInterface
{
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time
* 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
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $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, $clockSeq = null);
public function generate($node = null, ?int $clockSeq = null): string;
}

View File

@@ -0,0 +1,169 @@
<?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 DateTimeImmutable;
use DateTimeInterface;
use Ramsey\Uuid\Type\Hexadecimal;
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 that combine 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 $dateTime A date-time instance to use when
* generating bytes
*
* @inheritDoc
*/
public function generate($node = null, ?int $clockSeq = null, ?DateTimeInterface $dateTime = null): string
{
$time = ($dateTime ?? new DateTimeImmutable('now'))->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);
}
/** @var non-empty-string */
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 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 of these
* numbers to get 5 extra 24-bit numbers. Then, we consume those numbers
* 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.
*
* @link https://twitter.com/nicolasgrekas/status/1583356938825261061 Tweet from Nicolas Grekas
*/
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] + (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;
}
}