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/functions.php | src/functions.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
* phpcs:disable Squiz.Functions.GlobalFunction
*/
declare(strict_types=1);
namespace Ramsey\Uuid;
use DateTimeInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
/**
* Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, and the 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 non-empty-string Version 1 UUID as a string
*/
function v1($node = null, ?int $clockSeq = null): string
{
return Uuid::uuid1($node, $clockSeq)->toString();
}
/**
* Returns a version 2 (DCE Security) UUID from a local domain, local identifier, host ID, clock sequence, and the 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 a 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 non-empty-string Version 2 UUID as a string
*/
function v2(
int $localDomain,
?IntegerObject $localIdentifier = null,
?Hexadecimal $node = null,
?int $clockSeq = null,
): string {
return Uuid::uuid2($localDomain, $localIdentifier, $node, $clockSeq)->toString();
}
/**
* Returns a version 3 (name-based) UUID based on the MD5 hash of a namespace ID and a name
*
* @param UuidInterface | string $ns The namespace (must be a valid UUID)
*
* @return non-empty-string Version 3 UUID as a string
*
* @pure
*/
function v3($ns, string $name): string
{
return Uuid::uuid3($ns, $name)->toString();
}
/**
* Returns a version 4 (random) UUID
*
* @return non-empty-string Version 4 UUID as a string
*/
function v4(): string
{
return Uuid::uuid4()->toString();
}
/**
* Returns a version 5 (name-based) UUID based on the SHA-1 hash of a namespace ID and a name
*
* @param UuidInterface | string $ns The namespace (must be a valid UUID)
*
* @return non-empty-string Version 5 UUID as a string
*
* @pure
*/
function v5($ns, string $name): string
{
return Uuid::uuid5($ns, $name)->toString();
}
/**
* Returns a version 6 (reordered Gregorian time) UUID from a host ID, sequence number, and the current time
*
* @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 non-empty-string Version 6 UUID as a string
*/
function v6(?Hexadecimal $node = null, ?int $clockSeq = null): string
{
return Uuid::uuid6($node, $clockSeq)->toString();
}
/**
* Returns a version 7 (Unix Epoch time) UUID
*
* @param DateTimeInterface|null $dateTime An optional date/time from which to create the version 7 UUID. If not
* provided, the UUID is generated using the current date/time.
*
* @return non-empty-string Version 7 UUID as a string
*/
function v7(?DateTimeInterface $dateTime = null): string
{
return Uuid::uuid7($dateTime)->toString();
}
/**
* Returns a version 8 (custom format) UUID
*
* The bytes provided may contain any value according to your application's needs. Be aware, however, that other
* applications may not understand the semantics of the value.
*
* @param string $bytes A 16-byte octet string. This is an open blob of data that you may fill with 128 bits of
* information. Be aware, however, bits 48 through 51 will be replaced with the UUID version field, and bits 64 and
* 65 will be replaced with the UUID variant. You MUST NOT rely on these bits for your application needs.
*
* @return non-empty-string Version 8 UUID as a string
*
* @pure
*/
function v8(string $bytes): string
{
return Uuid::uuid8($bytes)->toString();
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/BinaryUtils.php | src/BinaryUtils.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;
/**
* Provides binary math utilities
*/
class BinaryUtils
{
/**
* Applies the variant field to the 16-bit clock sequence
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field
*
* @param int $clockSeq The 16-bit clock sequence value before the variant is applied
*
* @return int The 16-bit clock sequence multiplexed with the UUID variant
*
* @pure
*/
public static function applyVariant(int $clockSeq): int
{
return ($clockSeq & 0x3fff) | 0x8000;
}
/**
* Applies the version field to the 16-bit `time_hi_and_version` field
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field
*
* @param int $timeHi The value of the 16-bit `time_hi_and_version` field before the version is applied
* @param int $version The version to apply to the `time_hi` field
*
* @return int The 16-bit time_hi field of the timestamp multiplexed with the UUID version number
*
* @pure
*/
public static function applyVersion(int $timeHi, int $version): int
{
return ($timeHi & 0x0fff) | ($version << 12);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/UuidFactoryInterface.php | src/UuidFactoryInterface.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;
use DateTimeInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Validator\ValidatorInterface;
/**
* UuidFactoryInterface defines the common functionality all `UuidFactory` instances must implement
*/
interface UuidFactoryInterface
{
/**
* Creates a UUID from a byte string
*
* @param string $bytes A binary string
*
* @return UuidInterface A UuidInterface instance created from a binary string representation
*
* @pure
*/
public function fromBytes(string $bytes): UuidInterface;
/**
* Creates a UUID from a DateTimeInterface instance
*
* @param DateTimeInterface $dateTime The date and time
* @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 UuidInterface A UuidInterface instance that represents a version 1 UUID created from a DateTimeInterface instance
*/
public function fromDateTime(
DateTimeInterface $dateTime,
?Hexadecimal $node = null,
?int $clockSeq = null,
): UuidInterface;
/**
* Creates a UUID from a 128-bit integer string
*
* @param string $integer String representation of 128-bit integer
*
* @return UuidInterface A UuidInterface instance created from the string representation of a 128-bit integer
*
* @pure
*/
public function fromInteger(string $integer): UuidInterface;
/**
* Creates a UUID from the string standard representation
*
* @param string $uuid A hexadecimal string
*
* @return UuidInterface A UuidInterface instance created from a hexadecimal string representation
*
* @pure
*/
public function fromString(string $uuid): UuidInterface;
/**
* Returns the validator used by the factory
*/
public function getValidator(): ValidatorInterface;
/**
* Returns a version 1 (Gregorian time) UUID from a host ID, sequence number, and the 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 UuidInterface A UuidInterface instance that represents a version 1 UUID
*/
public function uuid1($node = null, ?int $clockSeq = null): UuidInterface;
/**
* Returns a version 2 (DCE Security) UUID from a local domain, local identifier, host ID, clock sequence, and the
* 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 a 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 UuidInterface A UuidInterface instance that represents a version 2 UUID
*/
public function uuid2(
int $localDomain,
?IntegerObject $localIdentifier = null,
?Hexadecimal $node = null,
?int $clockSeq = null,
): UuidInterface;
/**
* Returns a version 3 (name-based) UUID based on the MD5 hash of a namespace ID and a name
*
* @param UuidInterface | string $ns The namespace (must be a valid UUID)
* @param string $name The name to use for creating a UUID
*
* @return UuidInterface A UuidInterface instance that represents a version 3 UUID
*
* @pure
*/
public function uuid3($ns, string $name): UuidInterface;
/**
* Returns a version 4 (random) UUID
*
* @return UuidInterface A UuidInterface instance that represents a version 4 UUID
*/
public function uuid4(): UuidInterface;
/**
* Returns a version 5 (name-based) UUID based on the SHA-1 hash of a namespace ID and a name
*
* @param UuidInterface | string $ns The namespace (must be a valid UUID)
* @param string $name The name to use for creating a UUID
*
* @return UuidInterface A UuidInterface instance that represents a version 5 UUID
*
* @pure
*/
public function uuid5($ns, string $name): UuidInterface;
/**
* Returns a version 6 (reordered Gregorian time) UUID from a host ID, sequence number, and the current time
*
* @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 UuidInterface A UuidInterface instance that represents a version 6 UUID
*/
public function uuid6(?Hexadecimal $node = null, ?int $clockSeq = null): UuidInterface;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/FeatureSet.php | src/FeatureSet.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;
use Ramsey\Uuid\Builder\FallbackBuilder;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\GuidStringCodec;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\Time\PhpTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Generator\DceSecurityGenerator;
use Ramsey\Uuid\Generator\DceSecurityGeneratorInterface;
use Ramsey\Uuid\Generator\NameGeneratorFactory;
use Ramsey\Uuid\Generator\NameGeneratorInterface;
use Ramsey\Uuid\Generator\PeclUuidNameGenerator;
use Ramsey\Uuid\Generator\PeclUuidRandomGenerator;
use Ramsey\Uuid\Generator\PeclUuidTimeGenerator;
use Ramsey\Uuid\Generator\RandomGeneratorFactory;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Generator\TimeGeneratorFactory;
use Ramsey\Uuid\Generator\TimeGeneratorInterface;
use Ramsey\Uuid\Generator\UnixTimeGenerator;
use Ramsey\Uuid\Guid\GuidBuilder;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Math\CalculatorInterface;
use Ramsey\Uuid\Nonstandard\UuidBuilder as NonstandardUuidBuilder;
use Ramsey\Uuid\Provider\Dce\SystemDceSecurityProvider;
use Ramsey\Uuid\Provider\DceSecurityProviderInterface;
use Ramsey\Uuid\Provider\Node\FallbackNodeProvider;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Provider\Node\SystemNodeProvider;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\Time\SystemTimeProvider;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder;
use Ramsey\Uuid\Validator\GenericValidator;
use Ramsey\Uuid\Validator\ValidatorInterface;
use const PHP_INT_SIZE;
/**
* FeatureSet detects and exposes available features in the current environment
*
* A feature set is used by UuidFactory to determine the available features and capabilities of the environment.
*/
class FeatureSet
{
private ?TimeProviderInterface $timeProvider = null;
private CalculatorInterface $calculator;
private CodecInterface $codec;
private DceSecurityGeneratorInterface $dceSecurityGenerator;
private NameGeneratorInterface $nameGenerator;
private NodeProviderInterface $nodeProvider;
private NumberConverterInterface $numberConverter;
private RandomGeneratorInterface $randomGenerator;
private TimeConverterInterface $timeConverter;
private TimeGeneratorInterface $timeGenerator;
private TimeGeneratorInterface $unixTimeGenerator;
private UuidBuilderInterface $builder;
private ValidatorInterface $validator;
/**
* @param bool $useGuids True build UUIDs using the GuidStringCodec
* @param bool $force32Bit True to force the use of 32-bit functionality (primarily for testing purposes)
* @param bool $forceNoBigNumber (obsolete)
* @param bool $ignoreSystemNode True to disable attempts to check for the system node ID (primarily for testing purposes)
* @param bool $enablePecl True to enable the use of the PeclUuidTimeGenerator to generate version 1 UUIDs
*
* @phpstan-ignore constructor.unusedParameter ($forceNoBigNumber is deprecated)
*/
public function __construct(
bool $useGuids = false,
private bool $force32Bit = false,
bool $forceNoBigNumber = false,
private bool $ignoreSystemNode = false,
private bool $enablePecl = false,
) {
$this->randomGenerator = $this->buildRandomGenerator();
$this->setCalculator(new BrickMathCalculator());
$this->builder = $this->buildUuidBuilder($useGuids);
$this->codec = $this->buildCodec($useGuids);
$this->nodeProvider = $this->buildNodeProvider();
$this->nameGenerator = $this->buildNameGenerator();
$this->setTimeProvider(new SystemTimeProvider());
$this->setDceSecurityProvider(new SystemDceSecurityProvider());
$this->validator = new GenericValidator();
assert($this->timeProvider !== null);
$this->unixTimeGenerator = $this->buildUnixTimeGenerator();
}
/**
* Returns the builder configured for this environment
*/
public function getBuilder(): UuidBuilderInterface
{
return $this->builder;
}
/**
* Returns the calculator configured for this environment
*/
public function getCalculator(): CalculatorInterface
{
return $this->calculator;
}
/**
* Returns the codec configured for this environment
*/
public function getCodec(): CodecInterface
{
return $this->codec;
}
/**
* Returns the DCE Security generator configured for this environment
*/
public function getDceSecurityGenerator(): DceSecurityGeneratorInterface
{
return $this->dceSecurityGenerator;
}
/**
* Returns the name generator configured for this environment
*/
public function getNameGenerator(): NameGeneratorInterface
{
return $this->nameGenerator;
}
/**
* Returns the node provider configured for this environment
*/
public function getNodeProvider(): NodeProviderInterface
{
return $this->nodeProvider;
}
/**
* Returns the number converter configured for this environment
*/
public function getNumberConverter(): NumberConverterInterface
{
return $this->numberConverter;
}
/**
* Returns the random generator configured for this environment
*/
public function getRandomGenerator(): RandomGeneratorInterface
{
return $this->randomGenerator;
}
/**
* Returns the time converter configured for this environment
*/
public function getTimeConverter(): TimeConverterInterface
{
return $this->timeConverter;
}
/**
* Returns the time generator configured for this environment
*/
public function getTimeGenerator(): TimeGeneratorInterface
{
return $this->timeGenerator;
}
/**
* Returns the Unix Epoch time generator configured for this environment
*/
public function getUnixTimeGenerator(): TimeGeneratorInterface
{
return $this->unixTimeGenerator;
}
/**
* Returns the validator configured for this environment
*/
public function getValidator(): ValidatorInterface
{
return $this->validator;
}
/**
* Sets the calculator to use in this environment
*/
public function setCalculator(CalculatorInterface $calculator): void
{
$this->calculator = $calculator;
$this->numberConverter = $this->buildNumberConverter($calculator);
$this->timeConverter = $this->buildTimeConverter($calculator);
if (isset($this->timeProvider)) {
$this->timeGenerator = $this->buildTimeGenerator($this->timeProvider);
}
}
/**
* Sets the DCE Security provider to use in this environment
*/
public function setDceSecurityProvider(DceSecurityProviderInterface $dceSecurityProvider): void
{
$this->dceSecurityGenerator = $this->buildDceSecurityGenerator($dceSecurityProvider);
}
/**
* Sets the node provider to use in this environment
*/
public function setNodeProvider(NodeProviderInterface $nodeProvider): void
{
$this->nodeProvider = $nodeProvider;
if (isset($this->timeProvider)) {
$this->timeGenerator = $this->buildTimeGenerator($this->timeProvider);
}
}
/**
* Sets the time provider to use in this environment
*/
public function setTimeProvider(TimeProviderInterface $timeProvider): void
{
$this->timeProvider = $timeProvider;
$this->timeGenerator = $this->buildTimeGenerator($timeProvider);
}
/**
* Set the validator to use in this environment
*/
public function setValidator(ValidatorInterface $validator): void
{
$this->validator = $validator;
}
/**
* Returns a codec configured for this environment
*
* @param bool $useGuids Whether to build UUIDs using the GuidStringCodec
*/
private function buildCodec(bool $useGuids = false): CodecInterface
{
if ($useGuids) {
return new GuidStringCodec($this->builder);
}
return new StringCodec($this->builder);
}
/**
* Returns a DCE Security generator configured for this environment
*/
private function buildDceSecurityGenerator(
DceSecurityProviderInterface $dceSecurityProvider,
): DceSecurityGeneratorInterface {
return new DceSecurityGenerator($this->numberConverter, $this->timeGenerator, $dceSecurityProvider);
}
/**
* Returns a node provider configured for this environment
*/
private function buildNodeProvider(): NodeProviderInterface
{
if ($this->ignoreSystemNode) {
return new RandomNodeProvider();
}
return new FallbackNodeProvider([new SystemNodeProvider(), new RandomNodeProvider()]);
}
/**
* Returns a number converter configured for this environment
*/
private function buildNumberConverter(CalculatorInterface $calculator): NumberConverterInterface
{
return new GenericNumberConverter($calculator);
}
/**
* Returns a random generator configured for this environment
*/
private function buildRandomGenerator(): RandomGeneratorInterface
{
if ($this->enablePecl) {
return new PeclUuidRandomGenerator();
}
return (new RandomGeneratorFactory())->getGenerator();
}
/**
* Returns a time generator configured for this environment
*
* @param TimeProviderInterface $timeProvider The time provider to use with
* the time generator
*/
private function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGeneratorInterface
{
if ($this->enablePecl) {
return new PeclUuidTimeGenerator();
}
return (new TimeGeneratorFactory($this->nodeProvider, $this->timeConverter, $timeProvider))->getGenerator();
}
/**
* Returns a Unix Epoch time generator configured for this environment
*/
private function buildUnixTimeGenerator(): TimeGeneratorInterface
{
return new UnixTimeGenerator($this->randomGenerator);
}
/**
* Returns a name generator configured for this environment
*/
private function buildNameGenerator(): NameGeneratorInterface
{
if ($this->enablePecl) {
return new PeclUuidNameGenerator();
}
return (new NameGeneratorFactory())->getGenerator();
}
/**
* Returns a time converter configured for this environment
*/
private function buildTimeConverter(CalculatorInterface $calculator): TimeConverterInterface
{
$genericConverter = new GenericTimeConverter($calculator);
if ($this->is64BitSystem()) {
return new PhpTimeConverter($calculator, $genericConverter);
}
return $genericConverter;
}
/**
* Returns a UUID builder configured for this environment
*
* @param bool $useGuids Whether to build UUIDs using the GuidStringCodec
*/
private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface
{
if ($useGuids) {
return new GuidBuilder($this->numberConverter, $this->timeConverter);
}
return new FallbackBuilder([
new Rfc4122UuidBuilder($this->numberConverter, $this->timeConverter),
new NonstandardUuidBuilder($this->numberConverter, $this->timeConverter),
]);
}
/**
* Returns true if the PHP build is 64-bit
*/
private function is64BitSystem(): bool
{
return PHP_INT_SIZE === 8 && !$this->force32Bit;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Builder/FallbackBuilder.php | src/Builder/FallbackBuilder.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\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Exception\BuilderNotFoundException;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\UuidInterface;
/**
* FallbackBuilder builds a UUID by stepping through a list of UUID builders until a UUID can be constructed without exceptions
*
* @immutable
*/
class FallbackBuilder implements UuidBuilderInterface
{
/**
* @param iterable<UuidBuilderInterface> $builders An array of UUID builders
*/
public function __construct(private iterable $builders)
{
}
/**
* Builds and returns a UuidInterface instance using the first builder that succeeds
*
* @param CodecInterface $codec The codec to use for building this instance
* @param string $bytes The byte string from which to construct a UUID
*
* @return UuidInterface an instance of a UUID object
*
* @pure
*/
public function build(CodecInterface $codec, string $bytes): UuidInterface
{
$lastBuilderException = null;
foreach ($this->builders as $builder) {
try {
return $builder->build($codec, $bytes);
} catch (UnableToBuildUuidException $exception) {
$lastBuilderException = $exception;
continue;
}
}
throw new BuilderNotFoundException(
'Could not find a suitable builder for the provided codec and fields',
0,
$lastBuilderException,
);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Builder/DegradedUuidBuilder.php | src/Builder/DegradedUuidBuilder.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\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\DegradedTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\DegradedUuid;
use Ramsey\Uuid\Rfc4122\Fields as Rfc4122Fields;
use Ramsey\Uuid\UuidInterface;
/**
* @deprecated DegradedUuid instances are no longer necessary to support 32-bit systems. Please transition to {@see DefaultUuidBuilder}.
*
* @immutable
*/
class DegradedUuidBuilder implements UuidBuilderInterface
{
private TimeConverterInterface $timeConverter;
/**
* @param NumberConverterInterface $numberConverter The number converter to use when constructing the DegradedUuid
* @param TimeConverterInterface|null $timeConverter The time converter to use for converting timestamps extracted
* from a UUID to Unix timestamps
*/
public function __construct(
private NumberConverterInterface $numberConverter,
?TimeConverterInterface $timeConverter = null
) {
$this->timeConverter = $timeConverter ?: new DegradedTimeConverter();
}
/**
* Builds and returns a DegradedUuid
*
* @param CodecInterface $codec The codec to use for building this DegradedUuid instance
* @param string $bytes The byte string from which to construct a UUID
*
* @return DegradedUuid The DegradedUuidBuild returns an instance of Ramsey\Uuid\DegradedUuid
*
* @phpstan-impure
*/
public function build(CodecInterface $codec, string $bytes): UuidInterface
{
return new DegradedUuid(new Rfc4122Fields($bytes), $this->numberConverter, $codec, $this->timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Builder/UuidBuilderInterface.php | src/Builder/UuidBuilderInterface.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\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\UuidInterface;
/**
* A UUID builder builds instances of UuidInterface
*
* @immutable
*/
interface UuidBuilderInterface
{
/**
* Builds and returns a UuidInterface
*
* @param CodecInterface $codec The codec to use for building this UuidInterface instance
* @param string $bytes The byte string from which to construct a UUID
*
* @return UuidInterface Implementations may choose to return more specific instances of UUIDs that implement UuidInterface
*
* @pure
*/
public function build(CodecInterface $codec, string $bytes): UuidInterface;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Builder/BuilderCollection.php | src/Builder/BuilderCollection.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\Builder;
use Ramsey\Collection\AbstractCollection;
use Ramsey\Uuid\Converter\Number\GenericNumberConverter;
use Ramsey\Uuid\Converter\Time\GenericTimeConverter;
use Ramsey\Uuid\Converter\Time\PhpTimeConverter;
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 Traversable;
/**
* A collection of UuidBuilderInterface objects
*
* @deprecated this class has been deprecated and will be removed in 5.0.0. The use-case for this class comes from a
* pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced at runtime:
* that is no longer necessary, now that you can safely verify your code to be correct, and use more generic types
* like `iterable<T>` instead.
*
* @extends AbstractCollection<UuidBuilderInterface>
*/
class BuilderCollection extends AbstractCollection
{
public function getType(): string
{
return UuidBuilderInterface::class;
}
public function getIterator(): Traversable
{
return parent::getIterator();
}
/**
* Re-constructs the object from its serialized form
*
* @param string $serialized The serialized PHP string to unserialize into a UuidInterface instance
*/
public function unserialize($serialized): void
{
/** @var array<array-key, UuidBuilderInterface> $data */
$data = unserialize($serialized, [
'allowed_classes' => [
BrickMathCalculator::class,
GenericNumberConverter::class,
GenericTimeConverter::class,
GuidBuilder::class,
NonstandardUuidBuilder::class,
PhpTimeConverter::class,
Rfc4122UuidBuilder::class,
],
]);
$this->data = array_filter(
$data,
function ($unserialized): bool {
/** @phpstan-ignore instanceof.alwaysTrue */
return $unserialized instanceof UuidBuilderInterface;
},
);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Builder/DefaultUuidBuilder.php | src/Builder/DefaultUuidBuilder.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\Builder;
use Ramsey\Uuid\Rfc4122\UuidBuilder as Rfc4122UuidBuilder;
/**
* @deprecated Please transition to {@see Rfc4122UuidBuilder}.
*
* @immutable
*/
class DefaultUuidBuilder extends Rfc4122UuidBuilder
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Type/Decimal.php | src/Type/Decimal.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\Type;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use ValueError;
use function is_numeric;
use function sprintf;
use function str_starts_with;
/**
* A value object representing a decimal
*
* This class exists for type-safety purposes, to ensure that decimals returned from ramsey/uuid methods as strings are
* truly decimals and not some other kind of string.
*
* To support values as true decimals and not as floats or doubles, we store the decimals as strings.
*
* @immutable
*/
final class Decimal implements NumberInterface
{
private string $value;
private bool $isNegative;
public function __construct(float | int | string | self $value)
{
$value = (string) $value;
if (!is_numeric($value)) {
throw new InvalidArgumentException(
'Value must be a signed decimal or a string containing only '
. 'digits 0-9 and, optionally, a decimal point or sign (+ or -)'
);
}
// Remove the leading +-symbol.
if (str_starts_with($value, '+')) {
$value = substr($value, 1);
}
// For cases like `-0` or `-0.0000`, convert the value to `0`.
if (abs((float) $value) === 0.0) {
$value = '0';
}
if (str_starts_with($value, '-')) {
$this->isNegative = true;
} else {
$this->isNegative = false;
}
$this->value = $value;
}
public function isNegative(): bool
{
return $this->isNegative;
}
public function toString(): string
{
return $this->value;
}
public function __toString(): string
{
return $this->toString();
}
public function jsonSerialize(): string
{
return $this->toString();
}
public function serialize(): string
{
return $this->toString();
}
/**
* @return array{string: string}
*/
public function __serialize(): array
{
return ['string' => $this->toString()];
}
/**
* Constructs the object from a serialized string representation
*
* @param string $data The serialized string representation of the object
*/
public function unserialize(string $data): void
{
$this->__construct($data);
}
/**
* @param array{string?: string} $data
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
if (!isset($data['string'])) {
throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__));
}
// @codeCoverageIgnoreEnd
$this->unserialize($data['string']);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Type/Hexadecimal.php | src/Type/Hexadecimal.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\Type;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use ValueError;
use function preg_match;
use function sprintf;
use function substr;
/**
* A value object representing a hexadecimal number
*
* This class exists for type-safety purposes, to ensure that hexadecimal numbers returned from ramsey/uuid methods as
* strings are truly hexadecimal and not some other kind of string.
*
* @immutable
*/
final class Hexadecimal implements TypeInterface
{
/**
* @var non-empty-string
*/
private string $value;
/**
* @param self | string $value The hexadecimal value to store
*/
public function __construct(self | string $value)
{
$this->value = $value instanceof self ? (string) $value : $this->prepareValue($value);
}
/**
* @return non-empty-string
*
* @pure
*/
public function toString(): string
{
return $this->value;
}
/**
* @return non-empty-string
*/
public function __toString(): string
{
return $this->toString();
}
/**
* @return non-empty-string
*/
public function jsonSerialize(): string
{
return $this->toString();
}
/**
* @return non-empty-string
*/
public function serialize(): string
{
return $this->toString();
}
/**
* @return array{string: string}
*/
public function __serialize(): array
{
return ['string' => $this->toString()];
}
/**
* Constructs the object from a serialized string representation
*
* @param string $data The serialized string representation of the object
*/
public function unserialize(string $data): void
{
$this->__construct($data);
}
/**
* @param array{string?: string} $data
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
if (!isset($data['string'])) {
throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__));
}
// @codeCoverageIgnoreEnd
$this->unserialize($data['string']);
}
/**
* @return non-empty-string
*/
private function prepareValue(string $value): string
{
$value = strtolower($value);
if (str_starts_with($value, '0x')) {
$value = substr($value, 2);
}
if (!preg_match('/^[A-Fa-f0-9]+$/', $value)) {
throw new InvalidArgumentException('Value must be a hexadecimal number');
}
/** @var non-empty-string */
return $value;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Type/NumberInterface.php | src/Type/NumberInterface.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\Type;
/**
* NumberInterface ensures consistency in numeric values returned by ramsey/uuid
*
* @immutable
*/
interface NumberInterface extends TypeInterface
{
/**
* Returns true if this number is less than zero
*/
public function isNegative(): bool;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Type/Time.php | src/Type/Time.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\Type;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use ValueError;
use function json_decode;
use function json_encode;
use function sprintf;
/**
* A value object representing a timestamp
*
* This class exists for type-safety purposes, to ensure that timestamps used by ramsey/uuid are truly timestamp
* integers and not some other kind of string or integer.
*
* @immutable
*/
final class Time implements TypeInterface
{
private IntegerObject $seconds;
private IntegerObject $microseconds;
public function __construct(
IntegerObject | float | int | string $seconds,
IntegerObject | float | int | string $microseconds = 0,
) {
$this->seconds = new IntegerObject($seconds);
$this->microseconds = new IntegerObject($microseconds);
}
/**
* @pure
*/
public function getSeconds(): IntegerObject
{
return $this->seconds;
}
/**
* @pure
*/
public function getMicroseconds(): IntegerObject
{
return $this->microseconds;
}
public function toString(): string
{
return $this->seconds->toString() . '.' . sprintf('%06s', $this->microseconds->toString());
}
public function __toString(): string
{
return $this->toString();
}
/**
* @return string[]
*/
public function jsonSerialize(): array
{
return [
'seconds' => $this->getSeconds()->toString(),
'microseconds' => $this->getMicroseconds()->toString(),
];
}
public function serialize(): string
{
return (string) json_encode($this);
}
/**
* @return array{seconds: string, microseconds: string}
*/
public function __serialize(): array
{
return [
'seconds' => $this->getSeconds()->toString(),
'microseconds' => $this->getMicroseconds()->toString(),
];
}
/**
* Constructs the object from a serialized string representation
*
* @param string $data The serialized string representation of the object
*/
public function unserialize(string $data): void
{
/** @var array{seconds?: float | int | string, microseconds?: float | int | string} $time */
$time = json_decode($data, true);
if (!isset($time['seconds']) || !isset($time['microseconds'])) {
throw new UnsupportedOperationException('Attempted to unserialize an invalid value');
}
$this->__construct($time['seconds'], $time['microseconds']);
}
/**
* @param array{seconds?: string, microseconds?: string} $data
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
if (!isset($data['seconds']) || !isset($data['microseconds'])) {
throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__));
}
// @codeCoverageIgnoreEnd
$this->__construct($data['seconds'], $data['microseconds']);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Type/Integer.php | src/Type/Integer.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\Type;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use ValueError;
use function assert;
use function is_numeric;
use function preg_match;
use function sprintf;
use function substr;
/**
* A value object representing an integer
*
* This class exists for type-safety purposes, to ensure that integers returned from ramsey/uuid methods as strings are
* truly integers and not some other kind of string.
*
* To support large integers beyond PHP_INT_MAX and PHP_INT_MIN on both 64-bit and 32-bit systems, we store the integers
* as strings.
*
* @immutable
*/
final class Integer implements NumberInterface
{
/**
* @var numeric-string
*/
private string $value;
/**
* @phpstan-ignore property.readOnlyByPhpDocDefaultValue
*/
private bool $isNegative = false;
public function __construct(self | float | int | string $value)
{
$this->value = $value instanceof self ? (string) $value : $this->prepareValue($value);
}
public function isNegative(): bool
{
return $this->isNegative;
}
/**
* @return numeric-string
*
* @pure
*/
public function toString(): string
{
return $this->value;
}
/**
* @return numeric-string
*/
public function __toString(): string
{
return $this->toString();
}
public function jsonSerialize(): string
{
return $this->toString();
}
public function serialize(): string
{
return $this->toString();
}
/**
* @return array{string: string}
*/
public function __serialize(): array
{
return ['string' => $this->toString()];
}
/**
* Constructs the object from a serialized string representation
*
* @param string $data The serialized string representation of the object
*/
public function unserialize(string $data): void
{
$this->__construct($data);
}
/**
* @param array{string?: string} $data
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
if (!isset($data['string'])) {
throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__));
}
// @codeCoverageIgnoreEnd
$this->unserialize($data['string']);
}
/**
* @return numeric-string
*/
private function prepareValue(float | int | string $value): string
{
$value = (string) $value;
$sign = '+';
// If the value contains a sign, remove it for the digit pattern check.
if (str_starts_with($value, '-') || str_starts_with($value, '+')) {
$sign = substr($value, 0, 1);
$value = substr($value, 1);
}
if (!preg_match('/^\d+$/', $value)) {
throw new InvalidArgumentException(
'Value must be a signed integer or a string containing only '
. 'digits 0-9 and, optionally, a sign (+ or -)'
);
}
// Trim any leading zeros.
$value = ltrim($value, '0');
// Set to zero if the string is empty after trimming zeros.
if ($value === '') {
$value = '0';
}
// Add the negative sign back to the value.
if ($sign === '-' && $value !== '0') {
$value = $sign . $value;
/** @phpstan-ignore property.readOnlyByPhpDocAssignNotInConstructor */
$this->isNegative = true;
}
assert(is_numeric($value));
return $value;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Type/TypeInterface.php | src/Type/TypeInterface.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\Type;
use JsonSerializable;
use Serializable;
/**
* TypeInterface ensures consistency in typed values returned by ramsey/uuid
*
* @immutable
*/
interface TypeInterface extends JsonSerializable, Serializable
{
/**
* @pure
*/
public function toString(): string;
/**
* @pure
*/
public function __toString(): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Guid/Fields.php | src/Guid/Fields.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\Guid;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Fields\SerializableFieldsTrait;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\MaxTrait;
use Ramsey\Uuid\Rfc4122\NilTrait;
use Ramsey\Uuid\Rfc4122\VariantTrait;
use Ramsey\Uuid\Rfc4122\VersionTrait;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Uuid;
use function bin2hex;
use function dechex;
use function hexdec;
use function pack;
use function sprintf;
use function str_pad;
use function strlen;
use function substr;
use function unpack;
use const STR_PAD_LEFT;
/**
* GUIDs consist of a set of named fields, according to RFC 9562 (formerly RFC 4122)
*
* @see Guid
*
* @immutable
*/
final class Fields implements FieldsInterface
{
use MaxTrait;
use NilTrait;
use SerializableFieldsTrait;
use VariantTrait;
use VersionTrait;
/**
* @param string $bytes A 16-byte binary string representation of a UUID
*
* @throws InvalidArgumentException if the byte string is not exactly 16 bytes
* @throws InvalidArgumentException if the byte string does not represent a GUID
* @throws InvalidArgumentException if the byte string does not contain a valid version
*/
public function __construct(private string $bytes)
{
if (strlen($this->bytes) !== 16) {
throw new InvalidArgumentException(
'The byte string must be 16 bytes long; received ' . strlen($this->bytes) . ' bytes',
);
}
if (!$this->isCorrectVariant()) {
throw new InvalidArgumentException(
'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) '
. 'or Microsoft Corporation variants',
);
}
if (!$this->isCorrectVersion()) {
throw new InvalidArgumentException('The byte string received does not contain a valid version');
}
}
public function getBytes(): string
{
return $this->bytes;
}
public function getTimeLow(): Hexadecimal
{
// Swap the bytes from little endian to network byte order.
/** @var string[] $hex */
$hex = unpack(
'H*',
pack(
'v*',
hexdec(bin2hex(substr($this->bytes, 2, 2))),
hexdec(bin2hex(substr($this->bytes, 0, 2))),
),
);
return new Hexadecimal($hex[1] ?? '');
}
public function getTimeMid(): Hexadecimal
{
// Swap the bytes from little endian to network byte order.
/** @var string[] $hex */
$hex = unpack('H*', pack('v', hexdec(bin2hex(substr($this->bytes, 4, 2)))));
return new Hexadecimal($hex[1] ?? '');
}
public function getTimeHiAndVersion(): Hexadecimal
{
// Swap the bytes from little endian to network byte order.
/** @var string[] $hex */
$hex = unpack('H*', pack('v', hexdec(bin2hex(substr($this->bytes, 6, 2)))));
return new Hexadecimal($hex[1] ?? '');
}
public function getTimestamp(): Hexadecimal
{
return new Hexadecimal(sprintf(
'%03x%04s%08s',
hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff,
$this->getTimeMid()->toString(),
$this->getTimeLow()->toString()
));
}
public function getClockSeq(): Hexadecimal
{
if ($this->isMax()) {
$clockSeq = 0xffff;
} elseif ($this->isNil()) {
$clockSeq = 0x0000;
} else {
$clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff;
}
return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT));
}
public function getClockSeqHiAndReserved(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1)));
}
public function getClockSeqLow(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1)));
}
public function getNode(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 10)));
}
public function getVersion(): ?int
{
if ($this->isNil() || $this->isMax()) {
return null;
}
/** @var int[] $parts */
$parts = unpack('n*', $this->bytes);
return ($parts[4] >> 4) & 0x00f;
}
private function isCorrectVariant(): bool
{
if ($this->isNil() || $this->isMax()) {
return true;
}
$variant = $this->getVariant();
return $variant === Uuid::RFC_4122 || $variant === Uuid::RESERVED_MICROSOFT;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Guid/Guid.php | src/Guid/Guid.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\Guid;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Uuid;
/**
* Guid represents a UUID with "native" (little-endian) byte order
*
* From Wikipedia:
*
* > The first three fields are unsigned 32- and 16-bit integers and are subject to swapping, while the last two fields
* > consist of uninterpreted bytes, not subject to swapping. This byte swapping applies even for versions 3, 4, and 5,
* > where the canonical fields do not correspond to the content of the UUID.
*
* The first three fields of a GUID are encoded in little-endian byte order, while the last three fields are in network
* (big-endian) byte order. This is according to the history of the Microsoft GUID definition.
*
* According to the .NET Guid.ToByteArray method documentation:
*
* > Note that the order of bytes in the returned byte array is different from the string representation of a Guid value.
* > The order of the beginning four-byte group and the next two two-byte groups is reversed, whereas the order of the
* > last two-byte group and the closing six-byte group is the same.
*
* @link https://en.wikipedia.org/wiki/Universally_unique_identifier#Variants UUID Variants on Wikipedia
* @link https://docs.microsoft.com/en-us/windows/win32/api/guiddef/ns-guiddef-guid Windows GUID structure
* @link https://docs.microsoft.com/en-us/dotnet/api/system.guid .NET Guid Struct
* @link https://docs.microsoft.com/en-us/dotnet/api/system.guid.tobytearray .NET Guid.ToByteArray Method
*
* @immutable
*/
final class Guid extends Uuid
{
public function __construct(
Fields $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Guid/GuidBuilder.php | src/Guid/GuidBuilder.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\Guid;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\UuidInterface;
use Throwable;
/**
* GuidBuilder builds instances of Guid
*
* @see Guid
*
* @immutable
*/
class GuidBuilder implements UuidBuilderInterface
{
/**
* @param NumberConverterInterface $numberConverter The number converter to use when constructing the Guid
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to Unix timestamps
*/
public function __construct(
private NumberConverterInterface $numberConverter,
private TimeConverterInterface $timeConverter,
) {
}
/**
* Builds and returns a Guid
*
* @param CodecInterface $codec The codec to use for building this Guid instance
* @param string $bytes The byte string from which to construct a UUID
*
* @return Guid The GuidBuilder returns an instance of Ramsey\Uuid\Guid\Guid
*
* @pure
*/
public function build(CodecInterface $codec, string $bytes): UuidInterface
{
try {
/** @phpstan-ignore possiblyImpure.new */
return new Guid($this->buildFields($bytes), $this->numberConverter, $codec, $this->timeConverter);
} catch (Throwable $e) {
/** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */
throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* Proxy method to allow injecting a mock for testing
*
* @pure
*/
protected function buildFields(string $bytes): Fields
{
/** @phpstan-ignore possiblyImpure.new */
return new Fields($bytes);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Math/CalculatorInterface.php | src/Math/CalculatorInterface.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\Math;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\NumberInterface;
/**
* A calculator performs arithmetic operations on numbers
*
* @immutable
*/
interface CalculatorInterface
{
/**
* Returns the sum of all the provided parameters
*
* @param NumberInterface $augend The first addend (the integer being added to)
* @param NumberInterface ...$addends The additional integers to a add to the augend
*
* @return NumberInterface The sum of all the parameters
*
* @pure
*/
public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface;
/**
* Returns the difference of all the provided parameters
*
* @param NumberInterface $minuend The integer being subtracted from
* @param NumberInterface ...$subtrahends The integers to subtract from the minuend
*
* @return NumberInterface The difference after subtracting all parameters
*
* @pure
*/
public function subtract(NumberInterface $minuend, NumberInterface ...$subtrahends): NumberInterface;
/**
* Returns the product of all the provided parameters
*
* @param NumberInterface $multiplicand The integer to be multiplied
* @param NumberInterface ...$multipliers The factors by which to multiply the multiplicand
*
* @return NumberInterface The product of multiplying all the provided parameters
*
* @pure
*/
public function multiply(NumberInterface $multiplicand, NumberInterface ...$multipliers): NumberInterface;
/**
* Returns the quotient of the provided parameters divided left-to-right
*
* @param int $roundingMode The RoundingMode constant to use for this operation
* @param int $scale The scale to use for this operation
* @param NumberInterface $dividend The integer to be divided
* @param NumberInterface ...$divisors The integers to divide $dividend by, in the order in which the division
* operations should take place (left-to-right)
*
* @return NumberInterface The quotient of dividing the provided parameters left-to-right
*
* @pure
*/
public function divide(
int $roundingMode,
int $scale,
NumberInterface $dividend,
NumberInterface ...$divisors,
): NumberInterface;
/**
* Converts a value from an arbitrary base to a base-10 integer value
*
* @param string $value The value to convert
* @param int $base The base to convert from (i.e., 2, 16, 32, etc.)
*
* @return IntegerObject The base-10 integer value of the converted value
*
* @pure
*/
public function fromBase(string $value, int $base): IntegerObject;
/**
* Converts a base-10 integer value to an arbitrary base
*
* @param IntegerObject $value The integer value to convert
* @param int $base The base to convert to (i.e., 2, 16, 32, etc.)
*
* @return string The value represented in the specified base
*
* @pure
*/
public function toBase(IntegerObject $value, int $base): string;
/**
* Converts an Integer instance to a Hexadecimal instance
*
* @pure
*/
public function toHexadecimal(IntegerObject $value): Hexadecimal;
/**
* Converts a Hexadecimal instance to an Integer instance
*
* @pure
*/
public function toInteger(Hexadecimal $value): IntegerObject;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Math/BrickMathCalculator.php | src/Math/BrickMathCalculator.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\Math;
use Brick\Math\BigDecimal;
use Brick\Math\BigInteger;
use Brick\Math\Exception\MathException;
use Brick\Math\RoundingMode as BrickMathRounding;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Type\Decimal;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\NumberInterface;
/**
* A calculator using the brick/math library for arbitrary-precision arithmetic
*
* @immutable
*/
final class BrickMathCalculator implements CalculatorInterface
{
private const ROUNDING_MODE_MAP = [
RoundingMode::UNNECESSARY => BrickMathRounding::UNNECESSARY,
RoundingMode::UP => BrickMathRounding::UP,
RoundingMode::DOWN => BrickMathRounding::DOWN,
RoundingMode::CEILING => BrickMathRounding::CEILING,
RoundingMode::FLOOR => BrickMathRounding::FLOOR,
RoundingMode::HALF_UP => BrickMathRounding::HALF_UP,
RoundingMode::HALF_DOWN => BrickMathRounding::HALF_DOWN,
RoundingMode::HALF_CEILING => BrickMathRounding::HALF_CEILING,
RoundingMode::HALF_FLOOR => BrickMathRounding::HALF_FLOOR,
RoundingMode::HALF_EVEN => BrickMathRounding::HALF_EVEN,
];
public function add(NumberInterface $augend, NumberInterface ...$addends): NumberInterface
{
$sum = BigInteger::of($augend->toString());
foreach ($addends as $addend) {
$sum = $sum->plus($addend->toString());
}
/** @phpstan-ignore possiblyImpure.new */
return new IntegerObject((string) $sum);
}
public function subtract(NumberInterface $minuend, NumberInterface ...$subtrahends): NumberInterface
{
$difference = BigInteger::of($minuend->toString());
foreach ($subtrahends as $subtrahend) {
$difference = $difference->minus($subtrahend->toString());
}
/** @phpstan-ignore possiblyImpure.new */
return new IntegerObject((string) $difference);
}
public function multiply(NumberInterface $multiplicand, NumberInterface ...$multipliers): NumberInterface
{
$product = BigInteger::of($multiplicand->toString());
foreach ($multipliers as $multiplier) {
$product = $product->multipliedBy($multiplier->toString());
}
/** @phpstan-ignore possiblyImpure.new */
return new IntegerObject((string) $product);
}
public function divide(
int $roundingMode,
int $scale,
NumberInterface $dividend,
NumberInterface ...$divisors,
): NumberInterface {
/** @phpstan-ignore possiblyImpure.methodCall */
$brickRounding = $this->getBrickRoundingMode($roundingMode);
$quotient = BigDecimal::of($dividend->toString());
foreach ($divisors as $divisor) {
$quotient = $quotient->dividedBy($divisor->toString(), $scale, $brickRounding);
}
if ($scale === 0) {
/** @phpstan-ignore possiblyImpure.new */
return new IntegerObject((string) $quotient->toBigInteger());
}
/** @phpstan-ignore possiblyImpure.new */
return new Decimal((string) $quotient);
}
public function fromBase(string $value, int $base): IntegerObject
{
try {
/** @phpstan-ignore possiblyImpure.new */
return new IntegerObject((string) BigInteger::fromBase($value, $base));
} catch (MathException | \InvalidArgumentException $exception) {
throw new InvalidArgumentException(
$exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
}
public function toBase(IntegerObject $value, int $base): string
{
try {
return BigInteger::of($value->toString())->toBase($base);
} catch (MathException | \InvalidArgumentException $exception) {
throw new InvalidArgumentException(
$exception->getMessage(),
(int) $exception->getCode(),
$exception
);
}
}
public function toHexadecimal(IntegerObject $value): Hexadecimal
{
/** @phpstan-ignore possiblyImpure.new */
return new Hexadecimal($this->toBase($value, 16));
}
public function toInteger(Hexadecimal $value): IntegerObject
{
return $this->fromBase($value->toString(), 16);
}
/**
* Maps ramsey/uuid rounding modes to those used by brick/math
*
* @return BrickMathRounding::*
*/
private function getBrickRoundingMode(int $roundingMode)
{
return self::ROUNDING_MODE_MAP[$roundingMode] ?? BrickMathRounding::UNNECESSARY;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Math/RoundingMode.php | src/Math/RoundingMode.php | <?php
/**
* This file was originally part of brick/math
*
* Copyright (c) 2013-present Benjamin Morel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
* @link https://github.com/brick/math brick/math at GitHub
*/
declare(strict_types=1);
namespace Ramsey\Uuid\Math;
/**
* Specifies a rounding behavior for numerical operations capable of discarding precision.
*
* Each rounding mode indicates how the least significant returned digit of a rounded result is to be calculated. If
* fewer digits are returned than the digits needed to represent the exact numerical result, the discarded digits will
* be referred to as the discarded fraction regardless of the digits' contribution to the value of the number. In other
* words, considered as a numerical value, the discarded fraction could have an absolute value greater than one.
*/
final class RoundingMode
{
/**
* Asserts that the requested operation has an exact result; hence no rounding is necessary.
*/
public const UNNECESSARY = 0;
/**
* Rounds away from zero.
*
* Always increments the digit prior to a nonzero discarded fraction. Note that this rounding mode never decreases
* the magnitude of the calculated value.
*/
public const UP = 1;
/**
* Rounds towards zero.
*
* Never increments the digit prior to a discarded fraction (i.e., truncates). Note that this rounding mode never
* increases the magnitude of the calculated value.
*/
public const DOWN = 2;
/**
* Rounds towards positive infinity.
*
* If the result is positive, behaves as for UP; if negative, behaves as for DOWN. Note that this rounding mode
* never decreases the calculated value.
*/
public const CEILING = 3;
/**
* Rounds towards negative infinity.
*
* If the result is positive, behave as for DOWN; if negative, behave as for UP. Note that this rounding mode never
* increases the calculated value.
*/
public const FLOOR = 4;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round up.
*
* Behaves as for UP if the discarded fraction is >= 0.5; otherwise, behaves as for DOWN. Note that this is the
* rounding mode commonly taught at school.
*/
public const HALF_UP = 5;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round down.
*
* Behaves as for UP if the discarded fraction is > 0.5; otherwise, behaves as for DOWN.
*/
public const HALF_DOWN = 6;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards positive infinity.
*
* If the result is positive, behaves as for HALF_UP; if negative, behaves as for HALF_DOWN.
*/
public const HALF_CEILING = 7;
/**
* Rounds towards "nearest neighbor" unless both neighbors are equidistant, in which case round towards negative infinity.
*
* If the result is positive, behaves as for HALF_DOWN; if negative, behaves as for HALF_UP.
*/
public const HALF_FLOOR = 8;
/**
* Rounds towards the "nearest neighbor" unless both neighbors are equidistant, in which case rounds towards the even neighbor.
*
* Behaves as for HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for HALF_DOWN if it's even.
*
* Note that this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a
* sequence of calculations. It is sometimes known as "Banker's rounding", and is chiefly used in the USA.
*/
public const HALF_EVEN = 9;
/**
* Private constructor. This class is not instantiable.
*
* @codeCoverageIgnore
*/
private function __construct()
{
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Nonstandard/Uuid.php | src/Nonstandard/Uuid.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\Nonstandard;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Uuid as BaseUuid;
/**
* Nonstandard\Uuid is a UUID that doesn't conform to RFC 9562 (formerly RFC 4122)
*
* @immutable
* @pure
*/
final class Uuid extends BaseUuid
{
public function __construct(
Fields $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Nonstandard/UuidV6.php | src/Nonstandard/UuidV6.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\Nonstandard;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Lazy\LazyUuidFromString;
use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface;
use Ramsey\Uuid\Rfc4122\TimeTrait;
use Ramsey\Uuid\Rfc4122\UuidInterface;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Uuid as BaseUuid;
/**
* Reordered time, or version 6, UUIDs include timestamp, clock sequence, and node values that are combined into a
* 128-bit unsigned integer
*
* @deprecated Use {@see \Ramsey\Uuid\Rfc4122\UuidV6} instead.
*
* @link https://github.com/uuid6/uuid6-ietf-draft UUID version 6 IETF draft
* @link http://gh.peabody.io/uuidv6/ "Version 6" UUIDs
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.6 RFC 9562, 5.6. UUID Version 6
*
* @immutable
*/
class UuidV6 extends BaseUuid implements UuidInterface
{
use TimeTrait;
/**
* Creates a version 6 (reordered Gregorian time) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== BaseUuid::UUID_TYPE_REORDERED_TIME) {
throw new InvalidArgumentException(
'Fields used to create a UuidV6 must represent a version 6 (reordered time) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
/**
* Converts this UUID into an instance of a version 1 UUID
*/
public function toUuidV1(): UuidV1
{
$hex = $this->getHex()->toString();
$hex = substr($hex, 7, 5)
. substr($hex, 13, 3)
. substr($hex, 3, 4)
. '1' . substr($hex, 0, 3)
. substr($hex, 16);
/** @var LazyUuidFromString $uuid */
$uuid = BaseUuid::fromBytes((string) hex2bin($hex));
return $uuid->toUuidV1();
}
/**
* Converts a version 1 UUID into an instance of a version 6 UUID
*/
public static function fromUuidV1(UuidV1 $uuidV1): \Ramsey\Uuid\Rfc4122\UuidV6
{
$hex = $uuidV1->getHex()->toString();
$hex = substr($hex, 13, 3)
. substr($hex, 8, 4)
. substr($hex, 0, 5)
. '6' . substr($hex, 5, 3)
. substr($hex, 16);
/** @var LazyUuidFromString $uuid */
$uuid = BaseUuid::fromBytes((string) hex2bin($hex));
return $uuid->toUuidV6();
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Nonstandard/Fields.php | src/Nonstandard/Fields.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\Nonstandard;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Fields\SerializableFieldsTrait;
use Ramsey\Uuid\Rfc4122\FieldsInterface;
use Ramsey\Uuid\Rfc4122\VariantTrait;
use Ramsey\Uuid\Type\Hexadecimal;
use function bin2hex;
use function dechex;
use function hexdec;
use function sprintf;
use function str_pad;
use function strlen;
use function substr;
use const STR_PAD_LEFT;
/**
* Nonstandard UUID fields do not conform to the RFC 9562 (formerly RFC 4122) standard
*
* Since some systems may create nonstandard UUIDs, this implements the {@see FieldsInterface}, so that functionality of
* a nonstandard UUID is not degraded, in the event these UUIDs are expected to contain RFC 9562 (formerly RFC 4122) fields.
*
* Internally, this class represents the fields together as a 16-byte binary string.
*
* @immutable
*/
final class Fields implements FieldsInterface
{
use SerializableFieldsTrait;
use VariantTrait;
/**
* @param string $bytes A 16-byte binary string representation of a UUID
*
* @throws InvalidArgumentException if the byte string is not exactly 16 bytes
*/
public function __construct(private string $bytes)
{
if (strlen($this->bytes) !== 16) {
throw new InvalidArgumentException(
'The byte string must be 16 bytes long; received ' . strlen($this->bytes) . ' bytes',
);
}
}
public function getBytes(): string
{
return $this->bytes;
}
public function getClockSeq(): Hexadecimal
{
$clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff;
return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT));
}
public function getClockSeqHiAndReserved(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1)));
}
public function getClockSeqLow(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1)));
}
public function getNode(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 10)));
}
public function getTimeHiAndVersion(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 6, 2)));
}
public function getTimeLow(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 0, 4)));
}
public function getTimeMid(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 4, 2)));
}
public function getTimestamp(): Hexadecimal
{
return new Hexadecimal(sprintf(
'%03x%04s%08s',
hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff,
$this->getTimeMid()->toString(),
$this->getTimeLow()->toString()
));
}
public function getVersion(): ?int
{
return null;
}
public function isNil(): bool
{
return false;
}
public function isMax(): bool
{
return false;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Nonstandard/UuidBuilder.php | src/Nonstandard/UuidBuilder.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\Nonstandard;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\UuidInterface;
use Throwable;
/**
* Nonstandard\UuidBuilder builds instances of Nonstandard\Uuid
*
* @immutable
*/
class UuidBuilder implements UuidBuilderInterface
{
/**
* @param NumberConverterInterface $numberConverter The number converter to use when constructing the Nonstandard\Uuid
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to Unix timestamps
*/
public function __construct(
private NumberConverterInterface $numberConverter,
private TimeConverterInterface $timeConverter,
) {
}
/**
* Builds and returns a Nonstandard\Uuid
*
* @param CodecInterface $codec The codec to use for building this instance
* @param string $bytes The byte string from which to construct a UUID
*
* @return Uuid The Nonstandard\UuidBuilder returns an instance of Nonstandard\Uuid
*
* @pure
*/
public function build(CodecInterface $codec, string $bytes): UuidInterface
{
try {
/** @phpstan-ignore possiblyImpure.new */
return new Uuid($this->buildFields($bytes), $this->numberConverter, $codec, $this->timeConverter);
} catch (Throwable $e) {
/** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */
throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* Proxy method to allow injecting a mock for testing
*
* @pure
*/
protected function buildFields(string $bytes): Fields
{
/** @phpstan-ignore possiblyImpure.new */
return new Fields($bytes);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/VariantTrait.php | src/Rfc4122/VariantTrait.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\Rfc4122;
use Ramsey\Uuid\Exception\InvalidBytesException;
use Ramsey\Uuid\Uuid;
use function decbin;
use function str_pad;
use function str_starts_with;
use function strlen;
use function substr;
use function unpack;
use const STR_PAD_LEFT;
/**
* Provides common functionality for handling the variant, as defined by RFC 9562 (formerly RFC 4122)
*
* @immutable
*/
trait VariantTrait
{
/**
* Returns the bytes that comprise the fields
*/
abstract public function getBytes(): string;
/**
* Returns the variant
*
* The variant number describes the layout of the UUID. The variant number has the following meaning:
*
* - 0 - Reserved for NCS backward compatibility
* - 2 - The RFC 9562 (formerly RFC 4122) variant
* - 6 - Reserved, Microsoft Corporation backward compatibility
* - 7 - Reserved for future definition
*
* For RFC 9562 (formerly RFC 4122) variant UUIDs, this value should always be the integer `2`.
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field
*/
public function getVariant(): int
{
if (strlen($this->getBytes()) !== 16) {
throw new InvalidBytesException('Invalid number of bytes');
}
// According to RFC 9562, sections {@link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 4.1} and
// {@link https://www.rfc-editor.org/rfc/rfc9562#section-5.10 5.10}, the Max UUID falls within the range
// of the future variant.
if ($this->isMax()) {
return Uuid::RESERVED_FUTURE;
}
// According to RFC 9562, sections {@link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 4.1} and
// {@link https://www.rfc-editor.org/rfc/rfc9562#section-5.9 5.9}, the Nil UUID falls within the range
// of the Apollo NCS variant.
if ($this->isNil()) {
return Uuid::RESERVED_NCS;
}
/** @var int[] $parts */
$parts = unpack('n*', $this->getBytes());
// $parts[5] is a 16-bit, unsigned integer containing the variant bits of the UUID. We convert this integer into
// a string containing a binary representation, padded to 16 characters. We analyze the first three characters
// (three most-significant bits) to determine the variant.
$msb = substr(str_pad(decbin($parts[5]), 16, '0', STR_PAD_LEFT), 0, 3);
if ($msb === '111') {
return Uuid::RESERVED_FUTURE;
} elseif ($msb === '110') {
return Uuid::RESERVED_MICROSOFT;
} elseif (str_starts_with($msb, '10')) {
return Uuid::RFC_4122;
}
return Uuid::RESERVED_NCS;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidInterface.php | src/Rfc4122/UuidInterface.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\Rfc4122;
use Ramsey\Uuid\UuidInterface as BaseUuidInterface;
/**
* A universally unique identifier (UUID), as defined in RFC 9562 (formerly RFC 4122)
*
* @link https://www.rfc-editor.org/rfc/rfc9562 RFC 9562
*
* @immutable
*/
interface UuidInterface extends BaseUuidInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/NilTrait.php | src/Rfc4122/NilTrait.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\Rfc4122;
/**
* Provides common functionality for nil UUIDs
*
* @immutable
*/
trait NilTrait
{
/**
* Returns the bytes that comprise the fields
*
* @pure
*/
abstract public function getBytes(): string;
/**
* Returns true if the byte string represents a nil UUID
*/
public function isNil(): bool
{
return $this->getBytes() === "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV7.php | src/Rfc4122/UuidV7.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
/**
* Unix Epoch time, or version 7, UUIDs include a timestamp in milliseconds since the Unix Epoch, along with random bytes
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.7 RFC 9562, 5.7. UUID Version 7
*
* @immutable
*/
final class UuidV7 extends Uuid implements UuidInterface
{
use TimeTrait;
/**
* Creates a version 7 (Unix Epoch time) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_UNIX_TIME) {
throw new InvalidArgumentException(
'Fields used to create a UuidV7 must represent a version 7 (Unix Epoch time) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/NilUuid.php | src/Rfc4122/NilUuid.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\Rfc4122;
use Ramsey\Uuid\Uuid;
/**
* The nil UUID is a special form of UUID that has all 128 bits set to zero (`0`)
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.9 RFC 9562, 5.9. Nil UUID
*
* @immutable
*/
final class NilUuid extends Uuid implements UuidInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV5.php | src/Rfc4122/UuidV5.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
/**
* Version 5 UUIDs are named-based, using a combination of a namespace and name that are hashed into a 128-bit unsigned
* integer using the SHA1 hashing algorithm
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.5 RFC 9562, 5.5. UUID Version 5
*
* @immutable
*/
final class UuidV5 extends Uuid implements UuidInterface
{
/**
* Creates a version 5 (name-based, SHA1-hashed) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_HASH_SHA1) {
throw new InvalidArgumentException(
'Fields used to create a UuidV5 must represent a version 5 (named-based, SHA1-hashed) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/FieldsInterface.php | src/Rfc4122/FieldsInterface.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\Rfc4122;
use Ramsey\Uuid\Fields\FieldsInterface as BaseFieldsInterface;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* UUID fields, as defined by RFC 4122
*
* This interface defines the fields of an RFC 4122 variant UUID. Since RFC 9562 removed the concept of fields and
* instead defined layouts that are specific to a given version, this interface is a legacy artifact of the earlier, and
* now obsolete, RFC 4122.
*
* The fields of an RFC 4122 variant UUID are:
*
* * **time_low**: The low field of the timestamp, an unsigned 32-bit integer
* * **time_mid**: The middle field of the timestamp, an unsigned 16-bit integer
* * **time_hi_and_version**: The high field of the timestamp multiplexed with the version number, an unsigned 16-bit integer
* * **clock_seq_hi_and_reserved**: The high field of the clock sequence multiplexed with the variant, an unsigned 8-bit integer
* * **clock_seq_low**: The low field of the clock sequence, an unsigned 8-bit integer
* * **node**: The spatially unique node identifier, an unsigned 48-bit integer
*
* @link https://www.rfc-editor.org/rfc/rfc4122#section-4.1 RFC 4122, 4.1. Format
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4 RFC 9562, 4. UUID Format
*
* @immutable
*/
interface FieldsInterface extends BaseFieldsInterface
{
/**
* Returns the full 16-bit clock sequence, with the variant bits (two most significant bits) masked out
*/
public function getClockSeq(): Hexadecimal;
/**
* Returns the high field of the clock sequence multiplexed with the variant
*/
public function getClockSeqHiAndReserved(): Hexadecimal;
/**
* Returns the low field of the clock sequence
*/
public function getClockSeqLow(): Hexadecimal;
/**
* Returns the node field
*/
public function getNode(): Hexadecimal;
/**
* Returns the high field of the timestamp multiplexed with the version
*/
public function getTimeHiAndVersion(): Hexadecimal;
/**
* Returns the low field of the timestamp
*/
public function getTimeLow(): Hexadecimal;
/**
* Returns the middle field of the timestamp
*/
public function getTimeMid(): Hexadecimal;
/**
* Returns the full 60-bit timestamp, without the version
*/
public function getTimestamp(): Hexadecimal;
/**
* Returns the variant
*
* The variant number describes the layout of the UUID. The variant number has the following meaning:
*
* - 0 - Reserved for NCS backward compatibility
* - 2 - The RFC 9562 (formerly RFC 4122) variant
* - 6 - Reserved, Microsoft Corporation backward compatibility
* - 7 - Reserved for future definition
*
* For RFC 9562 (formerly RFC 4122) variant UUIDs, this value should always be the integer `2`.
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4.1 RFC 9562, 4.1. Variant Field
*/
public function getVariant(): int;
/**
* Returns the UUID version
*
* The version number describes how the UUID was generated and has the following meaning:
*
* 1. Gregorian time UUID
* 2. DCE security UUID
* 3. Name-based UUID hashed with MD5
* 4. Randomly generated UUID
* 5. Name-based UUID hashed with SHA-1
* 6. Reordered Gregorian time UUID
* 7. Unix Epoch time UUID
* 8. Custom format UUID
*
* This returns `null` if the UUID is not an RFC 9562 (formerly RFC 4122) variant, since the version is only
* meaningful for this variant.
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field
*
* @pure
*/
public function getVersion(): ?int;
/**
* Returns true if these fields represent a nil UUID
*
* The nil UUID is a special form of UUID that is specified to have all 128 bits set to zero.
*
* @pure
*/
public function isNil(): bool;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV6.php | src/Rfc4122/UuidV6.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\Rfc4122;
use Ramsey\Uuid\Nonstandard\UuidV6 as NonstandardUuidV6;
/**
* Reordered Gregorian time, or version 6, UUIDs include timestamp, clock sequence, and node values that are combined
* into a 128-bit unsigned integer
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.6 RFC 9562, 5.6. UUID Version 6
*
* @immutable
*/
final class UuidV6 extends NonstandardUuidV6 implements UuidInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV8.php | src/Rfc4122/UuidV8.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
/**
* Custom format, or version 8, UUIDs provide an RFC-compatible format for experimental or vendor-specific uses
*
* The only requirement for version 8 UUIDs is that the version and variant bits must be set. Otherwise, implementations
* are free to set the other bits according to their needs. As a result, the uniqueness of version 8 UUIDs is
* implementation-specific and should not be assumed.
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.8 RFC 9562, 5.8. UUID Version 8
*
* @immutable
*/
final class UuidV8 extends Uuid implements UuidInterface
{
/**
* Creates a version 8 (custom format) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_CUSTOM) {
throw new InvalidArgumentException(
'Fields used to create a UuidV8 must represent a version 8 (custom format) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/TimeTrait.php | src/Rfc4122/TimeTrait.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\Rfc4122;
use DateTimeImmutable;
use DateTimeInterface;
use Ramsey\Uuid\Exception\DateTimeException;
use Throwable;
use function str_pad;
use const STR_PAD_LEFT;
/**
* Provides common functionality for getting the time from a time-based UUID
*
* @immutable
*/
trait TimeTrait
{
/**
* Returns a DateTimeInterface object representing the timestamp associated with the UUID
*
* @return DateTimeImmutable A PHP DateTimeImmutable instance representing the timestamp of a time-based UUID
*/
public function getDateTime(): DateTimeInterface
{
$time = $this->timeConverter->convertTime($this->fields->getTimestamp());
try {
return new DateTimeImmutable(
'@'
. $time->getSeconds()->toString()
. '.'
. str_pad($time->getMicroseconds()->toString(), 6, '0', STR_PAD_LEFT)
);
} catch (Throwable $e) {
throw new DateTimeException($e->getMessage(), (int) $e->getCode(), $e);
}
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/Fields.php | src/Rfc4122/Fields.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\Rfc4122;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Fields\SerializableFieldsTrait;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Uuid;
use function bin2hex;
use function dechex;
use function hexdec;
use function sprintf;
use function str_pad;
use function strlen;
use function substr;
use function unpack;
use const STR_PAD_LEFT;
/**
* RFC 9562 (formerly RFC 4122) variant UUIDs consist of a set of named fields
*
* Internally, this class represents the fields together as a 16-byte binary string.
*
* @immutable
*/
final class Fields implements FieldsInterface
{
use MaxTrait;
use NilTrait;
use SerializableFieldsTrait;
use VariantTrait;
use VersionTrait;
/**
* @param string $bytes A 16-byte binary string representation of a UUID
*
* @throws InvalidArgumentException if the byte string is not exactly 16 bytes
* @throws InvalidArgumentException if the byte string does not represent an RFC 9562 (formerly RFC 4122) UUID
* @throws InvalidArgumentException if the byte string does not contain a valid version
*/
public function __construct(private string $bytes)
{
if (strlen($this->bytes) !== 16) {
throw new InvalidArgumentException(
'The byte string must be 16 bytes long; ' . 'received ' . strlen($this->bytes) . ' bytes',
);
}
if (!$this->isCorrectVariant()) {
throw new InvalidArgumentException(
'The byte string received does not conform to the RFC 9562 (formerly RFC 4122) variant',
);
}
if (!$this->isCorrectVersion()) {
throw new InvalidArgumentException(
'The byte string received does not contain a valid RFC 9562 (formerly RFC 4122) version',
);
}
}
/**
* @pure
*/
public function getBytes(): string
{
return $this->bytes;
}
public function getClockSeq(): Hexadecimal
{
if ($this->isMax()) {
$clockSeq = 0xffff;
} elseif ($this->isNil()) {
$clockSeq = 0x0000;
} else {
$clockSeq = hexdec(bin2hex(substr($this->bytes, 8, 2))) & 0x3fff;
}
return new Hexadecimal(str_pad(dechex($clockSeq), 4, '0', STR_PAD_LEFT));
}
public function getClockSeqHiAndReserved(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 8, 1)));
}
public function getClockSeqLow(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 9, 1)));
}
public function getNode(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 10)));
}
public function getTimeHiAndVersion(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 6, 2)));
}
public function getTimeLow(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 0, 4)));
}
public function getTimeMid(): Hexadecimal
{
return new Hexadecimal(bin2hex(substr($this->bytes, 4, 2)));
}
/**
* Returns the full 60-bit timestamp, without the version
*
* For version 2 UUIDs, the time_low field is the local identifier and should not be returned as part of the time.
* For this reason, we set the bottom 32 bits of the timestamp to 0's. As a result, there is some loss of timestamp
* fidelity, for version 2 UUIDs. The timestamp can be off by a range of 0 to 429.4967295 seconds (or 7 minutes, 9
* seconds, and 496,730 microseconds).
*
* For version 6 UUIDs, the timestamp order is reversed from the typical RFC 9562 (formerly RFC 4122) order (the
* time bits are in the correct bit order, so that it is monotonically increasing). In returning the timestamp
* value, we put the bits in the order: time_low + time_mid + time_hi.
*/
public function getTimestamp(): Hexadecimal
{
return new Hexadecimal(match ($this->getVersion()) {
Uuid::UUID_TYPE_DCE_SECURITY => sprintf(
'%03x%04s%08s',
hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff,
$this->getTimeMid()->toString(),
''
),
Uuid::UUID_TYPE_REORDERED_TIME => sprintf(
'%08s%04s%03x',
$this->getTimeLow()->toString(),
$this->getTimeMid()->toString(),
hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff
),
// The Unix timestamp in version 7 UUIDs is a 48-bit number, but for consistency, we will return a 60-bit
// number, padded to the left with zeros.
Uuid::UUID_TYPE_UNIX_TIME => sprintf(
'%011s%04s',
$this->getTimeLow()->toString(),
$this->getTimeMid()->toString(),
),
default => sprintf(
'%03x%04s%08s',
hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff,
$this->getTimeMid()->toString(),
$this->getTimeLow()->toString()
),
});
}
public function getVersion(): ?int
{
if ($this->isNil() || $this->isMax()) {
return null;
}
/** @var int[] $parts */
$parts = unpack('n*', $this->bytes);
return $parts[4] >> 12;
}
private function isCorrectVariant(): bool
{
if ($this->isNil() || $this->isMax()) {
return true;
}
return $this->getVariant() === Uuid::RFC_4122;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV4.php | src/Rfc4122/UuidV4.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
/**
* Random, or version 4, UUIDs are randomly or pseudo-randomly generated 128-bit integers
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.4 RFC 9562, 5.4. UUID Version 4
*
* @immutable
*/
final class UuidV4 extends Uuid implements UuidInterface
{
/**
* Creates a version 4 (random) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_RANDOM) {
throw new InvalidArgumentException(
'Fields used to create a UuidV4 must represent a version 4 (random) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/MaxTrait.php | src/Rfc4122/MaxTrait.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\Rfc4122;
/**
* Provides common functionality for max UUIDs
*
* @immutable
*/
trait MaxTrait
{
/**
* Returns the bytes that comprise the fields
*
* @pure
*/
abstract public function getBytes(): string;
/**
* Returns true if the byte string represents a max UUID
*
* @pure
*/
public function isMax(): bool
{
return $this->getBytes() === "\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff";
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/Validator.php | src/Rfc4122/Validator.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\Rfc4122;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\Validator\ValidatorInterface;
use function preg_match;
use function str_replace;
/**
* Rfc4122\Validator validates strings as UUIDs of the RFC 9562 (formerly RFC 4122) variant
*
* @immutable
*/
final class Validator implements ValidatorInterface
{
private const VALID_PATTERN = '\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';
/**
* @return non-empty-string
*/
public function getPattern(): string
{
return self::VALID_PATTERN;
}
public function validate(string $uuid): bool
{
/** @phpstan-ignore possiblyImpure.functionCall */
$uuid = strtolower(str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid));
/** @phpstan-ignore possiblyImpure.functionCall */
return $uuid === Uuid::NIL || $uuid === Uuid::MAX || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/MaxUuid.php | src/Rfc4122/MaxUuid.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\Rfc4122;
use Ramsey\Uuid\Uuid;
/**
* The max UUID is a special form of UUID that has all 128 bits set to one (`1`)
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.10 RFC 9562, 5.10. Max UUID
*
* @immutable
*/
final class MaxUuid extends Uuid implements UuidInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV3.php | src/Rfc4122/UuidV3.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
/**
* Version 3 UUIDs are named-based, using a combination of a namespace and name that are hashed into a 128-bit unsigned
* integer using the MD5 hashing algorithm
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.3 RFC 9562, 5.3. UUID Version 3
*
* @immutable
*/
final class UuidV3 extends Uuid implements UuidInterface
{
/**
* Creates a version 3 (name-based, MD5-hashed) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_HASH_MD5) {
throw new InvalidArgumentException(
'Fields used to create a UuidV3 must represent a version 3 (name-based, MD5-hashed) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/VersionTrait.php | src/Rfc4122/VersionTrait.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\Rfc4122;
use Ramsey\Uuid\Uuid;
/**
* Provides common functionality for handling the version, as defined by RFC 9562 (formerly RFC 4122)
*
* @immutable
*/
trait VersionTrait
{
/**
* Returns the UUID version
*
* The version number describes how the UUID was generated and has the following meaning:
*
* 1. Gregorian time UUID
* 2. DCE security UUID
* 3. Name-based UUID hashed with MD5
* 4. Randomly generated UUID
* 5. Name-based UUID hashed with SHA-1
* 6. Reordered Gregorian time UUID
* 7. Unix Epoch time UUID
* 8. Custom format UUID
*
* This returns `null` if the UUID is not an RFC 9562 (formerly RFC 4122) variant, since the version is only
* meaningful for this variant.
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-4.2 RFC 9562, 4.2. Version Field
*
* @pure
*/
abstract public function getVersion(): ?int;
/**
* Returns true if these fields represent a max UUID
*/
abstract public function isMax(): bool;
/**
* Returns true if these fields represent a nil UUID
*/
abstract public function isNil(): bool;
/**
* Returns true if the version matches one of those defined by RFC 9562 (formerly RFC 4122)
*
* @return bool True if the UUID version is valid, false otherwise
*/
private function isCorrectVersion(): bool
{
if ($this->isNil() || $this->isMax()) {
return true;
}
return match ($this->getVersion()) {
Uuid::UUID_TYPE_TIME, Uuid::UUID_TYPE_DCE_SECURITY,
Uuid::UUID_TYPE_HASH_MD5, Uuid::UUID_TYPE_RANDOM,
Uuid::UUID_TYPE_HASH_SHA1, Uuid::UUID_TYPE_REORDERED_TIME,
Uuid::UUID_TYPE_UNIX_TIME, Uuid::UUID_TYPE_CUSTOM => true,
default => false,
};
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV2.php | src/Rfc4122/UuidV2.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Uuid;
use function hexdec;
/**
* DCE Security version, or version 2, UUIDs include local domain identifier, local ID for the specified domain, and
* node values that are combined into a 128-bit unsigned integer
*
* It is important to note that a version 2 UUID suffers from some loss of timestamp fidelity, due to replacing the
* time_low field with the local identifier. When constructing the timestamp value for date purposes, we replace the
* local identifier bits with zeros. As a result, the timestamp can be off by a range of 0 to 429.4967295 seconds (or 7
* minutes, 9 seconds, and 496,730 microseconds).
*
* Astute observers might note this value directly corresponds to `2^32-1`, or `0xffffffff`. The local identifier is
* 32-bits, and we have set each of these bits to `0`, so the maximum range of timestamp drift is `0x00000000` to
* `0xffffffff` (counted in 100-nanosecond intervals).
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.2 RFC 9562, 5.2. UUID Version 2
* @link https://publications.opengroup.org/c311 DCE 1.1: Authentication and Security Services
* @link https://publications.opengroup.org/c706 DCE 1.1: Remote Procedure Call
* @link https://pubs.opengroup.org/onlinepubs/9696989899/chap5.htm#tagcjh_08_02_01_01 DCE 1.1: Auth & Sec, §5.2.1.1
* @link https://pubs.opengroup.org/onlinepubs/9696989899/chap11.htm#tagcjh_14_05_01_01 DCE 1.1: Auth & Sec, §11.5.1.1
* @link https://pubs.opengroup.org/onlinepubs/9629399/apdxa.htm DCE 1.1: RPC, Appendix A
* @link https://github.com/google/uuid Go package for UUIDs (includes DCE implementation)
*
* @immutable
*/
final class UuidV2 extends Uuid implements UuidInterface
{
use TimeTrait;
/**
* Creates a version 2 (DCE Security) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_DCE_SECURITY) {
throw new InvalidArgumentException(
'Fields used to create a UuidV2 must represent a version 2 (DCE Security) UUID'
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
/**
* Returns the local domain used to create this version 2 UUID
*/
public function getLocalDomain(): int
{
/** @var Rfc4122FieldsInterface $fields */
$fields = $this->getFields();
return (int) hexdec($fields->getClockSeqLow()->toString());
}
/**
* Returns the string name of the local domain
*/
public function getLocalDomainName(): string
{
return Uuid::DCE_DOMAIN_NAMES[$this->getLocalDomain()];
}
/**
* Returns the local identifier for the domain used to create this version 2 UUID
*/
public function getLocalIdentifier(): IntegerObject
{
/** @var Rfc4122FieldsInterface $fields */
$fields = $this->getFields();
return new IntegerObject($this->numberConverter->fromHex($fields->getTimeLow()->toString()));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidV1.php | src/Rfc4122/UuidV1.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\Rfc4122;
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 as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
/**
* Gregorian time, or version 1, UUIDs include timestamp, clock sequence, and node values, combined into a 128-bit unsigned integer
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-5.1 RFC 9562, 5.1. UUID Version 1
*
* @immutable
*/
final class UuidV1 extends Uuid implements UuidInterface
{
use TimeTrait;
/**
* Creates a version 1 (Gregorian time) UUID
*
* @param Rfc4122FieldsInterface $fields The fields from which to construct a UUID
* @param NumberConverterInterface $numberConverter The number converter to use for converting hex values to/from integers
* @param CodecInterface $codec The codec to use when encoding or decoding UUID strings
* @param TimeConverterInterface $timeConverter The time converter to use for converting timestamps extracted from a
* UUID to unix timestamps
*/
public function __construct(
Rfc4122FieldsInterface $fields,
NumberConverterInterface $numberConverter,
CodecInterface $codec,
TimeConverterInterface $timeConverter,
) {
if ($fields->getVersion() !== Uuid::UUID_TYPE_TIME) {
throw new InvalidArgumentException(
'Fields used to create a UuidV1 must represent a version 1 (time-based) UUID',
);
}
parent::__construct($fields, $numberConverter, $codec, $timeConverter);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Rfc4122/UuidBuilder.php | src/Rfc4122/UuidBuilder.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\Rfc4122;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Time\UnixTimeConverter;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\UnableToBuildUuidException;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Rfc4122\UuidInterface as Rfc4122UuidInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use Throwable;
/**
* UuidBuilder builds instances of RFC 9562 (formerly 4122) UUIDs
*
* @immutable
*/
class UuidBuilder implements UuidBuilderInterface
{
private TimeConverterInterface $unixTimeConverter;
/**
* Constructs the DefaultUuidBuilder
*
* @param NumberConverterInterface $numberConverter The number converter to use when constructing the Uuid
* @param TimeConverterInterface $timeConverter The time converter to use for converting Gregorian time extracted
* from version 1, 2, and 6 UUIDs to Unix timestamps
* @param TimeConverterInterface | null $unixTimeConverter The time converter to use for converter Unix Epoch time
* extracted from version 7 UUIDs to Unix timestamps
*/
public function __construct(
private NumberConverterInterface $numberConverter,
private TimeConverterInterface $timeConverter,
?TimeConverterInterface $unixTimeConverter = null,
) {
$this->unixTimeConverter = $unixTimeConverter ?? new UnixTimeConverter(new BrickMathCalculator());
}
/**
* Builds and returns a Uuid
*
* @param CodecInterface $codec The codec to use for building this Uuid instance
* @param string $bytes The byte string from which to construct a UUID
*
* @return Rfc4122UuidInterface UuidBuilder returns instances of Rfc4122UuidInterface
*
* @pure
*/
public function build(CodecInterface $codec, string $bytes): UuidInterface
{
try {
/** @var Fields $fields */
$fields = $this->buildFields($bytes);
if ($fields->isNil()) {
/** @phpstan-ignore possiblyImpure.new */
return new NilUuid($fields, $this->numberConverter, $codec, $this->timeConverter);
}
if ($fields->isMax()) {
/** @phpstan-ignore possiblyImpure.new */
return new MaxUuid($fields, $this->numberConverter, $codec, $this->timeConverter);
}
return match ($fields->getVersion()) {
/** @phpstan-ignore possiblyImpure.new */
Uuid::UUID_TYPE_TIME => new UuidV1($fields, $this->numberConverter, $codec, $this->timeConverter),
Uuid::UUID_TYPE_DCE_SECURITY
/** @phpstan-ignore possiblyImpure.new */
=> new UuidV2($fields, $this->numberConverter, $codec, $this->timeConverter),
/** @phpstan-ignore possiblyImpure.new */
Uuid::UUID_TYPE_HASH_MD5 => new UuidV3($fields, $this->numberConverter, $codec, $this->timeConverter),
/** @phpstan-ignore possiblyImpure.new */
Uuid::UUID_TYPE_RANDOM => new UuidV4($fields, $this->numberConverter, $codec, $this->timeConverter),
/** @phpstan-ignore possiblyImpure.new */
Uuid::UUID_TYPE_HASH_SHA1 => new UuidV5($fields, $this->numberConverter, $codec, $this->timeConverter),
Uuid::UUID_TYPE_REORDERED_TIME
/** @phpstan-ignore possiblyImpure.new */
=> new UuidV6($fields, $this->numberConverter, $codec, $this->timeConverter),
Uuid::UUID_TYPE_UNIX_TIME
/** @phpstan-ignore possiblyImpure.new */
=> new UuidV7($fields, $this->numberConverter, $codec, $this->unixTimeConverter),
/** @phpstan-ignore possiblyImpure.new */
Uuid::UUID_TYPE_CUSTOM => new UuidV8($fields, $this->numberConverter, $codec, $this->timeConverter),
default => throw new UnsupportedOperationException(
'The UUID version in the given fields is not supported by this UUID builder',
),
};
} catch (Throwable $e) {
/** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */
throw new UnableToBuildUuidException($e->getMessage(), (int) $e->getCode(), $e);
}
}
/**
* Proxy method to allow injecting a mock for testing
*
* @pure
*/
protected function buildFields(string $bytes): FieldsInterface
{
/** @phpstan-ignore possiblyImpure.new */
return new Fields($bytes);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Codec/TimestampFirstCombCodec.php | src/Codec/TimestampFirstCombCodec.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\Codec;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Ramsey\Uuid\UuidInterface;
use function bin2hex;
use function sprintf;
use function substr;
use function substr_replace;
/**
* TimestampFirstCombCodec encodes and decodes COMBs, with the timestamp as the first 48 bits
*
* In contrast with the TimestampLastCombCodec, the TimestampFirstCombCodec adds the timestamp to the first 48 bits of
* the COMB. To generate a timestamp-first COMB, set the TimestampFirstCombCodec as the codec, along with the
* CombGenerator as the random generator.
*
* ```
* $factory = new UuidFactory();
*
* $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder()));
*
* $factory->setRandomGenerator(new CombGenerator(
* $factory->getRandomGenerator(),
* $factory->getNumberConverter(),
* ));
*
* $timestampFirstComb = $factory->uuid4();
* ```
*
* @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
*
* @immutable
*/
class TimestampFirstCombCodec extends StringCodec
{
/**
* @return non-empty-string
*/
public function encode(UuidInterface $uuid): string
{
/** @phpstan-ignore possiblyImpure.methodCall */
$bytes = $this->swapBytes($uuid->getFields()->getBytes());
return sprintf(
'%08s-%04s-%04s-%04s-%012s',
bin2hex(substr($bytes, 0, 4)),
bin2hex(substr($bytes, 4, 2)),
bin2hex(substr($bytes, 6, 2)),
bin2hex(substr($bytes, 8, 2)),
bin2hex(substr($bytes, 10))
);
}
/**
* @return non-empty-string
*/
public function encodeBinary(UuidInterface $uuid): string
{
/** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */
return $this->swapBytes($uuid->getFields()->getBytes());
}
/**
* @throws InvalidUuidStringException
*
* @inheritDoc
*/
public function decode(string $encodedUuid): UuidInterface
{
/** @phpstan-ignore possiblyImpure.methodCall */
$bytes = $this->getBytes($encodedUuid);
/** @phpstan-ignore possiblyImpure.methodCall */
return $this->getBuilder()->build($this, $this->swapBytes($bytes));
}
public function decodeBytes(string $bytes): UuidInterface
{
/** @phpstan-ignore possiblyImpure.methodCall */
return $this->getBuilder()->build($this, $this->swapBytes($bytes));
}
/**
* Swaps bytes according to the timestamp-first COMB rules
*
* @pure
*/
private function swapBytes(string $bytes): string
{
$first48Bits = substr($bytes, 0, 6);
$last48Bits = substr($bytes, -6);
return substr_replace(substr_replace($bytes, $last48Bits, 0, 6), $first48Bits, -6);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Codec/GuidStringCodec.php | src/Codec/GuidStringCodec.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\Codec;
use Ramsey\Uuid\Guid\Guid;
use Ramsey\Uuid\UuidInterface;
use function bin2hex;
use function sprintf;
use function substr;
/**
* GuidStringCodec encodes and decodes globally unique identifiers (GUID)
*
* @see Guid
*
* @immutable
*/
class GuidStringCodec extends StringCodec
{
public function encode(UuidInterface $uuid): string
{
/** @phpstan-ignore possiblyImpure.methodCall */
$hex = bin2hex($uuid->getFields()->getBytes());
/** @var non-empty-string */
return sprintf(
'%02s%02s%02s%02s-%02s%02s-%02s%02s-%04s-%012s',
substr($hex, 6, 2),
substr($hex, 4, 2),
substr($hex, 2, 2),
substr($hex, 0, 2),
substr($hex, 10, 2),
substr($hex, 8, 2),
substr($hex, 14, 2),
substr($hex, 12, 2),
substr($hex, 16, 4),
substr($hex, 20),
);
}
public function decode(string $encodedUuid): UuidInterface
{
/** @phpstan-ignore possiblyImpure.methodCall */
$bytes = $this->getBytes($encodedUuid);
/** @phpstan-ignore possiblyImpure.methodCall, possiblyImpure.methodCall */
return $this->getBuilder()->build($this, $this->swapBytes($bytes));
}
public function decodeBytes(string $bytes): UuidInterface
{
// Call parent::decode() to preserve the correct byte order.
return parent::decode(bin2hex($bytes));
}
/**
* Swaps bytes according to the GUID rules
*/
private function swapBytes(string $bytes): string
{
return $bytes[3] . $bytes[2] . $bytes[1] . $bytes[0]
. $bytes[5] . $bytes[4] . $bytes[7] . $bytes[6]
. substr($bytes, 8);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Codec/TimestampLastCombCodec.php | src/Codec/TimestampLastCombCodec.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\Codec;
/**
* TimestampLastCombCodec encodes and decodes COMBs, with the timestamp as the last 48 bits
*
* The CombGenerator when used with the StringCodec (and, by proxy, the TimestampLastCombCodec) adds the timestamp to
* the last 48 bits of the COMB. The TimestampLastCombCodec is provided for the sake of consistency. In practice, it is
* identical to the standard StringCodec, but it may be used with the CombGenerator for additional context when reading
* code.
*
* Consider the following code. By default, the codec used by UuidFactory is the StringCodec, but here, we explicitly
* set the TimestampLastCombCodec. It is redundant, but it is clear that we intend this COMB to be generated with the
* timestamp appearing at the end.
*
* ```
* $factory = new UuidFactory();
*
* $factory->setCodec(new TimestampLastCombCodec($factory->getUuidBuilder()));
*
* $factory->setRandomGenerator(new CombGenerator(
* $factory->getRandomGenerator(),
* $factory->getNumberConverter(),
* ));
*
* $timestampLastComb = $factory->uuid4();
* ```
*
* @deprecated Please use {@see StringCodec} instead.
*
* @immutable
*/
class TimestampLastCombCodec extends StringCodec
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Codec/StringCodec.php | src/Codec/StringCodec.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\Codec;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use function bin2hex;
use function hex2bin;
use function implode;
use function sprintf;
use function str_replace;
use function strlen;
use function substr;
/**
* StringCodec encodes and decodes RFC 9562 (formerly RFC 4122) UUIDs
*
* @immutable
*/
class StringCodec implements CodecInterface
{
/**
* Constructs a StringCodec
*
* @param UuidBuilderInterface $builder The builder to use when encoding UUIDs
*/
public function __construct(private UuidBuilderInterface $builder)
{
}
public function encode(UuidInterface $uuid): string
{
/** @phpstan-ignore possiblyImpure.methodCall */
$hex = bin2hex($uuid->getFields()->getBytes());
/** @var non-empty-string */
return sprintf(
'%08s-%04s-%04s-%04s-%012s',
substr($hex, 0, 8),
substr($hex, 8, 4),
substr($hex, 12, 4),
substr($hex, 16, 4),
substr($hex, 20),
);
}
/**
* @return non-empty-string
*/
public function encodeBinary(UuidInterface $uuid): string
{
/** @phpstan-ignore-next-line PHPStan complains that this is not a non-empty-string. */
return $uuid->getFields()->getBytes();
}
/**
* @throws InvalidUuidStringException
*
* @inheritDoc
*/
public function decode(string $encodedUuid): UuidInterface
{
/** @phpstan-ignore possiblyImpure.methodCall */
return $this->builder->build($this, $this->getBytes($encodedUuid));
}
public function decodeBytes(string $bytes): UuidInterface
{
if (strlen($bytes) !== 16) {
throw new InvalidArgumentException('$bytes string should contain 16 characters.');
}
return $this->builder->build($this, $bytes);
}
/**
* Returns the UUID builder
*/
protected function getBuilder(): UuidBuilderInterface
{
return $this->builder;
}
/**
* Returns a byte string of the UUID
*/
protected function getBytes(string $encodedUuid): string
{
$parsedUuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}', '-'], '', $encodedUuid);
$components = [
substr($parsedUuid, 0, 8),
substr($parsedUuid, 8, 4),
substr($parsedUuid, 12, 4),
substr($parsedUuid, 16, 4),
substr($parsedUuid, 20),
];
if (!Uuid::isValid(implode('-', $components))) {
throw new InvalidUuidStringException('Invalid UUID string: ' . $encodedUuid);
}
return (string) hex2bin($parsedUuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Codec/CodecInterface.php | src/Codec/CodecInterface.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\Codec;
use Ramsey\Uuid\UuidInterface;
/**
* A codec encodes and decodes a UUID according to defined rules
*
* @immutable
*/
interface CodecInterface
{
/**
* Returns a hexadecimal string representation of a UuidInterface
*
* @param UuidInterface $uuid The UUID for which to create a hexadecimal string representation
*
* @return non-empty-string Hexadecimal string representation of a UUID
*
* @pure
*/
public function encode(UuidInterface $uuid): string;
/**
* Returns a binary string representation of a UuidInterface
*
* @param UuidInterface $uuid The UUID for which to create a binary string representation
*
* @return non-empty-string Binary string representation of a UUID
*
* @pure
*/
public function encodeBinary(UuidInterface $uuid): string;
/**
* Returns a UuidInterface derived from a hexadecimal string representation
*
* @param string $encodedUuid The hexadecimal string representation to convert into a UuidInterface instance
*
* @return UuidInterface An instance of a UUID decoded from a hexadecimal string representation
*
* @pure
*/
public function decode(string $encodedUuid): UuidInterface;
/**
* Returns a UuidInterface derived from a binary string representation
*
* @param string $bytes The binary string representation to convert into a UuidInterface instance
*
* @return UuidInterface An instance of a UUID decoded from a binary string representation
*
* @pure
*/
public function decodeBytes(string $bytes): UuidInterface;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Codec/OrderedTimeCodec.php | src/Codec/OrderedTimeCodec.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\Codec;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\Rfc4122\FieldsInterface as Rfc4122FieldsInterface;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
use function strlen;
use function substr;
/**
* OrderedTimeCodec encodes and decodes a UUID, optimizing the byte order for more efficient storage
*
* For binary representations of version 1 UUID, this codec may be used to reorganize the time fields, making the UUID
* closer to sequential when storing the bytes. According to Percona, this optimization can improve database INSERT and
* SELECT statements using the UUID column as a key.
*
* The string representation of the UUID will remain unchanged. Only the binary representation is reordered.
*
* PLEASE NOTE: Binary representations of UUIDs encoded with this codec must be decoded with this codec. Decoding using
* another codec can result in malformed UUIDs.
*
* @deprecated Please migrate to {@link https://uuid.ramsey.dev/en/stable/rfc4122/version6.html Version 6, reordered time-based UUIDs}.
*
* @link https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ Storing UUID Values in MySQL
*
* @immutable
*/
class OrderedTimeCodec extends StringCodec
{
/**
* Returns a binary string representation of a UUID, with the timestamp fields rearranged for optimized storage
*
* @return non-empty-string
*/
public function encodeBinary(UuidInterface $uuid): string
{
if (
/** @phpstan-ignore possiblyImpure.methodCall */
!($uuid->getFields() instanceof Rfc4122FieldsInterface)
/** @phpstan-ignore possiblyImpure.methodCall */
|| $uuid->getFields()->getVersion() !== Uuid::UUID_TYPE_TIME
) {
throw new InvalidArgumentException('Expected version 1 (time-based) UUID');
}
/** @phpstan-ignore possiblyImpure.methodCall */
$bytes = $uuid->getFields()->getBytes();
return $bytes[6] . $bytes[7] . $bytes[4] . $bytes[5]
. $bytes[0] . $bytes[1] . $bytes[2] . $bytes[3]
. substr($bytes, 8);
}
/**
* Returns a UuidInterface derived from an ordered-time binary string representation
*
* @throws InvalidArgumentException if $bytes is an invalid length
*
* @inheritDoc
*/
public function decodeBytes(string $bytes): UuidInterface
{
if (strlen($bytes) !== 16) {
throw new InvalidArgumentException('$bytes string should contain 16 characters.');
}
// Rearrange the bytes to their original order.
$rearrangedBytes = $bytes[4] . $bytes[5] . $bytes[6] . $bytes[7]
. $bytes[2] . $bytes[3] . $bytes[0] . $bytes[1]
. substr($bytes, 8);
$uuid = parent::decodeBytes($rearrangedBytes);
/** @phpstan-ignore possiblyImpure.methodCall */
$fields = $uuid->getFields();
if (!$fields instanceof Rfc4122FieldsInterface || $fields->getVersion() !== Uuid::UUID_TYPE_TIME) {
throw new UnsupportedOperationException(
'Attempting to decode a non-time-based UUID using OrderedTimeCodec',
);
}
return $uuid;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Fields/FieldsInterface.php | src/Fields/FieldsInterface.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\Fields;
use Serializable;
/**
* UUIDs consist of unsigned integers, the bytes of which are separated into fields and arranged in a particular layout
* defined by the specification for the variant
*
* @immutable
*/
interface FieldsInterface extends Serializable
{
/**
* Returns the bytes that comprise the fields
*
* @pure
*/
public function getBytes(): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Fields/SerializableFieldsTrait.php | src/Fields/SerializableFieldsTrait.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\Fields;
use ValueError;
use function base64_decode;
use function sprintf;
use function strlen;
/**
* Provides common serialization functionality to fields
*
* @immutable
*/
trait SerializableFieldsTrait
{
/**
* @param string $bytes The bytes that comprise the fields
*/
abstract public function __construct(string $bytes);
/**
* Returns the bytes that comprise the fields
*/
abstract public function getBytes(): string;
/**
* Returns a string representation of the object
*/
public function serialize(): string
{
return $this->getBytes();
}
/**
* @return array{bytes: string}
*/
public function __serialize(): array
{
return ['bytes' => $this->getBytes()];
}
/**
* Constructs the object from a serialized string representation
*
* @param string $data The serialized string representation of the object
*/
public function unserialize(string $data): void
{
if (strlen($data) === 16) {
$this->__construct($data);
} else {
$this->__construct(base64_decode($data));
}
}
/**
* @param array{bytes?: string} $data
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
if (!isset($data['bytes'])) {
throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__));
}
// @codeCoverageIgnoreEnd
$this->unserialize($data['bytes']);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/BuilderNotFoundException.php | src/Exception/BuilderNotFoundException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that no suitable builder could be found
*/
class BuilderNotFoundException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/InvalidUuidStringException.php | src/Exception/InvalidUuidStringException.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\Exception;
/**
* Thrown to indicate that the string received is not a valid UUID
*
* The InvalidArgumentException that this extends is the ramsey/uuid version of this exception. It exists in the same
* namespace as this class.
*/
class InvalidUuidStringException extends InvalidArgumentException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/InvalidBytesException.php | src/Exception/InvalidBytesException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that the bytes being operated on are invalid in some way
*/
class InvalidBytesException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/RandomSourceException.php | src/Exception/RandomSourceException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that the source of random data encountered an error
*
* This exception is used mostly to indicate that random_bytes() or random_int() threw an exception. However, it may be
* used for other sources of random data.
*/
class RandomSourceException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/NodeException.php | src/Exception/NodeException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that attempting to fetch or create a node ID encountered an error
*/
class NodeException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/UnableToBuildUuidException.php | src/Exception/UnableToBuildUuidException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate a builder is unable to build a UUID
*/
class UnableToBuildUuidException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/NameException.php | src/Exception/NameException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that an error occurred while attempting to hash a namespace and name
*/
class NameException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/UuidExceptionInterface.php | src/Exception/UuidExceptionInterface.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\Exception;
use Throwable;
interface UuidExceptionInterface extends Throwable
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/UnsupportedOperationException.php | src/Exception/UnsupportedOperationException.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\Exception;
use LogicException as PhpLogicException;
/**
* Thrown to indicate that the requested operation is not supported
*/
class UnsupportedOperationException extends PhpLogicException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/InvalidArgumentException.php | src/Exception/InvalidArgumentException.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\Exception;
use InvalidArgumentException as PhpInvalidArgumentException;
/**
* Thrown to indicate that the argument received is not valid
*/
class InvalidArgumentException extends PhpInvalidArgumentException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/TimeSourceException.php | src/Exception/TimeSourceException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that the source of time encountered an error
*/
class TimeSourceException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/DceSecurityException.php | src/Exception/DceSecurityException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate an exception occurred while dealing with DCE Security (version 2) UUIDs
*/
class DceSecurityException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Exception/DateTimeException.php | src/Exception/DateTimeException.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\Exception;
use RuntimeException as PhpRuntimeException;
/**
* Thrown to indicate that the PHP DateTime extension encountered an exception/error
*/
class DateTimeException extends PhpRuntimeException implements UuidExceptionInterface
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Lazy/LazyUuidFromString.php | src/Lazy/LazyUuidFromString.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\Lazy;
use DateTimeInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
use Ramsey\Uuid\Fields\FieldsInterface;
use Ramsey\Uuid\Rfc4122\UuidV1;
use Ramsey\Uuid\Rfc4122\UuidV6;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\UuidFactory;
use Ramsey\Uuid\UuidInterface;
use ValueError;
use function assert;
use function bin2hex;
use function hex2bin;
use function sprintf;
use function str_replace;
use function substr;
/**
* Lazy version of a UUID: its format has not been determined yet, so it is mostly only usable for string/bytes
* conversion. This object optimizes instantiation, serialization and string conversion time, at the cost of increased
* overhead for more advanced UUID operations.
*
* > [!NOTE]
* > The {@see FieldsInterface} does not declare methods that deprecated API relies upon: the API has been ported from
* > the {@see \Ramsey\Uuid\Uuid} definition, and is deprecated anyway.
*
* > [!NOTE]
* > The deprecated API from {@see \Ramsey\Uuid\Uuid} is in use here (on purpose): it will be removed once the
* > deprecated API is gone from this class too.
*
* @internal this type is used internally for performance reasons and is not supposed to be directly referenced in consumer libraries.
*/
final class LazyUuidFromString implements UuidInterface
{
public const VALID_REGEX = '/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ms';
private ?UuidInterface $unwrapped = null;
/**
* @param non-empty-string $uuid
*/
public function __construct(private string $uuid)
{
}
public static function fromBytes(string $bytes): self
{
$base16Uuid = bin2hex($bytes);
return new self(
substr($base16Uuid, 0, 8)
. '-'
. substr($base16Uuid, 8, 4)
. '-'
. substr($base16Uuid, 12, 4)
. '-'
. substr($base16Uuid, 16, 4)
. '-'
. substr($base16Uuid, 20, 12)
);
}
public function serialize(): string
{
return $this->uuid;
}
/**
* @return array{string: non-empty-string}
*/
public function __serialize(): array
{
return ['string' => $this->uuid];
}
/**
* {@inheritDoc}
*
* @param non-empty-string $data
*/
public function unserialize(string $data): void
{
$this->uuid = $data;
}
/**
* @param array{string?: non-empty-string} $data
*/
public function __unserialize(array $data): void
{
// @codeCoverageIgnoreStart
if (!isset($data['string'])) {
throw new ValueError(sprintf('%s(): Argument #1 ($data) is invalid', __METHOD__));
}
// @codeCoverageIgnoreEnd
$this->unserialize($data['string']);
}
public function getNumberConverter(): NumberConverterInterface
{
return ($this->unwrapped ?? $this->unwrap())->getNumberConverter();
}
/**
* @inheritDoc
*/
public function getFieldsHex(): array
{
return ($this->unwrapped ?? $this->unwrap())->getFieldsHex();
}
public function getClockSeqHiAndReservedHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getClockSeqHiAndReservedHex();
}
public function getClockSeqLowHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getClockSeqLowHex();
}
public function getClockSequenceHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getClockSequenceHex();
}
public function getDateTime(): DateTimeInterface
{
return ($this->unwrapped ?? $this->unwrap())->getDateTime();
}
public function getLeastSignificantBitsHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getLeastSignificantBitsHex();
}
public function getMostSignificantBitsHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getMostSignificantBitsHex();
}
public function getNodeHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getNodeHex();
}
public function getTimeHiAndVersionHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getTimeHiAndVersionHex();
}
public function getTimeLowHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getTimeLowHex();
}
public function getTimeMidHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getTimeMidHex();
}
public function getTimestampHex(): string
{
return ($this->unwrapped ?? $this->unwrap())->getTimestampHex();
}
public function getUrn(): string
{
return ($this->unwrapped ?? $this->unwrap())->getUrn();
}
public function getVariant(): ?int
{
return ($this->unwrapped ?? $this->unwrap())->getVariant();
}
public function getVersion(): ?int
{
return ($this->unwrapped ?? $this->unwrap())->getVersion();
}
public function compareTo(UuidInterface $other): int
{
return ($this->unwrapped ?? $this->unwrap())->compareTo($other);
}
public function equals(?object $other): bool
{
if (!$other instanceof UuidInterface) {
return false;
}
return $this->uuid === $other->toString();
}
public function getBytes(): string
{
/**
* @var non-empty-string
* @phpstan-ignore possiblyImpure.functionCall, possiblyImpure.functionCall
*/
return (string) hex2bin(str_replace('-', '', $this->uuid));
}
public function getFields(): FieldsInterface
{
return ($this->unwrapped ?? $this->unwrap())->getFields();
}
public function getHex(): Hexadecimal
{
return ($this->unwrapped ?? $this->unwrap())->getHex();
}
public function getInteger(): IntegerObject
{
return ($this->unwrapped ?? $this->unwrap())->getInteger();
}
public function toString(): string
{
return $this->uuid;
}
public function __toString(): string
{
return $this->uuid;
}
public function jsonSerialize(): string
{
return $this->uuid;
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getClockSeqHiAndReserved()}
* and use the arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getClockSeqHiAndReserved(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getClockSeqHiAndReserved()->toString());
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getClockSeqLow()} and use
* the arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getClockSeqLow(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getClockSeqLow()->toString());
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getClockSeq()} and use the
* arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getClockSequence(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getClockSeq()->toString());
}
/**
* @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be
* obtained by splitting in half the value returned by {@see UuidInterface::getHex()}.
*/
public function getLeastSignificantBits(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
return $instance->getNumberConverter()->fromHex(substr($instance->getHex()->toString(), 16));
}
/**
* @deprecated This method will be removed in 5.0.0. There is no direct alternative, but the same information may be
* obtained by splitting in half the value returned by {@see UuidInterface::getHex()}.
*/
public function getMostSignificantBits(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
return $instance->getNumberConverter()->fromHex(substr($instance->getHex()->toString(), 0, 16));
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getNode()} and use the
* arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getNode(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getNode()->toString());
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimeHiAndVersion()} and
* use the arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getTimeHiAndVersion(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getTimeHiAndVersion()->toString());
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimeLow()} and use the
* arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getTimeLow(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getTimeLow()->toString());
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimeMid()} and use the
* arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getTimeMid(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
return $instance->getNumberConverter()->fromHex($fields->getTimeMid()->toString());
}
/**
* @deprecated Use {@see UuidInterface::getFields()} to get a {@see FieldsInterface} instance. If it is a
* {@see Rfc4122FieldsInterface} instance, you may call {@see Rfc4122FieldsInterface::getTimestamp()} and use
* the arbitrary-precision math library of your choice to convert it to a string integer.
*/
public function getTimestamp(): string
{
$instance = ($this->unwrapped ?? $this->unwrap());
$fields = $instance->getFields();
assert($fields instanceof \Ramsey\Uuid\Rfc4122\FieldsInterface);
if ($fields->getVersion() !== 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
return $instance->getNumberConverter()->fromHex($fields->getTimestamp()->toString());
}
public function toUuidV1(): UuidV1
{
$instance = ($this->unwrapped ?? $this->unwrap());
if ($instance instanceof UuidV1) {
return $instance;
}
assert($instance instanceof UuidV6);
return $instance->toUuidV1();
}
public function toUuidV6(): UuidV6
{
$instance = ($this->unwrapped ?? $this->unwrap());
assert($instance instanceof UuidV6);
return $instance;
}
private function unwrap(): UuidInterface
{
return $this->unwrapped = (new UuidFactory())->fromString($this->uuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Validator/ValidatorInterface.php | src/Validator/ValidatorInterface.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\Validator;
/**
* A validator validates a string as a proper UUID
*
* @immutable
*/
interface ValidatorInterface
{
/**
* Returns the regular expression pattern used by this validator
*
* @return non-empty-string The regular expression pattern this validator uses
*/
public function getPattern(): string;
/**
* Returns true if the provided string represents a UUID
*
* @param string $uuid The string to validate as a UUID
*
* @return bool True if the string is a valid UUID, false otherwise
*
* @pure
*/
public function validate(string $uuid): bool;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Validator/GenericValidator.php | src/Validator/GenericValidator.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\Validator;
use Ramsey\Uuid\Uuid;
use function preg_match;
use function str_replace;
/**
* GenericValidator validates strings as UUIDs of any variant
*
* @immutable
*/
final class GenericValidator implements ValidatorInterface
{
/**
* Regular expression pattern for matching a UUID of any variant.
*/
private const VALID_PATTERN = '\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';
/**
* @return non-empty-string
*/
public function getPattern(): string
{
return self::VALID_PATTERN;
}
public function validate(string $uuid): bool
{
/** @phpstan-ignore possiblyImpure.functionCall */
$uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid);
/** @phpstan-ignore possiblyImpure.functionCall */
return $uuid === Uuid::NIL || preg_match('/' . self::VALID_PATTERN . '/Dms', $uuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/NodeProviderInterface.php | src/Provider/NodeProviderInterface.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\Provider;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* A node provider retrieves or generates a node ID
*/
interface NodeProviderInterface
{
/**
* Returns a node ID
*
* @return Hexadecimal The node ID as a hexadecimal string
*/
public function getNode(): Hexadecimal;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/TimeProviderInterface.php | src/Provider/TimeProviderInterface.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\Provider;
use Ramsey\Uuid\Type\Time;
/**
* A time provider retrieves the current time
*/
interface TimeProviderInterface
{
/**
* Returns a time object
*/
public function getTime(): Time;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/DceSecurityProviderInterface.php | src/Provider/DceSecurityProviderInterface.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\Provider;
use Ramsey\Uuid\Rfc4122\UuidV2;
use Ramsey\Uuid\Type\Integer as IntegerObject;
/**
* A DCE provider provides access to local domain identifiers for version 2, DCE Security, UUIDs
*
* @see UuidV2
*/
interface DceSecurityProviderInterface
{
/**
* Returns a user identifier for the system
*
* @link https://en.wikipedia.org/wiki/User_identifier User identifier
*/
public function getUid(): IntegerObject;
/**
* Returns a group identifier for the system
*
* @link https://en.wikipedia.org/wiki/Group_identifier Group identifier
*/
public function getGid(): IntegerObject;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Node/FallbackNodeProvider.php | src/Provider/Node/FallbackNodeProvider.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\Provider\Node;
use Ramsey\Uuid\Exception\NodeException;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* FallbackNodeProvider retrieves the system node ID by stepping through a list of providers until a node ID can be obtained
*/
class FallbackNodeProvider implements NodeProviderInterface
{
/**
* @param iterable<NodeProviderInterface> $providers Array of node providers
*/
public function __construct(private iterable $providers)
{
}
public function getNode(): Hexadecimal
{
$lastProviderException = null;
foreach ($this->providers as $provider) {
try {
return $provider->getNode();
} catch (NodeException $exception) {
$lastProviderException = $exception;
continue;
}
}
throw new NodeException(message: 'Unable to find a suitable node provider', previous: $lastProviderException);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Node/NodeProviderCollection.php | src/Provider/Node/NodeProviderCollection.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\Provider\Node;
use Ramsey\Collection\AbstractCollection;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
/**
* A collection of NodeProviderInterface objects
*
* @deprecated this class has been deprecated and will be removed in 5.0.0. The use-case for this class comes from a
* pre-`phpstan/phpstan` and pre-`vimeo/psalm` ecosystem, in which type safety had to be mostly enforced at runtime:
* that is no longer necessary, now that you can safely verify your code to be correct and use more generic types
* like `iterable<T>` instead.
*
* @extends AbstractCollection<NodeProviderInterface>
*/
class NodeProviderCollection extends AbstractCollection
{
public function getType(): string
{
return NodeProviderInterface::class;
}
/**
* Re-constructs the object from its serialized form
*
* @param string $serialized The serialized PHP string to unserialize into a UuidInterface instance
*/
public function unserialize($serialized): void
{
/** @var array<array-key, NodeProviderInterface> $data */
$data = unserialize($serialized, [
'allowed_classes' => [
Hexadecimal::class,
RandomNodeProvider::class,
StaticNodeProvider::class,
SystemNodeProvider::class,
],
]);
/** @phpstan-ignore-next-line */
$this->data = array_filter($data, fn ($unserialized): bool => $unserialized instanceof NodeProviderInterface);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Node/SystemNodeProvider.php | src/Provider/Node/SystemNodeProvider.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\Provider\Node;
use Ramsey\Uuid\Exception\NodeException;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use function array_filter;
use function array_map;
use function array_walk;
use function count;
use function ob_get_clean;
use function ob_start;
use function preg_match;
use function preg_match_all;
use function reset;
use function str_contains;
use function str_replace;
use function strtolower;
use function strtoupper;
use function substr;
use const GLOB_NOSORT;
use const PREG_PATTERN_ORDER;
/**
* SystemNodeProvider retrieves the system node ID, if possible
*
* The system node ID, or host ID, is often the same as the MAC address for a network interface on the host.
*/
class SystemNodeProvider implements NodeProviderInterface
{
/**
* Pattern to match nodes in `ifconfig` and `ipconfig` output.
*/
private const IFCONFIG_PATTERN = '/[^:]([0-9a-f]{2}([:-])[0-9a-f]{2}(\2[0-9a-f]{2}){4})[^:]/i';
/**
* Pattern to match nodes in sysfs stream output.
*/
private const SYSFS_PATTERN = '/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i';
public function getNode(): Hexadecimal
{
$node = $this->getNodeFromSystem();
if ($node === '') {
throw new NodeException('Unable to fetch a node for this system');
}
return new Hexadecimal($node);
}
/**
* Returns the system node if found
*/
protected function getNodeFromSystem(): string
{
/** @var string | null $node */
static $node = null;
if ($node !== null) {
return $node;
}
// First, try a Linux-specific approach.
$node = $this->getSysfs();
if ($node === '') {
// Search ifconfig output for MAC addresses & return the first one.
$node = $this->getIfconfig();
}
$node = str_replace([':', '-'], '', $node);
return $node;
}
/**
* Returns the network interface configuration for the system
*
* @codeCoverageIgnore
*/
protected function getIfconfig(): string
{
if (str_contains(strtolower((string) ini_get('disable_functions')), 'passthru')) {
return '';
}
/** @var string $phpOs */
$phpOs = constant('PHP_OS');
ob_start();
switch (strtoupper(substr($phpOs, 0, 3))) {
case 'WIN':
passthru('ipconfig /all 2>&1');
break;
case 'DAR':
passthru('ifconfig 2>&1');
break;
case 'FRE':
passthru('netstat -i -f link 2>&1');
break;
case 'LIN':
default:
passthru('netstat -ie 2>&1');
break;
}
$ifconfig = (string) ob_get_clean();
if (preg_match_all(self::IFCONFIG_PATTERN, $ifconfig, $matches, PREG_PATTERN_ORDER)) {
foreach ($matches[1] as $iface) {
if ($iface !== '00:00:00:00:00:00' && $iface !== '00-00-00-00-00-00') {
return $iface;
}
}
}
return '';
}
/**
* Returns MAC address from the first system interface via the sysfs interface
*/
protected function getSysfs(): string
{
/** @var string $phpOs */
$phpOs = constant('PHP_OS');
if (strtoupper($phpOs) !== 'LINUX') {
return '';
}
$addressPaths = glob('/sys/class/net/*/address', GLOB_NOSORT);
if ($addressPaths === false || count($addressPaths) === 0) {
return '';
}
/** @var array<array-key, string> $macs */
$macs = [];
array_walk($addressPaths, function (string $addressPath) use (&$macs): void {
if (is_readable($addressPath)) {
$macs[] = file_get_contents($addressPath);
}
});
/** @var callable $trim */
$trim = 'trim';
$macs = array_map($trim, $macs);
// Remove invalid entries.
$macs = array_filter($macs, function (mixed $address): bool {
assert(is_string($address));
return $address !== '00:00:00:00:00:00' && preg_match(self::SYSFS_PATTERN, $address);
});
/** @var bool | string $mac */
$mac = reset($macs);
return (string) $mac;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Node/RandomNodeProvider.php | src/Provider/Node/RandomNodeProvider.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\Provider\Node;
use Ramsey\Uuid\Exception\RandomSourceException;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Throwable;
use function bin2hex;
use function dechex;
use function hex2bin;
use function hexdec;
use function str_pad;
use function substr;
use const STR_PAD_LEFT;
/**
* RandomNodeProvider generates a random node ID
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-6.10 RFC 9562, 6.10. UUIDs That Do Not Identify the Host
*/
class RandomNodeProvider implements NodeProviderInterface
{
public function getNode(): Hexadecimal
{
try {
$nodeBytes = random_bytes(6);
} catch (Throwable $exception) {
throw new RandomSourceException($exception->getMessage(), (int) $exception->getCode(), $exception);
}
// Split the node bytes for math on 32-bit systems.
$nodeMsb = substr($nodeBytes, 0, 3);
$nodeLsb = substr($nodeBytes, 3);
// Set the multicast bit; see RFC 9562, section 6.10.
$nodeMsb = hex2bin(str_pad(dechex(hexdec(bin2hex($nodeMsb)) | 0x010000), 6, '0', STR_PAD_LEFT));
return new Hexadecimal(str_pad(bin2hex($nodeMsb . $nodeLsb), 12, '0', STR_PAD_LEFT));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Node/StaticNodeProvider.php | src/Provider/Node/StaticNodeProvider.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\Provider\Node;
use Ramsey\Uuid\Exception\InvalidArgumentException;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use function dechex;
use function hexdec;
use function str_pad;
use function substr;
use const STR_PAD_LEFT;
/**
* StaticNodeProvider provides a static node value with the multicast bit set
*
* @link https://www.rfc-editor.org/rfc/rfc9562#section-6.10 RFC 9562, 6.10. UUIDs That Do Not Identify the Host
*/
class StaticNodeProvider implements NodeProviderInterface
{
private Hexadecimal $node;
/**
* @param Hexadecimal $node The static node value to use
*/
public function __construct(Hexadecimal $node)
{
if (strlen($node->toString()) > 12) {
throw new InvalidArgumentException('Static node value cannot be greater than 12 hexadecimal characters');
}
$this->node = $this->setMulticastBit($node);
}
public function getNode(): Hexadecimal
{
return $this->node;
}
/**
* Set the multicast bit for the static node value
*/
private function setMulticastBit(Hexadecimal $node): Hexadecimal
{
$nodeHex = str_pad($node->toString(), 12, '0', STR_PAD_LEFT);
$firstOctet = substr($nodeHex, 0, 2);
$firstOctet = str_pad(dechex(hexdec($firstOctet) | 0x01), 2, '0', STR_PAD_LEFT);
return new Hexadecimal($firstOctet . substr($nodeHex, 2));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Time/SystemTimeProvider.php | src/Provider/Time/SystemTimeProvider.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\Provider\Time;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Type\Time;
use function gettimeofday;
/**
* SystemTimeProvider retrieves the current time using built-in PHP functions
*/
class SystemTimeProvider implements TimeProviderInterface
{
public function getTime(): Time
{
$time = gettimeofday();
return new Time($time['sec'], $time['usec']);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Time/FixedTimeProvider.php | src/Provider/Time/FixedTimeProvider.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\Provider\Time;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
/**
* FixedTimeProvider uses a known time to provide the time
*
* This provider allows the use of a previously generated, or known, time when generating time-based UUIDs.
*/
class FixedTimeProvider implements TimeProviderInterface
{
public function __construct(private Time $time)
{
}
/**
* Sets the `usec` component of the time
*
* @param IntegerObject | int | string $value The `usec` value to set
*/
public function setUsec($value): void
{
$this->time = new Time($this->time->getSeconds(), $value);
}
/**
* Sets the `sec` component of the time
*
* @param IntegerObject | int | string $value The `sec` value to set
*/
public function setSec($value): void
{
$this->time = new Time($value, $this->time->getMicroseconds());
}
public function getTime(): Time
{
return $this->time;
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Provider/Dce/SystemDceSecurityProvider.php | src/Provider/Dce/SystemDceSecurityProvider.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\Provider\Dce;
use Ramsey\Uuid\Exception\DceSecurityException;
use Ramsey\Uuid\Provider\DceSecurityProviderInterface;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use function escapeshellarg;
use function preg_split;
use function str_getcsv;
use function strrpos;
use function strtolower;
use function strtoupper;
use function substr;
use function trim;
use const PREG_SPLIT_NO_EMPTY;
/**
* SystemDceSecurityProvider retrieves the user or group identifiers from the system
*/
class SystemDceSecurityProvider implements DceSecurityProviderInterface
{
/**
* @throws DceSecurityException if unable to get a user identifier
*
* @inheritDoc
*/
public function getUid(): IntegerObject
{
/** @var IntegerObject | int | float | string | null $uid */
static $uid = null;
if ($uid instanceof IntegerObject) {
return $uid;
}
if ($uid === null) {
$uid = $this->getSystemUid();
}
if ($uid === '') {
throw new DceSecurityException(
'Unable to get a user identifier using the system DCE Security provider; please provide a custom '
. 'identifier or use a different provider',
);
}
$uid = new IntegerObject($uid);
return $uid;
}
/**
* @throws DceSecurityException if unable to get a group identifier
*
* @inheritDoc
*/
public function getGid(): IntegerObject
{
/** @var IntegerObject | int | float | string | null $gid */
static $gid = null;
if ($gid instanceof IntegerObject) {
return $gid;
}
if ($gid === null) {
$gid = $this->getSystemGid();
}
if ($gid === '') {
throw new DceSecurityException(
'Unable to get a group identifier using the system DCE Security provider; please provide a custom '
. 'identifier or use a different provider',
);
}
$gid = new IntegerObject($gid);
return $gid;
}
/**
* Returns the UID from the system
*/
private function getSystemUid(): string
{
if (!$this->hasShellExec()) {
return '';
}
return match ($this->getOs()) {
'WIN' => $this->getWindowsUid(),
default => trim((string) shell_exec('id -u')),
};
}
/**
* Returns the GID from the system
*/
private function getSystemGid(): string
{
if (!$this->hasShellExec()) {
return '';
}
return match ($this->getOs()) {
'WIN' => $this->getWindowsGid(),
default => trim((string) shell_exec('id -g')),
};
}
/**
* Returns true if shell_exec() is available for use
*/
private function hasShellExec(): bool
{
return !str_contains(strtolower((string) ini_get('disable_functions')), 'shell_exec');
}
/**
* Returns the PHP_OS string
*/
private function getOs(): string
{
/** @var string $phpOs */
$phpOs = constant('PHP_OS');
return strtoupper(substr($phpOs, 0, 3));
}
/**
* Returns the user identifier for a user on a Windows system
*
* Windows does not have the same concept as an effective POSIX UID for the running script. Instead, each user is
* uniquely identified by an SID (security identifier). The SID includes three 32-bit unsigned integers that make up
* a unique domain identifier, followed by an RID (relative identifier) that we will use as the UID. The primary
* caveat is that this UID may not be unique to the system, since it is, instead, unique to the domain.
*
* @link https://www.lifewire.com/what-is-an-sid-number-2626005 What Is an SID Number?
* @link https://learn.microsoft.com/en-us/openspecs/windows_protocols/ms-dtyp/81d92bba-d22b-4a8c-908a-554ab29148ab Well-known SID Structures
* @link https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/manage/understand-security-identifiers#well-known-sids Well-known SIDs
* @link https://www.windows-commandline.com/get-sid-of-user/ Get SID of user
*/
private function getWindowsUid(): string
{
$response = shell_exec('whoami /user /fo csv /nh');
if ($response === null) {
return '';
}
$sid = str_getcsv(trim((string) $response), escape: '\\')[1] ?? '';
if (($lastHyphen = strrpos($sid, '-')) === false) {
return '';
}
return trim(substr($sid, $lastHyphen + 1));
}
/**
* Returns a group identifier for a user on a Windows system
*
* Since Windows does not have the same concept as an effective POSIX GID for the running script, we will get the
* local group memberships for the user running the script. Then, we will get the SID (security identifier) for the
* first group that appears in that list. Finally, we will return the RID (relative identifier) for the group and
* use that as the GID.
*
* @link https://www.windows-commandline.com/list-of-user-groups-command-line/ List of user groups command line
*/
private function getWindowsGid(): string
{
$response = shell_exec('net user %username% | findstr /b /i "Local Group Memberships"');
if ($response === null) {
return '';
}
$userGroups = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY);
$firstGroup = trim($userGroups[1] ?? '', "* \t\n\r\0\x0B");
if ($firstGroup === '') {
return '';
}
$response = shell_exec('wmic group get name,sid | findstr /b /i ' . escapeshellarg($firstGroup));
if ($response === null) {
return '';
}
$userGroup = preg_split('/\s{2,}/', (string) $response, -1, PREG_SPLIT_NO_EMPTY);
$sid = $userGroup[1] ?? '';
if (($lastHyphen = strrpos($sid, '-')) === false) {
return '';
}
return trim(substr($sid, $lastHyphen + 1));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/TimeConverterInterface.php | src/Converter/TimeConverterInterface.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\Converter;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
/**
* A time converter converts timestamps into representations that may be used in UUIDs
*
* @immutable
*/
interface TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the count of 100-nanosecond intervals since
* UTC 00:00:00.00, 15 October 1582, for RFC 9562 (formerly RFC 4122) variant UUIDs
*
* @link https://www.rfc-editor.org/rfc/rfc9562#appendix-A RFC 9562, Appendix A. Test Vectors
*
* @param string $seconds A string representation of seconds since the Unix epoch for the time to calculate
* @param string $microseconds A string representation of the micro-seconds associated with the time to calculate
*
* @return Hexadecimal The full UUID timestamp as a Hexadecimal value
*
* @pure
*/
public function calculateTime(string $seconds, string $microseconds): Hexadecimal;
/**
* Converts a timestamp extracted from a UUID to a Unix timestamp
*
* @param Hexadecimal $uuidTimestamp A hexadecimal representation of a UUID timestamp; a UUID timestamp is a count
* of 100-nanosecond intervals since UTC 00:00:00.00, 15 October 1582.
*
* @return Time An instance of {@see Time}
*
* @pure
*/
public function convertTime(Hexadecimal $uuidTimestamp): Time;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/NumberConverterInterface.php | src/Converter/NumberConverterInterface.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\Converter;
/**
* A number converter converts UUIDs from hexadecimal characters into representations of integers and vice versa
*
* @immutable
*/
interface NumberConverterInterface
{
/**
* Converts a hexadecimal number into a string integer representation of the number
*
* The integer representation returned is a string representation of the integer to accommodate unsigned integers
* that are greater than `PHP_INT_MAX`.
*
* @param string $hex The hexadecimal string representation to convert
*
* @return numeric-string String representation of an integer
*
* @pure
*/
public function fromHex(string $hex): string;
/**
* Converts a string integer representation into a hexadecimal string representation of the number
*
* @param string $number A string integer representation to convert; this must be a numeric string to accommodate
* unsigned integers that are greater than `PHP_INT_MAX`.
*
* @return non-empty-string Hexadecimal string
*
* @pure
*/
public function toHex(string $number): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Number/GenericNumberConverter.php | src/Converter/Number/GenericNumberConverter.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\Converter\Number;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Math\CalculatorInterface;
use Ramsey\Uuid\Type\Integer as IntegerObject;
/**
* GenericNumberConverter uses the provided calculator to convert decimal numbers to and from hexadecimal values
*
* @immutable
*/
class GenericNumberConverter implements NumberConverterInterface
{
public function __construct(private CalculatorInterface $calculator)
{
}
/**
* @pure
*/
public function fromHex(string $hex): string
{
return $this->calculator->fromBase($hex, 16)->toString();
}
/**
* @pure
*/
public function toHex(string $number): string
{
/** @phpstan-ignore return.type, possiblyImpure.new */
return $this->calculator->toBase(new IntegerObject($number), 16);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Number/BigNumberConverter.php | src/Converter/Number/BigNumberConverter.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\Converter\Number;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
/**
* Previously used to integrate moontoast/math as a bignum arithmetic library, BigNumberConverter is deprecated in favor
* of GenericNumberConverter
*
* @deprecated Please transition to {@see GenericNumberConverter}.
*
* @immutable
*/
class BigNumberConverter implements NumberConverterInterface
{
private NumberConverterInterface $converter;
public function __construct()
{
$this->converter = new GenericNumberConverter(new BrickMathCalculator());
}
/**
* @pure
*/
public function fromHex(string $hex): string
{
return $this->converter->fromHex($hex);
}
/**
* @pure
*/
public function toHex(string $number): string
{
return $this->converter->toHex($number);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Number/DegradedNumberConverter.php | src/Converter/Number/DegradedNumberConverter.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\Converter\Number;
/**
* @deprecated DegradedNumberConverter is no longer necessary for converting numbers on 32-bit systems. Please
* transition to {@see GenericNumberConverter}.
*
* @immutable
*/
class DegradedNumberConverter extends BigNumberConverter
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Time/BigNumberTimeConverter.php | src/Converter/Time/BigNumberTimeConverter.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\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Time;
/**
* Previously used to integrate moontoast/math as a bignum arithmetic library, BigNumberTimeConverter is deprecated in
* favor of GenericTimeConverter
*
* @deprecated Please transition to {@see GenericTimeConverter}.
*
* @immutable
*/
class BigNumberTimeConverter implements TimeConverterInterface
{
private TimeConverterInterface $converter;
public function __construct()
{
$this->converter = new GenericTimeConverter(new BrickMathCalculator());
}
public function calculateTime(string $seconds, string $microseconds): Hexadecimal
{
return $this->converter->calculateTime($seconds, $microseconds);
}
public function convertTime(Hexadecimal $uuidTimestamp): Time
{
return $this->converter->convertTime($uuidTimestamp);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Time/DegradedTimeConverter.php | src/Converter/Time/DegradedTimeConverter.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\Converter\Time;
/**
* @deprecated DegradedTimeConverter is no longer necessary for converting time on 32-bit systems. Please transition to
* {@see GenericTimeConverter}.
*
* @immutable
*/
class DegradedTimeConverter extends BigNumberTimeConverter
{
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Time/PhpTimeConverter.php | src/Converter/Time/PhpTimeConverter.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\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Math\BrickMathCalculator;
use Ramsey\Uuid\Math\CalculatorInterface;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
use function count;
use function dechex;
use function explode;
use function is_float;
use function is_int;
use function str_pad;
use function strlen;
use function substr;
use const STR_PAD_LEFT;
use const STR_PAD_RIGHT;
/**
* PhpTimeConverter uses built-in PHP functions and standard math operations available to the PHP programming language
* to provide facilities for converting parts of time into representations that may be used in UUIDs
*
* @immutable
*/
class PhpTimeConverter implements TimeConverterInterface
{
/**
* The number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix epoch.
*/
private const GREGORIAN_TO_UNIX_INTERVALS = 0x01b21dd213814000;
/**
* The number of 100-nanosecond intervals in one second.
*/
private const SECOND_INTERVALS = 10_000_000;
/**
* The number of 100-nanosecond intervals in one microsecond.
*/
private const MICROSECOND_INTERVALS = 10;
private int $phpPrecision;
private CalculatorInterface $calculator;
private TimeConverterInterface $fallbackConverter;
public function __construct(
?CalculatorInterface $calculator = null,
?TimeConverterInterface $fallbackConverter = null,
) {
if ($calculator === null) {
$calculator = new BrickMathCalculator();
}
if ($fallbackConverter === null) {
$fallbackConverter = new GenericTimeConverter($calculator);
}
$this->calculator = $calculator;
$this->fallbackConverter = $fallbackConverter;
$this->phpPrecision = (int) ini_get('precision');
}
public function calculateTime(string $seconds, string $microseconds): Hexadecimal
{
$seconds = new IntegerObject($seconds); /** @phpstan-ignore possiblyImpure.new */
$microseconds = new IntegerObject($microseconds); /** @phpstan-ignore possiblyImpure.new */
// Calculate the count of 100-nanosecond intervals since the Gregorian calendar epoch
// for the given seconds and microseconds.
$uuidTime = ((int) $seconds->toString() * self::SECOND_INTERVALS)
+ ((int) $microseconds->toString() * self::MICROSECOND_INTERVALS)
+ self::GREGORIAN_TO_UNIX_INTERVALS;
// Check to see whether we've overflowed the max/min integer size.
// If so, we will default to a different time converter.
// @phpstan-ignore function.alreadyNarrowedType (the integer value might have overflowed)
if (!is_int($uuidTime)) {
return $this->fallbackConverter->calculateTime(
$seconds->toString(),
$microseconds->toString(),
);
}
/** @phpstan-ignore possiblyImpure.new */
return new Hexadecimal(
str_pad(dechex($uuidTime), 16, '0', STR_PAD_LEFT)
);
}
public function convertTime(Hexadecimal $uuidTimestamp): Time
{
$timestamp = $this->calculator->toInteger($uuidTimestamp);
// Convert the 100-nanosecond intervals into seconds and microseconds.
$splitTime = $this->splitTime(
($timestamp->toString() - self::GREGORIAN_TO_UNIX_INTERVALS) / self::SECOND_INTERVALS,
);
if (count($splitTime) === 0) {
return $this->fallbackConverter->convertTime($uuidTimestamp);
}
/** @phpstan-ignore possiblyImpure.new */
return new Time($splitTime['sec'], $splitTime['usec']);
}
/**
* @param float | int $time The time to split into seconds and microseconds
*
* @return string[]
*
* @pure
*/
private function splitTime(float | int $time): array
{
$split = explode('.', (string) $time, 2);
// If the $time value is a float but $split only has 1 element, then the float math was rounded up to the next
// second, so we want to return an empty array to allow use of the fallback converter.
if (is_float($time) && count($split) === 1) {
return [];
}
if (count($split) === 1) {
return ['sec' => $split[0], 'usec' => '0'];
}
// If the microseconds are less than six characters AND the length of the number is greater than or equal to the
// PHP precision, then it's possible that we lost some precision for the microseconds. Return an empty array so
// that we can choose to use the fallback converter.
if (strlen($split[1]) < 6 && strlen((string) $time) >= $this->phpPrecision) {
return [];
}
$microseconds = $split[1];
// Ensure the microseconds are no longer than 6 digits. If they are,
// truncate the number to the first 6 digits and round up, if needed.
if (strlen($microseconds) > 6) {
$roundingDigit = (int) substr($microseconds, 6, 1);
$microseconds = (int) substr($microseconds, 0, 6);
if ($roundingDigit >= 5) {
$microseconds++;
}
}
return [
'sec' => $split[0],
'usec' => str_pad((string) $microseconds, 6, '0', STR_PAD_RIGHT),
];
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Time/GenericTimeConverter.php | src/Converter/Time/GenericTimeConverter.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\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Math\CalculatorInterface;
use Ramsey\Uuid\Math\RoundingMode;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
use function explode;
use function str_pad;
use const STR_PAD_LEFT;
/**
* GenericTimeConverter uses the provided calculator to calculate and convert time values
*
* @immutable
*/
class GenericTimeConverter implements TimeConverterInterface
{
/**
* The number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix epoch.
*/
private const GREGORIAN_TO_UNIX_INTERVALS = '122192928000000000';
/**
* The number of 100-nanosecond intervals in one second.
*/
private const SECOND_INTERVALS = '10000000';
/**
* The number of 100-nanosecond intervals in one microsecond.
*/
private const MICROSECOND_INTERVALS = '10';
public function __construct(private CalculatorInterface $calculator)
{
}
public function calculateTime(string $seconds, string $microseconds): Hexadecimal
{
/** @phpstan-ignore possiblyImpure.new */
$timestamp = new Time($seconds, $microseconds);
// Convert the seconds into a count of 100-nanosecond intervals.
$sec = $this->calculator->multiply(
$timestamp->getSeconds(),
new IntegerObject(self::SECOND_INTERVALS), /** @phpstan-ignore possiblyImpure.new */
);
// Convert the microseconds into a count of 100-nanosecond intervals.
$usec = $this->calculator->multiply(
$timestamp->getMicroseconds(),
new IntegerObject(self::MICROSECOND_INTERVALS), /** @phpstan-ignore possiblyImpure.new */
);
/**
* Combine the intervals of seconds and microseconds and add the count of 100-nanosecond intervals from the
* Gregorian calendar epoch to the Unix epoch. This gives us the correct count of 100-nanosecond intervals since
* the Gregorian calendar epoch for the given seconds and microseconds.
*
* @var IntegerObject $uuidTime
* @phpstan-ignore possiblyImpure.new
*/
$uuidTime = $this->calculator->add($sec, $usec, new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS));
/**
* PHPStan considers CalculatorInterface::toHexadecimal, Hexadecimal:toString impure.
*
* @phpstan-ignore possiblyImpure.new
*/
return new Hexadecimal(str_pad($this->calculator->toHexadecimal($uuidTime)->toString(), 16, '0', STR_PAD_LEFT));
}
public function convertTime(Hexadecimal $uuidTimestamp): Time
{
// From the total, subtract the number of 100-nanosecond intervals from the Gregorian calendar epoch to the Unix
// epoch. This gives us the number of 100-nanosecond intervals from the Unix epoch, which also includes the microtime.
$epochNanoseconds = $this->calculator->subtract(
$this->calculator->toInteger($uuidTimestamp),
new IntegerObject(self::GREGORIAN_TO_UNIX_INTERVALS), /** @phpstan-ignore possiblyImpure.new */
);
// Convert the 100-nanosecond intervals into seconds and microseconds.
$unixTimestamp = $this->calculator->divide(
RoundingMode::HALF_UP,
6,
$epochNanoseconds,
new IntegerObject(self::SECOND_INTERVALS), /** @phpstan-ignore possiblyImpure.new */
);
$split = explode('.', (string) $unixTimestamp, 2);
/** @phpstan-ignore possiblyImpure.new */
return new Time($split[0], $split[1] ?? 0);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Converter/Time/UnixTimeConverter.php | src/Converter/Time/UnixTimeConverter.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\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Math\CalculatorInterface;
use Ramsey\Uuid\Math\RoundingMode;
use Ramsey\Uuid\Type\Hexadecimal;
use Ramsey\Uuid\Type\Integer as IntegerObject;
use Ramsey\Uuid\Type\Time;
use function explode;
use function str_pad;
use const STR_PAD_LEFT;
/**
* UnixTimeConverter converts Unix Epoch timestamps to/from hexadecimal values consisting of milliseconds elapsed since
* the Unix Epoch
*
* @immutable
*/
class UnixTimeConverter implements TimeConverterInterface
{
private const MILLISECONDS = 1000;
public function __construct(private CalculatorInterface $calculator)
{
}
public function calculateTime(string $seconds, string $microseconds): Hexadecimal
{
/** @phpstan-ignore possiblyImpure.new */
$timestamp = new Time($seconds, $microseconds);
// Convert the seconds into milliseconds.
$sec = $this->calculator->multiply(
$timestamp->getSeconds(),
new IntegerObject(self::MILLISECONDS) /** @phpstan-ignore possiblyImpure.new */
);
// Convert the microseconds into milliseconds; the scale is zero because we need to discard the fractional part.
$usec = $this->calculator->divide(
RoundingMode::DOWN, // Always round down to stay in the previous millisecond.
0,
$timestamp->getMicroseconds(),
new IntegerObject(self::MILLISECONDS), /** @phpstan-ignore possiblyImpure.new */
);
/** @var IntegerObject $unixTime */
$unixTime = $this->calculator->add($sec, $usec);
/** @phpstan-ignore possiblyImpure.new */
return new Hexadecimal(
str_pad(
$this->calculator->toHexadecimal($unixTime)->toString(),
12,
'0',
STR_PAD_LEFT
),
);
}
public function convertTime(Hexadecimal $uuidTimestamp): Time
{
$milliseconds = $this->calculator->toInteger($uuidTimestamp);
$unixTimestamp = $this->calculator->divide(
RoundingMode::HALF_UP,
6,
$milliseconds,
new IntegerObject(self::MILLISECONDS), /** @phpstan-ignore possiblyImpure.new */
);
$split = explode('.', (string) $unixTimestamp, 2);
/** @phpstan-ignore possiblyImpure.new */
return new Time($split[0], $split[1] ?? '0');
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/PeclUuidNameGenerator.php | src/Generator/PeclUuidNameGenerator.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\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
{
/**
* @pure
*/
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string
{
$uuid = match ($hashAlgorithm) {
'md5' => uuid_generate_md5($ns->toString(), $name), /** @phpstan-ignore possiblyImpure.functionCall */
'sha1' => uuid_generate_sha1($ns->toString(), $name), /** @phpstan-ignore possiblyImpure.functionCall */
default => throw new NameException(
sprintf('Unable to hash namespace and name with algorithm \'%s\'', $hashAlgorithm),
),
};
/** @phpstan-ignore possiblyImpure.functionCall */
return (string) uuid_parse($uuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/NameGeneratorInterface.php | src/Generator/NameGeneratorInterface.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\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
*
* @pure
*/
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/PeclUuidTimeGenerator.php | src/Generator/PeclUuidTimeGenerator.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 function uuid_create;
use function uuid_parse;
use const UUID_TYPE_TIME;
/**
* PeclUuidTimeGenerator generates strings of binary data for time-base UUIDs, using ext-uuid
*
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidTimeGenerator implements TimeGeneratorInterface
{
/**
* @inheritDoc
*/
public function generate($node = null, ?int $clockSeq = null): string
{
$uuid = uuid_create(UUID_TYPE_TIME);
return (string) uuid_parse($uuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/DefaultNameGenerator.php | src/Generator/DefaultNameGenerator.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\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
{
/**
* @pure
*/
public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string
{
try {
return hash($hashAlgorithm, $ns->getBytes() . $name, true);
} catch (ValueError $e) {
throw new NameException(
message: sprintf('Unable to hash namespace and name with algorithm \'%s\'', $hashAlgorithm),
previous: $e,
);
}
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/PeclUuidRandomGenerator.php | src/Generator/PeclUuidRandomGenerator.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 function uuid_create;
use function uuid_parse;
use const UUID_TYPE_RANDOM;
/**
* PeclUuidRandomGenerator generates strings of random binary data using ext-uuid
*
* @link https://pecl.php.net/package/uuid ext-uuid
*/
class PeclUuidRandomGenerator implements RandomGeneratorInterface
{
public function generate(int $length): string
{
$uuid = uuid_create(UUID_TYPE_RANDOM);
return (string) uuid_parse($uuid);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/DefaultTimeGenerator.php | src/Generator/DefaultTimeGenerator.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\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 generates strings of binary data based on a node ID, clock sequence, and the current time
*/
class DefaultTimeGenerator implements TimeGeneratorInterface
{
public function __construct(
private NodeProviderInterface $nodeProvider,
private TimeConverterInterface $timeConverter,
private TimeProviderInterface $timeProvider,
) {
}
/**
* @throws InvalidArgumentException if the parameters contain invalid values
* @throws RandomSourceException if random_int() throws an exception/error
*
* @inheritDoc
*/
public function generate($node = null, ?int $clockSeq = null): string
{
if ($node instanceof Hexadecimal) {
$node = $node->toString();
}
$node = $this->getValidNode($node);
if ($clockSeq === null) {
try {
// This does not use "stable storage"; see RFC 9562, section 6.3.
$clockSeq = random_int(0, 0x3fff);
} catch (Throwable $exception) {
throw new RandomSourceException($exception->getMessage(), (int) $exception->getCode(), $exception);
}
}
$time = $this->timeProvider->getTime();
$uuidTime = $this->timeConverter->calculateTime(
$time->getSeconds()->toString(),
$time->getMicroseconds()->toString()
);
$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 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
*/
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.
if (is_int($node)) {
$node = dechex($node);
}
if (!preg_match('/^[A-Fa-f0-9]+$/', (string) $node) || strlen((string) $node) > 12) {
throw new InvalidArgumentException('Invalid node value');
}
return (string) hex2bin(str_pad((string) $node, 12, '0', STR_PAD_LEFT));
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/TimeGeneratorFactory.php | src/Generator/TimeGeneratorFactory.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\TimeConverterInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* TimeGeneratorFactory retrieves a default time generator, based on the environment
*/
class TimeGeneratorFactory
{
public function __construct(
private NodeProviderInterface $nodeProvider,
private TimeConverterInterface $timeConverter,
private TimeProviderInterface $timeProvider,
) {
}
/**
* Returns a default time generator, based on the current environment
*/
public function getGenerator(): TimeGeneratorInterface
{
return new DefaultTimeGenerator($this->nodeProvider, $this->timeConverter, $this->timeProvider);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/RandomBytesGenerator.php | src/Generator/RandomBytesGenerator.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\Exception\RandomSourceException;
use Throwable;
/**
* RandomBytesGenerator generates strings of random binary data using the built-in `random_bytes()` PHP function
*
* @link http://php.net/random_bytes random_bytes()
*/
class RandomBytesGenerator implements RandomGeneratorInterface
{
/**
* @throws RandomSourceException if random_bytes() throws an exception/error
*
* @inheritDoc
*/
public function generate(int $length): string
{
try {
return random_bytes($length);
} catch (Throwable $exception) {
throw new RandomSourceException($exception->getMessage(), (int) $exception->getCode(), $exception);
}
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/RandomLibAdapter.php | src/Generator/RandomLibAdapter.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 RandomLib\Factory;
use RandomLib\Generator;
/**
* RandomLibAdapter generates strings of random binary data using the paragonie/random-lib library
*
* @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
{
private Generator $generator;
/**
* Constructs a RandomLibAdapter
*
* By default, if no Generator is passed in, this creates a high-strength generator to use when generating random
* binary data.
*
* @param Generator | null $generator The generator to use when generating binary data
*/
public function __construct(?Generator $generator = null)
{
if ($generator === null) {
$factory = new Factory();
$generator = $factory->getHighStrengthGenerator();
}
$this->generator = $generator;
}
public function generate(int $length): string
{
return $this->generator->generate($length);
}
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
ramsey/uuid | https://github.com/ramsey/uuid/blob/8429c78ca35a09f27565311b98101e2826affde0/src/Generator/RandomGeneratorInterface.php | src/Generator/RandomGeneratorInterface.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;
/**
* A random generator generates strings of random binary data
*/
interface RandomGeneratorInterface
{
/**
* Generates a string of randomized binary data
*
* @param int<1, max> $length The number of bytes to generate of random binary data
*
* @return string A binary string
*/
public function generate(int $length): string;
}
| php | MIT | 8429c78ca35a09f27565311b98101e2826affde0 | 2026-01-04T15:03:10.515964Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.