Added Laravel project

This commit is contained in:
2017-09-17 00:35:10 +02:00
parent a3c19304d5
commit ecf605b8f5
6246 changed files with 682270 additions and 2 deletions

View File

@@ -0,0 +1,43 @@
<?php
namespace Ramsey\Uuid;
/**
* Provides binary math utilities
*/
class BinaryUtils
{
/**
* Applies the RFC 4122 variant field to the `clock_seq_hi_and_reserved` field
*
* @param $clockSeqHi
* @return int The high field of the clock sequence multiplexed with the variant
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
*/
public static function applyVariant($clockSeqHi)
{
// Set the variant to RFC 4122
$clockSeqHi = $clockSeqHi & 0x3f;
$clockSeqHi &= ~(0xc0);
$clockSeqHi |= 0x80;
return $clockSeqHi;
}
/**
* Applies the RFC 4122 version number to the `time_hi_and_version` field
*
* @param string $timeHi
* @param integer $version
* @return int The high field of the timestamp multiplexed with the version number
* @link http://tools.ietf.org/html/rfc4122#section-4.1.3
*/
public static function applyVersion($timeHi, $version)
{
$timeHi = hexdec($timeHi) & 0x0fff;
$timeHi &= ~(0xf000);
$timeHi |= $version << 12;
return $timeHi;
}
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Uuid;
/**
* DefaultUuidBuilder is the default UUID builder for ramsey/uuid; it builds
* instances of Uuid objects
*/
class DefaultUuidBuilder implements UuidBuilderInterface
{
/**
* @var NumberConverterInterface
*/
private $converter;
/**
* Constructs the DefaultUuidBuilder
*
* @param NumberConverterInterface $converter The number converter to use when constructing the Uuid
*/
public function __construct(NumberConverterInterface $converter)
{
$this->converter = $converter;
}
/**
* Builds a Uuid
*
* @param CodecInterface $codec The codec to use for building this Uuid
* @param array $fields An array of fields from which to construct the Uuid;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return Uuid
*/
public function build(CodecInterface $codec, array $fields)
{
return new Uuid($fields, $this->converter, $codec);
}
}

View File

@@ -0,0 +1,53 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\DegradedUuid;
/**
* DegradedUuidBuilder builds instances of DegradedUuid
*/
class DegradedUuidBuilder implements UuidBuilderInterface
{
/**
* @var NumberConverterInterface
*/
private $converter;
/**
* Constructs the DegradedUuidBuilder
*
* @param NumberConverterInterface $converter The number converter to use when constructing the DegradedUuid
*/
public function __construct(NumberConverterInterface $converter)
{
$this->converter = $converter;
}
/**
* Builds a DegradedUuid
*
* @param CodecInterface $codec The codec to use for building this DegradedUuid
* @param array $fields An array of fields from which to construct the DegradedUuid;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return DegradedUuid
*/
public function build(CodecInterface $codec, array $fields)
{
return new DegradedUuid($fields, $this->converter, $codec);
}
}

View File

@@ -0,0 +1,34 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Builder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\UuidInterface;
/**
* UuidBuilderInterface builds instances UuidInterface
*/
interface UuidBuilderInterface
{
/**
* Builds an instance of a UuidInterface
*
* @param CodecInterface $codec The codec to use for building this UuidInterface instance
* @param array $fields An array of fields from which to construct a UuidInterface instance;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return UuidInterface
*/
public function build(CodecInterface $codec, array $fields);
}

View File

@@ -0,0 +1,55 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Codec;
use Ramsey\Uuid\UuidInterface;
/**
* CodecInterface represents a UUID coder-decoder
*/
interface CodecInterface
{
/**
* Encodes a UuidInterface as a string representation of a UUID
*
* @param UuidInterface $uuid
* @return string Hexadecimal string representation of a UUID
*/
public function encode(UuidInterface $uuid);
/**
* Encodes a UuidInterface as a binary representation of a UUID
*
* @param UuidInterface $uuid
* @return string Binary string representation of a UUID
*/
public function encodeBinary(UuidInterface $uuid);
/**
* Decodes a string representation of a UUID into a UuidInterface object instance
*
* @param string $encodedUuid
* @return UuidInterface
*/
public function decode($encodedUuid);
/**
* Decodes a binary representation of a UUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes);
}

View File

@@ -0,0 +1,100 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Codec;
use Ramsey\Uuid\UuidInterface;
/**
* GuidStringCodec encodes and decodes globally unique identifiers (GUID)
*
* @link https://en.wikipedia.org/wiki/Globally_unique_identifier
*/
class GuidStringCodec extends StringCodec
{
/**
* Encodes a UuidInterface as a string representation of a GUID
*
* @param UuidInterface $uuid
* @return string Hexadecimal string representation of a GUID
*/
public function encode(UuidInterface $uuid)
{
$components = array_values($uuid->getFieldsHex());
// Swap byte-order on the first three fields
$this->swapFields($components);
return vsprintf(
'%08s-%04s-%04s-%02s%02s-%012s',
$components
);
}
/**
* Encodes a UuidInterface as a binary representation of a GUID
*
* @param UuidInterface $uuid
* @return string Binary string representation of a GUID
*/
public function encodeBinary(UuidInterface $uuid)
{
$components = array_values($uuid->getFieldsHex());
return hex2bin(implode('', $components));
}
/**
* Decodes a string representation of a GUID into a UuidInterface object instance
*
* @param string $encodedUuid
* @return UuidInterface
*/
public function decode($encodedUuid)
{
$components = $this->extractComponents($encodedUuid);
$this->swapFields($components);
return $this->getBuilder()->build($this, $this->getFields($components));
}
/**
* Decodes a binary representation of a GUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes)
{
// Specifically call parent::decode to preserve correct byte order
return parent::decode(bin2hex($bytes));
}
/**
* Swaps fields to support GUID byte order
*
* @param array $components An array of UUID components (the UUID exploded on its dashes)
* @return void
*/
protected function swapFields(array &$components)
{
$hex = unpack('H*', pack('L', hexdec($components[0])));
$components[0] = $hex[1];
$hex = unpack('H*', pack('S', hexdec($components[1])));
$components[1] = $hex[1];
$hex = unpack('H*', pack('S', hexdec($components[2])));
$components[2] = $hex[1];
}
}

View File

@@ -0,0 +1,67 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Codec;
use InvalidArgumentException;
use Ramsey\Uuid\UuidInterface;
/**
* OrderedTimeCodec optimizes the bytes to increment UUIDs when time goes by, to improve database INSERTs.
* The string value will be unchanged from StringCodec. Only works for UUID type 1.
*/
class OrderedTimeCodec extends StringCodec
{
/**
* Encodes a UuidInterface as an optimized binary representation of a UUID
*
* @param UuidInterface $uuid
* @return string Binary string representation of a UUID
*/
public function encodeBinary(UuidInterface $uuid)
{
$fields = $uuid->getFieldsHex();
$optimized = [
$fields['time_hi_and_version'],
$fields['time_mid'],
$fields['time_low'],
$fields['clock_seq_hi_and_reserved'],
$fields['clock_seq_low'],
$fields['node'],
];
return hex2bin(implode('', $optimized));
}
/**
* Decodes an optimized binary representation of a UUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes)
{
if (strlen($bytes) !== 16) {
throw new InvalidArgumentException('$bytes string should contain 16 characters.');
}
$hex = unpack('H*', $bytes)[1];
// Rearrange the fields to their original order
$hex = substr($hex, 8, 4) . substr($hex, 12, 4) . substr($hex, 4, 4) . substr($hex, 0, 4) . substr($hex, 16);
return $this->decode($hex);
}
}

View File

@@ -0,0 +1,167 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Codec;
use InvalidArgumentException;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Exception\InvalidUuidStringException;
use Ramsey\Uuid\Uuid;
use Ramsey\Uuid\UuidInterface;
/**
* StringCodec encodes and decodes RFC 4122 UUIDs
*
* @link http://tools.ietf.org/html/rfc4122
*/
class StringCodec implements CodecInterface
{
/**
* @var UuidBuilderInterface
*/
private $builder;
/**
* Constructs a StringCodec for use encoding and decoding UUIDs
*
* @param UuidBuilderInterface $builder The UUID builder to use when encoding UUIDs
*/
public function __construct(UuidBuilderInterface $builder)
{
$this->builder = $builder;
}
/**
* Encodes a UuidInterface as a string representation of a UUID
*
* @param UuidInterface $uuid
* @return string Hexadecimal string representation of a UUID
*/
public function encode(UuidInterface $uuid)
{
$fields = array_values($uuid->getFieldsHex());
return vsprintf(
'%08s-%04s-%04s-%02s%02s-%012s',
$fields
);
}
/**
* Encodes a UuidInterface as a binary representation of a UUID
*
* @param UuidInterface $uuid
* @return string Binary string representation of a UUID
*/
public function encodeBinary(UuidInterface $uuid)
{
return hex2bin($uuid->getHex());
}
/**
* Decodes a string representation of a UUID into a UuidInterface object instance
*
* @param string $encodedUuid
* @return UuidInterface
*/
public function decode($encodedUuid)
{
$components = $this->extractComponents($encodedUuid);
$fields = $this->getFields($components);
return $this->builder->build($this, $fields);
}
/**
* Decodes a binary representation of a UUID into a UuidInterface object instance
*
* @param string $bytes
* @return UuidInterface
*/
public function decodeBytes($bytes)
{
if (strlen($bytes) !== 16) {
throw new InvalidArgumentException('$bytes string should contain 16 characters.');
}
$hexUuid = unpack('H*', $bytes);
return $this->decode($hexUuid[1]);
}
/**
* Returns the UUID builder
*
* @return UuidBuilderInterface
*/
protected function getBuilder()
{
return $this->builder;
}
/**
* Returns an array of UUID components (the UUID exploded on its dashes)
*
* @param string $encodedUuid
* @return array
*/
protected function extractComponents($encodedUuid)
{
$nameParsed = str_replace(array(
'urn:',
'uuid:',
'{',
'}',
'-'
), '', $encodedUuid);
// We have stripped out the dashes and are breaking up the string using
// substr(). In this way, we can accept a full hex value that doesn't
// contain dashes.
$components = array(
substr($nameParsed, 0, 8),
substr($nameParsed, 8, 4),
substr($nameParsed, 12, 4),
substr($nameParsed, 16, 4),
substr($nameParsed, 20)
);
$nameParsed = implode('-', $components);
if (!Uuid::isValid($nameParsed)) {
throw new InvalidUuidStringException('Invalid UUID string: ' . $encodedUuid);
}
return $components;
}
/**
* Returns the fields that make up this UUID
*
* @see \Ramsey\Uuid\UuidInterface::getFieldsHex()
* @param array $components
* @return array
*/
protected function getFields(array $components)
{
return array(
'time_low' => str_pad($components[0], 8, '0', STR_PAD_LEFT),
'time_mid' => str_pad($components[1], 4, '0', STR_PAD_LEFT),
'time_hi_and_version' => str_pad($components[2], 4, '0', STR_PAD_LEFT),
'clock_seq_hi_and_reserved' => str_pad(substr($components[3], 0, 2), 2, '0', STR_PAD_LEFT),
'clock_seq_low' => str_pad(substr($components[3], 2), 2, '0', STR_PAD_LEFT),
'node' => str_pad($components[4], 12, '0', STR_PAD_LEFT)
);
}
}

View File

@@ -0,0 +1,105 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Codec;
use Ramsey\Uuid\UuidInterface;
/**
* TimestampLastCombCodec encodes and decodes COMB UUIDs which have the timestamp as the first 48 bits.
* To be used with MySQL, PostgreSQL, Oracle.
*/
class TimestampFirstCombCodec extends StringCodec
{
/**
* Encodes a UuidInterface as a string representation of a timestamp first COMB UUID
*
* @param UuidInterface $uuid
*
* @return string Hexadecimal string representation of a GUID
*/
public function encode(UuidInterface $uuid)
{
$sixPieceComponents = array_values($uuid->getFieldsHex());
$this->swapTimestampAndRandomBits($sixPieceComponents);
return vsprintf(
'%08s-%04s-%04s-%02s%02s-%012s',
$sixPieceComponents
);
}
/**
* Encodes a UuidInterface as a binary representation of timestamp first COMB UUID
*
* @param UuidInterface $uuid
*
* @return string Binary string representation of timestamp first COMB UUID
*/
public function encodeBinary(UuidInterface $uuid)
{
$stringEncoding = $this->encode($uuid);
return hex2bin(str_replace('-', '', $stringEncoding));
}
/**
* Decodes a string representation of timestamp first COMB UUID into a UuidInterface object instance
*
* @param string $encodedUuid
*
* @return UuidInterface
*/
public function decode($encodedUuid)
{
$fivePieceComponents = $this->extractComponents($encodedUuid);
$this->swapTimestampAndRandomBits($fivePieceComponents);
return $this->getBuilder()->build($this, $this->getFields($fivePieceComponents));
}
/**
* Decodes a binary representation of timestamp first COMB UUID into a UuidInterface object instance
*
* @param string $bytes
*
* @return UuidInterface
*/
public function decodeBytes($bytes)
{
return $this->decode(bin2hex($bytes));
}
/**
* Swaps the first 48 bits with the last 48 bits
*
* @param array $components An array of UUID components (the UUID exploded on its dashes)
*
* @return void
*/
protected function swapTimestampAndRandomBits(array &$components)
{
$last48Bits = $components[4];
if (count($components) == 6) {
$last48Bits = $components[5];
$components[5] = $components[0] . $components[1];
} else {
$components[4] = $components[0] . $components[1];
}
$components[0] = substr($last48Bits, 0, 8);
$components[1] = substr($last48Bits, 8, 4);
}
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Codec;
/**
* TimestampLastCombCodec encodes and decodes COMB UUIDs which have the timestamp as the last 48 bits.
* To be used with MSSQL.
*/
class TimestampLastCombCodec extends StringCodec
{
}

View File

@@ -0,0 +1,54 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter\Number;
use Moontoast\Math\BigNumber;
use Ramsey\Uuid\Converter\NumberConverterInterface;
/**
* BigNumberConverter converts UUIDs from hexadecimal characters into
* moontoast/math `BigNumber` representations of integers and vice versa
*/
class BigNumberConverter implements NumberConverterInterface
{
/**
* Converts a hexadecimal number into a `Moontoast\Math\BigNumber` representation
*
* @param string $hex The hexadecimal string representation to convert
* @return BigNumber
*/
public function fromHex($hex)
{
$number = BigNumber::convertToBase10($hex, 16);
return new BigNumber($number);
}
/**
* Converts an integer or `Moontoast\Math\BigNumber` integer representation
* into a hexadecimal string representation
*
* @param int|string|BigNumber $integer An integer or `Moontoast\Math\BigNumber`
* @return string Hexadecimal string
*/
public function toHex($integer)
{
if (!$integer instanceof BigNumber) {
$integer = new BigNumber($integer);
}
return BigNumber::convertFromBase10($integer, 16);
}
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter\Number;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Ramsey\Uuid\Converter\NumberConverterInterface;
/**
* DegradedNumberConverter throws `UnsatisfiedDependencyException` exceptions
* if attempting to use number conversion functionality in an environment that
* does not support large integers (i.e. when moontoast/math is not available)
*/
class DegradedNumberConverter implements NumberConverterInterface
{
/**
* Throws an `UnsatisfiedDependencyException`
*
* @param string $hex The hexadecimal string representation to convert
* @return void
* @throws UnsatisfiedDependencyException
*/
public function fromHex($hex)
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' without support for large '
. 'integers, since integer is an unsigned '
. '128-bit integer; Moontoast\Math\BigNumber is required.'
);
}
/**
* Throws an `UnsatisfiedDependencyException`
*
* @param mixed $integer An integer representation to convert
* @return void
* @throws UnsatisfiedDependencyException
*/
public function toHex($integer)
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' without support for large '
. 'integers, since integer is an unsigned '
. '128-bit integer; Moontoast\Math\BigNumber is required. '
);
}
}

View File

@@ -0,0 +1,44 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter;
/**
* NumberConverterInterface converts UUIDs from hexadecimal characters into
* representations of integers and vice versa
*/
interface NumberConverterInterface
{
/**
* Converts a hexadecimal number into an integer representation of the number
*
* The integer representation returned may be an object or a string
* representation of the integer, depending on the implementation.
*
* @param string $hex The hexadecimal string representation to convert
* @return mixed
*/
public function fromHex($hex);
/**
* Converts an integer representation into a hexadecimal string representation
* of the number
*
* @param mixed $integer An integer representation to convert; this may be
* a true integer, a string integer, or a object representation that
* this converter can understand
* @return string Hexadecimal string
*/
public function toHex($integer);
}

View File

@@ -0,0 +1,58 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter\Time;
use Moontoast\Math\BigNumber;
use Ramsey\Uuid\Converter\TimeConverterInterface;
/**
* BigNumberTimeConverter uses the moontoast/math library's `BigNumber` to
* provide facilities for converting parts of time into representations that may
* be used in UUIDs
*/
class BigNumberTimeConverter implements TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the time_low,
* time_mid, and time_high fields used by RFC 4122 version 1 UUIDs
*
* @param string $seconds
* @param string $microSeconds
* @return string[] An array containing `low`, `mid`, and `high` keys
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2
*/
public function calculateTime($seconds, $microSeconds)
{
$uuidTime = new BigNumber('0');
$sec = new BigNumber($seconds);
$sec->multiply('10000000');
$usec = new BigNumber($microSeconds);
$usec->multiply('10');
$uuidTime->add($sec)
->add($usec)
->add('122192928000000000');
$uuidTimeHex = sprintf('%016s', $uuidTime->convertToBase(16));
return array(
'low' => substr($uuidTimeHex, 8),
'mid' => substr($uuidTimeHex, 4, 4),
'hi' => substr($uuidTimeHex, 0, 4),
);
}
}

View File

@@ -0,0 +1,42 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
/**
* DegradedTimeConverter throws `UnsatisfiedDependencyException` exceptions
* if attempting to use time conversion functionality in an environment that
* does not support large integers (i.e. when moontoast/math is not available)
*/
class DegradedTimeConverter implements TimeConverterInterface
{
/**
* Throws an `UnsatisfiedDependencyException`
*
* @param string $seconds
* @param string $microSeconds
* @return void
* @throws UnsatisfiedDependencyException
*/
public function calculateTime($seconds, $microSeconds)
{
throw new UnsatisfiedDependencyException(
'When calling ' . __METHOD__ . ' on a 32-bit system, '
. 'Moontoast\Math\BigNumber must be present.'
);
}
}

View File

@@ -0,0 +1,47 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter\Time;
use Ramsey\Uuid\Converter\TimeConverterInterface;
/**
* 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
*/
class PhpTimeConverter implements TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the time_low,
* time_mid, and time_high fields used by RFC 4122 version 1 UUIDs
*
* @param string $seconds
* @param string $microSeconds
* @return string[] An array containing `low`, `mid`, and `high` keys
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2
*/
public function calculateTime($seconds, $microSeconds)
{
// 0x01b21dd213814000 is the number of 100-ns intervals between the
// UUID epoch 1582-10-15 00:00:00 and the Unix epoch 1970-01-01 00:00:00.
$uuidTime = ($seconds * 10000000) + ($microSeconds * 10) + 0x01b21dd213814000;
return array(
'low' => sprintf('%08x', $uuidTime & 0xffffffff),
'mid' => sprintf('%04x', ($uuidTime >> 32) & 0xffff),
'hi' => sprintf('%04x', ($uuidTime >> 48) & 0x0fff),
);
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Converter;
/**
* TimeConverterInterface provides facilities for converting parts of time into
* representations that may be used in UUIDs
*/
interface TimeConverterInterface
{
/**
* Uses the provided seconds and micro-seconds to calculate the time_low,
* time_mid, and time_high fields used by RFC 4122 version 1 UUIDs
*
* @param string $seconds
* @param string $microSeconds
* @return string[] An array guaranteed to contain `low`, `mid`, and `high` keys
* @link http://tools.ietf.org/html/rfc4122#section-4.2.2
*/
public function calculateTime($seconds, $microSeconds);
}

View File

@@ -0,0 +1,111 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid;
use Ramsey\Uuid\Exception\UnsatisfiedDependencyException;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
/**
* DegradedUuid represents an RFC 4122 UUID on 32-bit systems
*
* @see Uuid
*/
class DegradedUuid extends Uuid
{
public function getDateTime()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
$time = $this->converter->fromHex($this->getTimestampHex());
$ts = new \Moontoast\Math\BigNumber($time, 20);
$ts->subtract('122192928000000000');
$ts->divide('10000000.0');
$ts->round();
$unixTime = $ts->getValue();
return new \DateTime("@{$unixTime}");
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
*/
public function getFields()
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since some '
. 'values overflow the system max integer value'
. '; consider calling getFieldsHex instead'
);
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
*/
public function getNode()
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since node '
. 'is an unsigned 48-bit integer and can overflow the system '
. 'max integer value'
. '; consider calling getNodeHex instead'
);
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
*/
public function getTimeLow()
{
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since time_low '
. 'is an unsigned 32-bit integer and can overflow the system '
. 'max integer value'
. '; consider calling getTimeLowHex instead'
);
}
/**
* For degraded UUIDs, throws an `UnsatisfiedDependencyException` when
* called on a 32-bit system
*
* @throws UnsatisfiedDependencyException if called on a 32-bit system
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
*/
public function getTimestamp()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
throw new UnsatisfiedDependencyException(
'Cannot call ' . __METHOD__ . ' on a 32-bit system, since timestamp '
. 'is an unsigned 60-bit integer and can overflow the system '
. 'max integer value'
. '; consider calling getTimestampHex instead'
);
}
}

View File

@@ -0,0 +1,22 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Exception;
/**
* Thrown to indicate that the parsed UUID string is invalid.
*/
class InvalidUuidStringException extends \InvalidArgumentException
{
}

View File

@@ -0,0 +1,23 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Exception;
/**
* Thrown to indicate that the requested operation has dependencies that have not
* been satisfied.
*/
class UnsatisfiedDependencyException extends \RuntimeException
{
}

View File

@@ -0,0 +1,22 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Exception;
/**
* Thrown to indicate that the requested operation is not supported.
*/
class UnsupportedOperationException extends \RuntimeException
{
}

View File

@@ -0,0 +1,333 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Generator\PeclUuidTimeGenerator;
use Ramsey\Uuid\Provider\Node\FallbackNodeProvider;
use Ramsey\Uuid\Provider\Node\RandomNodeProvider;
use Ramsey\Uuid\Provider\Node\SystemNodeProvider;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Converter\Number\BigNumberConverter;
use Ramsey\Uuid\Converter\Number\DegradedNumberConverter;
use Ramsey\Uuid\Converter\Time\BigNumberTimeConverter;
use Ramsey\Uuid\Converter\Time\DegradedTimeConverter;
use Ramsey\Uuid\Converter\Time\PhpTimeConverter;
use Ramsey\Uuid\Provider\Time\SystemTimeProvider;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
use Ramsey\Uuid\Builder\DefaultUuidBuilder;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Codec\StringCodec;
use Ramsey\Uuid\Codec\GuidStringCodec;
use Ramsey\Uuid\Builder\DegradedUuidBuilder;
use Ramsey\Uuid\Generator\RandomGeneratorFactory;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Generator\TimeGeneratorFactory;
use Ramsey\Uuid\Generator\TimeGeneratorInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
/**
* FeatureSet detects and exposes available features in the current environment
* (32- or 64-bit, available dependencies, etc.)
*/
class FeatureSet
{
/**
* @var bool
*/
private $disableBigNumber = false;
/**
* @var bool
*/
private $disable64Bit = false;
/**
* @var bool
*/
private $ignoreSystemNode = false;
/**
* @var bool
*/
private $enablePecl = false;
/**
* @var UuidBuilderInterface
*/
private $builder;
/**
* @var CodecInterface
*/
private $codec;
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var NumberConverterInterface
*/
private $numberConverter;
/**
* @var RandomGeneratorInterface
*/
private $randomGenerator;
/**
* @var TimeGeneratorInterface
*/
private $timeGenerator;
/**
* Constructs a `FeatureSet` for use by a `UuidFactory` to determine or set
* features available to the environment
*
* @param bool $useGuids Whether to build UUIDs using the `GuidStringCodec`
* @param bool $force32Bit Whether to force the use of 32-bit functionality
* (primarily for testing purposes)
* @param bool $forceNoBigNumber Whether to disable the use of moontoast/math
* `BigNumber` (primarily for testing purposes)
* @param bool $ignoreSystemNode Whether to disable attempts to check for
* the system host ID (primarily for testing purposes)
* @param bool $enablePecl Whether to enable the use of the `PeclUuidTimeGenerator`
* to generate version 1 UUIDs
*/
public function __construct(
$useGuids = false,
$force32Bit = false,
$forceNoBigNumber = false,
$ignoreSystemNode = false,
$enablePecl = false
) {
$this->disableBigNumber = $forceNoBigNumber;
$this->disable64Bit = $force32Bit;
$this->ignoreSystemNode = $ignoreSystemNode;
$this->enablePecl = $enablePecl;
$this->numberConverter = $this->buildNumberConverter();
$this->builder = $this->buildUuidBuilder();
$this->codec = $this->buildCodec($useGuids);
$this->nodeProvider = $this->buildNodeProvider();
$this->randomGenerator = $this->buildRandomGenerator();
$this->setTimeProvider(new SystemTimeProvider());
}
/**
* Returns the builder configured for this environment
*
* @return UuidBuilderInterface
*/
public function getBuilder()
{
return $this->builder;
}
/**
* Returns the UUID UUID coder-decoder configured for this environment
*
* @return CodecInterface
*/
public function getCodec()
{
return $this->codec;
}
/**
* Returns the system node ID provider configured for this environment
*
* @return NodeProviderInterface
*/
public function getNodeProvider()
{
return $this->nodeProvider;
}
/**
* Returns the number converter configured for this environment
*
* @return NumberConverterInterface
*/
public function getNumberConverter()
{
return $this->numberConverter;
}
/**
* Returns the random UUID generator configured for this environment
*
* @return RandomGeneratorInterface
*/
public function getRandomGenerator()
{
return $this->randomGenerator;
}
/**
* Returns the time-based UUID generator configured for this environment
*
* @return TimeGeneratorInterface
*/
public function getTimeGenerator()
{
return $this->timeGenerator;
}
/**
* Sets the time provider for use in this environment
*
* @param TimeProviderInterface $timeProvider
*/
public function setTimeProvider(TimeProviderInterface $timeProvider)
{
$this->timeGenerator = $this->buildTimeGenerator($timeProvider);
}
/**
* Determines which UUID coder-decoder to use and returns the configured
* codec for this environment
*
* @param bool $useGuids Whether to build UUIDs using the `GuidStringCodec`
* @return CodecInterface
*/
protected function buildCodec($useGuids = false)
{
if ($useGuids) {
return new GuidStringCodec($this->builder);
}
return new StringCodec($this->builder);
}
/**
* Determines which system node ID provider to use and returns the configured
* system node ID provider for this environment
*
* @return NodeProviderInterface
*/
protected function buildNodeProvider()
{
if ($this->ignoreSystemNode) {
return new RandomNodeProvider();
}
return new FallbackNodeProvider([
new SystemNodeProvider(),
new RandomNodeProvider()
]);
}
/**
* Determines which number converter to use and returns the configured
* number converter for this environment
*
* @return NumberConverterInterface
*/
protected function buildNumberConverter()
{
if ($this->hasBigNumber()) {
return new BigNumberConverter();
}
return new DegradedNumberConverter();
}
/**
* Determines which random UUID generator to use and returns the configured
* random UUID generator for this environment
*
* @return RandomGeneratorInterface
*/
protected function buildRandomGenerator()
{
return (new RandomGeneratorFactory())->getGenerator();
}
/**
* Determines which time-based UUID generator to use and returns the configured
* time-based UUID generator for this environment
*
* @param TimeProviderInterface $timeProvider
* @return TimeGeneratorInterface
*/
protected function buildTimeGenerator(TimeProviderInterface $timeProvider)
{
if ($this->enablePecl) {
return new PeclUuidTimeGenerator();
}
return (new TimeGeneratorFactory(
$this->nodeProvider,
$this->buildTimeConverter(),
$timeProvider
))->getGenerator();
}
/**
* Determines which time converter to use and returns the configured
* time converter for this environment
*
* @return TimeConverterInterface
*/
protected function buildTimeConverter()
{
if ($this->is64BitSystem()) {
return new PhpTimeConverter();
} elseif ($this->hasBigNumber()) {
return new BigNumberTimeConverter();
}
return new DegradedTimeConverter();
}
/**
* Determines which UUID builder to use and returns the configured UUID
* builder for this environment
*
* @return UuidBuilderInterface
*/
protected function buildUuidBuilder()
{
if ($this->is64BitSystem()) {
return new DefaultUuidBuilder($this->numberConverter);
}
return new DegradedUuidBuilder($this->numberConverter);
}
/**
* Returns true if the system has `Moontoast\Math\BigNumber`
*
* @return bool
*/
protected function hasBigNumber()
{
return class_exists('Moontoast\Math\BigNumber') && !$this->disableBigNumber;
}
/**
* Returns true if the system is 64-bit, false otherwise
*
* @return bool
*/
protected function is64BitSystem()
{
return PHP_INT_SIZE == 8 && !$this->disable64Bit;
}
}

View File

@@ -0,0 +1,85 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Converter\NumberConverterInterface;
/**
* CombGenerator provides functionality to generate COMB (combined GUID/timestamp)
* sequential UUIDs
*
* @link https://en.wikipedia.org/wiki/Globally_unique_identifier#Sequential_algorithms
*/
class CombGenerator implements RandomGeneratorInterface
{
const TIMESTAMP_BYTES = 6;
/**
* @var RandomGeneratorInterface
*/
private $randomGenerator;
/**
* @var NumberConverterInterface
*/
private $converter;
/**
* Constructs a `CombGenerator` using a random-number generator and a number converter
*
* @param RandomGeneratorInterface $generator Random-number generator for the non-time part.
* @param NumberConverterInterface $numberConverter Instance of number converter.
*/
public function __construct(RandomGeneratorInterface $generator, NumberConverterInterface $numberConverter)
{
$this->converter = $numberConverter;
$this->randomGenerator = $generator;
}
/**
* Generates a string of binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
if ($length < self::TIMESTAMP_BYTES || $length < 0) {
throw new \InvalidArgumentException('Length must be a positive integer.');
}
$hash = '';
if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) {
$hash = $this->randomGenerator->generate($length - self::TIMESTAMP_BYTES);
}
$lsbTime = str_pad($this->converter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT);
return hex2bin(str_pad(bin2hex($hash), $length - self::TIMESTAMP_BYTES, '0') . $lsbTime);
}
/**
* Returns current timestamp as integer, precise to 0.00001 seconds
*
* @return string
*/
private function timestamp()
{
$time = explode(' ', microtime(false));
return $time[1] . substr($time[0], 2, 5);
}
}

View File

@@ -0,0 +1,132 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\BinaryUtils;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* DefaultTimeGenerator provides functionality to generate strings of binary
* data for version 1 UUIDs based on a host ID, sequence number, and the current
* time
*/
class DefaultTimeGenerator implements TimeGeneratorInterface
{
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var TimeConverterInterface
*/
private $timeConverter;
/**
* @var TimeProviderInterface
*/
private $timeProvider;
/**
* Constructs a `DefaultTimeGenerator` using a node provider, time converter,
* and time provider
*
* @param NodeProviderInterface $nodeProvider
* @param TimeConverterInterface $timeConverter
* @param TimeProviderInterface $timeProvider
*/
public function __construct(
NodeProviderInterface $nodeProvider,
TimeConverterInterface $timeConverter,
TimeProviderInterface $timeProvider
) {
$this->nodeProvider = $nodeProvider;
$this->timeConverter = $timeConverter;
$this->timeProvider = $timeProvider;
}
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time
*
* If $node is not given, we will attempt to obtain the local hardware
* address. If $clockSeq is given, it is used as the sequence number;
* otherwise a random 14-bit sequence number is chosen.
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $clockSeq A 14-bit number used to help avoid duplicates that
* could arise when the clock is set backwards in time or if the node ID
* changes.
* @return string A binary string
*/
public function generate($node = null, $clockSeq = null)
{
$node = $this->getValidNode($node);
if ($clockSeq === null) {
// Not using "stable storage"; see RFC 4122, Section 4.2.1.1
$clockSeq = mt_rand(0, 1 << 14);
}
// Create a 60-bit time value as a count of 100-nanosecond intervals
// since 00:00:00.00, 15 October 1582
$timeOfDay = $this->timeProvider->currentTime();
$uuidTime = $this->timeConverter->calculateTime($timeOfDay['sec'], $timeOfDay['usec']);
$timeHi = BinaryUtils::applyVersion($uuidTime['hi'], 1);
$clockSeqHi = BinaryUtils::applyVariant($clockSeq >> 8);
$hex = vsprintf(
'%08s%04s%04s%02s%02s%012s',
array(
$uuidTime['low'],
$uuidTime['mid'],
sprintf('%04x', $timeHi),
sprintf('%02x', $clockSeqHi),
sprintf('%02x', $clockSeq & 0xff),
$node,
)
);
return hex2bin($hex);
}
/**
* Uses the node provider given when constructing this instance to get
* the node ID (usually a MAC address)
*
* @param string|int $node A node value that may be used to override the node provider
* @return string Hexadecimal representation of the node ID
*/
protected function getValidNode($node)
{
if ($node === null) {
$node = $this->nodeProvider->getNode();
}
// Convert the node to hex, if it is still an integer
if (is_int($node)) {
$node = sprintf('%012x', $node);
}
if (!ctype_xdigit($node) || strlen($node) > 12) {
throw new \InvalidArgumentException('Invalid node value');
}
return strtolower(sprintf('%012s', $node));
}
}

View File

@@ -0,0 +1,41 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* MtRandRandomGenerator provides functionality to generate strings of random
* binary data using the `mt_rand()` PHP function
*
* @link http://php.net/mt_rand
*/
class MtRandGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
$bytes = '';
for ($i = 1; $i <= $length; $i++) {
$bytes = chr(mt_rand(0, 255)) . $bytes;
}
return $bytes;
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* OpenSslRandomGenerator provides functionality to generate strings of random
* binary data using the `openssl_random_pseudo_bytes()` PHP function
*
* The use of this generator requires PHP to be compiled using the
* `--with-openssl` option.
*
* @link http://php.net/openssl_random_pseudo_bytes
*/
class OpenSslGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return openssl_random_pseudo_bytes($length);
}
}

View File

@@ -0,0 +1,37 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* PeclUuidRandomGenerator provides functionality to generate strings of random
* binary data using the PECL UUID PHP extension
*
* @link https://pecl.php.net/package/uuid
*/
class PeclUuidRandomGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
$uuid = uuid_create(UUID_TYPE_RANDOM);
return uuid_parse($uuid);
}
}

View File

@@ -0,0 +1,38 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* PeclUuidTimeGenerator provides functionality to generate strings of binary
* data for version 1 UUIDs using the PECL UUID PHP extension
*
* @link https://pecl.php.net/package/uuid
*/
class PeclUuidTimeGenerator implements TimeGeneratorInterface
{
/**
* Generate a version 1 UUID using the PECL UUID extension
*
* @param int|string $node Not used in this context
* @param int $clockSeq Not used in this context
* @return string A binary string
*/
public function generate($node = null, $clockSeq = null)
{
$uuid = uuid_create(UUID_TYPE_TIME);
return uuid_parse($uuid);
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* RandomBytesGenerator provides functionality to generate strings of random
* binary data using `random_bytes()` function in PHP 7+ or paragonie/random_compat
*
* @link http://php.net/random_bytes
* @link https://github.com/paragonie/random_compat
*/
class RandomBytesGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return random_bytes($length);
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* A factory for retrieving a random generator, based on the environment
*/
class RandomGeneratorFactory
{
/**
* Returns a default random generator, based on the current environment
*
* @return RandomGeneratorInterface
*/
public static function getGenerator()
{
return new RandomBytesGenerator();
}
}

View File

@@ -0,0 +1,30 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* RandomGeneratorInterface provides functionality to generate strings of random
* binary data
*/
interface RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length);
}

View File

@@ -0,0 +1,62 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
use RandomLib\Generator;
use RandomLib\Factory;
/**
* RandomLibAdapter provides functionality to generate strings of random
* binary data using the ircmaxell/random-lib library
*
* @link https://packagist.org/packages/ircmaxell/random-lib
*/
class RandomLibAdapter implements RandomGeneratorInterface
{
/**
* @var Generator
*/
private $generator;
/**
* Constructs a `RandomLibAdapter` using a `RandomLib\Generator`
*
* By default, if no `Generator` is passed in, this creates a medium-strength
* generator to use when generating random binary data.
*
* @param Generator $generator An ircmaxell/random-lib `Generator`
*/
public function __construct(Generator $generator = null)
{
$this->generator = $generator;
if ($this->generator === null) {
$factory = new Factory();
$this->generator = $factory->getMediumStrengthGenerator();
}
}
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return $this->generator->generate($length);
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* SodiumRandomGenerator provides functionality to generate strings of random
* binary data using the PECL libsodium extension
*
* @link http://pecl.php.net/package/libsodium
* @link https://paragonie.com/book/pecl-libsodium
*/
class SodiumRandomGenerator implements RandomGeneratorInterface
{
/**
* Generates a string of random binary data of the specified length
*
* @param integer $length The number of bytes of random binary data to generate
* @return string A binary string
*/
public function generate($length)
{
return \Sodium\randombytes_buf($length);
}
}

View File

@@ -0,0 +1,72 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
use Ramsey\Uuid\Converter\TimeConverterInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* A factory for retrieving a time generator, based on the environment
*/
class TimeGeneratorFactory
{
/**
* @var NodeProviderInterface
*/
private $nodeProvider;
/**
* @var TimeConverterInterface
*/
private $timeConverter;
/**
* @var TimeProviderInterface
*/
private $timeProvider;
/**
* Constructs a `TimeGeneratorFactory` using a node provider, time converter,
* and time provider
*
* @param NodeProviderInterface $nodeProvider
* @param TimeConverterInterface $timeConverter
* @param TimeProviderInterface $timeProvider
*/
public function __construct(
NodeProviderInterface $nodeProvider,
TimeConverterInterface $timeConverter,
TimeProviderInterface $timeProvider
) {
$this->nodeProvider = $nodeProvider;
$this->timeConverter = $timeConverter;
$this->timeProvider = $timeProvider;
}
/**
* Returns a default time generator, based on the current environment
*
* @return TimeGeneratorInterface
*/
public function getGenerator()
{
return new DefaultTimeGenerator(
$this->nodeProvider,
$this->timeConverter,
$this->timeProvider
);
}
}

View File

@@ -0,0 +1,35 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Generator;
/**
* TimeGeneratorInterface provides functionality to generate strings of binary
* data for version 1 UUIDs based on a host ID, sequence number, and the current
* time
*/
interface TimeGeneratorInterface
{
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $clockSeq A 14-bit number used to help avoid duplicates that
* could arise when the clock is set backwards in time or if the node ID
* changes.
* @return string A binary string
*/
public function generate($node = null, $clockSeq = null);
}

View File

@@ -0,0 +1,57 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider\Node;
use Ramsey\Uuid\Provider\NodeProviderInterface;
/**
* FallbackNodeProvider attempts to gain the system host ID from an array of
* providers, falling back to the next in line in the event a host ID can not be
* obtained
*/
class FallbackNodeProvider implements NodeProviderInterface
{
/**
* @var NodeProviderInterface[]
*/
private $nodeProviders;
/**
* Constructs a `FallbackNodeProvider` using an array of node providers
*
* @param NodeProviderInterface[] $providers Array of node providers
*/
public function __construct(array $providers)
{
$this->nodeProviders = $providers;
}
/**
* Returns the system node ID by iterating over an array of node providers
* and returning the first non-empty value found
*
* @return string System node ID as a hexadecimal string
*/
public function getNode()
{
foreach ($this->nodeProviders as $provider) {
if ($node = $provider->getNode()) {
return $node;
}
}
return null;
}
}

View File

@@ -0,0 +1,36 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider\Node;
use Ramsey\Uuid\Provider\NodeProviderInterface;
/**
* RandomNodeProvider provides functionality to generate a random node ID, in
* the event that the node ID could not be obtained from the host system
*
* @link http://tools.ietf.org/html/rfc4122#section-4.5
*/
class RandomNodeProvider implements NodeProviderInterface
{
/**
* Returns the system node ID
*
* @return string System node ID as a hexadecimal string
*/
public function getNode()
{
return sprintf('%06x%06x', mt_rand(0, 0xffffff), mt_rand(0, 0xffffff));
}
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider\Node;
use Ramsey\Uuid\Provider\NodeProviderInterface;
/**
* SystemNodeProvider provides functionality to get the system node ID (MAC
* address) using external system calls
*/
class SystemNodeProvider implements NodeProviderInterface
{
/**
* Returns the system node ID
*
* @return string|false System node ID as a hexadecimal string, or false if it is not found
*/
public function getNode()
{
static $node = null;
if ($node !== null) {
return $node;
}
$pattern = '/[^:]([0-9A-Fa-f]{2}([:-])[0-9A-Fa-f]{2}(\2[0-9A-Fa-f]{2}){4})[^:]/';
$matches = array();
// Search the ifconfig output for all MAC addresses and return
// the first one found
$node = false;
if (preg_match_all($pattern, $this->getIfconfig(), $matches, PREG_PATTERN_ORDER)) {
$node = $matches[1][0];
$node = str_replace([':', '-'], '', $node);
}
return $node;
}
/**
* Returns the network interface configuration for the system
*
* @codeCoverageIgnore
* @return string
*/
protected function getIfconfig()
{
ob_start();
switch (strtoupper(substr(php_uname('a'), 0, 3))) {
case 'WIN':
passthru('ipconfig /all 2>&1');
break;
case 'DAR':
passthru('ifconfig 2>&1');
break;
case 'LIN':
default:
passthru('netstat -ie 2>&1');
break;
}
return ob_get_clean();
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider;
/**
* NodeProviderInterface provides functionality to get the node ID (or host ID
* in the form of the system's MAC address) from a specific type of node provider
*/
interface NodeProviderInterface
{
/**
* Returns the system node ID
*
* @return string System node ID as a hexadecimal string
*/
public function getNode();
}

View File

@@ -0,0 +1,76 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider\Time;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* FixedTimeProvider uses an previously-generated timestamp to provide the time
*
* This provider allows the use of a previously-generated timestamp, such as one
* stored in a database, when creating version 1 UUIDs.
*/
class FixedTimeProvider implements TimeProviderInterface
{
/**
* @var int[] Array containing `sec` and `usec` components of a timestamp
*/
private $fixedTime;
/**
* Constructs a `FixedTimeProvider` using the provided `$timestamp`
*
* @param int[] Array containing `sec` and `usec` components of a timestamp
* @throws \InvalidArgumentException if the `$timestamp` does not contain `sec` or `usec` components
*/
public function __construct(array $timestamp)
{
if (!array_key_exists('sec', $timestamp) || !array_key_exists('usec', $timestamp)) {
throw new \InvalidArgumentException('Array must contain sec and usec keys.');
}
$this->fixedTime = $timestamp;
}
/**
* Sets the `usec` component of the timestamp
*
* @param int $value The `usec` value to set
*/
public function setUsec($value)
{
$this->fixedTime['usec'] = $value;
}
/**
* Sets the `sec` component of the timestamp
*
* @param int $value The `sec` value to set
*/
public function setSec($value)
{
$this->fixedTime['sec'] = $value;
}
/**
* Returns a timestamp array
*
* @return int[] Array containing `sec` and `usec` components of a timestamp
*/
public function currentTime()
{
return $this->fixedTime;
}
}

View File

@@ -0,0 +1,33 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider\Time;
use Ramsey\Uuid\Provider\TimeProviderInterface;
/**
* SystemTimeProvider uses built-in PHP functions to provide the time
*/
class SystemTimeProvider implements TimeProviderInterface
{
/**
* Returns a timestamp array
*
* @return int[] Array containing `sec` and `usec` components of a timestamp
*/
public function currentTime()
{
return gettimeofday();
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid\Provider;
/**
* TimeProviderInterface provides functionality to get the time from a specific
* type of time provider
*/
interface TimeProviderInterface
{
/**
* Returns a timestamp array
*
* @return int[] Array guaranteed to contain `sec` and `usec` components of a timestamp
*/
public function currentTime();
}

714
Laravel/vendor/ramsey/uuid/src/Uuid.php vendored Normal file
View File

@@ -0,0 +1,714 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
/**
* Represents a universally unique identifier (UUID), according to RFC 4122.
*
* This class provides immutable UUID objects (the Uuid class) and the static
* methods `uuid1()`, `uuid3()`, `uuid4()`, and `uuid5()` for generating version
* 1, 3, 4, and 5 UUIDs as specified in RFC 4122.
*
* If all you want is a unique ID, you should probably call `uuid1()` or `uuid4()`.
* Note that `uuid1()` may compromise privacy since it creates a UUID containing
* the computers network address. `uuid4()` creates a random UUID.
*
* @link http://tools.ietf.org/html/rfc4122
* @link http://en.wikipedia.org/wiki/Universally_unique_identifier
* @link http://docs.python.org/3/library/uuid.html
* @link http://docs.oracle.com/javase/6/docs/api/java/util/UUID.html
*/
class Uuid implements UuidInterface
{
/**
* When this namespace is specified, the name string is a fully-qualified domain name.
* @link http://tools.ietf.org/html/rfc4122#appendix-C
*/
const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
/**
* When this namespace is specified, the name string is a URL.
* @link http://tools.ietf.org/html/rfc4122#appendix-C
*/
const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
/**
* When this namespace is specified, the name string is an ISO OID.
* @link http://tools.ietf.org/html/rfc4122#appendix-C
*/
const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8';
/**
* When this namespace is specified, the name string is an X.500 DN in DER or a text output format.
* @link http://tools.ietf.org/html/rfc4122#appendix-C
*/
const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8';
/**
* The nil UUID is special form of UUID that is specified to have all 128 bits set to zero.
* @link http://tools.ietf.org/html/rfc4122#section-4.1.7
*/
const NIL = '00000000-0000-0000-0000-000000000000';
/**
* Reserved for NCS compatibility.
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
*/
const RESERVED_NCS = 0;
/**
* Specifies the UUID layout given in RFC 4122.
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
*/
const RFC_4122 = 2;
/**
* Reserved for Microsoft compatibility.
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
*/
const RESERVED_MICROSOFT = 6;
/**
* Reserved for future definition.
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
*/
const RESERVED_FUTURE = 7;
/**
* Regular expression pattern for matching a valid UUID of any variant.
*/
const VALID_PATTERN = '^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$';
/**
* Version 1 (time-based) UUID object constant identifier
*/
const UUID_TYPE_TIME = 1;
/**
* Version 2 (identifier-based) UUID object constant identifier
*/
const UUID_TYPE_IDENTIFIER = 2;
/**
* Version 3 (name-based and hashed with MD5) UUID object constant identifier
*/
const UUID_TYPE_HASH_MD5 = 3;
/**
* Version 4 (random) UUID object constant identifier
*/
const UUID_TYPE_RANDOM = 4;
/**
* Version 5 (name-based and hashed with SHA1) UUID object constant identifier
*/
const UUID_TYPE_HASH_SHA1 = 5;
/**
* The factory to use when creating UUIDs.
* @var UuidFactoryInterface
*/
private static $factory = null;
/**
* The codec to use when encoding or decoding UUID strings.
* @var CodecInterface
*/
protected $codec;
/**
* The fields that make up this UUID.
*
* This is initialized to the nil value.
*
* @var array
* @see UuidInterface::getFieldsHex()
*/
protected $fields = array(
'time_low' => '00000000',
'time_mid' => '0000',
'time_hi_and_version' => '0000',
'clock_seq_hi_and_reserved' => '00',
'clock_seq_low' => '00',
'node' => '000000000000',
);
/**
* The number converter to use for converting hex values to/from integers.
* @var NumberConverterInterface
*/
protected $converter;
/**
* Creates a universally unique identifier (UUID) from an array of fields.
*
* Unless you're making advanced use of this library to generate identifiers
* that deviate from RFC 4122, you probably do not want to instantiate a
* UUID directly. Use the static methods, instead:
*
* ```
* use Ramsey\Uuid\Uuid;
*
* $timeBasedUuid = Uuid::uuid1();
* $namespaceMd5Uuid = Uuid::uuid3(Uuid::NAMESPACE_URL, 'http://php.net/');
* $randomUuid = Uuid::uuid4();
* $namespaceSha1Uuid = Uuid::uuid5(Uuid::NAMESPACE_URL, 'http://php.net/');
* ```
*
* @param array $fields An array of fields from which to construct a UUID;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @param NumberConverterInterface $converter 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.
*/
public function __construct(
array $fields,
NumberConverterInterface $converter,
CodecInterface $codec
) {
$this->fields = $fields;
$this->codec = $codec;
$this->converter = $converter;
}
/**
* Converts this UUID object to a string when the object is used in any
* string context.
*
* @return string
* @link http://www.php.net/manual/en/language.oop5.magic.php#object.tostring
*/
public function __toString()
{
return $this->toString();
}
/**
* Converts this UUID object to a string when the object is serialized
* with `json_encode()`
*
* @return string
* @link http://php.net/manual/en/class.jsonserializable.php
*/
public function jsonSerialize()
{
return $this->toString();
}
/**
* Converts this UUID object to a string when the object is serialized
* with `serialize()`
*
* @return string
* @link http://php.net/manual/en/class.serializable.php
*/
public function serialize()
{
return $this->toString();
}
/**
* Re-constructs the object from its serialized form.
*
* @param string $serialized
* @link http://php.net/manual/en/class.serializable.php
*/
public function unserialize($serialized)
{
$uuid = self::fromString($serialized);
$this->codec = $uuid->codec;
$this->converter = $uuid->converter;
$this->fields = $uuid->fields;
}
public function compareTo(UuidInterface $other)
{
$comparison = 0;
if ($this->getMostSignificantBitsHex() < $other->getMostSignificantBitsHex()) {
$comparison = -1;
} elseif ($this->getMostSignificantBitsHex() > $other->getMostSignificantBitsHex()) {
$comparison = 1;
} elseif ($this->getLeastSignificantBitsHex() < $other->getLeastSignificantBitsHex()) {
$comparison = -1;
} elseif ($this->getLeastSignificantBitsHex() > $other->getLeastSignificantBitsHex()) {
$comparison = 1;
}
return $comparison;
}
public function equals($other)
{
if (!($other instanceof UuidInterface)) {
return false;
}
return ($this->compareTo($other) == 0);
}
public function getBytes()
{
return $this->codec->encodeBinary($this);
}
/**
* Returns the high field of the clock sequence multiplexed with the variant
* (bits 65-72 of the UUID).
*
* @return int Unsigned 8-bit integer value of clock_seq_hi_and_reserved
*/
public function getClockSeqHiAndReserved()
{
return hexdec($this->getClockSeqHiAndReservedHex());
}
public function getClockSeqHiAndReservedHex()
{
return $this->fields['clock_seq_hi_and_reserved'];
}
/**
* Returns the low field of the clock sequence (bits 73-80 of the UUID).
*
* @return int Unsigned 8-bit integer value of clock_seq_low
*/
public function getClockSeqLow()
{
return hexdec($this->getClockSeqLowHex());
}
public function getClockSeqLowHex()
{
return $this->fields['clock_seq_low'];
}
/**
* Returns the clock sequence value associated with this UUID.
*
* For UUID version 1, the clock sequence is used to help avoid
* duplicates that could arise when the clock is set backwards in time
* or if the node ID changes.
*
* For UUID version 3 or 5, the clock sequence is a 14-bit value
* constructed from a name as described in RFC 4122, Section 4.3.
*
* For UUID version 4, clock sequence is a randomly or pseudo-randomly
* generated 14-bit value as described in RFC 4122, Section 4.4.
*
* @return int Unsigned 14-bit integer value of clock sequence
* @link http://tools.ietf.org/html/rfc4122#section-4.1.5
*/
public function getClockSequence()
{
return (($this->getClockSeqHiAndReserved() & 0x3f) << 8)
| $this->getClockSeqLow();
}
public function getClockSequenceHex()
{
return sprintf('%04x', $this->getClockSequence());
}
public function getNumberConverter()
{
return $this->converter;
}
public function getDateTime()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
$unixTime = ($this->getTimestamp() - 0x01b21dd213814000) / 1e7;
$unixTime = number_format($unixTime, 0, '', '');
return new \DateTime("@{$unixTime}");
}
/**
* Returns an array of the fields of this UUID, with keys named according
* to the RFC 4122 names for the fields.
*
* * **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
*
* @return array The UUID fields represented as integer values
* @link http://tools.ietf.org/html/rfc4122#section-4.1.2
*/
public function getFields()
{
return array(
'time_low' => $this->getTimeLow(),
'time_mid' => $this->getTimeMid(),
'time_hi_and_version' => $this->getTimeHiAndVersion(),
'clock_seq_hi_and_reserved' => $this->getClockSeqHiAndReserved(),
'clock_seq_low' => $this->getClockSeqLow(),
'node' => $this->getNode(),
);
}
public function getFieldsHex()
{
return $this->fields;
}
public function getHex()
{
return str_replace('-', '', $this->toString());
}
public function getInteger()
{
return $this->converter->fromHex($this->getHex());
}
/**
* Returns the least significant 64 bits of this UUID's 128 bit value.
*
* @return mixed Converted representation of the unsigned 64-bit integer value
*/
public function getLeastSignificantBits()
{
return $this->converter->fromHex($this->getLeastSignificantBitsHex());
}
public function getLeastSignificantBitsHex()
{
return sprintf(
'%02s%02s%012s',
$this->fields['clock_seq_hi_and_reserved'],
$this->fields['clock_seq_low'],
$this->fields['node']
);
}
/**
* Returns the most significant 64 bits of this UUID's 128 bit value.
*
* @return mixed Converted representation of the unsigned 64-bit integer value
*/
public function getMostSignificantBits()
{
return $this->converter->fromHex($this->getMostSignificantBitsHex());
}
public function getMostSignificantBitsHex()
{
return sprintf(
'%08s%04s%04s',
$this->fields['time_low'],
$this->fields['time_mid'],
$this->fields['time_hi_and_version']
);
}
/**
* Returns the node value associated with this UUID
*
* For UUID version 1, the node field consists of an IEEE 802 MAC
* address, usually the host address. For systems with multiple IEEE
* 802 addresses, any available one can be used. The lowest addressed
* octet (octet number 10) contains the global/local bit and the
* unicast/multicast bit, and is the first octet of the address
* transmitted on an 802.3 LAN.
*
* For systems with no IEEE address, a randomly or pseudo-randomly
* generated value may be used; see RFC 4122, Section 4.5. The
* multicast bit must be set in such addresses, in order that they
* will never conflict with addresses obtained from network cards.
*
* For UUID version 3 or 5, the node field is a 48-bit value constructed
* from a name as described in RFC 4122, Section 4.3.
*
* For UUID version 4, the node field is a randomly or pseudo-randomly
* generated 48-bit value as described in RFC 4122, Section 4.4.
*
* @return int Unsigned 48-bit integer value of node
* @link http://tools.ietf.org/html/rfc4122#section-4.1.6
*/
public function getNode()
{
return hexdec($this->getNodeHex());
}
public function getNodeHex()
{
return $this->fields['node'];
}
/**
* Returns the high field of the timestamp multiplexed with the version
* number (bits 49-64 of the UUID).
*
* @return int Unsigned 16-bit integer value of time_hi_and_version
*/
public function getTimeHiAndVersion()
{
return hexdec($this->getTimeHiAndVersionHex());
}
public function getTimeHiAndVersionHex()
{
return $this->fields['time_hi_and_version'];
}
/**
* Returns the low field of the timestamp (the first 32 bits of the UUID).
*
* @return int Unsigned 32-bit integer value of time_low
*/
public function getTimeLow()
{
return hexdec($this->getTimeLowHex());
}
public function getTimeLowHex()
{
return $this->fields['time_low'];
}
/**
* Returns the middle field of the timestamp (bits 33-48 of the UUID).
*
* @return int Unsigned 16-bit integer value of time_mid
*/
public function getTimeMid()
{
return hexdec($this->getTimeMidHex());
}
public function getTimeMidHex()
{
return $this->fields['time_mid'];
}
/**
* Returns the timestamp value associated with this UUID.
*
* The 60 bit timestamp value is constructed from the time_low,
* time_mid, and time_hi fields of this UUID. The resulting
* timestamp is measured in 100-nanosecond units since midnight,
* October 15, 1582 UTC.
*
* The timestamp value is only meaningful in a time-based UUID, which
* has version type 1. If this UUID is not a time-based UUID then
* this method throws UnsupportedOperationException.
*
* @return int Unsigned 60-bit integer value of the timestamp
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
* @link http://tools.ietf.org/html/rfc4122#section-4.1.4
*/
public function getTimestamp()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
return hexdec($this->getTimestampHex());
}
public function getTimestampHex()
{
if ($this->getVersion() != 1) {
throw new UnsupportedOperationException('Not a time-based UUID');
}
return sprintf(
'%03x%04s%08s',
($this->getTimeHiAndVersion() & 0x0fff),
$this->fields['time_mid'],
$this->fields['time_low']
);
}
public function getUrn()
{
return 'urn:uuid:' . $this->toString();
}
public function getVariant()
{
$clockSeq = $this->getClockSeqHiAndReserved();
if (0 === ($clockSeq & 0x80)) {
$variant = self::RESERVED_NCS;
} elseif (0 === ($clockSeq & 0x40)) {
$variant = self::RFC_4122;
} elseif (0 === ($clockSeq & 0x20)) {
$variant = self::RESERVED_MICROSOFT;
} else {
$variant = self::RESERVED_FUTURE;
}
return $variant;
}
public function getVersion()
{
if ($this->getVariant() == self::RFC_4122) {
return (int) (($this->getTimeHiAndVersion() >> 12) & 0x0f);
}
return null;
}
public function toString()
{
return $this->codec->encode($this);
}
/**
* Returns the currently set factory used to create UUIDs.
*
* @return UuidFactoryInterface
*/
public static function getFactory()
{
if (!self::$factory) {
self::$factory = new UuidFactory();
}
return self::$factory;
}
/**
* Sets the factory used to create UUIDs.
*
* @param UuidFactoryInterface $factory
*/
public static function setFactory(UuidFactoryInterface $factory)
{
self::$factory = $factory;
}
/**
* Creates a UUID from a byte string.
*
* @param string $bytes
* @return UuidInterface
*/
public static function fromBytes($bytes)
{
return self::getFactory()->fromBytes($bytes);
}
/**
* Creates a UUID from the string standard representation.
*
* @param string $name A string that specifies a UUID
* @return UuidInterface
*/
public static function fromString($name)
{
return self::getFactory()->fromString($name);
}
/**
* Creates a UUID from a 128-bit integer string.
*
* @param string $integer String representation of 128-bit integer
* @return UuidInterface
*/
public static function fromInteger($integer)
{
return self::getFactory()->fromInteger($integer);
}
/**
* Check if a string is a valid UUID.
*
* @param string $uuid The string UUID to test
* @return boolean
*/
public static function isValid($uuid)
{
$uuid = str_replace(array('urn:', 'uuid:', '{', '}'), '', $uuid);
if ($uuid == self::NIL) {
return true;
}
if (!preg_match('/' . self::VALID_PATTERN . '/', $uuid)) {
return false;
}
return true;
}
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time.
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $clockSeq A 14-bit number used to help avoid duplicates that
* could arise when the clock is set backwards in time or if the node ID
* changes.
* @return UuidInterface
*/
public static function uuid1($node = null, $clockSeq = null)
{
return self::getFactory()->uuid1($node, $clockSeq);
}
/**
* Generate a version 3 UUID based on the MD5 hash of a namespace identifier
* (which is a UUID) and a name (which is a string).
*
* @param string $ns The UUID namespace in which to create the named UUID
* @param string $name The name to create a UUID for
* @return UuidInterface
*/
public static function uuid3($ns, $name)
{
return self::getFactory()->uuid3($ns, $name);
}
/**
* Generate a version 4 (random) UUID.
*
* @return UuidInterface
*/
public static function uuid4()
{
return self::getFactory()->uuid4();
}
/**
* Generate a version 5 UUID based on the SHA-1 hash of a namespace
* identifier (which is a UUID) and a name (which is a string).
*
* @param string $ns The UUID namespace in which to create the named UUID
* @param string $name The name to create a UUID for
* @return UuidInterface
*/
public static function uuid5($ns, $name)
{
return self::getFactory()->uuid5($ns, $name);
}
}

View File

@@ -0,0 +1,292 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Provider\NodeProviderInterface;
use Ramsey\Uuid\Generator\RandomGeneratorInterface;
use Ramsey\Uuid\Generator\TimeGeneratorInterface;
use Ramsey\Uuid\Codec\CodecInterface;
use Ramsey\Uuid\Builder\UuidBuilderInterface;
class UuidFactory implements UuidFactoryInterface
{
/**
* @var CodecInterface
*/
private $codec = null;
/**
* @var NodeProviderInterface
*/
private $nodeProvider = null;
/**
* @var NumberConverterInterface
*/
private $numberConverter = null;
/**
* @var RandomGeneratorInterface
*/
private $randomGenerator = null;
/**
* @var TimeGeneratorInterface
*/
private $timeGenerator = null;
/**
* @var UuidBuilderInterface
*/
private $uuidBuilder = null;
/**
* Constructs a `UuidFactory` for creating `Ramsey\Uuid\UuidInterface` instances
*
* @param FeatureSet $features A set of features for use when creating UUIDs
*/
public function __construct(FeatureSet $features = null)
{
$features = $features ?: new FeatureSet();
$this->codec = $features->getCodec();
$this->nodeProvider = $features->getNodeProvider();
$this->numberConverter = $features->getNumberConverter();
$this->randomGenerator = $features->getRandomGenerator();
$this->timeGenerator = $features->getTimeGenerator();
$this->uuidBuilder = $features->getBuilder();
}
/**
* Returns the UUID coder-decoder used by this factory
*
* @return CodecInterface
*/
public function getCodec()
{
return $this->codec;
}
/**
* Sets the UUID coder-decoder used by this factory
*
* @param CodecInterface $codec
*/
public function setCodec(CodecInterface $codec)
{
$this->codec = $codec;
}
/**
* Returns the system node ID provider used by this factory
*
* @return NodeProviderInterface
*/
public function getNodeProvider()
{
return $this->nodeProvider;
}
/**
* Returns the random UUID generator used by this factory
*
* @return RandomGeneratorInterface
*/
public function getRandomGenerator()
{
return $this->randomGenerator;
}
/**
* Returns the time-based UUID generator used by this factory
*
* @return TimeGeneratorInterface
*/
public function getTimeGenerator()
{
return $this->timeGenerator;
}
/**
* Sets the time-based UUID generator this factory will use to generate version 1 UUIDs
*
* @param TimeGeneratorInterface $generator
*/
public function setTimeGenerator(TimeGeneratorInterface $generator)
{
$this->timeGenerator = $generator;
}
/**
* Returns the number converter used by this factory
*
* @return NumberConverterInterface
*/
public function getNumberConverter()
{
return $this->numberConverter;
}
/**
* Sets the random UUID generator this factory will use to generate version 4 UUIDs
*
* @param RandomGeneratorInterface $generator
*/
public function setRandomGenerator(RandomGeneratorInterface $generator)
{
$this->randomGenerator = $generator;
}
/**
* Sets the number converter this factory will use
*
* @param NumberConverterInterface $converter
*/
public function setNumberConverter(NumberConverterInterface $converter)
{
$this->numberConverter = $converter;
}
/**
* Returns the UUID builder this factory uses when creating `Uuid` instances
*
* @return UuidBuilderInterface $builder
*/
public function getUuidBuilder()
{
return $this->uuidBuilder;
}
/**
* Sets the UUID builder this factory will use when creating `Uuid` instances
*
* @param UuidBuilderInterface $builder
*/
public function setUuidBuilder(UuidBuilderInterface $builder)
{
$this->uuidBuilder = $builder;
}
public function fromBytes($bytes)
{
return $this->codec->decodeBytes($bytes);
}
public function fromString($uuid)
{
$uuid = strtolower($uuid);
return $this->codec->decode($uuid);
}
public function fromInteger($integer)
{
$hex = $this->numberConverter->toHex($integer);
$hex = str_pad($hex, 32, '0', STR_PAD_LEFT);
return $this->fromString($hex);
}
public function uuid1($node = null, $clockSeq = null)
{
$bytes = $this->timeGenerator->generate($node, $clockSeq);
$hex = bin2hex($bytes);
return $this->uuidFromHashedName($hex, 1);
}
public function uuid3($ns, $name)
{
return $this->uuidFromNsAndName($ns, $name, 3, 'md5');
}
public function uuid4()
{
$bytes = $this->randomGenerator->generate(16);
// When converting the bytes to hex, it turns into a 32-character
// hexadecimal string that looks a lot like an MD5 hash, so at this
// point, we can just pass it to uuidFromHashedName.
$hex = bin2hex($bytes);
return $this->uuidFromHashedName($hex, 4);
}
public function uuid5($ns, $name)
{
return $this->uuidFromNsAndName($ns, $name, 5, 'sha1');
}
/**
* Returns a `Uuid`
*
* Uses the configured builder and codec and the provided array of hexadecimal
* value UUID fields to construct a `Uuid` object.
*
* @param array $fields An array of fields from which to construct a UUID;
* see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure.
* @return UuidInterface
*/
public function uuid(array $fields)
{
return $this->uuidBuilder->build($this->codec, $fields);
}
/**
* Returns a version 3 or 5 namespaced `Uuid`
*
* @param string|UuidInterface $ns The UUID namespace to use
* @param string $name The string to hash together with the namespace
* @param int $version The version of UUID to create (3 or 5)
* @param string $hashFunction The hash function to use when hashing together
* the namespace and name
* @return UuidInterface
*/
protected function uuidFromNsAndName($ns, $name, $version, $hashFunction)
{
if (!($ns instanceof UuidInterface)) {
$ns = $this->codec->decode($ns);
}
$hash = call_user_func($hashFunction, ($ns->getBytes() . $name));
return $this->uuidFromHashedName($hash, $version);
}
/**
* Returns a `Uuid` created from `$hash` with the version field set to `$version`
* and the variant field set for RFC 4122
*
* @param string $hash The hash to use when creating the UUID
* @param int $version The UUID version to set for this hash (1, 3, 4, or 5)
* @return UuidInterface
*/
protected function uuidFromHashedName($hash, $version)
{
$timeHi = BinaryUtils::applyVersion(substr($hash, 12, 4), $version);
$clockSeqHi = BinaryUtils::applyVariant(hexdec(substr($hash, 16, 2)));
$fields = array(
'time_low' => substr($hash, 0, 8),
'time_mid' => substr($hash, 8, 4),
'time_hi_and_version' => str_pad(dechex($timeHi), 4, '0', STR_PAD_LEFT),
'clock_seq_hi_and_reserved' => str_pad(dechex($clockSeqHi), 2, '0', STR_PAD_LEFT),
'clock_seq_low' => substr($hash, 18, 2),
'node' => substr($hash, 20, 12),
);
return $this->uuid($fields);
}
}

View File

@@ -0,0 +1,89 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid;
/**
* UuidFactoryInterface defines common functionality all `UuidFactory` instances
* must implement
*/
interface UuidFactoryInterface
{
/**
* Generate a version 1 UUID from a host ID, sequence number, and the current time.
*
* @param int|string $node A 48-bit number representing the hardware address
* This number may be represented as an integer or a hexadecimal string.
* @param int $clockSeq A 14-bit number used to help avoid duplicates that
* could arise when the clock is set backwards in time or if the node ID
* changes.
* @return UuidInterface
*/
public function uuid1($node = null, $clockSeq = null);
/**
* Generate a version 3 UUID based on the MD5 hash of a namespace identifier
* (which is a UUID) and a name (which is a string).
*
* @param string $ns The UUID namespace in which to create the named UUID
* @param string $name The name to create a UUID for
* @return UuidInterface
*/
public function uuid3($ns, $name);
/**
* Generate a version 4 (random) UUID.
*
* @return UuidInterface
*/
public function uuid4();
/**
* Generate a version 5 UUID based on the SHA-1 hash of a namespace
* identifier (which is a UUID) and a name (which is a string).
*
* @param string $ns The UUID namespace in which to create the named UUID
* @param string $name The name to create a UUID for
* @return UuidInterface
*/
public function uuid5($ns, $name);
/**
* Creates a UUID from a byte string.
*
* @param string $bytes A 16-byte string representation of a UUID
* @return UuidInterface
*/
public function fromBytes($bytes);
/**
* Creates a UUID from the string standard representation
*
* @param string $uuid A string representation of a UUID
* @return UuidInterface
*/
public function fromString($uuid);
/**
* Creates a `Uuid` from an integer representation
*
* The integer representation may be a real integer, a string integer, or
* an integer representation supported by a configured number converter.
*
* @param mixed $integer The integer to use when creating a `Uuid` from an
* integer; may be of any type understood by the configured number converter
* @return UuidInterface
*/
public function fromInteger($integer);
}

View File

@@ -0,0 +1,267 @@
<?php
/**
* This file is part of the ramsey/uuid library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) Ben Ramsey <ben@benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
* @link https://benramsey.com/projects/ramsey-uuid/ Documentation
* @link https://packagist.org/packages/ramsey/uuid Packagist
* @link https://github.com/ramsey/uuid GitHub
*/
namespace Ramsey\Uuid;
use Ramsey\Uuid\Converter\NumberConverterInterface;
use Ramsey\Uuid\Exception\UnsupportedOperationException;
/**
* UuidInterface defines common functionality for all universally unique
* identifiers (UUIDs)
*/
interface UuidInterface extends \JsonSerializable, \Serializable
{
/**
* Compares this UUID to the specified UUID.
*
* The first of two UUIDs is greater than the second if the most
* significant field in which the UUIDs differ is greater for the first
* UUID.
*
* * Q. What's the value of being able to sort UUIDs?
* * A. Use them as keys in a B-Tree or similar mapping.
*
* @param UuidInterface $other UUID to which this UUID is compared
* @return int -1, 0 or 1 as this UUID is less than, equal to, or greater than `$uuid`
*/
public function compareTo(UuidInterface $other);
/**
* Compares this object to the specified object.
*
* The result is true if and only if the argument is not null, is a UUID
* object, has the same variant, and contains the same value, bit for bit,
* as this UUID.
*
* @param object $other
* @return bool True if `$other` is equal to this UUID
*/
public function equals($other);
/**
* Returns the UUID as a 16-byte string (containing the six integer fields
* in big-endian byte order).
*
* @return string
*/
public function getBytes();
/**
* Returns the number converter to use for converting hex values to/from integers.
*
* @return NumberConverterInterface
*/
public function getNumberConverter();
/**
* Returns the hexadecimal value of the UUID.
*
* @return string
*/
public function getHex();
/**
* Returns an array of the fields of this UUID, with keys named according
* to the RFC 4122 names for the fields.
*
* * **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
*
* @return array The UUID fields represented as hexadecimal values
*/
public function getFieldsHex();
/**
* Returns the high field of the clock sequence multiplexed with the variant
* (bits 65-72 of the UUID).
*
* @return string Hexadecimal value of clock_seq_hi_and_reserved
*/
public function getClockSeqHiAndReservedHex();
/**
* Returns the low field of the clock sequence (bits 73-80 of the UUID).
*
* @return string Hexadecimal value of clock_seq_low
*/
public function getClockSeqLowHex();
/**
* Returns the clock sequence value associated with this UUID.
*
* @return string Hexadecimal value of clock sequence
*/
public function getClockSequenceHex();
/**
* Returns a PHP `DateTime` object representing the timestamp associated
* with this UUID.
*
* The timestamp value is only meaningful in a time-based UUID, which
* has version type 1. If this UUID is not a time-based UUID then
* this method throws `UnsupportedOperationException`.
*
* @return \DateTime A PHP DateTime representation of the date
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
*/
public function getDateTime();
/**
* Returns the integer value of the UUID, converted to an appropriate number
* representation.
*
* @return mixed Converted representation of the unsigned 128-bit integer value
*/
public function getInteger();
/**
* Returns the least significant 64 bits of this UUID's 128 bit value.
*
* @return string Hexadecimal value of least significant bits
*/
public function getLeastSignificantBitsHex();
/**
* Returns the most significant 64 bits of this UUID's 128 bit value.
*
* @return string Hexadecimal value of most significant bits
*/
public function getMostSignificantBitsHex();
/**
* Returns the node value associated with this UUID
*
* For UUID version 1, the node field consists of an IEEE 802 MAC
* address, usually the host address. For systems with multiple IEEE
* 802 addresses, any available one can be used. The lowest addressed
* octet (octet number 10) contains the global/local bit and the
* unicast/multicast bit, and is the first octet of the address
* transmitted on an 802.3 LAN.
*
* For systems with no IEEE address, a randomly or pseudo-randomly
* generated value may be used; see RFC 4122, Section 4.5. The
* multicast bit must be set in such addresses, in order that they
* will never conflict with addresses obtained from network cards.
*
* For UUID version 3 or 5, the node field is a 48-bit value constructed
* from a name as described in RFC 4122, Section 4.3.
*
* For UUID version 4, the node field is a randomly or pseudo-randomly
* generated 48-bit value as described in RFC 4122, Section 4.4.
*
* @return string Hexadecimal value of node
* @link http://tools.ietf.org/html/rfc4122#section-4.1.6
*/
public function getNodeHex();
/**
* Returns the high field of the timestamp multiplexed with the version
* number (bits 49-64 of the UUID).
*
* @return string Hexadecimal value of time_hi_and_version
*/
public function getTimeHiAndVersionHex();
/**
* Returns the low field of the timestamp (the first 32 bits of the UUID).
*
* @return string Hexadecimal value of time_low
*/
public function getTimeLowHex();
/**
* Returns the middle field of the timestamp (bits 33-48 of the UUID).
*
* @return string Hexadecimal value of time_mid
*/
public function getTimeMidHex();
/**
* Returns the timestamp value associated with this UUID.
*
* The 60 bit timestamp value is constructed from the time_low,
* time_mid, and time_hi fields of this UUID. The resulting
* timestamp is measured in 100-nanosecond units since midnight,
* October 15, 1582 UTC.
*
* The timestamp value is only meaningful in a time-based UUID, which
* has version type 1. If this UUID is not a time-based UUID then
* this method throws UnsupportedOperationException.
*
* @return string Hexadecimal value of the timestamp
* @throws UnsupportedOperationException If this UUID is not a version 1 UUID
* @link http://tools.ietf.org/html/rfc4122#section-4.1.4
*/
public function getTimestampHex();
/**
* Returns the string representation of the UUID as a URN.
*
* @return string
* @link http://en.wikipedia.org/wiki/Uniform_Resource_Name
*/
public function getUrn();
/**
* Returns the variant number associated with this UUID.
*
* 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 4122 variant (used by this class)
* * 6 - Reserved, Microsoft Corporation backward compatibility
* * 7 - Reserved for future definition
*
* @return int
* @link http://tools.ietf.org/html/rfc4122#section-4.1.1
*/
public function getVariant();
/**
* Returns the version number associated with this UUID.
*
* The version number describes how this UUID was generated and has the
* following meaning:
*
* * 1 - Time-based UUID
* * 2 - DCE security UUID
* * 3 - Name-based UUID hashed with MD5
* * 4 - Randomly generated UUID
* * 5 - Name-based UUID hashed with SHA-1
*
* Returns null if this UUID is not an RFC 4122 variant, since version
* is only meaningful for this variant.
*
* @return int|null
* @link http://tools.ietf.org/html/rfc4122#section-4.1.3
*/
public function getVersion();
/**
* Converts this UUID into a string representation.
*
* @return string
*/
public function toString();
}