diff --git a/.gitattributes b/.gitattributes index a3066a5..ed1e6ce 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,6 +3,8 @@ .gitignore export-ignore .travis.yml export-ignore docs/ export-ignore +phpcs.xml.dist export-ignore +phpstan-tests.neon export-ignore phpstan.neon export-ignore phpunit.xml.dist export-ignore resources/ export-ignore diff --git a/.gitignore b/.gitignore index dcd4b15..4dfe4c6 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ .phpunit.result.cache /build/ /composer.lock +/phpcs.xml /phpunit.xml /vendor/ diff --git a/composer.json b/composer.json index 636a02d..69a6bd9 100644 --- a/composer.json +++ b/composer.json @@ -17,6 +17,7 @@ "require-dev": { "ext-gmp": "*", "codeception/aspect-mock": "^3", + "dealerdirect/phpcodesniffer-composer-installer": "^0.5.0", "doctrine/annotations": "^1.8", "goaop/framework": "^2", "jakub-onderka/php-parallel-lint": "^1", @@ -25,10 +26,12 @@ "paragonie/random-lib": "^2", "php-mock/php-mock-phpunit": "^2.5", "phpstan/extension-installer": "^1.0", + "phpstan/phpdoc-parser": "0.4.1", "phpstan/phpstan": "^0.12", "phpstan/phpstan-mockery": "^0.12", "phpstan/phpstan-phpunit": "^0.12", "phpunit/phpunit": "^8.5", + "slevomat/coding-standard": "^6.0", "squizlabs/php_codesniffer": "^3.5" }, "suggest": { @@ -68,7 +71,8 @@ }, "scripts": { "lint": "parallel-lint src tests", - "phpcs": "phpcs src tests --standard=psr2 -sp --colors", + "phpcbf": "phpcbf -vpw", + "phpcs": "phpcs", "phpstan": [ "phpstan analyse -c phpstan.neon src --level max --no-progress", "phpstan analyse -c phpstan-tests.neon tests --level max --no-progress" diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..7d846fd --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,431 @@ + + + + ramsey/uuid coding standard + + + + + ./src + ./tests + + + + + + + + + + + + + + + + + + + + + error + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 5 + + + + + + + + + + + diff --git a/phpstan-tests.neon b/phpstan-tests.neon index b075903..8bf714d 100644 --- a/phpstan-tests.neon +++ b/phpstan-tests.neon @@ -1,6 +1,7 @@ parameters: autoload_files: - tests/phpstan-bootstrap.php + checkMissingIterableValueType: false reportUnmatchedIgnoredErrors: false ignoreErrors: - diff --git a/src/BinaryUtils.php b/src/BinaryUtils.php index 2b223b1..27d22c0 100644 --- a/src/BinaryUtils.php +++ b/src/BinaryUtils.php @@ -1,5 +1,17 @@ + * @license http://opensource.org/licenses/MIT MIT + */ + +declare(strict_types=1); + namespace Ramsey\Uuid; /** @@ -10,13 +22,16 @@ class BinaryUtils /** * Applies the RFC 4122 variant field to the `clock_seq_hi_and_reserved` field * - * @param int $clockSeqHi + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant + * + * @param int $clockSeqHi The value of `clock_seq_hi_and_reserved` field + * before the RFC 4122 variant is applied + * * @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): int + public static function applyVariant(int $clockSeqHi): int { - // Set the variant to RFC 4122 + // Set the variant to RFC 4122. $clockSeqHi = $clockSeqHi & 0x3f; $clockSeqHi |= 0x80; @@ -26,10 +41,13 @@ class BinaryUtils /** * Applies the RFC 4122 version number to the `time_hi_and_version` field * - * @param string $timeHi - * @param int $version + * @link http://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version + * + * @param string $timeHi The value of the `time_hi_and_version` field before + * the RFC 4122 version is applied + * @param int $version The RFC 4122 version to apply to the `time_hi` field + * * @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(string $timeHi, int $version): int { diff --git a/src/Builder/DefaultUuidBuilder.php b/src/Builder/DefaultUuidBuilder.php index 0721fc4..67c98f2 100644 --- a/src/Builder/DefaultUuidBuilder.php +++ b/src/Builder/DefaultUuidBuilder.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Codec\CodecInterface; @@ -21,8 +21,7 @@ use Ramsey\Uuid\Uuid; use Ramsey\Uuid\UuidInterface; /** - * DefaultUuidBuilder is the default UUID builder for ramsey/uuid; it builds - * instances of Uuid objects + * DefaultUuidBuilder builds instances of Uuid */ class DefaultUuidBuilder implements UuidBuilderInterface { @@ -32,34 +31,42 @@ class DefaultUuidBuilder implements UuidBuilderInterface private $numberConverter; /** - * The time converter to use for converting timestamps extracted from UUIDs to unix timestamps * @var TimeConverterInterface */ - protected $timeConverter; + private $timeConverter; /** * Constructs the DefaultUuidBuilder * - * @param NumberConverterInterface $numberConverter The number converter to use when constructing the Uuid + * @param NumberConverterInterface $numberConverter The number converter to + * use when constructing the Uuid * @param TimeConverterInterface $timeConverter The time converter to use - * for converting timestamps extracted from a UUID to unix timestamps + * for converting timestamps extracted from a UUID to Unix timestamps */ - public function __construct(NumberConverterInterface $numberConverter, TimeConverterInterface $timeConverter) - { + public function __construct( + NumberConverterInterface $numberConverter, + TimeConverterInterface $timeConverter + ) { $this->numberConverter = $numberConverter; $this->timeConverter = $timeConverter; } /** - * Builds a Uuid + * Builds and returns 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; + * @param CodecInterface $codec The codec to use for building this Uuid instance + * @param string[] $fields An array of fields from which to construct a Uuid instance; * see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure. - * @return Uuid + * + * @return Uuid The DefaultUuidBuilder returns an instance of Ramsey\Uuid\Uuid */ public function build(CodecInterface $codec, array $fields): UuidInterface { - return new Uuid($fields, $this->numberConverter, $codec, $this->timeConverter); + return new Uuid( + $fields, + $this->numberConverter, + $codec, + $this->timeConverter + ); } } diff --git a/src/Builder/DegradedUuidBuilder.php b/src/Builder/DegradedUuidBuilder.php index 947d267..f1aa9c2 100644 --- a/src/Builder/DegradedUuidBuilder.php +++ b/src/Builder/DegradedUuidBuilder.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Codec\CodecInterface; @@ -31,34 +31,42 @@ class DegradedUuidBuilder implements UuidBuilderInterface private $numberConverter; /** - * The time converter to use for converting timestamps extracted from UUIDs to unix timestamps * @var TimeConverterInterface */ - protected $timeConverter; + private $timeConverter; /** * Constructs the DegradedUuidBuilder * - * @param NumberConverterInterface $numberConverter The number converter to use when constructing the DegradedUuid + * @param NumberConverterInterface $numberConverter The number converter to + * use when constructing the DegradedUuid * @param TimeConverterInterface $timeConverter The time converter to use - * for converting timestamps extracted from a UUID to unix timestamps + * for converting timestamps extracted from a UUID to Unix timestamps */ - public function __construct(NumberConverterInterface $numberConverter, TimeConverterInterface $timeConverter) - { + public function __construct( + NumberConverterInterface $numberConverter, + TimeConverterInterface $timeConverter + ) { $this->numberConverter = $numberConverter; $this->timeConverter = $timeConverter; } /** - * Builds a DegradedUuid + * Builds and returns 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; + * @param CodecInterface $codec The codec to use for building this DegradedUuid instance + * @param string[] $fields An array of fields from which to construct a DegradedUuid instance; * see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure. - * @return DegradedUuid + * + * @return DegradedUuid The DegradedUuidBuild returns an instance of Ramsey\Uuid\DegradedUuid */ public function build(CodecInterface $codec, array $fields): UuidInterface { - return new DegradedUuid($fields, $this->numberConverter, $codec, $this->timeConverter); + return new DegradedUuid( + $fields, + $this->numberConverter, + $codec, + $this->timeConverter + ); } } diff --git a/src/Builder/UuidBuilderInterface.php b/src/Builder/UuidBuilderInterface.php index 22457b4..7c1225b 100644 --- a/src/Builder/UuidBuilderInterface.php +++ b/src/Builder/UuidBuilderInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Builder; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\UuidInterface; /** - * UuidBuilderInterface builds instances UuidInterface + * A UUID builder builds instances of UuidInterface */ interface UuidBuilderInterface { /** - * Builds an instance of a UuidInterface + * Builds and returns 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; + * @param string[] $fields An array of fields from which to construct a UuidInterface instance; * see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure. - * @return UuidInterface + * + * @return UuidInterface Implementations may choose to return more specific + * instances of UUIDs that implement UuidInterface */ public function build(CodecInterface $codec, array $fields): UuidInterface; } diff --git a/src/Codec/CodecInterface.php b/src/Codec/CodecInterface.php index 8b34ac6..041a996 100644 --- a/src/Codec/CodecInterface.php +++ b/src/Codec/CodecInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Codec; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\UuidInterface; /** - * CodecInterface represents a UUID coder-decoder + * A codec encodes and decodes a UUID according to defined rules */ interface CodecInterface { /** - * Encodes a UuidInterface as a string representation of a UUID + * Returns a hexadecimal string representation of a UuidInterface + * + * @param UuidInterface $uuid The UUID for which to create a hexadecimal + * string representation * - * @param UuidInterface $uuid * @return string Hexadecimal string representation of a UUID */ public function encode(UuidInterface $uuid): string; /** - * Encodes a UuidInterface as a binary representation of a UUID + * Returns a binary string representation of a UuidInterface + * + * @param UuidInterface $uuid The UUID for which to create a binary string + * representation * - * @param UuidInterface $uuid * @return string Binary string representation of a UUID */ public function encodeBinary(UuidInterface $uuid): string; /** - * Decodes a string representation of a UUID into a UuidInterface object instance + * Returns a UuidInterface derived from a hexadecimal string representation * - * @param string $encodedUuid - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string $encodedUuid The hexadecimal string representation to + * convert into a UuidInterface instance + * + * @return UuidInterface An instance of a UUID decoded from a hexadecimal + * string representation */ public function decode(string $encodedUuid): UuidInterface; /** - * Decodes a binary representation of a UUID into a UuidInterface object instance + * Returns a UuidInterface derived from a binary string representation * - * @param string $bytes - * @return UuidInterface - * @throws InvalidUuidStringException - * @throws InvalidArgumentException if string has not 16 characters + * @param string $bytes The binary string representation to convert into a + * UuidInterface instance + * + * @return UuidInterface An instance of a UUID decoded from a binary string + * representation */ public function decodeBytes(string $bytes): UuidInterface; } diff --git a/src/Codec/GuidStringCodec.php b/src/Codec/GuidStringCodec.php index 24b434a..4328a1d 100644 --- a/src/Codec/GuidStringCodec.php +++ b/src/Codec/GuidStringCodec.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Codec; +use InvalidArgumentException; use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\UuidInterface; /** * GuidStringCodec encodes and decodes globally unique identifiers (GUID) * - * @link https://en.wikipedia.org/wiki/Globally_unique_identifier + * @link https://en.wikipedia.org/wiki/Globally_unique_identifier 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): string { $components = array_values($uuid->getFieldsHex()); - // Swap byte-order on the first three fields + // Swap byte-order on the first three fields. $this->swapFields($components); return vsprintf( @@ -43,12 +38,6 @@ class GuidStringCodec extends StringCodec ); } - /** - * 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): string { $components = array_values($uuid->getFieldsHex()); @@ -57,11 +46,9 @@ class GuidStringCodec extends StringCodec } /** - * Decodes a string representation of a GUID into a UuidInterface object instance - * - * @param string $encodedUuid - * @return UuidInterface * @throws InvalidUuidStringException + * + * @inheritDoc */ public function decode(string $encodedUuid): UuidInterface { @@ -73,11 +60,9 @@ class GuidStringCodec extends StringCodec } /** - * Decodes a binary representation of a GUID into a UuidInterface object instance + * @throws InvalidArgumentException if $bytes is an invalid length * - * @param string $bytes - * @return UuidInterface - * @throws InvalidUuidStringException + * @inheritDoc */ public function decodeBytes(string $bytes): UuidInterface { @@ -86,17 +71,18 @@ class GuidStringCodec extends StringCodec } /** - * Swaps fields to support GUID byte order + * Swap fields to support GUID byte order * - * @param array $components An array of UUID components (the UUID exploded on its dashes) - * @return void + * @param string[] $components An array of UUID components (the UUID exploded on its dashes) */ - protected function swapFields(array &$components) + private function swapFields(array &$components): void { $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]; } diff --git a/src/Codec/OrderedTimeCodec.php b/src/Codec/OrderedTimeCodec.php index e39416a..d5316fe 100644 --- a/src/Codec/OrderedTimeCodec.php +++ b/src/Codec/OrderedTimeCodec.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ + +declare(strict_types=1); + namespace Ramsey\Uuid\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. + * OrderedTimeCodec encodes and decodes a UUID, optimizing the byte order for + * more efficient storage + * + * For binary representations of version 1 UUID, this codec may be used to + * reorganize the time fields, making the UUID closer to sequential when storing + * the bytes. According to Percona, this optimization can improve database + * INSERTs and SELECTs using the UUID column as a key. + * + * The string representation of the UUID will remain unchanged. Only the binary + * representation is reordered. + * + * **PLEASE NOTE:** Binary representations of UUIDs encoded with this codec must + * be decoded with this codec. Decoding using another codec can result in + * malformed UUIDs. + * + * @link https://www.percona.com/blog/2014/12/19/store-uuid-optimized-way/ Storing UUID Values in MySQL */ class OrderedTimeCodec extends StringCodec { - /** - * Encodes a UuidInterface as an optimized binary representation of a UUID + * Returns a binary string representation of a UUID, with the timestamp + * fields rearranged for optimized storage * - * @param UuidInterface $uuid - * @return string Binary string representation of a UUID + * @inheritDoc */ public function encodeBinary(UuidInterface $uuid): string { @@ -46,22 +60,29 @@ class OrderedTimeCodec extends StringCodec } /** - * Decodes an optimized binary representation of a UUID into a UuidInterface object instance + * Returns a UuidInterface derived from an ordered-time binary string + * representation * - * @param string $bytes - * @return UuidInterface - * @throws InvalidArgumentException if string has not 16 characters + * @throws InvalidArgumentException if $bytes is an invalid length + * + * @inheritDoc */ public function decodeBytes(string $bytes): UuidInterface { if (strlen($bytes) !== 16) { - throw new InvalidArgumentException('$bytes string should contain 16 characters.'); + 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); + $hex = substr($hex, 8, 4) + . substr($hex, 12, 4) + . substr($hex, 4, 4) + . substr($hex, 0, 4) + . substr($hex, 16); return $this->decode($hex); } diff --git a/src/Codec/StringCodec.php b/src/Codec/StringCodec.php index 738ceb2..75e98fa 100644 --- a/src/Codec/StringCodec.php +++ b/src/Codec/StringCodec.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Codec; use InvalidArgumentException; @@ -33,21 +33,15 @@ class StringCodec implements CodecInterface private $builder; /** - * Constructs a StringCodec for use encoding and decoding UUIDs + * Constructs a StringCodec * - * @param UuidBuilderInterface $builder The UUID builder to use when encoding UUIDs + * @param UuidBuilderInterface $builder The 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): string { $fields = array_values($uuid->getFieldsHex()); @@ -58,23 +52,15 @@ class StringCodec implements CodecInterface ); } - /** - * 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): string { return (string) hex2bin($uuid->getHex()); } /** - * Decodes a string representation of a UUID into a UuidInterface object instance - * - * @param string $encodedUuid - * @return UuidInterface * @throws InvalidUuidStringException + * + * @inheritDoc */ public function decode(string $encodedUuid): UuidInterface { @@ -85,16 +71,16 @@ class StringCodec implements CodecInterface } /** - * Decodes a binary representation of a UUID into a UuidInterface object instance + * @throws InvalidArgumentException if $bytes is an invalid length * - * @param string $bytes - * @return UuidInterface - * @throws InvalidArgumentException if string has not 16 characters + * @inheritDoc */ public function decodeBytes(string $bytes): UuidInterface { if (strlen($bytes) !== 16) { - throw new InvalidArgumentException('$bytes string should contain 16 characters.'); + throw new InvalidArgumentException( + '$bytes string should contain 16 characters.' + ); } $hexUuid = unpack('H*', $bytes); @@ -104,10 +90,8 @@ class StringCodec implements CodecInterface /** * Returns the UUID builder - * - * @return UuidBuilderInterface */ - protected function getBuilder() + protected function getBuilder(): UuidBuilderInterface { return $this->builder; } @@ -115,18 +99,20 @@ class StringCodec implements CodecInterface /** * Returns an array of UUID components (the UUID exploded on its dashes) * - * @param string $encodedUuid - * @return array + * @param string $encodedUuid A hexadecimal string representation of a UUID + * + * @return string[] + * * @throws InvalidUuidStringException */ - protected function extractComponents($encodedUuid) + protected function extractComponents(string $encodedUuid): array { $nameParsed = str_replace([ 'urn:', 'uuid:', '{', '}', - '-' + '-', ], '', $encodedUuid); // We have stripped out the dashes and are breaking up the string using @@ -137,13 +123,15 @@ class StringCodec implements CodecInterface substr($nameParsed, 8, 4), substr($nameParsed, 12, 4), substr($nameParsed, 16, 4), - substr($nameParsed, 20) + substr($nameParsed, 20), ]; $nameParsed = implode('-', $components); if (!Uuid::isValid($nameParsed)) { - throw new InvalidUuidStringException('Invalid UUID string: ' . $encodedUuid); + throw new InvalidUuidStringException( + 'Invalid UUID string: ' . $encodedUuid + ); } return $components; @@ -153,10 +141,13 @@ class StringCodec implements CodecInterface * Returns the fields that make up this UUID * * @see \Ramsey\Uuid\UuidInterface::getFieldsHex() - * @param array $components - * @return array + * + * @param string[] $components An array of hexadecimal strings representing + * the fields of an RFC 4122 UUID + * + * @return string[] */ - protected function getFields(array $components) + protected function getFields(array $components): array { return [ 'time_low' => str_pad($components[0], 8, '0', STR_PAD_LEFT), @@ -164,7 +155,7 @@ class StringCodec implements CodecInterface '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) + 'node' => str_pad($components[4], 12, '0', STR_PAD_LEFT), ]; } } diff --git a/src/Codec/TimestampFirstCombCodec.php b/src/Codec/TimestampFirstCombCodec.php index 006c3bc..997146d 100644 --- a/src/Codec/TimestampFirstCombCodec.php +++ b/src/Codec/TimestampFirstCombCodec.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ + +declare(strict_types=1); + namespace Ramsey\Uuid\Codec; +use InvalidArgumentException; use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\UuidInterface; /** - * TimestampFirstCombCodec encodes and decodes COMB UUIDs which have the timestamp as the first 48 bits. - * To be used with MySQL, PostgreSQL, Oracle. + * TimestampFirstCombCodec encodes and decodes COMBs, with the timestamp as the + * first 48 bits + * + * In contrast with the TimestampLastCombCodec, the TimestampFirstCombCodec + * adds the timestamp to the first 48 bits of the COMB. To generate a + * timestamp-first COMB, set the TimestampFirstCombCodec as the codec, along + * with the CombGenerator as the random generator. + * + * ``` php + * $factory = new UuidFactory(); + * + * $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder())); + * + * $factory->setRandomGenerator(new CombGenerator( + * $factory->getRandomGenerator(), + * $factory->getNumberConverter() + * )); + * + * $timestampFirstComb = $factory->uuid4(); + * ``` + * + * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys */ 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): string { $sixPieceComponents = array_values($uuid->getFieldsHex()); @@ -41,13 +56,6 @@ class TimestampFirstCombCodec extends StringCodec ); } - /** - * 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): string { $stringEncoding = $this->encode($uuid); @@ -56,12 +64,9 @@ class TimestampFirstCombCodec extends StringCodec } /** - * Decodes a string representation of timestamp first COMB UUID into a UuidInterface object instance - * - * @param string $encodedUuid - * - * @return UuidInterface * @throws InvalidUuidStringException + * + * @inheritDoc */ public function decode(string $encodedUuid): UuidInterface { @@ -73,12 +78,9 @@ class TimestampFirstCombCodec extends StringCodec } /** - * Decodes a binary representation of timestamp first COMB UUID into a UuidInterface object instance + * @throws InvalidArgumentException if $bytes is an invalid length * - * @param string $bytes - * - * @return UuidInterface - * @throws InvalidUuidStringException + * @inheritDoc */ public function decodeBytes(string $bytes): UuidInterface { @@ -88,14 +90,13 @@ class TimestampFirstCombCodec extends StringCodec /** * 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 + * @param string[] $components An array of UUID components (the UUID exploded on its dashes) */ - protected function swapTimestampAndRandomBits(array &$components) + private function swapTimestampAndRandomBits(array &$components): void { $last48Bits = $components[4]; - if (count($components) == 6) { + + if (count($components) === 6) { $last48Bits = $components[5]; $components[5] = $components[0] . $components[1]; } else { diff --git a/src/Codec/TimestampLastCombCodec.php b/src/Codec/TimestampLastCombCodec.php index 240f613..2cf595d 100644 --- a/src/Codec/TimestampLastCombCodec.php +++ b/src/Codec/TimestampLastCombCodec.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ + +declare(strict_types=1); + namespace Ramsey\Uuid\Codec; /** - * TimestampLastCombCodec encodes and decodes COMB UUIDs which have the timestamp as the last 48 bits. - * To be used with MSSQL. + * TimestampLastCombCodec encodes and decodes COMBs, with the timestamp as the + * last 48 bits + * + * The CombGenerator when used with the StringCodec (and, by proxy, the + * TimestampLastCombCodec) adds the timestamp to the last 48 bits of the COMB. + * The TimestampLastCombCodec is provided for the sake of consistency. In + * practice, it is identical to the standard StringCodec but, it may be used + * with the CombGenerator for additional context when reading code. + * + * Consider the following code. By default, the codec used by UuidFactory is the + * StringCodec, but here, we explicitly set the TimestampLastCombCodec. It is + * redundant, but it is clear that we intend this COMB to be generated with the + * timestamp appearing at the end. + * + * ``` php + * $factory = new UuidFactory(); + * + * $factory->setCodec(new TimestampLastCombCodec($factory->getUuidBuilder())); + * + * $factory->setRandomGenerator(new CombGenerator( + * $factory->getRandomGenerator(), + * $factory->getNumberConverter() + * )); + * + * $timestampLastComb = $factory->uuid4(); + * ``` + * + * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys */ class TimestampLastCombCodec extends StringCodec { diff --git a/src/Converter/DependencyCheckTrait.php b/src/Converter/DependencyCheckTrait.php index fcc531f..a4e4a90 100644 --- a/src/Converter/DependencyCheckTrait.php +++ b/src/Converter/DependencyCheckTrait.php @@ -8,11 +8,10 @@ * * @copyright Copyright (c) Ben Ramsey * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter; use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; @@ -26,7 +25,6 @@ trait DependencyCheckTrait * Returns boolean true if the current build of PHP is a 64-bit build, * throws UnsatisfiedDependencyException otherwise * - * @return bool * @throws UnsatisfiedDependencyException if PHP is not 64-bit */ private function check64BitPhp(): bool @@ -44,7 +42,6 @@ trait DependencyCheckTrait * Returns boolean true if the GMP extension is loaded, throws * UnsatisfiedDependencyException otherwise * - * @return bool * @throws UnsatisfiedDependencyException if GMP is not loaded */ private function checkGmpExtension(): bool @@ -62,7 +59,6 @@ trait DependencyCheckTrait * Returns boolean true if the moontoast/math library is present, throws * UnsatisfiedDependencyException otherwise * - * @return bool * @throws UnsatisfiedDependencyException if moontoast/math is not loaded */ private function checkMoontoastMathLibrary(): bool diff --git a/src/Converter/Number/BigNumberConverter.php b/src/Converter/Number/BigNumberConverter.php index 941807c..419ef19 100644 --- a/src/Converter/Number/BigNumberConverter.php +++ b/src/Converter/Number/BigNumberConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Number; use InvalidArgumentException; @@ -31,16 +31,10 @@ class BigNumberConverter implements NumberConverterInterface use NumberStringTrait; /** - * Converts a hexadecimal number into an string integer representation of - * the number - * - * The integer representation returned is a string representation of the - * integer, to accommodate unsigned integers greater than PHP_INT_MAX. - * - * @param string $hex The hexadecimal string representation to convert - * @return string * @throws InvalidArgumentException if $hex is not a hexadecimal string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function fromHex(string $hex): string { @@ -51,15 +45,10 @@ class BigNumberConverter implements NumberConverterInterface } /** - * Converts a string integer representation into a hexadecimal string - * representation of the number - * - * @param string $number A string integer representation to convert; this - * must be a numeric string to accommodate unsigned integers greater - * than PHP_INT_MAX. - * @return string Hexadecimal string * @throws InvalidArgumentException if $integer is not an integer string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function toHex(string $number): string { diff --git a/src/Converter/Number/DegradedNumberConverter.php b/src/Converter/Number/DegradedNumberConverter.php index a9bf141..7f9973d 100644 --- a/src/Converter/Number/DegradedNumberConverter.php +++ b/src/Converter/Number/DegradedNumberConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Number; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; use Ramsey\Uuid\Converter\NumberConverterInterface; +use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; /** * DegradedNumberConverter is chosen if all other options for large integer @@ -25,15 +25,9 @@ use Ramsey\Uuid\Converter\NumberConverterInterface; class DegradedNumberConverter implements NumberConverterInterface { /** - * Converts a hexadecimal number into an string integer representation of - * the number - * - * The integer representation returned is a string representation of the - * integer, to accommodate unsigned integers greater than PHP_INT_MAX. - * - * @param string $hex The hexadecimal string representation to convert - * @return string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function fromHex(string $hex): string { @@ -46,14 +40,9 @@ class DegradedNumberConverter implements NumberConverterInterface } /** - * Converts a string integer representation into a hexadecimal string - * representation of the number - * - * @param string $number A string integer representation to convert; this - * must be a numeric string to accommodate unsigned integers greater - * than PHP_INT_MAX. - * @return string Hexadecimal string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function toHex(string $number): string { diff --git a/src/Converter/Number/GmpConverter.php b/src/Converter/Number/GmpConverter.php index e275c76..7c444b7 100644 --- a/src/Converter/Number/GmpConverter.php +++ b/src/Converter/Number/GmpConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Number; use InvalidArgumentException; @@ -31,12 +31,10 @@ class GmpConverter implements NumberConverterInterface use NumberStringTrait; /** - * Converts a hexadecimal string representation into a decimal string representation - * - * @param string $hex The hexadecimal string representation to convert - * @return string * @throws InvalidArgumentException if $hex is not a hexadecimal string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function fromHex(string $hex): string { @@ -49,14 +47,10 @@ class GmpConverter implements NumberConverterInterface } /** - * Converts an integer or a decimal string representation into a hexadecimal string representation - * - * @param string $number A string integer representation to convert; this - * must be a numeric string to accommodate unsigned integers greater - * than PHP_INT_MAX. - * @return string Hexadecimal string * @throws InvalidArgumentException if $integer is not an integer string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function toHex(string $number): string { diff --git a/src/Converter/NumberConverterInterface.php b/src/Converter/NumberConverterInterface.php index 3a29e8d..8f0d587 100644 --- a/src/Converter/NumberConverterInterface.php +++ b/src/Converter/NumberConverterInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; - /** - * NumberConverterInterface converts UUIDs from hexadecimal characters into + * A number converter converts UUIDs from hexadecimal characters into * representations of integers and vice versa */ interface NumberConverterInterface @@ -31,9 +28,8 @@ interface NumberConverterInterface * integer, to accommodate unsigned integers greater than PHP_INT_MAX. * * @param string $hex The hexadecimal string representation to convert - * @return string - * @throws InvalidArgumentException if $hex is not a hexadecimal string - * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @return string String representation of an integer */ public function fromHex(string $hex): string; @@ -44,9 +40,8 @@ interface NumberConverterInterface * @param string $number A string integer representation to convert; this * must be a numeric string to accommodate unsigned integers greater * than PHP_INT_MAX. + * * @return string Hexadecimal string - * @throws InvalidArgumentException if $integer is not an integer string - * @throws UnsatisfiedDependencyException if the chosen converter is not present */ public function toHex(string $number): string; } diff --git a/src/Converter/NumberStringTrait.php b/src/Converter/NumberStringTrait.php index 9454744..bc8c56c 100644 --- a/src/Converter/NumberStringTrait.php +++ b/src/Converter/NumberStringTrait.php @@ -8,11 +8,10 @@ * * @copyright Copyright (c) Ben Ramsey * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter; use InvalidArgumentException; @@ -29,7 +28,11 @@ trait NumberStringTrait * * @param string $integer The string integer value to check * @param string $param The name of the parameter being checked - * @return bool + * + * @return bool True if $integer contains only digits, false otherwise + * + * @throws InvalidArgumentException if the string $integer does not contain + * only digits for a positive or negative integer */ private function checkIntegerString(string $integer, string $param): bool { @@ -54,7 +57,11 @@ trait NumberStringTrait * * @param string $hex The hexadecimal string value to check * @param string $param The name of the parameter being checked - * @return bool + * + * @return bool True if $hex contains only hexadecimal characters, false otherwise + * + * @throws InvalidArgumentException if the string $hex does not contain only + * hexadecimal characters */ private function checkHexadecimalString(string $hex, string $param): bool { diff --git a/src/Converter/Time/BigNumberTimeConverter.php b/src/Converter/Time/BigNumberTimeConverter.php index 10d916f..dfc7c26 100644 --- a/src/Converter/Time/BigNumberTimeConverter.php +++ b/src/Converter/Time/BigNumberTimeConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Time; use InvalidArgumentException; @@ -32,15 +32,10 @@ class BigNumberTimeConverter implements TimeConverterInterface use NumberStringTrait; /** - * 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 * @throws InvalidArgumentException if $seconds or $microseconds are not integer strings * @throws UnsatisfiedDependencyException if the chosen converter is not present - * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 + * + * @inheritDoc */ public function calculateTime(string $seconds, string $microSeconds): array { @@ -71,14 +66,10 @@ class BigNumberTimeConverter implements TimeConverterInterface } /** - * Converts a timestamp extracted from a UUID to a unix timestamp - * - * @param string $timestamp A string integer representation of a timestamp; - * this must be a numeric string to accommodate unsigned integers - * greater than PHP_INT_MAX. - * @return string * @throws InvalidArgumentException if $timestamp is not an integer string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function convertTime(string $timestamp): string { diff --git a/src/Converter/Time/DegradedTimeConverter.php b/src/Converter/Time/DegradedTimeConverter.php index 8653bab..53dff3b 100644 --- a/src/Converter/Time/DegradedTimeConverter.php +++ b/src/Converter/Time/DegradedTimeConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Time; use Ramsey\Uuid\Converter\TimeConverterInterface; @@ -25,14 +25,9 @@ use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; class DegradedTimeConverter 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 guaranteed to contain `low`, `mid`, and `high` keys * @throws UnsatisfiedDependencyException if the chosen converter is not present - * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 + * + * @inheritDoc */ public function calculateTime(string $seconds, string $microSeconds): array { @@ -45,13 +40,9 @@ class DegradedTimeConverter implements TimeConverterInterface } /** - * Converts a timestamp extracted from a UUID to a unix timestamp - * - * @param string $timestamp A string integer representation of a timestamp; - * this must be a numeric string to accommodate unsigned integers - * greater than PHP_INT_MAX. - * @return string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function convertTime(string $timestamp): string { diff --git a/src/Converter/Time/GmpTimeConverter.php b/src/Converter/Time/GmpTimeConverter.php index fd15bdf..b5fbe10 100644 --- a/src/Converter/Time/GmpTimeConverter.php +++ b/src/Converter/Time/GmpTimeConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Time; use InvalidArgumentException; @@ -30,15 +30,10 @@ class GmpTimeConverter implements TimeConverterInterface use NumberStringTrait; /** - * 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 * @throws InvalidArgumentException if $seconds or $microseconds are not integer strings * @throws UnsatisfiedDependencyException if the chosen converter is not present - * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 + * + * @inheritDoc */ public function calculateTime(string $seconds, string $microSeconds): array { @@ -65,14 +60,10 @@ class GmpTimeConverter implements TimeConverterInterface } /** - * Converts a timestamp extracted from a UUID to a unix timestamp - * - * @param string $timestamp A string integer representation of a timestamp; - * this must be a numeric string to accommodate unsigned integers - * greater than PHP_INT_MAX. - * @return string * @throws InvalidArgumentException if $timestamp is not an integer string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function convertTime(string $timestamp): string { @@ -82,7 +73,7 @@ class GmpTimeConverter implements TimeConverterInterface $timestamp = gmp_init($timestamp); $timestamp = gmp_sub($timestamp, gmp_init('122192928000000000')); $d = gmp_init('10000000'); - list($q, $r) = gmp_div_qr($timestamp, $d); + [$q, $r] = gmp_div_qr($timestamp, $d); // If $r >= $d/2, we have to round up $sign = gmp_sign(gmp_sub($d, gmp_add($r, $r))); diff --git a/src/Converter/Time/PhpTimeConverter.php b/src/Converter/Time/PhpTimeConverter.php index b76599d..7f621a3 100644 --- a/src/Converter/Time/PhpTimeConverter.php +++ b/src/Converter/Time/PhpTimeConverter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter\Time; use InvalidArgumentException; @@ -31,15 +31,10 @@ class PhpTimeConverter implements TimeConverterInterface use NumberStringTrait; /** - * 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 * @throws InvalidArgumentException if $seconds or $microseconds are not integer strings * @throws UnsatisfiedDependencyException if the chosen converter is not present - * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 + * + * @inheritDoc */ public function calculateTime(string $seconds, string $microSeconds): array { @@ -59,14 +54,10 @@ class PhpTimeConverter implements TimeConverterInterface } /** - * Converts a timestamp extracted from a UUID to a unix timestamp - * - * @param string $timestamp A string integer representation of a timestamp; - * this must be a numeric string to accommodate unsigned integers - * greater than PHP_INT_MAX. - * @return string * @throws InvalidArgumentException if $timestamp is not an integer string * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @inheritDoc */ public function convertTime(string $timestamp): string { diff --git a/src/Converter/TimeConverterInterface.php b/src/Converter/TimeConverterInterface.php index 8861eb1..c089538 100644 --- a/src/Converter/TimeConverterInterface.php +++ b/src/Converter/TimeConverterInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Converter; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; - /** - * TimeConverterInterface provides facilities for converting parts of time into - * representations that may be used in UUIDs + * A time converter converts timestamps into representations that may be used + * in UUIDs */ interface TimeConverterInterface { @@ -27,24 +24,25 @@ 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 + * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 RFC 4122, § 4.2.2: Generation Details + * + * @param string $seconds A string representation of the number of seconds + * since the Unix epoch for the time to calculate + * @param string $microSeconds A string representation of the micro-seconds + * associated with the time to calculate + * * @return string[] An array guaranteed to contain `low`, `mid`, and `hi` keys - * @throws InvalidArgumentException if $seconds or $microseconds are not integer strings - * @throws UnsatisfiedDependencyException if the chosen converter is not present - * @link http://tools.ietf.org/html/rfc4122#section-4.2.2 */ public function calculateTime(string $seconds, string $microSeconds): array; /** - * Converts a timestamp extracted from a UUID to a unix timestamp + * Converts a timestamp extracted from a UUID to a Unix timestamp * * @param string $timestamp A string integer representation of a timestamp; * this must be a numeric string to accommodate unsigned integers * greater than PHP_INT_MAX. - * @return string - * @throws InvalidArgumentException if $timestamp is not an integer string - * @throws UnsatisfiedDependencyException if the chosen converter is not present + * + * @return string String representation of an integer */ public function convertTime(string $timestamp): string; } diff --git a/src/DegradedUuid.php b/src/DegradedUuid.php index c53154b..5810f36 100644 --- a/src/DegradedUuid.php +++ b/src/DegradedUuid.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid; use DateTimeImmutable; use DateTimeInterface; -use Moontoast\Math\BigNumber; use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; use Ramsey\Uuid\Exception\UnsupportedOperationException; /** * DegradedUuid represents an RFC 4122 UUID on 32-bit systems * - * @see Uuid + * Some of the functionality of a DegradedUuid is not present or degraded, since + * 32-bit systems are unable to perform the necessary mathematical operations or + * represent the integers appropriately. */ class DegradedUuid extends Uuid { /** - * @inheritdoc + * @return DateTimeImmutable An immutable instance of DateTimeInterface + * + * @throws UnsupportedOperationException if UUID is not time-based */ public function getDateTime(): DateTimeInterface { - if ($this->getVersion() != 1) { + if ($this->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } @@ -43,11 +46,9 @@ class DegradedUuid extends Uuid } /** - * For degraded UUIDs, throws an `UnsatisfiedDependencyException` when - * called on a 32-bit system - * - * @return array * @throws UnsatisfiedDependencyException if called on a 32-bit system + * + * @inheritDoc */ public function getFields(): array { @@ -59,10 +60,6 @@ class DegradedUuid extends Uuid } /** - * For degraded UUIDs, throws an `UnsatisfiedDependencyException` when - * called on a 32-bit system - * - * @return int * @throws UnsatisfiedDependencyException if called on a 32-bit system */ public function getNode(): int @@ -76,10 +73,6 @@ class DegradedUuid extends Uuid } /** - * For degraded UUIDs, throws an `UnsatisfiedDependencyException` when - * called on a 32-bit system - * - * @return int * @throws UnsatisfiedDependencyException if called on a 32-bit system */ public function getTimeLow(): int @@ -93,16 +86,12 @@ class DegradedUuid extends Uuid } /** - * For degraded UUIDs, throws an `UnsatisfiedDependencyException` when - * called on a 32-bit system - * - * @return int * @throws UnsatisfiedDependencyException if called on a 32-bit system - * @throws UnsupportedOperationException If this UUID is not a version 1 UUID + * @throws UnsupportedOperationException if UUID is not time-based */ public function getTimestamp(): int { - if ($this->getVersion() != 1) { + if ($this->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } diff --git a/src/Exception/InvalidUuidStringException.php b/src/Exception/InvalidUuidStringException.php index 7df0e8c..2f98181 100644 --- a/src/Exception/InvalidUuidStringException.php +++ b/src/Exception/InvalidUuidStringException.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Exception; use InvalidArgumentException; diff --git a/src/Exception/UnsatisfiedDependencyException.php b/src/Exception/UnsatisfiedDependencyException.php index 89c7396..7a3657d 100644 --- a/src/Exception/UnsatisfiedDependencyException.php +++ b/src/Exception/UnsatisfiedDependencyException.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Exception; use RuntimeException; diff --git a/src/Exception/UnsupportedOperationException.php b/src/Exception/UnsupportedOperationException.php index 4340947..09ed1c5 100644 --- a/src/Exception/UnsupportedOperationException.php +++ b/src/Exception/UnsupportedOperationException.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Exception; use RuntimeException; diff --git a/src/FeatureSet.php b/src/FeatureSet.php index 6aead22..641589d 100644 --- a/src/FeatureSet.php +++ b/src/FeatureSet.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid; use Ramsey\Uuid\Builder\DefaultUuidBuilder; @@ -20,32 +20,34 @@ use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Codec\GuidStringCodec; use Ramsey\Uuid\Codec\StringCodec; -use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\Number\BigNumberConverter; use Ramsey\Uuid\Converter\Number\DegradedNumberConverter; use Ramsey\Uuid\Converter\Number\GmpConverter; -use Ramsey\Uuid\Converter\TimeConverterInterface; +use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\Time\BigNumberTimeConverter; use Ramsey\Uuid\Converter\Time\DegradedTimeConverter; use Ramsey\Uuid\Converter\Time\GmpTimeConverter; use Ramsey\Uuid\Converter\Time\PhpTimeConverter; +use Ramsey\Uuid\Converter\TimeConverterInterface; use Ramsey\Uuid\Generator\PeclUuidTimeGenerator; use Ramsey\Uuid\Generator\RandomGeneratorFactory; use Ramsey\Uuid\Generator\RandomGeneratorInterface; use Ramsey\Uuid\Generator\TimeGeneratorFactory; use Ramsey\Uuid\Generator\TimeGeneratorInterface; -use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\Node\FallbackNodeProvider; use Ramsey\Uuid\Provider\Node\RandomNodeProvider; use Ramsey\Uuid\Provider\Node\SystemNodeProvider; -use Ramsey\Uuid\Provider\TimeProviderInterface; +use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\Time\SystemTimeProvider; +use Ramsey\Uuid\Provider\TimeProviderInterface; use Ramsey\Uuid\Validator\Validator; use Ramsey\Uuid\Validator\ValidatorInterface; /** * FeatureSet detects and exposes available features in the current environment - * (32- or 64-bit, available dependencies, etc.) + * + * A feature set is used by UuidFactory to determine the available features and + * capabilities of the environment. */ class FeatureSet { @@ -95,10 +97,9 @@ class FeatureSet private $numberConverter; /** - * The time converter to use for converting timestamps extracted from UUIDs to unix timestamps * @var TimeConverterInterface */ - protected $timeConverter; + private $timeConverter; /** * @var RandomGeneratorInterface @@ -116,28 +117,25 @@ class FeatureSet private $validator; /** - * 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 + * @param bool $useGuids True build UUIDs using the GuidStringCodec + * @param bool $force32Bit True to force the use of 32-bit functionality * (primarily for testing purposes) - * @param bool $forceNoBigNumber 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` + * @param bool $forceNoBigNumber True to disable the use of moontoast/math + * (primarily for testing purposes) + * @param bool $ignoreSystemNode True to disable attempts to check for the + * system node ID (primarily for testing purposes) + * @param bool $enablePecl True to enable the use of the PeclUuidTimeGenerator * to generate version 1 UUIDs - * @param bool $forceNoGmp Whether to disable the use of the GMP PHP-extension - * (primarily for testing purposes) + * @param bool $forceNoGmp True to disable the use of ext-gmp (primarily + * for testing purposes) */ public function __construct( - $useGuids = false, - $force32Bit = false, - $forceNoBigNumber = false, - $ignoreSystemNode = false, - $enablePecl = false, - $forceNoGmp = false + bool $useGuids = false, + bool $force32Bit = false, + bool $forceNoBigNumber = false, + bool $ignoreSystemNode = false, + bool $enablePecl = false, + bool $forceNoGmp = false ) { $this->disableBigNumber = $forceNoBigNumber; $this->disableGmp = $forceNoGmp; @@ -152,13 +150,11 @@ class FeatureSet $this->nodeProvider = $this->buildNodeProvider(); $this->randomGenerator = $this->buildRandomGenerator(); $this->setTimeProvider(new SystemTimeProvider()); - $this->validator = new Validator; + $this->validator = new Validator(); } /** * Returns the builder configured for this environment - * - * @return UuidBuilderInterface */ public function getBuilder(): UuidBuilderInterface { @@ -166,9 +162,7 @@ class FeatureSet } /** - * Returns the UUID UUID coder-decoder configured for this environment - * - * @return CodecInterface + * Returns the codec configured for this environment */ public function getCodec(): CodecInterface { @@ -176,9 +170,7 @@ class FeatureSet } /** - * Returns the system node ID provider configured for this environment - * - * @return NodeProviderInterface + * Returns the node provider configured for this environment */ public function getNodeProvider(): NodeProviderInterface { @@ -187,8 +179,6 @@ class FeatureSet /** * Returns the number converter configured for this environment - * - * @return NumberConverterInterface */ public function getNumberConverter(): NumberConverterInterface { @@ -196,9 +186,7 @@ class FeatureSet } /** - * Returns the random UUID generator configured for this environment - * - * @return RandomGeneratorInterface + * Returns the random generator configured for this environment */ public function getRandomGenerator(): RandomGeneratorInterface { @@ -206,9 +194,7 @@ class FeatureSet } /** - * Returns the time-based UUID generator configured for this environment - * - * @return TimeGeneratorInterface + * Returns the time generator configured for this environment */ public function getTimeGenerator(): TimeGeneratorInterface { @@ -216,9 +202,7 @@ class FeatureSet } /** - * Returns the validator to use for this environment - * - * @return ValidatorInterface + * Returns the validator configured for this environment */ public function getValidator(): ValidatorInterface { @@ -226,35 +210,27 @@ class FeatureSet } /** - * Sets the time provider for use in this environment - * - * @param TimeProviderInterface $timeProvider - * @return void + * Sets the time provider to use in this environment */ - public function setTimeProvider(TimeProviderInterface $timeProvider) + public function setTimeProvider(TimeProviderInterface $timeProvider): void { $this->timeGenerator = $this->buildTimeGenerator($timeProvider); } /** * Set the validator to use in this environment - * - * @param ValidatorInterface $validator - * @return void */ - public function setValidator(ValidatorInterface $validator) + public function setValidator(ValidatorInterface $validator): void { $this->validator = $validator; } /** - * Determines which UUID coder-decoder to use and returns the configured - * codec for this environment + * Returns a codec configured for this environment * - * @param bool $useGuids Whether to build UUIDs using the `GuidStringCodec` - * @return CodecInterface + * @param bool $useGuids Whether to build UUIDs using the GuidStringCodec */ - protected function buildCodec(bool $useGuids = false): CodecInterface + private function buildCodec(bool $useGuids = false): CodecInterface { if ($useGuids) { return new GuidStringCodec($this->builder); @@ -264,12 +240,9 @@ class FeatureSet } /** - * Determines which system node ID provider to use and returns the configured - * system node ID provider for this environment - * - * @return NodeProviderInterface + * Returns a node provider configured for this environment */ - protected function buildNodeProvider(): NodeProviderInterface + private function buildNodeProvider(): NodeProviderInterface { if ($this->ignoreSystemNode) { return new RandomNodeProvider(); @@ -277,17 +250,14 @@ class FeatureSet return new FallbackNodeProvider([ new SystemNodeProvider(), - new RandomNodeProvider() + new RandomNodeProvider(), ]); } /** - * Determines which number converter to use and returns the configured - * number converter for this environment - * - * @return NumberConverterInterface + * Returns a number converter configured for this environment */ - protected function buildNumberConverter(): NumberConverterInterface + private function buildNumberConverter(): NumberConverterInterface { if ($this->hasGmp()) { return new GmpConverter(); @@ -301,24 +271,20 @@ class FeatureSet } /** - * Determines which random UUID generator to use and returns the configured - * random UUID generator for this environment - * - * @return RandomGeneratorInterface + * Returns a random generator configured for this environment */ - protected function buildRandomGenerator(): RandomGeneratorInterface + private function buildRandomGenerator(): RandomGeneratorInterface { return (new RandomGeneratorFactory())->getGenerator(); } /** - * Determines which time-based UUID generator to use and returns the configured - * time-based UUID generator for this environment + * Returns a time generator configured for this environment * - * @param TimeProviderInterface $timeProvider - * @return TimeGeneratorInterface + * @param TimeProviderInterface $timeProvider The time provider to use with + * the time generator */ - protected function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGeneratorInterface + private function buildTimeGenerator(TimeProviderInterface $timeProvider): TimeGeneratorInterface { if ($this->enablePecl) { return new PeclUuidTimeGenerator(); @@ -332,12 +298,9 @@ class FeatureSet } /** - * Determines which time converter to use and returns the configured - * time converter for this environment - * - * @return TimeConverterInterface + * Returns a time converter configured for this environment */ - protected function buildTimeConverter(): TimeConverterInterface + private function buildTimeConverter(): TimeConverterInterface { if ($this->is64BitSystem()) { return new PhpTimeConverter(); @@ -355,12 +318,9 @@ class FeatureSet } /** - * Determines which UUID builder to use and returns the configured UUID - * builder for this environment - * - * @return UuidBuilderInterface + * Returns a UUID builder configured for this environment */ - protected function buildUuidBuilder(): UuidBuilderInterface + private function buildUuidBuilder(): UuidBuilderInterface { if ($this->is64BitSystem()) { return new DefaultUuidBuilder($this->numberConverter, $this->timeConverter); @@ -370,32 +330,26 @@ class FeatureSet } /** - * Returns true if the system has `Moontoast\Math\BigNumber` - * - * @return bool + * Returns true if moontoast/math is available */ - protected function hasBigNumber(): bool + private function hasBigNumber(): bool { return class_exists('Moontoast\Math\BigNumber') && !$this->disableBigNumber; } /** - * Returns true if the system has the GMP PHP-extension - * - * @return bool + * Returns true if ext-gmp is available */ - protected function hasGmp(): bool + private function hasGmp(): bool { return extension_loaded('gmp') && !$this->disableGmp; } /** - * Returns true if the system is 64-bit, false otherwise - * - * @return bool + * Returns true if the PHP build is 64-bit */ - protected function is64BitSystem(): bool + private function is64BitSystem(): bool { - return PHP_INT_SIZE == 8 && !$this->disable64Bit; + return PHP_INT_SIZE === 8 && !$this->disable64Bit; } } diff --git a/src/Generator/CombGenerator.php b/src/Generator/CombGenerator.php index 386e0e5..303f2a5 100644 --- a/src/Generator/CombGenerator.php +++ b/src/Generator/CombGenerator.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; -use Exception; use InvalidArgumentException; use Ramsey\Uuid\Converter\NumberConverterInterface; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; /** - * CombGenerator provides functionality to generate COMB (combined GUID/timestamp) - * sequential UUIDs + * CombGenerator generates COMBs (combined UUID/timestamp) * - * @link https://en.wikipedia.org/wiki/Globally_unique_identifier#Sequential_algorithms + * The CombGenerator, when used with the StringCodec (and, by proxy, the + * TimestampLastCombCodec) or the TimestampFirstCombCodec, combines the current + * timestamp with a UUID (hence the name "COMB"). The timestamp either appears + * as the first or last 48 bits of the COMB, depending on the codec used. + * + * By default, COMBs will have the timestamp set as the last 48 bits of the + * identifier. + * + * ``` php + * $factory = new UuidFactory(); + * + * $factory->setRandomGenerator(new CombGenerator( + * $factory->getRandomGenerator(), + * $factory->getNumberConverter() + * )); + * + * $comb = $factory->uuid4(); + * ``` + * + * To generate a COMB with the timestamp as the first 48 bits, set the + * TimestampFirstCombCodec as the codec. + * + * ``` php + * $factory->setCodec(new TimestampFirstCombCodec($factory->getUuidBuilder())); + * ``` + * + * @link https://www.informit.com/articles/printerfriendly/25862 The Cost of GUIDs as Primary Keys */ class CombGenerator implements RandomGeneratorInterface { - const TIMESTAMP_BYTES = 6; + public const TIMESTAMP_BYTES = 6; /** * @var RandomGeneratorInterface @@ -39,48 +62,52 @@ class CombGenerator implements RandomGeneratorInterface */ 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) - { + public function __construct( + RandomGeneratorInterface $generator, + NumberConverterInterface $numberConverter + ) { $this->converter = $numberConverter; $this->randomGenerator = $generator; } /** - * Generates a string of binary data of the specified length + * @throws InvalidArgumentException if $length is not a positive integer + * greater than or equal to CombGenerator::TIMESTAMP_BYTES * - * @param int $length The number of bytes of random binary data to generate - * @return string A binary string - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException if length is not a positive integer - * @throws Exception + * @inheritDoc */ public function generate(int $length): string { if ($length < self::TIMESTAMP_BYTES || $length < 0) { - throw new InvalidArgumentException('Length must be a positive integer.'); + throw new InvalidArgumentException( + 'Length must be a positive integer greater than or equal to ' . self::TIMESTAMP_BYTES + ); } $hash = ''; - if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) { $hash = $this->randomGenerator->generate($length - self::TIMESTAMP_BYTES); } - $lsbTime = str_pad($this->converter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT); + $lsbTime = str_pad( + $this->converter->toHex($this->timestamp()), + self::TIMESTAMP_BYTES * 2, + '0', + STR_PAD_LEFT + ); - return (string) hex2bin(str_pad(bin2hex((string) $hash), $length - self::TIMESTAMP_BYTES, '0') . $lsbTime); + return (string) hex2bin( + str_pad( + bin2hex((string) $hash), + $length - self::TIMESTAMP_BYTES, + '0' + ) + . $lsbTime + ); } /** - * Returns current timestamp as integer, precise to 0.00001 seconds - * - * @return string + * Returns current timestamp a string integer, precise to 0.00001 seconds */ private function timestamp(): string { diff --git a/src/Generator/DefaultTimeGenerator.php b/src/Generator/DefaultTimeGenerator.php index e6670a9..c7e36b6 100644 --- a/src/Generator/DefaultTimeGenerator.php +++ b/src/Generator/DefaultTimeGenerator.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; -use Exception; use InvalidArgumentException; use Ramsey\Uuid\BinaryUtils; use Ramsey\Uuid\Converter\TimeConverterInterface; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; 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 + * DefaultTimeGenerator generates strings of binary data based on a node ID, + * clock sequence, and the current time */ class DefaultTimeGenerator implements TimeGeneratorInterface { @@ -44,14 +41,6 @@ class DefaultTimeGenerator implements TimeGeneratorInterface */ 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, @@ -63,34 +52,21 @@ class DefaultTimeGenerator implements TimeGeneratorInterface } /** - * Generate a version 1 UUID from a host ID, sequence number, and the current time + * @throws InvalidArgumentException if the parameters contain invalid values * - * 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 - * @throws UnsatisfiedDependencyException if called on a 32-bit system and - * `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception if it was not possible to gather sufficient entropy + * @inheritDoc */ - public function generate($node = null, int $clockSeq = null): string + public function generate($node = null, ?int $clockSeq = null): string { $node = $this->getValidNode($node); if ($clockSeq === null) { - // Not using "stable storage"; see RFC 4122, Section 4.2.1.1 + // This does not use "stable storage"; see RFC 4122, Section 4.2.1.1. $clockSeq = random_int(0, 0x3fff); } // Create a 60-bit time value as a count of 100-nanosecond intervals - // since 00:00:00.00, 15 October 1582 + // since 00:00:00.00, 15 October 1582. $timeOfDay = $this->timeProvider->currentTime(); $uuidTime = $this->timeConverter->calculateTime( (string) ($timeOfDay['sec'] ?? ''), @@ -120,17 +96,18 @@ class DefaultTimeGenerator implements TimeGeneratorInterface * the node ID (usually a MAC address) * * @param string|int|null $node A node value that may be used to override the node provider + * * @return string Hexadecimal representation of the node ID + * * @throws InvalidArgumentException - * @throws Exception */ - protected function getValidNode($node): string + private function getValidNode($node): string { if ($node === null) { $node = $this->nodeProvider->getNode(); } - // Convert the node to hex, if it is still an integer + // Convert the node to hex, if it is still an integer. if (is_int($node)) { $node = sprintf('%012x', $node); } diff --git a/src/Generator/PeclUuidRandomGenerator.php b/src/Generator/PeclUuidRandomGenerator.php index 39de343..51fda0f 100644 --- a/src/Generator/PeclUuidRandomGenerator.php +++ b/src/Generator/PeclUuidRandomGenerator.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; /** - * PeclUuidRandomGenerator provides functionality to generate strings of random - * binary data using the PECL UUID PHP extension + * PeclUuidRandomGenerator generates strings of random binary data using ext-uuid * - * @link https://pecl.php.net/package/uuid + * @link https://pecl.php.net/package/uuid ext-uuid */ class PeclUuidRandomGenerator implements RandomGeneratorInterface { - /** - * Generates a string of random binary data of the specified length - * - * @param int $length The number of bytes of random binary data to generate - * @return string A binary string - */ public function generate(int $length): string { $uuid = uuid_create(UUID_TYPE_RANDOM); diff --git a/src/Generator/PeclUuidTimeGenerator.php b/src/Generator/PeclUuidTimeGenerator.php index 693f7e6..1b569c6 100644 --- a/src/Generator/PeclUuidTimeGenerator.php +++ b/src/Generator/PeclUuidTimeGenerator.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; /** - * PeclUuidTimeGenerator provides functionality to generate strings of binary - * data for version 1 UUIDs using the PECL UUID PHP extension + * PeclUuidTimeGenerator generates strings of binary data for time-base UUIDs, + * using ext-uuid * - * @link https://pecl.php.net/package/uuid + * @link https://pecl.php.net/package/uuid ext-uuid */ class PeclUuidTimeGenerator implements TimeGeneratorInterface { /** - * Generate a version 1 UUID using the PECL UUID extension - * - * @param int|string $node Not used in this context - * @param int $clockSeq Not used in this context - * @return string A binary string + * @inheritDoc */ - public function generate($node = null, int $clockSeq = null): string + public function generate($node = null, ?int $clockSeq = null): string { $uuid = uuid_create(UUID_TYPE_TIME); diff --git a/src/Generator/RandomBytesGenerator.php b/src/Generator/RandomBytesGenerator.php index 63b21bb..23cf042 100644 --- a/src/Generator/RandomBytesGenerator.php +++ b/src/Generator/RandomBytesGenerator.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; -use Exception; - /** - * RandomBytesGenerator provides functionality to generate strings of random - * binary data using `random_bytes()` function in PHP 7+ or paragonie/random_compat + * RandomBytesGenerator generates strings of random binary data using the + * built-in `random_bytes()` PHP function * - * @link http://php.net/random_bytes - * @link https://github.com/paragonie/random_compat + * @link http://php.net/random_bytes random_bytes() */ class RandomBytesGenerator implements RandomGeneratorInterface { - /** - * Generates a string of random binary data of the specified length - * - * @param int $length The number of bytes of random binary data to generate - * @return string A binary string - * @throws Exception if it was not possible to gather sufficient entropy - */ public function generate(int $length): string { return random_bytes($length); diff --git a/src/Generator/RandomGeneratorFactory.php b/src/Generator/RandomGeneratorFactory.php index ee968ec..4f2cdb5 100644 --- a/src/Generator/RandomGeneratorFactory.php +++ b/src/Generator/RandomGeneratorFactory.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; /** - * A factory for retrieving a random generator, based on the environment + * RandomGeneratorFactory retrieves a default random generator, based on the + * environment */ class RandomGeneratorFactory { /** * Returns a default random generator, based on the current environment - * - * @return RandomGeneratorInterface */ public static function getGenerator(): RandomGeneratorInterface { diff --git a/src/Generator/RandomGeneratorInterface.php b/src/Generator/RandomGeneratorInterface.php index 266d444..5c83cb4 100644 --- a/src/Generator/RandomGeneratorInterface.php +++ b/src/Generator/RandomGeneratorInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; -use Exception; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; - /** - * RandomGeneratorInterface provides functionality to generate strings of random - * binary data + * A random generator generates strings of random binary data */ interface RandomGeneratorInterface { /** - * Generates a string of random binary data of the specified length + * Generates a string of randomized binary data * * @param int $length The number of bytes of random binary data to generate - * @return string|null A binary string - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception if it was not possible to gather sufficient entropy + * + * @return string A binary string */ - public function generate(int $length): ?string; + public function generate(int $length): string; } diff --git a/src/Generator/RandomLibAdapter.php b/src/Generator/RandomLibAdapter.php index 20c7659..24ed569 100644 --- a/src/Generator/RandomLibAdapter.php +++ b/src/Generator/RandomLibAdapter.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; -use RandomLib\Generator; use RandomLib\Factory; +use RandomLib\Generator; /** - * RandomLibAdapter provides functionality to generate strings of random - * binary data using the paragonie/random-lib library + * RandomLibAdapter generates strings of random binary data using the + * paragonie/random-lib library * - * @link https://packagist.org/packages/paragonie/random-lib + * @link https://packagist.org/packages/paragonie/random-lib paragonie/random-lib */ class RandomLibAdapter implements RandomGeneratorInterface { @@ -31,31 +31,24 @@ class RandomLibAdapter implements RandomGeneratorInterface private $generator; /** - * Constructs a `RandomLibAdapter` using a `RandomLib\Generator` + * Constructs a RandomLibAdapter * - * By default, if no `Generator` is passed in, this creates a high-strength + * By default, if no Generator is passed in, this creates a high-strength * generator to use when generating random binary data. * - * @param Generator $generator An paragonie/random-lib `Generator` + * @param Generator|null $generator The generator to use when generating binary data */ - public function __construct(Generator $generator = null) + public function __construct(?Generator $generator = null) { if ($generator === null) { $factory = new Factory(); - $generator = $factory->getHighStrengthGenerator(); } $this->generator = $generator; } - /** - * Generates a string of random binary data of the specified length - * - * @param int $length The number of bytes of random binary data to generate - * @return string|null A binary string - */ - public function generate(int $length): ?string + public function generate(int $length): string { return $this->generator->generate($length); } diff --git a/src/Generator/TimeGeneratorFactory.php b/src/Generator/TimeGeneratorFactory.php index f1129a8..3d55fc4 100644 --- a/src/Generator/TimeGeneratorFactory.php +++ b/src/Generator/TimeGeneratorFactory.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; use Ramsey\Uuid\Converter\TimeConverterInterface; @@ -19,7 +19,8 @@ use Ramsey\Uuid\Provider\NodeProviderInterface; use Ramsey\Uuid\Provider\TimeProviderInterface; /** - * A factory for retrieving a time generator, based on the environment + * TimeGeneratorFactory retrieves a default time generator, based on the + * environment */ class TimeGeneratorFactory { @@ -38,14 +39,6 @@ class TimeGeneratorFactory */ 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, @@ -58,8 +51,6 @@ class TimeGeneratorFactory /** * Returns a default time generator, based on the current environment - * - * @return TimeGeneratorInterface */ public function getGenerator(): TimeGeneratorInterface { diff --git a/src/Generator/TimeGeneratorInterface.php b/src/Generator/TimeGeneratorInterface.php index cf0cb2e..afcd87e 100644 --- a/src/Generator/TimeGeneratorInterface.php +++ b/src/Generator/TimeGeneratorInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Generator; -use Exception; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; - /** - * TimeGeneratorInterface provides functionality to generate strings of binary - * data for version 1 UUIDs based on a host ID, sequence number, and the current - * time + * A time generator generates strings of binary data based on a node ID, + * clock sequence, and the current time */ interface TimeGeneratorInterface { /** - * Generate a version 1 UUID from a host ID, sequence number, and the current time + * Generate a binary string from a node ID, clock sequence, and current time * - * @param 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|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. + * changes + * * @return string A binary string - * @throws UnsatisfiedDependencyException if called on a 32-bit system and - * `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception if it was not possible to gather sufficient entropy */ - public function generate($node = null, int $clockSeq = null): string; + public function generate($node = null, ?int $clockSeq = null): string; } diff --git a/src/Provider/Node/FallbackNodeProvider.php b/src/Provider/Node/FallbackNodeProvider.php index 9918c1d..e4e4504 100644 --- a/src/Provider/Node/FallbackNodeProvider.php +++ b/src/Provider/Node/FallbackNodeProvider.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider\Node; -use Exception; 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 + * FallbackNodeProvider retrieves the system node ID by stepping through a list + * of providers until a node ID can be obtained */ class FallbackNodeProvider implements NodeProviderInterface { @@ -30,8 +28,6 @@ class FallbackNodeProvider implements NodeProviderInterface private $nodeProviders; /** - * Constructs a `FallbackNodeProvider` using an array of node providers - * * @param NodeProviderInterface[] $providers Array of node providers */ public function __construct(array $providers) @@ -40,13 +36,9 @@ class FallbackNodeProvider implements NodeProviderInterface } /** - * Returns the system node ID by iterating over an array of node providers - * and returning the first non-empty value found - * - * @return string|null System node ID as a hexadecimal string - * @throws Exception + * @inheritDoc */ - public function getNode(): ?string + public function getNode() { foreach ($this->nodeProviders as $provider) { if ($node = $provider->getNode()) { diff --git a/src/Provider/Node/RandomNodeProvider.php b/src/Provider/Node/RandomNodeProvider.php index b284a63..830113c 100644 --- a/src/Provider/Node/RandomNodeProvider.php +++ b/src/Provider/Node/RandomNodeProvider.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider\Node; -use Exception; 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 + * RandomNodeProvider generates a random node ID * - * @link http://tools.ietf.org/html/rfc4122#section-4.5 + * @link http://tools.ietf.org/html/rfc4122#section-4.5 RFC 4122, § 4.5: Node IDs that Do Not Identify the Host */ class RandomNodeProvider implements NodeProviderInterface { /** - * Returns the system node ID - * - * @return string System node ID as a hexadecimal string - * @throws Exception if it was not possible to gather sufficient entropy + * @inheritDoc */ - public function getNode(): string + public function getNode() { $nodeBytes = random_bytes(6); diff --git a/src/Provider/Node/SystemNodeProvider.php b/src/Provider/Node/SystemNodeProvider.php index 0308924..25f28e3 100644 --- a/src/Provider/Node/SystemNodeProvider.php +++ b/src/Provider/Node/SystemNodeProvider.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider\Node; use Ramsey\Uuid\Provider\NodeProviderInterface; /** - * SystemNodeProvider provides functionality to get the system node ID (MAC - * address) using external system calls + * SystemNodeProvider retrieves the system node ID, if possible + * + * The system node ID, or host ID, is often the same as the MAC address for a + * network interface on the host. */ class SystemNodeProvider implements NodeProviderInterface { /** - * Returns the system node ID - * - * @return string|null|false System node ID as a hexadecimal string, or false if it is not found + * @inheritDoc */ public function getNode() { @@ -38,11 +38,11 @@ class SystemNodeProvider implements NodeProviderInterface $pattern = '/[^:]([0-9A-Fa-f]{2}([:-])[0-9A-Fa-f]{2}(\2[0-9A-Fa-f]{2}){4})[^:]/'; $matches = []; - // first try a linux specific way + // First, try a Linux-specific approach. $node = $this->getSysfs(); // Search the ifconfig output for all MAC addresses and return - // the first one found + // the first one found. if ($node === false) { if (preg_match_all($pattern, $this->getIfconfig(), $matches, PREG_PATTERN_ORDER)) { $node = $matches[1][0] ?? false; @@ -64,11 +64,12 @@ class SystemNodeProvider implements NodeProviderInterface * Returns the network interface configuration for the system * * @codeCoverageIgnore - * @return string */ - protected function getIfconfig(): string + private function getIfconfig(): string { - if (strpos(strtolower((string) ini_get('disable_functions')), 'passthru') !== false) { + $disabledFunctions = strtolower((string) ini_get('disable_functions')); + + if (strpos($disabledFunctions, 'passthru') !== false) { return ''; } @@ -76,16 +77,20 @@ class SystemNodeProvider implements NodeProviderInterface switch (strtoupper(substr(constant('PHP_OS'), 0, 3))) { case 'WIN': passthru('ipconfig /all 2>&1'); + break; case 'DAR': passthru('ifconfig 2>&1'); + break; case 'FRE': passthru('netstat -i -f link 2>&1'); + break; case 'LIN': default: passthru('netstat -ie 2>&1'); + break; } @@ -93,7 +98,7 @@ class SystemNodeProvider implements NodeProviderInterface } /** - * Returns mac address from the first system interface via the sysfs interface + * Returns MAC address from the first system interface via the sysfs interface * * @return string|bool */ @@ -104,12 +109,12 @@ class SystemNodeProvider implements NodeProviderInterface if (strtoupper(constant('PHP_OS')) === 'LINUX') { $addressPaths = glob('/sys/class/net/*/address', GLOB_NOSORT); - if (empty($addressPaths)) { + if ($addressPaths === false || count($addressPaths) === 0) { return false; } $macs = []; - array_walk($addressPaths, function ($addressPath) use (&$macs) { + array_walk($addressPaths, function ($addressPath) use (&$macs): void { if (is_readable($addressPath)) { $macs[] = file_get_contents($addressPath); } @@ -117,14 +122,10 @@ class SystemNodeProvider implements NodeProviderInterface $macs = array_map('trim', $macs); - // remove invalid entries + // Remove invalid entries. $macs = array_filter($macs, function ($address) { - return ( - // localhost adapter - $address !== '00:00:00:00:00:00' - // must match mac address - && preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i', $address) - ); + return $address !== '00:00:00:00:00:00' + && preg_match('/^([0-9a-f]{2}:){5}[0-9a-f]{2}$/i', $address); }); $mac = reset($macs); diff --git a/src/Provider/NodeProviderInterface.php b/src/Provider/NodeProviderInterface.php index a150456..0f7c024 100644 --- a/src/Provider/NodeProviderInterface.php +++ b/src/Provider/NodeProviderInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider; -use Exception; - /** - * 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 + * A node provider retrieves the system node ID + * + * The system node ID, or host ID, is often the same as the MAC address for a + * network interface on the host. */ interface NodeProviderInterface { /** * Returns the system node ID * - * @return string|null|false System node ID as a hexadecimal string - * @throws Exception if it was not possible to gather sufficient entropy + * @return string|false|null System node ID as a hexadecimal string */ public function getNode(); } diff --git a/src/Provider/Time/FixedTimeProvider.php b/src/Provider/Time/FixedTimeProvider.php index d743a57..b9e24e4 100644 --- a/src/Provider/Time/FixedTimeProvider.php +++ b/src/Provider/Time/FixedTimeProvider.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider\Time; use InvalidArgumentException; use Ramsey\Uuid\Provider\TimeProviderInterface; /** - * FixedTimeProvider uses an previously-generated timestamp to provide the time + * FixedTimeProvider uses an known 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. + * This provider allows the use of a previously-generated, or known, timestamp + * when generating time-based UUIDs. */ class FixedTimeProvider implements TimeProviderInterface { @@ -31,10 +31,11 @@ class FixedTimeProvider implements TimeProviderInterface private $fixedTime; /** - * Constructs a `FixedTimeProvider` using the provided `$timestamp` + * @param int[] $timestamp Array containing `sec` and `usec` components of + * a timestamp * - * @param int[] $timestamp Array containing `sec` and `usec` components of a timestamp - * @throws InvalidArgumentException if the `$timestamp` does not contain `sec` or `usec` components + * @throws InvalidArgumentException if the `$timestamp` does not contain + * `sec` or `usec` components */ public function __construct(array $timestamp) { @@ -49,9 +50,8 @@ class FixedTimeProvider implements TimeProviderInterface * Sets the `usec` component of the timestamp * * @param int $value The `usec` value to set - * @return void */ - public function setUsec(int $value) + public function setUsec(int $value): void { $this->fixedTime['usec'] = $value; } @@ -60,17 +60,14 @@ class FixedTimeProvider implements TimeProviderInterface * Sets the `sec` component of the timestamp * * @param int $value The `sec` value to set - * @return void */ - public function setSec(int $value) + public function setSec(int $value): void { $this->fixedTime['sec'] = $value; } /** - * Returns a timestamp array - * - * @return int[] Array containing `sec` and `usec` components of a timestamp + * @inheritDoc */ public function currentTime(): array { diff --git a/src/Provider/Time/SystemTimeProvider.php b/src/Provider/Time/SystemTimeProvider.php index eb8ab1a..cf562d7 100644 --- a/src/Provider/Time/SystemTimeProvider.php +++ b/src/Provider/Time/SystemTimeProvider.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider\Time; use Ramsey\Uuid\Provider\TimeProviderInterface; /** - * SystemTimeProvider uses built-in PHP functions to provide the time + * SystemTimeProvider retrieves the current time using built-in PHP functions */ class SystemTimeProvider implements TimeProviderInterface { /** - * Returns a timestamp array - * - * @return int[] Array containing `sec` and `usec` components of a timestamp + * @inheritDoc */ public function currentTime(): array { diff --git a/src/Provider/TimeProviderInterface.php b/src/Provider/TimeProviderInterface.php index 1bd6263..abeab1d 100644 --- a/src/Provider/TimeProviderInterface.php +++ b/src/Provider/TimeProviderInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Provider; /** - * TimeProviderInterface provides functionality to get the time from a specific - * type of time provider + * A time provider retrieves the current time */ interface TimeProviderInterface { /** * Returns a timestamp array * - * @return int[] Array guaranteed to contain `sec` and `usec` components of a timestamp + * @return int[] Array containing `sec` and `usec` components of a timestamp */ public function currentTime(): array; } diff --git a/src/Uuid.php b/src/Uuid.php index 5953250..9c4a084 100644 --- a/src/Uuid.php +++ b/src/Uuid.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid; use DateTimeImmutable; use DateTimeInterface; -use Exception; -use InvalidArgumentException; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; use Ramsey\Uuid\Converter\TimeConverterInterface; -use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; use Ramsey\Uuid\Exception\UnsupportedOperationException; /** - * Represents a universally unique identifier (UUID), according to RFC 4122. + * Represents a RFC 4122 universally unique identifier (UUID) * * This class provides immutable UUID objects (the Uuid class) and the static * methods `uuid1()`, `uuid3()`, `uuid4()`, and `uuid5()` for generating version @@ -36,113 +33,131 @@ use Ramsey\Uuid\Exception\UnsupportedOperationException; * Note that `uuid1()` may compromise privacy since it creates a UUID containing * the computer’s 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 + * @link http://tools.ietf.org/html/rfc4122 RFC 4122 */ 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 + * When this namespace is specified, the name string is a fully-qualified + * domain name + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs */ - const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; + public 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 + * When this namespace is specified, the name string is a URL + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs */ - const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; + public 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 + * When this namespace is specified, the name string is an ISO OID + * + * @link http://tools.ietf.org/html/rfc4122#appendix-C RFC 4122, Appendix C: Some Name Space IDs */ - const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8'; + public 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 + * 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 RFC 4122, Appendix C: Some Name Space IDs */ - const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'; + public 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 + * The nil UUID is a 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 RFC 4122, § 4.1.7: Nil UUID */ - const NIL = '00000000-0000-0000-0000-000000000000'; + public const NIL = '00000000-0000-0000-0000-000000000000'; /** - * Reserved for NCS compatibility. - * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 + * Variant: reserved, NCS backward compatibility + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant */ - const RESERVED_NCS = 0; + public const RESERVED_NCS = 0; /** - * Specifies the UUID layout given in RFC 4122. - * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 + * Variant: the UUID layout specified in RFC 4122 + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant */ - const RFC_4122 = 2; + public const RFC_4122 = 2; /** - * Reserved for Microsoft compatibility. - * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 + * Variant: reserved, Microsoft Corporation backward compatibility + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant */ - const RESERVED_MICROSOFT = 6; + public const RESERVED_MICROSOFT = 6; /** - * Reserved for future definition. - * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 + * Variant: reserved for future definition + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant */ - const RESERVED_FUTURE = 7; + public const RESERVED_FUTURE = 7; /** - * Version 1 (time-based) UUID object constant identifier + * Version 1 (time-based) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ - const UUID_TYPE_TIME = 1; + public const UUID_TYPE_TIME = 1; /** - * Version 2 (identifier-based) UUID object constant identifier + * Version 2 (identifier-based) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ - const UUID_TYPE_IDENTIFIER = 2; + public const UUID_TYPE_IDENTIFIER = 2; /** - * Version 3 (name-based and hashed with MD5) UUID object constant identifier + * Version 3 (name-based and hashed with MD5) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ - const UUID_TYPE_HASH_MD5 = 3; + public const UUID_TYPE_HASH_MD5 = 3; /** - * Version 4 (random) UUID object constant identifier + * Version 4 (random) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ - const UUID_TYPE_RANDOM = 4; + public const UUID_TYPE_RANDOM = 4; /** - * Version 5 (name-based and hashed with SHA1) UUID object constant identifier + * Version 5 (name-based and hashed with SHA1) UUID + * + * @link https://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ - const UUID_TYPE_HASH_SHA1 = 5; + public 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; + private $codec; /** - * The fields that make up this UUID. + * The fields that make up this UUID * * This is initialized to the nil value. * - * @var array * @see UuidInterface::getFieldsHex() + * + * @var string[] */ - protected $fields = [ + private $fields = [ 'time_low' => '00000000', 'time_mid' => '0000', 'time_hi_and_version' => '0000', @@ -152,19 +167,17 @@ class Uuid implements UuidInterface ]; /** - * The number converter to use for converting hex values to/from integers. * @var NumberConverterInterface */ protected $numberConverter; /** - * The time converter to use for converting timestamps extracted from UUIDs to unix timestamps * @var TimeConverterInterface */ protected $timeConverter; /** - * Creates a universally unique identifier (UUID) from an array of fields. + * 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 @@ -179,12 +192,12 @@ class Uuid implements UuidInterface * $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 string[] $fields An array of fields from which to construct a UUID; + * see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure * @param NumberConverterInterface $numberConverter The number converter to use - * for converting hex values to/from integers. + * for converting hex values to/from integers * @param CodecInterface $codec The codec to use when encoding or decoding - * UUID strings. + * UUID strings * @param TimeConverterInterface $timeConverter The time converter to use * for converting timestamps extracted from a UUID to unix timestamps */ @@ -200,24 +213,13 @@ class Uuid implements UuidInterface $this->timeConverter = $timeConverter; } - /** - * 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(): string { 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 + * Converts the UUID to a string for JSON serialization */ public function jsonSerialize(): string { @@ -225,11 +227,7 @@ class Uuid implements UuidInterface } /** - * 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 + * Converts the UUID to a string for PHP serialization */ public function serialize(): string { @@ -237,14 +235,14 @@ class Uuid implements UuidInterface } /** - * Re-constructs the object from its serialized form. + * Re-constructs the object from its serialized form * - * @param string $serialized - * @return void - * @throws InvalidUuidStringException - * @link http://php.net/manual/en/class.serializable.php + * @param string $serialized The serialized PHP string to unserialize into + * a UuidInterface instance + * + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint */ - public function unserialize($serialized) + public function unserialize($serialized): void { /** @var \Ramsey\Uuid\Uuid $uuid */ $uuid = self::fromString($serialized); @@ -280,7 +278,7 @@ class Uuid implements UuidInterface return false; } - return $this->compareTo($other) == 0; + return $this->compareTo($other) === 0; } public function getBytes(): string @@ -290,9 +288,6 @@ class Uuid implements UuidInterface /** * 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(): int { @@ -305,9 +300,7 @@ class Uuid implements UuidInterface } /** - * 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 + * Returns the low field of the clock sequence */ public function getClockSeqLow(): int { @@ -320,7 +313,7 @@ class Uuid implements UuidInterface } /** - * Returns the clock sequence value associated with this UUID. + * Returns the full clock sequence value * * For UUID version 1, the clock sequence is used to help avoid * duplicates that could arise when the clock is set backwards in time @@ -332,8 +325,7 @@ class Uuid implements UuidInterface * 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 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.5 RFC 4122, § 4.1.5: Clock Sequence */ public function getClockSequence(): int { @@ -351,11 +343,13 @@ class Uuid implements UuidInterface } /** - * @inheritdoc + * @return DateTimeImmutable An immutable instance of DateTimeInterface + * + * @throws UnsupportedOperationException if UUID is not time-based */ public function getDateTime(): DateTimeInterface { - if ($this->getVersion() != 1) { + if ($this->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } @@ -379,8 +373,9 @@ class Uuid implements UuidInterface * * **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 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.2 RFC 4122, § 4.1.2: Layout and Byte Order + * + * @return int[] The UUID fields represented as integer values */ public function getFields(): array { @@ -394,6 +389,9 @@ class Uuid implements UuidInterface ]; } + /** + * @inheritDoc + */ public function getFieldsHex(): array { return $this->fields; @@ -405,7 +403,7 @@ class Uuid implements UuidInterface } /** - * @inheritdoc + * @inheritDoc */ public function getInteger() { @@ -413,10 +411,11 @@ class Uuid implements UuidInterface } /** - * Returns the least significant 64 bits of this UUID's 128 bit value. + * Returns the least significant 64 bits of the UUID * - * @return mixed Converted representation of the unsigned 64-bit integer value - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present + * @return mixed + * + * @throws UnsatisfiedDependencyException if large integer support is not available */ public function getLeastSignificantBits() { @@ -434,10 +433,11 @@ class Uuid implements UuidInterface } /** - * Returns the most significant 64 bits of this UUID's 128 bit value. + * Returns the most significant 64 bits of the UUID * - * @return mixed Converted representation of the unsigned 64-bit integer value - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present + * @return mixed + * + * @throws UnsatisfiedDependencyException if large integer support is not available */ public function getMostSignificantBits() { @@ -475,8 +475,9 @@ class Uuid implements UuidInterface * 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. * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.6 RFC 4122, § 4.1.6: Node + * * @return int Unsigned 48-bit integer value of node - * @link http://tools.ietf.org/html/rfc4122#section-4.1.6 */ public function getNode(): int { @@ -490,9 +491,6 @@ class Uuid implements UuidInterface /** * 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(): int { @@ -505,9 +503,7 @@ class Uuid implements UuidInterface } /** - * Returns the low field of the timestamp (the first 32 bits of the UUID). - * - * @return int Unsigned 32-bit integer value of time_low + * Returns the low field of the timestamp */ public function getTimeLow(): int { @@ -520,9 +516,7 @@ class Uuid implements UuidInterface } /** - * Returns the middle field of the timestamp (bits 33-48 of the UUID). - * - * @return int Unsigned 16-bit integer value of time_mid + * Returns the middle field of the timestamp */ public function getTimeMid(): int { @@ -535,7 +529,7 @@ class Uuid implements UuidInterface } /** - * Returns the timestamp value associated with this UUID. + * Returns the full timestamp value * * The 60 bit timestamp value is constructed from the time_low, * time_mid, and time_hi fields of this UUID. The resulting @@ -543,28 +537,24 @@ class Uuid implements UuidInterface * 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. + * has version type 1. * - * @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 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.4 RFC 4122, § 4.1.4: Timestamp + * + * @throws UnsupportedOperationException if UUID is not time-based */ public function getTimestamp(): int { - if ($this->getVersion() != 1) { + if ($this->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } return (int) hexdec($this->getTimestampHex()); } - /** - * @inheritdoc - */ public function getTimestampHex(): string { - if ($this->getVersion() != 1) { + if ($this->getVersion() !== 1) { throw new UnsupportedOperationException('Not a time-based UUID'); } @@ -585,15 +575,15 @@ class Uuid implements UuidInterface { $clockSeq = $this->getClockSeqHiAndReserved(); - if (0 === ($clockSeq & 0x80)) { + if (($clockSeq & 0x80) === 0) { return self::RESERVED_NCS; } - if (0 === ($clockSeq & 0x40)) { + if (($clockSeq & 0x40) === 0) { return self::RFC_4122; } - if (0 === ($clockSeq & 0x20)) { + if (($clockSeq & 0x20) === 0) { return self::RESERVED_MICROSOFT; } @@ -602,7 +592,7 @@ class Uuid implements UuidInterface public function getVersion(): ?int { - if ($this->getVariant() == self::RFC_4122) { + if ($this->getVariant() === self::RFC_4122) { return (int) (($this->getTimeHiAndVersion() >> 12) & 0x0f); } @@ -615,9 +605,7 @@ class Uuid implements UuidInterface } /** - * Returns the currently set factory used to create UUIDs. - * - * @return UuidFactoryInterface + * Returns the factory used to create UUIDs */ public static function getFactory(): UuidFactoryInterface { @@ -629,23 +617,23 @@ class Uuid implements UuidInterface } /** - * Sets the factory used to create UUIDs. + * Sets the factory used to create UUIDs * - * @param UuidFactoryInterface $factory - * @return void + * @param UuidFactoryInterface $factory A factory that will be used by this + * class to create UUIDs */ - public static function setFactory(UuidFactoryInterface $factory) + public static function setFactory(UuidFactoryInterface $factory): void { self::$factory = $factory; } /** - * Creates a UUID from a byte string. + * Creates a UUID from a byte string * - * @param string $bytes - * @return UuidInterface - * @throws InvalidUuidStringException - * @throws InvalidArgumentException + * @param string $bytes A binary string + * + * @return UuidInterface A UuidInterface instance created from a binary + * string representation */ public static function fromBytes(string $bytes): UuidInterface { @@ -653,24 +641,25 @@ class Uuid implements UuidInterface } /** - * Creates a UUID from the string standard representation. + * Creates a UUID from the string standard representation * - * @param string $name A string that specifies a UUID - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string $uuid A hexadecimal string + * + * @return UuidInterface A UuidInterface instance created from a hexadecimal + * string representation */ - public static function fromString(string $name): UuidInterface + public static function fromString(string $uuid): UuidInterface { - return self::getFactory()->fromString($name); + return self::getFactory()->fromString($uuid); } /** - * Creates a UUID from a 128-bit integer string. + * Creates a UUID from a 128-bit integer string * * @param string $integer String representation of 128-bit integer - * @return UuidInterface - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidUuidStringException + * + * @return UuidInterface A UuidInterface instance created from the string + * representation of a 128-bit integer */ public static function fromInteger(string $integer): UuidInterface { @@ -678,10 +667,11 @@ class Uuid implements UuidInterface } /** - * Check if a string is a valid UUID. + * Returns true if the provided string is a valid UUID * - * @param string $uuid The string UUID to test - * @return boolean + * @param string $uuid A string to validate as a UUID + * + * @return bool True if the string is a valid UUID, false otherwise */ public static function isValid(string $uuid): bool { @@ -689,18 +679,17 @@ class Uuid implements UuidInterface } /** - * Generate a version 1 UUID from a host ID, sequence number, and the current time. + * Returns a version 1 (time-based) 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|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 - * @throws UnsatisfiedDependencyException if called on a 32-bit system and - * `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception if it was not possible to gather sufficient entropy + * changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID */ public static function uuid1($node = null, ?int $clockSeq = null): UuidInterface { @@ -708,13 +697,14 @@ class Uuid implements UuidInterface } /** - * 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). + * Returns a version 3 (name-based) UUID based on the MD5 hash of a + * namespace ID and a name * - * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID - * @param string $name The name to create a UUID for - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 3 UUID */ public static function uuid3($ns, string $name): UuidInterface { @@ -722,12 +712,10 @@ class Uuid implements UuidInterface } /** - * Generate a version 4 (random) UUID. + * Returns a version 4 (random) UUID * - * @return UuidInterface - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception + * @return UuidInterface A UuidInterface instance that represents a + * version 4 UUID */ public static function uuid4(): UuidInterface { @@ -735,13 +723,14 @@ class Uuid implements UuidInterface } /** - * 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). + * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a + * namespace ID and a name * - * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID - * @param string $name The name to create a UUID for - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 5 UUID */ public static function uuid5($ns, string $name): UuidInterface { diff --git a/src/UuidFactory.php b/src/UuidFactory.php index 9a2b309..ad35bf5 100644 --- a/src/UuidFactory.php +++ b/src/UuidFactory.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid; use Ramsey\Uuid\Builder\UuidBuilderInterface; use Ramsey\Uuid\Codec\CodecInterface; use Ramsey\Uuid\Converter\NumberConverterInterface; -use Ramsey\Uuid\Exception\InvalidUuidStringException; use Ramsey\Uuid\Generator\RandomGeneratorInterface; use Ramsey\Uuid\Generator\TimeGeneratorInterface; use Ramsey\Uuid\Provider\NodeProviderInterface; @@ -61,11 +60,9 @@ class UuidFactory implements UuidFactoryInterface private $validator = null; /** - * Constructs a `UuidFactory` for creating `Ramsey\Uuid\UuidInterface` instances - * - * @param FeatureSet $features A set of features for use when creating UUIDs + * @param FeatureSet $features A set of available features in the current environment */ - public function __construct(FeatureSet $features = null) + public function __construct(?FeatureSet $features = null) { $features = $features ?: new FeatureSet(); @@ -79,9 +76,7 @@ class UuidFactory implements UuidFactoryInterface } /** - * Returns the UUID coder-decoder used by this factory - * - * @return CodecInterface + * Returns the codec used by this factory */ public function getCodec(): CodecInterface { @@ -89,20 +84,17 @@ class UuidFactory implements UuidFactoryInterface } /** - * Sets the UUID coder-decoder used by this factory + * Sets the codec to use for this factory * - * @param CodecInterface $codec - * @return void + * @param CodecInterface $codec A UUID encoder-decoder */ - public function setCodec(CodecInterface $codec) + public function setCodec(CodecInterface $codec): void { $this->codec = $codec; } /** - * Returns the system node ID provider used by this factory - * - * @return NodeProviderInterface + * Returns the node provider used by this factory */ public function getNodeProvider(): NodeProviderInterface { @@ -110,9 +102,7 @@ class UuidFactory implements UuidFactoryInterface } /** - * Returns the random UUID generator used by this factory - * - * @return RandomGeneratorInterface + * Returns the random generator used by this factory */ public function getRandomGenerator(): RandomGeneratorInterface { @@ -120,9 +110,7 @@ class UuidFactory implements UuidFactoryInterface } /** - * Returns the time-based UUID generator used by this factory - * - * @return TimeGeneratorInterface + * Returns the time generator used by this factory */ public function getTimeGenerator(): TimeGeneratorInterface { @@ -130,20 +118,18 @@ class UuidFactory implements UuidFactoryInterface } /** - * Sets the time-based UUID generator this factory will use to generate version 1 UUIDs + * Sets the time generator to use for this factory * - * @param TimeGeneratorInterface $generator - * @return void + * @param TimeGeneratorInterface $generator A generator to generate binary + * data, based on the time */ - public function setTimeGenerator(TimeGeneratorInterface $generator) + public function setTimeGenerator(TimeGeneratorInterface $generator): void { $this->timeGenerator = $generator; } /** * Returns the number converter used by this factory - * - * @return NumberConverterInterface */ public function getNumberConverter(): NumberConverterInterface { @@ -151,31 +137,29 @@ class UuidFactory implements UuidFactoryInterface } /** - * Sets the random UUID generator this factory will use to generate version 4 UUIDs + * Sets the random generator to use for this factory * - * @param RandomGeneratorInterface $generator - * @return void + * @param RandomGeneratorInterface $generator A generator to generate binary + * data, based on some random input */ - public function setRandomGenerator(RandomGeneratorInterface $generator) + public function setRandomGenerator(RandomGeneratorInterface $generator): void { $this->randomGenerator = $generator; } /** - * Sets the number converter this factory will use + * Sets the number converter to use for this factory * - * @param NumberConverterInterface $converter - * @return void + * @param NumberConverterInterface $converter A converter to use for working + * with large integers (i.e. integers greater than PHP_INT_MAX) */ - public function setNumberConverter(NumberConverterInterface $converter) + public function setNumberConverter(NumberConverterInterface $converter): void { $this->numberConverter = $converter; } /** - * Returns the UUID builder this factory uses when creating `Uuid` instances - * - * @return UuidBuilderInterface $builder + * Returns the UUID builder used by this factory */ public function getUuidBuilder(): UuidBuilderInterface { @@ -183,54 +167,45 @@ class UuidFactory implements UuidFactoryInterface } /** - * Sets the UUID builder this factory will use when creating `Uuid` instances + * Sets the UUID builder to use for this factory * - * @param UuidBuilderInterface $builder - * @return void + * @param UuidBuilderInterface $builder A builder for constructing instances + * of UuidInterface */ - public function setUuidBuilder(UuidBuilderInterface $builder) + public function setUuidBuilder(UuidBuilderInterface $builder): void { $this->uuidBuilder = $builder; } - /** - * @return ValidatorInterface - */ public function getValidator(): ValidatorInterface { return $this->validator; } /** - * @param ValidatorInterface $validator - * @return void + * Sets the validator to use for this factory + * + * @param ValidatorInterface $validator A validator to use for validating + * whether a string is a valid UUID */ - public function setValidator(ValidatorInterface $validator) + public function setValidator(ValidatorInterface $validator): void { $this->validator = $validator; } - /** - * @inheritdoc - */ public function fromBytes(string $bytes): UuidInterface { return $this->codec->decodeBytes($bytes); } - /** - * @inheritdoc - */ public function fromString(string $uuid): UuidInterface { $uuid = strtolower($uuid); + return $this->codec->decode($uuid); } - /** - * @inheritdoc - */ - public function fromInteger($integer): UuidInterface + public function fromInteger(string $integer): UuidInterface { $hex = $this->numberConverter->toHex($integer); $hex = str_pad($hex, 32, '0', STR_PAD_LEFT); @@ -239,7 +214,7 @@ class UuidFactory implements UuidFactoryInterface } /** - * @inheritdoc + * @inheritDoc */ public function uuid1($node = null, ?int $clockSeq = null): UuidInterface { @@ -250,16 +225,13 @@ class UuidFactory implements UuidFactoryInterface } /** - * @inheritdoc + * @inheritDoc */ public function uuid3($ns, string $name): UuidInterface { return $this->uuidFromNsAndName($ns, $name, 3, 'md5'); } - /** - * @inheritdoc - */ public function uuid4(): UuidInterface { $bytes = $this->randomGenerator->generate(16); @@ -273,7 +245,7 @@ class UuidFactory implements UuidFactoryInterface } /** - * @inheritdoc + * @inheritDoc */ public function uuid5($ns, string $name): UuidInterface { @@ -281,14 +253,16 @@ class UuidFactory implements UuidFactoryInterface } /** - * Returns a `Uuid` + * Returns a Uuid created from the provided fields * - * Uses the configured builder and codec and the provided array of hexadecimal - * value UUID fields to construct a `Uuid` object. + * 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 + * @param string[] $fields An array of fields from which to construct a UUID; + * see {@see \Ramsey\Uuid\UuidInterface::getFieldsHex()} for array structure + * + * @return UuidInterface An instance of UuidInterface, created from the + * provided fields */ public function uuid(array $fields): UuidInterface { @@ -296,36 +270,38 @@ class UuidFactory implements UuidFactoryInterface } /** - * Returns a version 3 or 5 namespaced `Uuid` + * 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 string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to hash together with the namespace * @param int $version The version of UUID to create (3 or 5) * @param callable $hashFunction The hash function to use when hashing together * the namespace and name - * @return UuidInterface - * @throws InvalidUuidStringException + * + * @return UuidInterface An instance of UuidInterface, created by hashing + * together the provided namespace and name */ - protected function uuidFromNsAndName($ns, string $name, int $version, callable $hashFunction): UuidInterface + private function uuidFromNsAndName($ns, string $name, int $version, callable $hashFunction): UuidInterface { if (!($ns instanceof UuidInterface)) { $ns = $this->codec->decode($ns); } - $hash = call_user_func($hashFunction, ($ns->getBytes() . $name)); + $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 + * Returns an RFC 4122 variant Uuid, created from the provided hash and version * - * @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 + * @param string $hash The hashed string to convert to a UUID + * @param int $version The RFC 4122 version to apply to the UUID + * + * @return UuidInterface An instance of UuidInterface, created from the + * hashed string and version */ - protected function uuidFromHashedName(string $hash, int $version): UuidInterface + private function uuidFromHashedName(string $hash, int $version): UuidInterface { $timeHi = BinaryUtils::applyVersion(substr($hash, 12, 4), $version); $clockSeqHi = BinaryUtils::applyVariant((int) hexdec(substr($hash, 16, 2))); diff --git a/src/UuidFactoryInterface.php b/src/UuidFactoryInterface.php index 700a8c7..d6bbc83 100644 --- a/src/UuidFactoryInterface.php +++ b/src/UuidFactoryInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid; -use Exception; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\InvalidUuidStringException; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; use Ramsey\Uuid\Validator\ValidatorInterface; /** @@ -27,88 +23,84 @@ use Ramsey\Uuid\Validator\ValidatorInterface; interface UuidFactoryInterface { /** - * @return ValidatorInterface + * Returns the validator to use for the factory */ public function getValidator(): ValidatorInterface; /** - * Generate a version 1 UUID from a host ID, sequence number, and the current time. + * Returns a version 1 (time-based) UUID from a host ID, sequence number, + * and the current time * - * @param int|string|null $node A 48-bit number representing the hardware address - * This number may be represented as an integer or a hexadecimal string. - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * @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 - * @throws UnsatisfiedDependencyException if called on a 32-bit system and - * `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception if it was not possible to gather sufficient entropy + * changes + * + * @return UuidInterface A UuidInterface instance that represents a + * version 1 UUID */ public function uuid1($node = null, ?int $clockSeq = null): UuidInterface; /** - * 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). + * Returns a version 3 (name-based) UUID based on the MD5 hash of a + * namespace ID and a name * - * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID - * @param string $name The name to create a UUID for - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 3 UUID */ public function uuid3($ns, string $name): UuidInterface; /** - * Generate a version 4 (random) UUID. + * Returns a version 4 (random) UUID * - * @return UuidInterface - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception + * @return UuidInterface A UuidInterface instance that represents a + * version 4 UUID */ public function uuid4(): UuidInterface; /** - * 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). + * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a + * namespace ID and a name * - * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID - * @param string $name The name to create a UUID for - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string|UuidInterface $ns The namespace (must be a valid UUID) + * @param string $name The name to use for creating a UUID + * + * @return UuidInterface A UuidInterface instance that represents a + * version 5 UUID */ public function uuid5($ns, string $name): UuidInterface; /** - * Creates a UUID from a byte string. + * Creates a UUID from a byte string * - * @param string $bytes A 16-byte string representation of a UUID - * @return UuidInterface - * @throws InvalidUuidStringException - * @throws InvalidArgumentException if string has not 16 characters + * @param string $bytes A binary string + * + * @return UuidInterface A UuidInterface instance created from a binary + * string representation */ public function fromBytes(string $bytes): UuidInterface; /** * Creates a UUID from the string standard representation * - * @param string $uuid A string representation of a UUID - * @return UuidInterface - * @throws InvalidUuidStringException + * @param string $uuid A hexadecimal string + * + * @return UuidInterface A UuidInterface instance created from a hexadecimal + * string representation */ public function fromString(string $uuid): UuidInterface; /** - * Creates a `Uuid` from an integer representation + * Creates a UUID from a 128-bit integer string * - * The integer representation may be a real integer, a string integer, or - * an integer representation supported by a configured number converter. + * @param string $integer String representation of 128-bit integer * - * @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 - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidUuidStringException + * @return UuidInterface A UuidInterface instance created from the string + * representation of a 128-bit integer */ - public function fromInteger($integer): UuidInterface; + public function fromInteger(string $integer): UuidInterface; } diff --git a/src/UuidInterface.php b/src/UuidInterface.php index f73f6fd..844b425 100644 --- a/src/UuidInterface.php +++ b/src/UuidInterface.php @@ -1,4 +1,5 @@ * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid; use DateTimeInterface; use JsonSerializable; use Ramsey\Uuid\Converter\NumberConverterInterface; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; -use Ramsey\Uuid\Exception\UnsupportedOperationException; use Serializable; /** - * UuidInterface defines common functionality for all universally unique - * identifiers (UUIDs) + * A UUID is a universally unique identifier adhering to an agreed-upon + * representation format and standard for generation */ interface UuidInterface extends JsonSerializable, Serializable { /** - * Compares this UUID to the specified UUID. + * Returns -1, 0, or 1 if the UUID is less than, equal to, or greater than + * the other 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 @@ -37,48 +36,39 @@ interface UuidInterface extends JsonSerializable, Serializable * * 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` + * @param UuidInterface $other The UUID to compare + * + * @return int -1, 0, or 1 if the UUID is less than, equal to, or greater than $other */ public function compareTo(UuidInterface $other): int; /** - * Compares this object to the specified object. + * Returns true if the UUID is equal to the provided 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|null $other - * @return bool True if `$other` is equal to this UUID + * as the UUID. */ public function equals(?object $other): bool; /** - * Returns the UUID as a 16-byte string (containing the six integer fields - * in big-endian byte order). - * - * @return string + * Returns the binary string representation of the UUID */ public function getBytes(): string; /** - * Returns the number converter to use for converting hex values to/from integers. - * - * @return NumberConverterInterface + * Returns the number converter to use when converting hex values to/from integers */ public function getNumberConverter(): NumberConverterInterface; /** - * Returns the hexadecimal value of the UUID. - * - * @return string + * Returns the hexadecimal string representation of the UUID */ public function getHex(): string; /** - * Returns an array of the fields of this UUID, with keys named according - * to the RFC 4122 names for the fields. + * Returns an array of the fields of the 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 @@ -91,72 +81,70 @@ interface UuidInterface extends JsonSerializable, Serializable * * **node**: The spatially unique node identifier, an unsigned 48-bit * integer * - * @return array The UUID fields represented as hexadecimal values + * @link http://tools.ietf.org/html/rfc4122#section-4.1.2 RFC 4122, § 4.1.2: Layout and Byte Order + * + * @return string[] */ public function getFieldsHex(): array; /** * 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(): string; /** - * Returns the low field of the clock sequence (bits 73-80 of the UUID). - * - * @return string Hexadecimal value of clock_seq_low + * Returns the low field of the clock sequence */ public function getClockSeqLowHex(): string; /** - * Returns the clock sequence value associated with this UUID. + * Returns the full clock sequence value * - * @return string Hexadecimal value of clock sequence + * 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. + * + * @link http://tools.ietf.org/html/rfc4122#section-4.1.5 RFC 4122, § 4.1.5: Clock Sequence */ public function getClockSequenceHex(): string; /** - * Returns a PHP object that implements `DateTimeInterface` representing - * the timestamp associated with this UUID. + * Returns a DateTimeInterface object representing the timestamp associated + * with the 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`. + * has version type 1. * - * @return DateTimeInterface A PHP DateTimeImmutable representation of the date - * @throws UnsupportedOperationException If this UUID is not a version 1 UUID - * @throws UnsatisfiedDependencyException if called in a 32-bit system and - * `Moontoast\Math\BigNumber` is not present + * @return DateTimeInterface A PHP DateTimeInterface instance representing + * the timestamp of a version 1 UUID */ public function getDateTime(): DateTimeInterface; /** - * Returns the integer value of the UUID, converted to an appropriate number - * representation. + * Returns the 128-bit integer value of the UUID as a string * - * @return mixed Converted representation of the unsigned 128-bit integer value - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present + * @return mixed */ public function getInteger(); /** - * Returns the least significant 64 bits of this UUID's 128 bit value. - * - * @return string Hexadecimal value of least significant bits + * Returns the least significant 64 bits of the UUID */ public function getLeastSignificantBitsHex(): string; /** - * Returns the most significant 64 bits of this UUID's 128 bit value. - * - * @return string Hexadecimal value of most significant bits + * Returns the most significant 64 bits of the UUID */ public function getMostSignificantBitsHex(): string; /** - * Returns the node value associated with this UUID + * Returns the node value * * For UUID version 1, the node field consists of an IEEE 802 MAC * address, usually the host address. For systems with multiple IEEE @@ -176,79 +164,66 @@ interface UuidInterface extends JsonSerializable, Serializable * 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 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.6 RFC 4122, § 4.1.6: Node */ public function getNodeHex(): string; /** * 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(): string; /** - * Returns the low field of the timestamp (the first 32 bits of the UUID). - * - * @return string Hexadecimal value of time_low + * Returns the low field of the timestamp */ public function getTimeLowHex(): string; /** - * Returns the middle field of the timestamp (bits 33-48 of the UUID). - * - * @return string Hexadecimal value of time_mid + * Returns the middle field of the timestamp */ public function getTimeMidHex(): string; /** - * Returns the timestamp value associated with this UUID. + * Returns the full timestamp value * * The 60 bit timestamp value is constructed from the time_low, - * time_mid, and time_hi fields of this UUID. The resulting + * time_mid, and time_hi fields of the 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. + * has version type 1. * - * @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 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.4 RFC 4122, § 4.1.4: Timestamp */ public function getTimestampHex(): string; /** - * Returns the string representation of the UUID as a URN. + * Returns the string representation of the UUID as a URN * - * @return string - * @link http://en.wikipedia.org/wiki/Uniform_Resource_Name + * @link http://en.wikipedia.org/wiki/Uniform_Resource_Name Uniform Resource Name */ public function getUrn(): string; /** - * Returns the variant number associated with this UUID. + * Returns the variant * * The variant number describes the layout of the UUID. The variant * number has the following meaning: * * * 0 - Reserved for NCS backward compatibility - * * 2 - The RFC 4122 variant (used by this class) + * * 2 - The RFC 4122 variant * * 6 - Reserved, Microsoft Corporation backward compatibility * * 7 - Reserved for future definition * - * @return int - * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.1 RFC 4122, § 4.1.1: Variant */ public function getVariant(): int; /** - * Returns the version number associated with this UUID. + * Returns the version * - * The version number describes how this UUID was generated and has the + * The version number describes how the UUID was generated and has the * following meaning: * * * 1 - Time-based UUID @@ -257,25 +232,20 @@ interface UuidInterface extends JsonSerializable, Serializable * * 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 + * This returns null if the 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 + * @link http://tools.ietf.org/html/rfc4122#section-4.1.3 RFC 4122, § 4.1.3: Version */ public function getVersion(): ?int; /** - * Returns a string representation of this UUID. - * - * @return string + * Returns a string representation of the UUID */ public function toString(): string; /** - * Allows casting this UUID to a string representation. - * - * @return string + * Casts the UUID to a string representation */ public function __toString(): string; } diff --git a/src/Validator/Validator.php b/src/Validator/Validator.php index 95704a2..9d20636 100644 --- a/src/Validator/Validator.php +++ b/src/Validator/Validator.php @@ -1,39 +1,32 @@ * @copyright Copyright (c) Ben Ramsey * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Validator; use Ramsey\Uuid\Uuid; /** - * Default validation behavior + * Validator validates strings as UUIDs of any variant */ class Validator implements ValidatorInterface { /** - * Regular expression pattern for matching a valid UUID of any variant. + * Regular expression pattern for matching a 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}$'; + public 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}$'; - /** - * Validate that a string represents a UUID - * - * @param string $uuid - * @return bool Returns TRUE if the string was validated as a valid UUID or FALSE on failure - */ - public function validate($uuid): bool + public function validate(string $uuid): bool { $uuid = str_replace(['urn:', 'uuid:', 'URN:', 'UUID:', '{', '}'], '', $uuid); diff --git a/src/Validator/ValidatorInterface.php b/src/Validator/ValidatorInterface.php index 8cbd0e5..58a413b 100644 --- a/src/Validator/ValidatorInterface.php +++ b/src/Validator/ValidatorInterface.php @@ -1,30 +1,30 @@ * @copyright Copyright (c) Ben Ramsey * @license http://opensource.org/licenses/MIT MIT - * @link https://benramsey.com/projects/ramsey-uuid/ Documentation - * @link https://packagist.org/packages/ramsey/uuid Packagist - * @link https://github.com/ramsey/uuid GitHub */ +declare(strict_types=1); + namespace Ramsey\Uuid\Validator; /** - * Outlines common behavior of UUID validators + * A validator validates a string as a proper UUID */ interface ValidatorInterface { /** - * Validate that a string represents a UUID + * Returns true if the provided string represents a UUID * - * @param string $uuid - * @return bool Returns TRUE if the string was validated as a valid UUID or FALSE on failure + * @param string $uuid The string to validate as a UUID + * + * @return bool True if the string is a valid UUID, false otherwise */ public function validate(string $uuid): bool; } diff --git a/src/functions.php b/src/functions.php index b5db341..735eb0b 100644 --- a/src/functions.php +++ b/src/functions.php @@ -8,71 +8,54 @@ * * @copyright Copyright (c) Ben Ramsey * @license http://opensource.org/licenses/MIT MIT + * phpcs:disable Squiz.Functions.GlobalFunction */ +declare(strict_types=1); + namespace Ramsey\Uuid; -use Exception; -use InvalidArgumentException; -use Ramsey\Uuid\Exception\InvalidUuidStringException; -use Ramsey\Uuid\Exception\UnsatisfiedDependencyException; - /** - * Generate a version 1 UUID from a host ID, sequence number, and the current time. + * Returns a version 1 (time-based) UUID from a host ID, sequence number, + * and the current time * - * @param int|string|null $node A 48-bit number representing the hardware address - * This number may be represented as an integer or a hexadecimal string. - * @param int|null $clockSeq A 14-bit number used to help avoid duplicates that + * @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 - * @throws UnsatisfiedDependencyException if called on a 32-bit system and - * `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception if it was not possible to gather sufficient entropy + * changes */ -function v1($node = null, $clockSeq = null) +function v1($node = null, ?int $clockSeq = null): string { return Uuid::uuid1($node, $clockSeq)->toString(); } /** - * 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). + * Returns a version 3 (name-based) UUID based on the MD5 hash of a + * namespace ID and a name * - * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID - * @param string $name The name to create a UUID for - * @return string - * @throws InvalidUuidStringException + * @param string|UuidInterface $ns The namespace (must be a valid UUID) */ -function v3($ns, $name) +function v3($ns, string $name): string { return Uuid::uuid3($ns, $name)->toString(); } /** - * Generate a version 4 (random) UUID. - * - * @return string - * @throws UnsatisfiedDependencyException if `Moontoast\Math\BigNumber` is not present - * @throws InvalidArgumentException - * @throws Exception + * Returns a version 4 (random) UUID */ -function v4() +function v4(): string { return Uuid::uuid4()->toString(); } /** - * 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). + * Returns a version 5 (name-based) UUID based on the SHA-1 hash of a + * namespace ID and a name * - * @param string|UuidInterface $ns The UUID namespace in which to create the named UUID - * @param string $name The name to create a UUID for - * @return string - * @throws InvalidUuidStringException + * @param string|UuidInterface $ns The namespace (must be a valid UUID) */ -function v5($ns, $name) +function v5($ns, string $name): string { return Uuid::uuid5($ns, $name)->toString(); } diff --git a/tests/Builder/DefaultUuidBuilderTest.php b/tests/Builder/DefaultUuidBuilderTest.php index 26aaf8b..2191001 100644 --- a/tests/Builder/DefaultUuidBuilderTest.php +++ b/tests/Builder/DefaultUuidBuilderTest.php @@ -1,5 +1,7 @@ '5411', 'clock_seq_hi_and_reserved' => '73', 'clock_seq_low' => '22', - 'node' => 'be0725c8ce01' + 'node' => 'be0725c8ce01', ]; $result = $builder->build($codec, $fields); diff --git a/tests/Builder/DegradedUuidBuilderTest.php b/tests/Builder/DegradedUuidBuilderTest.php index b8668f6..1d22135 100644 --- a/tests/Builder/DegradedUuidBuilderTest.php +++ b/tests/Builder/DegradedUuidBuilderTest.php @@ -1,5 +1,7 @@ '5411', 'clock_seq_hi_and_reserved' => '73', 'clock_seq_low' => '22', - 'node' => 'be0725c8ce01' + 'node' => 'be0725c8ce01', ]; $result = $builder->build($codec, $fields); diff --git a/tests/Codec/GuidStringCodecTest.php b/tests/Codec/GuidStringCodecTest.php index 6b46398..179099e 100644 --- a/tests/Codec/GuidStringCodecTest.php +++ b/tests/Codec/GuidStringCodecTest.php @@ -1,5 +1,7 @@ 'abcd', 'clock_seq_hi_and_reserved' => 'ab', 'clock_seq_low' => 'ef', - 'node' => '1234abcd4321']; + 'node' => '1234abcd4321', + ]; } protected function tearDown(): void @@ -73,7 +76,6 @@ class GuidStringCodecTest extends TestCase $this->assertEquals('12345678-1234-abcd-abef-1234abcd4321', $result); } - public function testEncodeBinaryUsesFieldsArray(): void { $this->uuid->expects($this->once()) diff --git a/tests/Codec/OrderedTimeCodecTest.php b/tests/Codec/OrderedTimeCodecTest.php index 5464c22..1041dd7 100644 --- a/tests/Codec/OrderedTimeCodecTest.php +++ b/tests/Codec/OrderedTimeCodecTest.php @@ -1,5 +1,7 @@ '11d8', 'clock_seq_hi_and_reserved' => '96', 'clock_seq_low' => '69', - 'node' => '0800200c9a66']; + 'node' => '0800200c9a66', + ]; } protected function tearDown(): void diff --git a/tests/Codec/StringCodecTest.php b/tests/Codec/StringCodecTest.php index 6d2ca24..8536990 100644 --- a/tests/Codec/StringCodecTest.php +++ b/tests/Codec/StringCodecTest.php @@ -1,5 +1,7 @@ 'abcd', 'clock_seq_hi_and_reserved' => 'ab', 'clock_seq_low' => 'ef', - 'node' => '1234abcd4321']; + 'node' => '1234abcd4321', + ]; } protected function tearDown(): void diff --git a/tests/Converter/Number/BigNumberConverterTest.php b/tests/Converter/Number/BigNumberConverterTest.php index 393e14f..877df98 100644 --- a/tests/Converter/Number/BigNumberConverterTest.php +++ b/tests/Converter/Number/BigNumberConverterTest.php @@ -1,5 +1,7 @@ sprintf('%08x', $calculatedTime & 0xffffffff), 'mid' => sprintf('%04x', ($calculatedTime >> 32) & 0xffff), - 'hi' => sprintf('%04x', ($calculatedTime >> 48) & 0x0fff) + 'hi' => sprintf('%04x', ($calculatedTime >> 48) & 0x0fff), ]; $converter = new BigNumberTimeConverter(); diff --git a/tests/Converter/Time/DegradedTimeConverterTest.php b/tests/Converter/Time/DegradedTimeConverterTest.php index 1b49732..9597240 100644 --- a/tests/Converter/Time/DegradedTimeConverterTest.php +++ b/tests/Converter/Time/DegradedTimeConverterTest.php @@ -1,5 +1,7 @@ sprintf('%08x', $calculatedTime & 0xffffffff), 'mid' => sprintf('%04x', ($calculatedTime >> 32) & 0xffff), - 'hi' => sprintf('%04x', ($calculatedTime >> 48) & 0x0fff) + 'hi' => sprintf('%04x', ($calculatedTime >> 48) & 0x0fff), ]; $converter = new GmpTimeConverter(); diff --git a/tests/Converter/Time/PhpTimeConverterTest.php b/tests/Converter/Time/PhpTimeConverterTest.php index 59196e9..c30c654 100644 --- a/tests/Converter/Time/PhpTimeConverterTest.php +++ b/tests/Converter/Time/PhpTimeConverterTest.php @@ -1,5 +1,7 @@ sprintf('%08x', $calculatedTime & 0xffffffff), 'mid' => sprintf('%04x', ($calculatedTime >> 32) & 0xffff), - 'hi' => sprintf('%04x', ($calculatedTime >> 48) & 0x0fff) + 'hi' => sprintf('%04x', ($calculatedTime >> 48) & 0x0fff), ]; $converter = new PhpTimeConverter(); diff --git a/tests/Encoder/TimestampFirstCombCodecTest.php b/tests/Encoder/TimestampFirstCombCodecTest.php index 2c7ad75..61e390e 100644 --- a/tests/Encoder/TimestampFirstCombCodecTest.php +++ b/tests/Encoder/TimestampFirstCombCodecTest.php @@ -1,5 +1,7 @@ '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', - 'node' => '0800200c9a66' + 'node' => '0800200c9a66', ] ); $this->codec->decode('0800200c-9a66-11e1-9b21-ff6f8cb0c57d'); @@ -81,7 +83,7 @@ class TimestampFirstCombCodecTest extends TestCase 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', - 'node' => '0800200c9a66' + 'node' => '0800200c9a66', ] ); $this->codec->decodeBytes((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d')); diff --git a/tests/Encoder/TimestampLastCombCodecTest.php b/tests/Encoder/TimestampLastCombCodecTest.php index 475d7dd..1b4fb08 100644 --- a/tests/Encoder/TimestampLastCombCodecTest.php +++ b/tests/Encoder/TimestampLastCombCodecTest.php @@ -1,4 +1,7 @@ '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', - 'node' => 'ff6f8cb0c57d' + 'node' => 'ff6f8cb0c57d', ] ); $this->codec->decode('0800200c-9a66-11e1-9b21-ff6f8cb0c57d'); @@ -80,7 +83,7 @@ class TimestampLastCombCodecTest extends TestCase 'time_hi_and_version' => '11e1', 'clock_seq_hi_and_reserved' => '9b', 'clock_seq_low' => '21', - 'node' => 'ff6f8cb0c57d' + 'node' => 'ff6f8cb0c57d', ] ); $this->codec->decodeBytes((string) hex2bin('0800200c9a6611e19b21ff6f8cb0c57d')); diff --git a/tests/FunctionsTest.php b/tests/FunctionsTest.php index e8590bf..2764dbb 100644 --- a/tests/FunctionsTest.php +++ b/tests/FunctionsTest.php @@ -1,8 +1,11 @@ timestampBytes); + $expectedLength = $length - $this->timestampBytes; /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); @@ -60,7 +62,7 @@ class CombGeneratorTest extends TestCase /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); $randomGenerator->method('generate') - ->with(($length - $this->timestampBytes)) + ->with($length - $this->timestampBytes) ->willReturn($hash); /** @var MockObject & NumberConverterInterface $converter */ @@ -79,7 +81,7 @@ class CombGeneratorTest extends TestCase } /** - * @return array[] + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification */ public function lengthLessThanSix(): array { @@ -87,11 +89,11 @@ class CombGeneratorTest extends TestCase } /** - * @dataProvider lengthLessThanSix - * @param int $length * @throws Exception + * + * @dataProvider lengthLessThanSix */ - public function testGenerateWithLessThanTimestampBytesThrowsException($length): void + public function testGenerateWithLessThanTimestampBytesThrowsException(int $length): void { /** @var MockObject & RandomGeneratorInterface $randomGenerator */ $randomGenerator = $this->getMockBuilder(RandomGeneratorInterface::class)->getMock(); diff --git a/tests/Generator/DefaultTimeGeneratorTest.php b/tests/Generator/DefaultTimeGeneratorTest.php index 8ce1e9f..e3e90a0 100644 --- a/tests/Generator/DefaultTimeGeneratorTest.php +++ b/tests/Generator/DefaultTimeGeneratorTest.php @@ -1,5 +1,7 @@ timeConverter->method('calculateTime') ->with($this->currentTime['sec'], $this->currentTime['usec']) ->willReturn($this->calculatedTime); - $binaryUtils = Mockery::mock('alias:'.BinaryUtils::class); + $binaryUtils = Mockery::mock('alias:' . BinaryUtils::class); $binaryUtils->shouldReceive('applyVersion') ->with($this->calculatedTime['hi'], 1) ->andReturn(971); @@ -158,7 +160,7 @@ class DefaultTimeGeneratorTest extends TestCase { $this->timeProvider->method('currentTime')->willReturn($this->currentTime); $this->timeConverter->method('calculateTime')->willReturn($this->calculatedTime); - $binaryUtils = Mockery::mock('alias:'.BinaryUtils::class); + $binaryUtils = Mockery::mock('alias:' . BinaryUtils::class); $binaryUtils->shouldReceive('applyVersion')->andReturn(971); $binaryUtils->shouldReceive('applyVariant')->andReturn(143); @@ -200,7 +202,7 @@ class DefaultTimeGeneratorTest extends TestCase */ public function testGenerateUsesRandomSequenceWhenClockSeqNull(): void { - $random_int = AspectMock::func('Ramsey\Uuid\Generator', 'random_int', 9622); + $randomInt = AspectMock::func('Ramsey\Uuid\Generator', 'random_int', 9622); $this->timeProvider->method('currentTime') ->willReturn($this->currentTime); $this->timeConverter->expects($this->once()) @@ -213,6 +215,6 @@ class DefaultTimeGeneratorTest extends TestCase $this->timeProvider ); $defaultTimeGenerator->generate($this->nodeId); - $random_int->verifyInvokedOnce([0, 0x3fff]); + $randomInt->verifyInvokedOnce([0, 0x3fff]); } } diff --git a/tests/Generator/PeclUuidRandomGeneratorTest.php b/tests/Generator/PeclUuidRandomGeneratorTest.php index 7841ebd..ab89aa7 100644 --- a/tests/Generator/PeclUuidRandomGeneratorTest.php +++ b/tests/Generator/PeclUuidRandomGeneratorTest.php @@ -1,5 +1,7 @@ uuidString); $parse = AspectMock::func('Ramsey\Uuid\Generator', 'uuid_parse', $this->uuidBinary); - $generator = new PeclUuidRandomGenerator; + $generator = new PeclUuidRandomGenerator(); $uuid = $generator->generate($this->length); $this->assertEquals($this->uuidBinary, $uuid); diff --git a/tests/Generator/PeclUuidTestCase.php b/tests/Generator/PeclUuidTestCase.php index c0dbff6..cb0f6b7 100644 --- a/tests/Generator/PeclUuidTestCase.php +++ b/tests/Generator/PeclUuidTestCase.php @@ -1,5 +1,7 @@ uuidString); $parse = AspectMock::func('Ramsey\Uuid\Generator', 'uuid_parse', $this->uuidBinary); - $generator = new PeclUuidTimeGenerator; + $generator = new PeclUuidTimeGenerator(); $uuid = $generator->generate(); $this->assertEquals($this->uuidBinary, $uuid); @@ -32,7 +34,7 @@ class PeclUuidTimeGeneratorTest extends PeclUuidTestCase { $create = AspectMock::func('Ramsey\Uuid\Generator', 'uuid_create', $this->uuidString); $parse = AspectMock::func('Ramsey\Uuid\Generator', 'uuid_parse', $this->uuidBinary); - $generator = new PeclUuidTimeGenerator; + $generator = new PeclUuidTimeGenerator(); $uuid = $generator->generate(); $this->assertEquals($this->uuidBinary, $uuid); diff --git a/tests/Generator/RandomBytesGeneratorTest.php b/tests/Generator/RandomBytesGeneratorTest.php index 67c34b9..c1f4875 100644 --- a/tests/Generator/RandomBytesGeneratorTest.php +++ b/tests/Generator/RandomBytesGeneratorTest.php @@ -1,5 +1,7 @@ getMock(); $generator->expects($this->once()) ->method('generate') - ->with($length); + ->with($length) + ->willReturn('foo'); $adapter = new RandomLibAdapter($generator); $adapter->generate($length); diff --git a/tests/Generator/TimeGeneratorFactoryTest.php b/tests/Generator/TimeGeneratorFactoryTest.php index 0b7a0c8..dcf1a34 100644 --- a/tests/Generator/TimeGeneratorFactoryTest.php +++ b/tests/Generator/TimeGeneratorFactoryTest.php @@ -1,5 +1,7 @@ arrangeMockFunctions( null, null, - function () use ($netstatOutput) { + function () use ($netstatOutput): void { echo $netstatOutput; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act upon the system under test/*/ + /* Act upon the system under test */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert the result match expectations /*/ + /* Assert the result match expectations */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertSame($expected, $node); @@ -90,29 +88,26 @@ class SystemNodeProviderTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * * @dataProvider provideInvalidNetStatOutput - * - * @param string $netstatOutput */ - public function testGetNodeShouldNotReturnsSystemNodeForInvalidMacAddress($netstatOutput): void + public function testGetNodeShouldNotReturnsSystemNodeForInvalidMacAddress(string $netstatOutput): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () use ($netstatOutput) { + function () use ($netstatOutput): void { echo $netstatOutput; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertFalse($node); @@ -121,30 +116,26 @@ class SystemNodeProviderTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * * @dataProvider provideNotationalFormats - * - * @param string $formatted - * @param string $expected */ - public function testGetNodeReturnsNodeStrippedOfNotationalFormatting($formatted, $expected): void + public function testGetNodeReturnsNodeStrippedOfNotationalFormatting(string $formatted, string $expected): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () use ($formatted) { + function () use ($formatted): void { echo "\n{$formatted}\n"; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertEquals($expected, $node); @@ -153,29 +144,26 @@ class SystemNodeProviderTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * * @dataProvider provideInvalidNotationalFormats - * - * @param string $formatted */ - public function testGetNodeDoesNotAcceptIncorrectNotationalFormatting($formatted): void + public function testGetNodeDoesNotAcceptIncorrectNotationalFormatting(string $formatted): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () use ($formatted) { + function () use ($formatted): void { echo "\n{$formatted}\n"; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertEquals(false, $node); @@ -187,22 +175,22 @@ class SystemNodeProviderTest extends TestCase */ public function testGetNodeReturnsFirstMacAddressFound(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () { + function (): void { echo "\nAA-BB-CC-DD-EE-FF\n00-11-22-33-44-55\nFF-11-EE-22-DD-33\n"; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertEquals('AABBCCDDEEFF', $node); @@ -214,22 +202,22 @@ class SystemNodeProviderTest extends TestCase */ public function testGetNodeReturnsFalseWhenNodeIsNotFound(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () { + function (): void { echo 'some string that does not match the mac address'; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertFalse($node); @@ -241,23 +229,23 @@ class SystemNodeProviderTest extends TestCase */ public function testGetNodeWillNotExecuteSystemCallIfFailedFirstTime(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () { + function (): void { echo 'some string that does not match the mac address'; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $provider->getNode(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertFalse($node); @@ -266,15 +254,11 @@ class SystemNodeProviderTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * * @dataProvider provideCommandPerOs - * - * @param string $os - * @param string $command */ - public function testGetNodeGetsNetworkInterfaceConfig($os, $command): void + public function testGetNodeGetsNetworkInterfaceConfig(string $os, string $command): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( 'whatever', ['mock address path'], @@ -284,11 +268,11 @@ class SystemNodeProviderTest extends TestCase true ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $globBodyAssert = null; $fileGetContentsAssert = null; $isReadableAssert = null; @@ -315,23 +299,23 @@ class SystemNodeProviderTest extends TestCase */ public function testGetNodeReturnsSameNodeUponSubsequentCalls(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () { + function (): void { echo "\nAA-BB-CC-DD-EE-FF\n"; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); $node2 = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertEquals($node, $node2); @@ -343,23 +327,23 @@ class SystemNodeProviderTest extends TestCase */ public function testSubsequentCallsToGetNodeDoNotRecallIfconfig(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, - function () { + function (): void { echo "\nAA-BB-CC-DD-EE-FF\n"; }, 'NOT LINUX', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); $node2 = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions(null, null, ['netstat -ie 2>&1'], ['PHP_OS'], ['disable_functions']); $this->assertEquals($node, $node2); @@ -368,22 +352,19 @@ class SystemNodeProviderTest extends TestCase /** * @runInSeparateProcess * @preserveGlobalState disabled - * * @dataProvider provideCommandPerOs - * - * @param string $os - * @param string $command */ - public function testCallGetsysfsOnLinux($os, $command): void + public function testCallGetsysfsOnLinux(string $os, string $command): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( function () { static $macs = ["00:00:00:00:00:00\n", "01:02:03:04:05:06\n"]; + return array_shift($macs); }, ['mock address path 1', 'mock address path 2'], - function () { + function (): void { echo "\n01-02-03-04-05-06\n"; }, $os, @@ -391,11 +372,11 @@ class SystemNodeProviderTest extends TestCase true ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $fileGetContentsAssert = null; $globBodyAssert = null; $passthruBodyAssert = [$command]; @@ -429,22 +410,22 @@ class SystemNodeProviderTest extends TestCase */ public function testCallGetsysfsOnLinuxWhenGlobReturnsFalse(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, false, - function () { + function (): void { echo "\n01-02-03-04-05-06\n"; }, 'Linux', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions( null, ['/sys/class/net/*/address'], @@ -462,22 +443,22 @@ class SystemNodeProviderTest extends TestCase */ public function testCallGetsysfsOnLinuxWhenGlobReturnsEmptyArray(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, [], - function () { + function (): void { echo "\n01-02-03-04-05-06\n"; }, 'Linux', 'nothing disabled' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions( null, ['/sys/class/net/*/address'], @@ -495,11 +476,11 @@ class SystemNodeProviderTest extends TestCase */ public function testCallGetsysfsOnLinuxWhenGlobFilesAreNotReadable(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, ['mock address path 1', 'mock address path 2'], - function () { + function (): void { echo "\n01-02-03-04-05-06\n"; }, 'Linux', @@ -507,11 +488,11 @@ class SystemNodeProviderTest extends TestCase false ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions( null, ['/sys/class/net/*/address'], @@ -524,14 +505,13 @@ class SystemNodeProviderTest extends TestCase $this->assertEquals('010203040506', $node); } - /** * @runInSeparateProcess * @preserveGlobalState disabled */ public function testGetNodeReturnsFalseWhenPassthruIsDisabled(): void { - /*/ Arrange /*/ + /* Arrange */ $this->arrangeMockFunctions( null, null, @@ -540,11 +520,11 @@ class SystemNodeProviderTest extends TestCase 'PASSTHRU,some_other_function' ); - /*/ Act /*/ + /* Act */ $provider = new SystemNodeProvider(); $node = $provider->getNode(); - /*/ Assert /*/ + /* Assert */ $this->assertMockFunctions( null, null, @@ -583,7 +563,7 @@ class SystemNodeProviderTest extends TestCase self::MOCK_IS_READABLE => $isReadableBody, ]; - array_walk($mockFunction, function ($body, $key) { + array_walk($mockFunction, function ($body, $key): void { $this->functionProxies[$key] = AspectMock::func(self::PROVIDER_NAMESPACE, $key, $body); }); } @@ -617,7 +597,7 @@ class SystemNodeProviderTest extends TestCase self::MOCK_IS_READABLE => $isReadableAssert, ]; - array_walk($mockFunctionAsserts, function ($asserts, $key) { + array_walk($mockFunctionAsserts, function ($asserts, $key): void { if ($asserts === null) { $this->functionProxies[$key]->verifyNeverInvoked(); } elseif (is_array($asserts)) { @@ -632,6 +612,7 @@ class SystemNodeProviderTest extends TestCase 'Given parameter for %s must be an array or NULL, "%s" given.', [$key, gettype($asserts)] ); + throw new InvalidArgumentException($error); } }); @@ -640,7 +621,7 @@ class SystemNodeProviderTest extends TestCase /** * Provides the command that should be executed per supported OS * - * @return array[] + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification */ public function provideCommandPerOs(): array { @@ -657,14 +638,14 @@ class SystemNodeProviderTest extends TestCase /** * Values that are NOT parsed to a mac address by the class under test * - * @return array[] + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification */ public function provideInvalidNetStatOutput(): array { return [ 'Not an octal value' => [ - "The program 'netstat' is currently not installed.' . - ' You can install it by typing:\nsudo apt install net-tools\n" + "The program 'netstat' is currently not installed. " . + "You can install it by typing:\nsudo apt install net-tools\n", ], 'One character too short' => ["\nA-BB-CC-DD-EE-FF\n"], 'One tuple too short' => ["\nBB-CC-DD-EE-FF\n"], @@ -682,7 +663,7 @@ class SystemNodeProviderTest extends TestCase /** * Provides notations that the class under test should NOT attempt to strip * - * @return array[] + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification */ public function provideInvalidNotationalFormats(): array { @@ -701,25 +682,25 @@ class SystemNodeProviderTest extends TestCase /** * Provides mac addresses that the class under test should strip notational format from * - * @return array[] + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification */ public function provideNotationalFormats(): array { return [ ['01-23-45-67-89-ab', '0123456789ab'], - ['01:23:45:67:89:ab', '0123456789ab'] + ['01:23:45:67:89:ab', '0123456789ab'], ]; } /** * Values that are parsed to a mac address by the class under test * - * @return array[] + * @phpcsSuppress SlevomatCodingStandard.TypeHints.ReturnTypeHint.MissingTraversableTypeHintSpecification */ public function provideValidNetStatOutput(): array { return [ - /*/ Full output of related command /*/ + /* Full output of related command */ 'Full output - Linux' => [<<<'TXT' Kernel Interface table docker0 Link encap:Ethernet HWaddr 01:23:45:67:89:ab @@ -748,7 +729,8 @@ class SystemNodeProviderTest extends TestCase collisions:0 txqueuelen:1000 RX bytes:1094983 (1.0 MB) TX bytes:1094983 (1.0 MB) TXT - , '0123456789ab'], + , '0123456789ab', + ], 'Full output - MacOS' => [<<<'TXT' lo0: flags=8049 mtu 16384 options=1203 @@ -815,7 +797,8 @@ TXT inet6 fe80::57c6:d692:9d41:d28f%utun0 prefixlen 64 scopeid 0xe nd6 options=201 TXT - , '10ddb1b4e48e'], + , '10ddb1b4e48e', + ], 'Full output - Window' => [<<<'TXT' Windows IP Configuration @@ -854,32 +837,34 @@ TXT DHCP Enabled. . . . . . . . . . . : No Autoconfiguration Enabled . . . . : Yes TXT - , '080027B842C6'], + , '080027B842C6', + ], 'Full output - FreeBSD' => [<<<'TXT' Name Mtu Network Address Ipkts Ierrs Idrop Opkts Oerrs Coll em0 1500 08:00:27:71:a1:00 65514 0 0 42918 0 0 em1 1500 08:00:27:d0:60:a0 1199 0 0 535 0 0 lo0 16384 lo0 4 0 0 4 0 0 TXT - , '08002771a100'], + , '08002771a100', + ], - /*/ The single line that is relevant /*/ + /* The single line that is relevant */ 'Linux - single line' => ["\ndocker0 Link encap:Ethernet HWaddr 01:23:45:67:89:ab\n", '0123456789ab'], 'MacOS - Single line ' => ["\nether 10:dd:b1:b4:e4:8e\n", '10ddb1b4e48e'], 'Window - single line' => ["\nPhysical Address. . . . . . . . . : 08-00-27-B8-42-C6\n", '080027B842C6'], - /*/ Minimal subsets of the single line to show the differences /*/ + /* Minimal subsets of the single line to show the differences */ 'with colon, with linebreak, with space' => ["\n : AA-BB-CC-DD-EE-FF\n", 'AABBCCDDEEFF'], 'without colon, with linebreak, with space' => ["\n AA-BB-CC-DD-EE-FF \n", 'AABBCCDDEEFF'], 'without colon, with linebreak, without space' => ["\nAA-BB-CC-DD-EE-FF\n", 'AABBCCDDEEFF'], 'without colon, without linebreak, with space' => [' AA-BB-CC-DD-EE-FF ', 'AABBCCDDEEFF'], - /*/ Other accepted variations /*/ + /* Other accepted variations */ 'Actual mac - 1' => ["\n52:54:00:14:91:69\n", '525400149169'], 'Actual mac - 2' => ["\n00:16:3e:a9:73:f0\n", '00163ea973f0'], 'FF:FF:FF:FF:FF:FF' => ["\nFF:FF:FF:FF:FF:FF\n", 'FFFFFFFFFFFF'], - /*/ Incorrect variations that are also accepted /*/ + /* Incorrect variations that are also accepted */ 'Local host' => ["\n00:00:00:00:00:00\n", '000000000000'], 'Too long -- extra character' => ["\nABC-01-23-45-67-89\n", 'BC0123456789'], 'Too long -- extra tuple' => ["\n01-AA-BB-CC-DD-EE-FF\n", '01AABBCCDDEE'], diff --git a/tests/Provider/Time/FixedTimeProviderTest.php b/tests/Provider/Time/FixedTimeProviderTest.php index 5c8295a..cf28459 100644 --- a/tests/Provider/Time/FixedTimeProviderTest.php +++ b/tests/Provider/Time/FixedTimeProviderTest.php @@ -1,5 +1,7 @@ assertInstanceOf(Uuid::class, $guid); - // UUID's and GUID's share the same textual representation + + // UUID's and GUID's share the same textual representation. $this->assertEquals($uuid->toString(), $guid->toString()); - // But not the same binary representation (this assertion is valid on little endian hosts - // only) + + // But not the same binary representation (this assertion is valid on + // little endian hosts only). $this->assertNotEquals(bin2hex($uuid->getBytes()), bin2hex($guid->getBytes())); } /** - * Tests that UUID and GUID's have the same textual representation and the same binary representation. + * Tests that UUID and GUID's have the same textual representation and the + * same binary representation. + * * This test is only valid on big endian hosts. */ public function testFromGuidStringOnBigEndianHost(): void @@ -113,7 +122,7 @@ class UuidTest extends TestCase public function testGetBytes(): void { $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); - $this->assertEquals(16, \strlen($uuid->getBytes())); + $this->assertEquals(16, strlen($uuid->getBytes())); $this->assertEquals('/2+MsMV9EeGbIQgAIAyaZg==', base64_encode($uuid->getBytes())); } @@ -163,22 +172,22 @@ class UuidTest extends TestCase { // Check a recent date $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c')); // Check an old date $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c')); // Check a future date $uuid = Uuid::fromString('ff9785f6-ffff-1fff-9669-00007ffffffe'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c')); // Check the oldest date $uuid = Uuid::fromString('00000000-0000-1000-9669-00007ffffffe'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c')); } @@ -189,22 +198,22 @@ class UuidTest extends TestCase // Check a recent date $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c')); // Check an old date $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c')); // Check a future date $uuid = Uuid::fromString('ff9785f6-ffff-1fff-9669-00007ffffffe'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c')); // Check the oldest date $uuid = Uuid::fromString('00000000-0000-1000-9669-00007ffffffe'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c')); } @@ -215,22 +224,22 @@ class UuidTest extends TestCase // Check a recent date $uuid = Uuid::fromString('ff6f8cb0-c57d-11e1-9b21-0800200c9a66'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('2012-07-04T02:14:34+00:00', $uuid->getDateTime()->format('c')); // Check an old date $uuid = Uuid::fromString('0901e600-0154-1000-9b21-0800200c9a66'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('1582-10-16T16:34:04+00:00', $uuid->getDateTime()->format('c')); // Check a future date $uuid = Uuid::fromString('ff9785f6-ffff-1fff-9669-00007ffffffe'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('5236-03-31T21:21:00+00:00', $uuid->getDateTime()->format('c')); // Check the oldest date $uuid = Uuid::fromString('00000000-0000-1000-9669-00007ffffffe'); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals('1582-10-15T00:00:00+00:00', $uuid->getDateTime()->format('c')); } @@ -639,7 +648,7 @@ class UuidTest extends TestCase { $uuid = Uuid::uuid1(); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals(2, $uuid->getVariant()); $this->assertEquals(1, $uuid->getVersion()); } @@ -651,7 +660,7 @@ class UuidTest extends TestCase /** @var Uuid $uuid */ $uuid = Uuid::uuid1((int) 0x0800200c9a66, 0x1669); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals(2, $uuid->getVariant()); $this->assertEquals(1, $uuid->getVersion()); $this->assertEquals(5737, $uuid->getClockSequence()); @@ -665,12 +674,12 @@ class UuidTest extends TestCase $uuid = Uuid::uuid1('7160355e'); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals(2, $uuid->getVariant()); $this->assertEquals(1, $uuid->getVersion()); $this->assertEquals('00007160355e', $uuid->getNodeHex()); - if (PHP_INT_SIZE == 8) { + if (PHP_INT_SIZE === 8) { $this->assertEquals(1902130526, $uuid->getNode()); } } @@ -681,12 +690,12 @@ class UuidTest extends TestCase $uuid = Uuid::uuid1('71B0aD5e'); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals(2, $uuid->getVariant()); $this->assertEquals(1, $uuid->getVersion()); $this->assertEquals('000071b0ad5e', $uuid->getNodeHex()); - if (PHP_INT_SIZE == 8) { + if (PHP_INT_SIZE === 8) { $this->assertEquals(1907404126, $uuid->getNode()); } } @@ -696,14 +705,14 @@ class UuidTest extends TestCase /** @var Uuid $uuid */ $uuid = Uuid::uuid1(0x7fffffff, 0x1669); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals(2, $uuid->getVariant()); $this->assertEquals(1, $uuid->getVersion()); $this->assertEquals(5737, $uuid->getClockSequence()); $this->assertEquals('00007fffffff', $uuid->getNodeHex()); $this->assertEquals('9669-00007fffffff', substr($uuid->toString(), 19)); - if (PHP_INT_SIZE == 8) { + if (PHP_INT_SIZE === 8) { $this->assertEquals(2147483647, $uuid->getNode()); } } @@ -738,7 +747,7 @@ class UuidTest extends TestCase $uuid = Uuid::uuid1(); $this->assertInstanceOf(Uuid::class, $uuid); - $this->assertInstanceOf(\DateTimeInterface::class, $uuid->getDateTime()); + $this->assertInstanceOf(DateTimeInterface::class, $uuid->getDateTime()); $this->assertEquals(2, $uuid->getVariant()); $this->assertEquals(1, $uuid->getVersion()); } @@ -746,8 +755,8 @@ class UuidTest extends TestCase /** * The "python.org" UUID is a known entity, so we're testing that this * library generates a matching UUID for the same name. - * @see http://docs.python.org/library/uuid.html * + * @see http://docs.python.org/library/uuid.html */ public function testUuid3WithNamespaceAsUuidObject(): void { @@ -761,8 +770,8 @@ class UuidTest extends TestCase /** * The "python.org" UUID is a known entity, so we're testing that this * library generates a matching UUID for the same name. - * @see http://docs.python.org/library/uuid.html * + * @see http://docs.python.org/library/uuid.html */ public function testUuid3WithNamespaceAsUuidString(): void { @@ -777,7 +786,6 @@ class UuidTest extends TestCase * * Taken from the Python UUID tests in * http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py - * */ public function testUuid3WithKnownUuids(): void { @@ -792,7 +800,7 @@ class UuidTest extends TestCase $this->assertEquals(Uuid::RFC_4122, $uobj->getVariant()); $this->assertEquals(3, $uobj->getVersion()); $this->assertEquals(Uuid::fromString($ustr), $uobj); - $this->assertEquals((string)$uobj, $ustr); + $this->assertEquals((string) $uobj, $ustr); } } @@ -813,7 +821,6 @@ class UuidTest extends TestCase $mock->expects($this->any()) ->method('generate') ->willReturnCallback(function ($length) { - // Makes first fields of UUIDs equal return str_pad('', $length, '0'); }); @@ -844,7 +851,6 @@ class UuidTest extends TestCase $mock->expects($this->any()) ->method('generate') ->willReturnCallback(function ($length) { - // Makes first fields of UUIDs equal return str_pad('', $length, '0'); }); @@ -887,8 +893,8 @@ class UuidTest extends TestCase /** * The "python.org" UUID is a known entity, so we're testing that this * library generates a matching UUID for the same name. - * @see http://docs.python.org/library/uuid.html * + * @see http://docs.python.org/library/uuid.html */ public function testUuid5WithNamespaceAsUuidObject(): void { @@ -902,8 +908,8 @@ class UuidTest extends TestCase /** * The "python.org" UUID is a known entity, so we're testing that this * library generates a matching UUID for the same name. - * @see http://docs.python.org/library/uuid.html * + * @see http://docs.python.org/library/uuid.html */ public function testUuid5WithNamespaceAsUuidString(): void { @@ -918,7 +924,6 @@ class UuidTest extends TestCase * * Taken from the Python UUID tests in * http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py - * */ public function testUuid5WithKnownUuids(): void { @@ -933,7 +938,7 @@ class UuidTest extends TestCase $this->assertEquals(Uuid::RFC_4122, $uobj->getVariant()); $this->assertEquals(5, $uobj->getVersion()); $this->assertEquals(Uuid::fromString($ustr), $uobj); - $this->assertEquals((string)$uobj, $ustr); + $this->assertEquals((string) $uobj, $ustr); } } @@ -1012,7 +1017,7 @@ class UuidTest extends TestCase Uuid::setFactory(new UuidFactory($featureSet)); $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('c4dbe7e2-097f-11e2-9669-00007ffffffe', (string)$uuidA); + $this->assertEquals('c4dbe7e2-097f-11e2-9669-00007ffffffe', (string) $uuidA); $this->assertEquals('c4dbe7e2', $uuidA->getTimeLowHex()); $this->assertEquals('097f', $uuidA->getTimeMidHex()); $this->assertEquals('11e2', $uuidA->getTimeHiAndVersionHex()); @@ -1021,7 +1026,7 @@ class UuidTest extends TestCase $timeOfDay->setUsec(0); $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('c4b18100-097f-11e2-9669-00007ffffffe', (string)$uuidB); + $this->assertEquals('c4b18100-097f-11e2-9669-00007ffffffe', (string) $uuidB); $this->assertEquals('c4b18100', $uuidB->getTimeLowHex()); $this->assertEquals('097f', $uuidB->getTimeMidHex()); $this->assertEquals('11e2', $uuidB->getTimeHiAndVersionHex()); @@ -1030,7 +1035,7 @@ class UuidTest extends TestCase $timeOfDay->setUsec(999999); $uuidC = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('c54a1776-097f-11e2-9669-00007ffffffe', (string)$uuidC); + $this->assertEquals('c54a1776-097f-11e2-9669-00007ffffffe', (string) $uuidC); $this->assertEquals('c54a1776', $uuidC->getTimeLowHex()); $this->assertEquals('097f', $uuidC->getTimeMidHex()); $this->assertEquals('11e2', $uuidC->getTimeHiAndVersionHex()); @@ -1083,12 +1088,12 @@ class UuidTest extends TestCase { $this->skipIfNoGmp(); - $timeOfDay = new FixedTimeProvider(array( + $timeOfDay = new FixedTimeProvider([ 'sec' => 1348845514, 'usec' => 277885, 'minuteswest' => 0, 'dsttime' => 0, - )); + ]); $featureSet = new FeatureSet(false, true); $featureSet->setTimeProvider($timeOfDay); @@ -1098,7 +1103,7 @@ class UuidTest extends TestCase // For usec = 277885 $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('c4dbe7e2-097f-11e2-9669-00007ffffffe', (string)$uuidA); + $this->assertEquals('c4dbe7e2-097f-11e2-9669-00007ffffffe', (string) $uuidA); $this->assertEquals('c4dbe7e2', $uuidA->getTimeLowHex()); $this->assertEquals('097f', $uuidA->getTimeMidHex()); $this->assertEquals('11e2', $uuidA->getTimeHiAndVersionHex()); @@ -1107,7 +1112,7 @@ class UuidTest extends TestCase $timeOfDay->setUsec(0); $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('c4b18100-097f-11e2-9669-00007ffffffe', (string)$uuidB); + $this->assertEquals('c4b18100-097f-11e2-9669-00007ffffffe', (string) $uuidB); $this->assertEquals('c4b18100', $uuidB->getTimeLowHex()); $this->assertEquals('097f', $uuidB->getTimeMidHex()); $this->assertEquals('11e2', $uuidB->getTimeHiAndVersionHex()); @@ -1116,7 +1121,7 @@ class UuidTest extends TestCase $timeOfDay->setUsec(999999); $uuidC = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('c54a1776-097f-11e2-9669-00007ffffffe', (string)$uuidC); + $this->assertEquals('c54a1776-097f-11e2-9669-00007ffffffe', (string) $uuidC); $this->assertEquals('c54a1776', $uuidC->getTimeLowHex()); $this->assertEquals('097f', $uuidC->getTimeMidHex()); $this->assertEquals('11e2', $uuidC->getTimeHiAndVersionHex()); @@ -1140,7 +1145,7 @@ class UuidTest extends TestCase Uuid::setFactory(new UuidFactory($featureSet)); $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('ff9785f6-ffff-1fff-9669-00007ffffffe', (string)$uuidA); + $this->assertEquals('ff9785f6-ffff-1fff-9669-00007ffffffe', (string) $uuidA); $this->assertEquals('ff9785f6', $uuidA->getTimeLowHex()); $this->assertEquals('ffff', $uuidA->getTimeMidHex()); $this->assertEquals('1fff', $uuidA->getTimeHiAndVersionHex()); @@ -1158,7 +1163,7 @@ class UuidTest extends TestCase Uuid::setFactory(new UuidFactory($featureSet)); $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('00000000-0000-1000-9669-00007ffffffe', (string)$uuidB); + $this->assertEquals('00000000-0000-1000-9669-00007ffffffe', (string) $uuidB); $this->assertEquals('00000000', $uuidB->getTimeLowHex()); $this->assertEquals('0000', $uuidB->getTimeMidHex()); $this->assertEquals('1000', $uuidB->getTimeHiAndVersionHex()); @@ -1167,7 +1172,6 @@ class UuidTest extends TestCase /** * This test ensures that the UUIDs generated by the 32-bit GMP path match * those generated by the 64-bit path, given the same 64-bit time values. - * */ public function testCalculateUuidTimeUpperLowerBounds64BitThrough32BitGmpPath(): void { @@ -1190,7 +1194,7 @@ class UuidTest extends TestCase $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('ff9785f6-ffff-1fff-9669-00007ffffffe', (string)$uuidA); + $this->assertEquals('ff9785f6-ffff-1fff-9669-00007ffffffe', (string) $uuidA); $this->assertEquals('ff9785f6', $uuidA->getTimeLowHex()); $this->assertEquals('ffff', $uuidA->getTimeMidHex()); $this->assertEquals('1fff', $uuidA->getTimeHiAndVersionHex()); @@ -1209,7 +1213,7 @@ class UuidTest extends TestCase $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('00000000-0000-1000-9669-00007ffffffe', (string)$uuidB); + $this->assertEquals('00000000-0000-1000-9669-00007ffffffe', (string) $uuidB); $this->assertEquals('00000000', $uuidB->getTimeLowHex()); $this->assertEquals('0000', $uuidB->getTimeMidHex()); $this->assertEquals('1000', $uuidB->getTimeHiAndVersionHex()); @@ -1218,7 +1222,6 @@ class UuidTest extends TestCase /** * This test ensures that the UUIDs generated by the 32-bit Moontoast path match * those generated by the 64-bit path, given the same 64-bit time values. - * */ public function testCalculateUuidTimeUpperLowerBounds64BitThrough32BitMoontoastPath(): void { @@ -1228,12 +1231,12 @@ class UuidTest extends TestCase $featureSet = new FeatureSet(false, true, false, false, false, true); // 5235-03-31T21:20:59+00:00 - $timeOfDay = new FixedTimeProvider(array( + $timeOfDay = new FixedTimeProvider([ 'sec' => (int) 103072857659, 'usec' => 999999, 'minuteswest' => 0, 'dsttime' => 0, - )); + ]); $featureSet->setTimeProvider($timeOfDay); @@ -1247,12 +1250,12 @@ class UuidTest extends TestCase $this->assertEquals('1fff', $uuidA->getTimeHiAndVersionHex()); // 1582-10-15T00:00:00+00:00 - $timeOfDay = new FixedTimeProvider(array( + $timeOfDay = new FixedTimeProvider([ 'sec' => (int) -12219292800, 'usec' => 0, 'minuteswest' => 0, 'dsttime' => 0, - )); + ]); $featureSet->setTimeProvider($timeOfDay); @@ -1285,7 +1288,7 @@ class UuidTest extends TestCase $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('13813ff6-6912-11fe-9669-00007ffffffe', (string)$uuidA); + $this->assertEquals('13813ff6-6912-11fe-9669-00007ffffffe', (string) $uuidA); $this->assertEquals('13813ff6', $uuidA->getTimeLowHex()); $this->assertEquals('6912', $uuidA->getTimeMidHex()); $this->assertEquals('11fe', $uuidA->getTimeHiAndVersionHex()); @@ -1304,7 +1307,7 @@ class UuidTest extends TestCase $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('1419d680-d292-1165-9669-00007ffffffe', (string)$uuidB); + $this->assertEquals('1419d680-d292-1165-9669-00007ffffffe', (string) $uuidB); $this->assertEquals('1419d680', $uuidB->getTimeLowHex()); $this->assertEquals('d292', $uuidB->getTimeMidHex()); $this->assertEquals('1165', $uuidB->getTimeHiAndVersionHex()); @@ -1315,12 +1318,12 @@ class UuidTest extends TestCase $this->skipIfNoMoontoastMath(); // 2038-01-19T03:14:07+00:00 - $timeOfDay = new FixedTimeProvider(array( + $timeOfDay = new FixedTimeProvider([ 'sec' => 2147483647, 'usec' => 999999, 'minuteswest' => 0, 'dsttime' => 0, - )); + ]); $featureSet = new FeatureSet(false, true, false, false, false, true); $featureSet->setTimeProvider($timeOfDay); @@ -1335,12 +1338,12 @@ class UuidTest extends TestCase $this->assertEquals('11fe', $uuidA->getTimeHiAndVersionHex()); // 1901-12-13T20:45:53+00:00 - $timeOfDay = new FixedTimeProvider(array( + $timeOfDay = new FixedTimeProvider([ 'sec' => -2147483647, 'usec' => 0, 'minuteswest' => 0, 'dsttime' => 0, - )); + ]); $featureSet->setTimeProvider($timeOfDay); @@ -1357,7 +1360,6 @@ class UuidTest extends TestCase /** * This test ensures that the UUIDs generated by the 64-bit path match * those generated by the 32-bit path, given the same 32-bit time values. - * */ public function testCalculateUuidTimeUpperLowerBounds32BitThrough64BitPath(): void { @@ -1378,7 +1380,7 @@ class UuidTest extends TestCase $uuidA = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('13813ff6-6912-11fe-9669-00007ffffffe', (string)$uuidA); + $this->assertEquals('13813ff6-6912-11fe-9669-00007ffffffe', (string) $uuidA); $this->assertEquals('13813ff6', $uuidA->getTimeLowHex()); $this->assertEquals('6912', $uuidA->getTimeMidHex()); $this->assertEquals('11fe', $uuidA->getTimeHiAndVersionHex()); @@ -1396,7 +1398,7 @@ class UuidTest extends TestCase Uuid::setFactory(new UuidFactory($featureSet)); $uuidB = Uuid::uuid1(0x00007ffffffe, 0x1669); - $this->assertEquals('1419d680-d292-1165-9669-00007ffffffe', (string)$uuidB); + $this->assertEquals('1419d680-d292-1165-9669-00007ffffffe', (string) $uuidB); $this->assertEquals('1419d680', $uuidB->getTimeLowHex()); $this->assertEquals('d292', $uuidB->getTimeMidHex()); $this->assertEquals('1165', $uuidB->getTimeHiAndVersionHex()); @@ -1432,7 +1434,7 @@ class UuidTest extends TestCase $factory = new UuidFactory($featureSet); while ($currentTime <= $endTime) { - foreach (array(0, 50000, 250000, 500000, 750000, 999999) as $usec) { + foreach ([0, 50000, 250000, 500000, 750000, 999999] as $usec) { $timeOfDay->setSec($currentTime); $timeOfDay->setUsec($usec); @@ -1467,12 +1469,12 @@ class UuidTest extends TestCase $currentTime = strtotime('2012-12-11T00:00:00+00:00'); $endTime = $currentTime + 3600; - $timeOfDay = new FixedTimeProvider(array( + $timeOfDay = new FixedTimeProvider([ 'sec' => $currentTime, 'usec' => 0, 'minuteswest' => 0, 'dsttime' => 0, - )); + ]); $smallIntFeatureSet = new FeatureSet(false, true); $smallIntFeatureSet->setTimeProvider($timeOfDay); @@ -1535,7 +1537,7 @@ class UuidTest extends TestCase $this->assertTrue(Uuid::isValid($argument)); // reset the static validator - $factory->setValidator(new Validator); + $factory->setValidator(new Validator()); } public function testUsingNilAsValidUuid(): void @@ -1671,7 +1673,6 @@ class UuidTest extends TestCase * * Taken from the Python UUID tests in * http://hg.python.org/cpython/file/2f4c4db9aee5/Lib/test/test_uuid.py - * */ public function testUuidPassesPythonTests(): void { @@ -1969,11 +1970,11 @@ class UuidTest extends TestCase Uuid::fromInteger($test['int']), ]; foreach ($uuids as $uuid) { - $this->assertEquals($test['string'], (string)$uuid); + $this->assertEquals($test['string'], (string) $uuid); $this->assertEquals($test['hex'], $uuid->getHex()); $this->assertEquals(base64_decode($test['bytes']), $uuid->getBytes()); if ($this->hasGmp() || $this->hasMoontoastMath()) { - $this->assertEquals($test['int'], (string)$uuid->getInteger()); + $this->assertEquals($test['int'], (string) $uuid->getInteger()); } $this->assertEquals($test['fields'], $uuid->getFieldsHex()); $this->assertEquals($test['fields']['time_low'], $uuid->getTimeLowHex()); @@ -1983,7 +1984,7 @@ class UuidTest extends TestCase $this->assertEquals($test['fields']['clock_seq_low'], $uuid->getClockSeqLowHex()); $this->assertEquals($test['fields']['node'], $uuid->getNodeHex()); $this->assertEquals($test['urn'], $uuid->getUrn()); - if ($uuid->getVersion() == 1) { + if ($uuid->getVersion() === 1) { $this->assertEquals($test['time'], $uuid->getTimestampHex()); } $this->assertEquals($test['clock_seq'], $uuid->getClockSequenceHex()); diff --git a/tests/Validator/ValidatorTest.php b/tests/Validator/ValidatorTest.php index 3a05093..fb0914a 100644 --- a/tests/Validator/ValidatorTest.php +++ b/tests/Validator/ValidatorTest.php @@ -1,5 +1,7 @@ validator = $this->getMockBuilder(Validator::class) ->disableOriginalConstructor() ->onlyMethods([]) diff --git a/tests/phpstan-bootstrap.php b/tests/phpstan-bootstrap.php index 8c3db30..de35e38 100644 --- a/tests/phpstan-bootstrap.php +++ b/tests/phpstan-bootstrap.php @@ -1,5 +1,11 @@