From ae247f1dcd5b73ffe1882d9c135f79738386e731 Mon Sep 17 00:00:00 2001 From: Ben Ramsey Date: Thu, 15 Sep 2022 22:14:04 -0500 Subject: [PATCH] chore: clean up types and PHP 8-ify the code --- phpstan.neon.dist | 2 +- src/Builder/DegradedUuidBuilder.php | 13 +-- src/Builder/FallbackBuilder.php | 8 +- src/Codec/StringCodec.php | 8 +- src/Converter/Number/BigNumberConverter.php | 5 +- .../Number/GenericNumberConverter.php | 8 +- src/Converter/Time/BigNumberTimeConverter.php | 5 +- src/Converter/Time/GenericTimeConverter.php | 8 +- src/Converter/Time/PhpTimeConverter.php | 21 +--- src/Converter/Time/UnixTimeConverter.php | 5 +- src/FeatureSet.php | 108 +++--------------- src/Fields/SerializableFieldsTrait.php | 13 ++- src/Generator/CombGenerator.php | 20 +--- src/Generator/DceSecurityGenerator.php | 27 +---- src/Generator/DefaultTimeGenerator.php | 28 +---- src/Generator/PeclUuidNameGenerator.php | 21 ++-- src/Generator/RandomLibAdapter.php | 5 +- src/Generator/TimeGeneratorFactory.php | 24 +--- src/Generator/UnixTimeGenerator.php | 13 +-- src/Guid/Fields.php | 13 +-- src/Guid/GuidBuilder.php | 16 +-- src/Lazy/LazyUuidFromString.php | 23 ++-- src/Nonstandard/Fields.php | 13 +-- src/Nonstandard/UuidBuilder.php | 16 +-- .../Dce/SystemDceSecurityProvider.php | 29 ++--- src/Provider/Node/FallbackNodeProvider.php | 10 +- src/Provider/Node/StaticNodeProvider.php | 5 +- src/Provider/Time/FixedTimeProvider.php | 14 +-- src/Rfc4122/Fields.php | 83 ++++++-------- src/Rfc4122/UuidBuilder.php | 8 +- src/Rfc4122/VariantTrait.php | 18 ++- src/Rfc4122/VersionTrait.php | 19 ++- src/Type/Decimal.php | 25 ++-- src/Type/Hexadecimal.php | 16 +-- src/Type/Integer.php | 19 +-- src/Type/Time.php | 28 ++--- src/Uuid.php | 49 +++----- src/UuidFactory.php | 75 ++++-------- tests/Generator/RandomLibAdapterTest.php | 6 +- 39 files changed, 222 insertions(+), 605 deletions(-) diff --git a/phpstan.neon.dist b/phpstan.neon.dist index d31b4708..46766b19 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -17,7 +17,7 @@ parameters: count: 9 path: ./src/Lazy/LazyUuidFromString.php - - message: '#^Property Ramsey\\Uuid\\FeatureSet::\$disableBigNumber is never read, only written#' + message: '#^Constructor of class Ramsey\\Uuid\\FeatureSet has an unused parameter \$forceNoBigNumber\.#' count: 1 path: ./src/FeatureSet.php diff --git a/src/Builder/DegradedUuidBuilder.php b/src/Builder/DegradedUuidBuilder.php index 23931e41..20b38421 100644 --- a/src/Builder/DegradedUuidBuilder.php +++ b/src/Builder/DegradedUuidBuilder.php @@ -30,15 +30,7 @@ */ class DegradedUuidBuilder implements UuidBuilderInterface { - /** - * @var NumberConverterInterface - */ - private $numberConverter; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; + private TimeConverterInterface $timeConverter; /** * @param NumberConverterInterface $numberConverter The number converter to @@ -47,10 +39,9 @@ class DegradedUuidBuilder implements UuidBuilderInterface * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - NumberConverterInterface $numberConverter, + private NumberConverterInterface $numberConverter, ?TimeConverterInterface $timeConverter = null ) { - $this->numberConverter = $numberConverter; $this->timeConverter = $timeConverter ?: new DegradedTimeConverter(); } diff --git a/src/Builder/FallbackBuilder.php b/src/Builder/FallbackBuilder.php index 8ab438a1..ba5f31fb 100644 --- a/src/Builder/FallbackBuilder.php +++ b/src/Builder/FallbackBuilder.php @@ -27,17 +27,11 @@ */ class FallbackBuilder implements UuidBuilderInterface { - /** - * @var iterable - */ - private $builders; - /** * @param iterable $builders An array of UUID builders */ - public function __construct(iterable $builders) + public function __construct(private iterable $builders) { - $this->builders = $builders; } /** diff --git a/src/Codec/StringCodec.php b/src/Codec/StringCodec.php index 58c9f580..4b6e4e5b 100644 --- a/src/Codec/StringCodec.php +++ b/src/Codec/StringCodec.php @@ -36,19 +36,13 @@ */ class StringCodec implements CodecInterface { - /** - * @var UuidBuilderInterface - */ - private $builder; - /** * Constructs a StringCodec * * @param UuidBuilderInterface $builder The builder to use when encoding UUIDs */ - public function __construct(UuidBuilderInterface $builder) + public function __construct(private UuidBuilderInterface $builder) { - $this->builder = $builder; } public function encode(UuidInterface $uuid): string diff --git a/src/Converter/Number/BigNumberConverter.php b/src/Converter/Number/BigNumberConverter.php index fef63fd0..99b88b3b 100644 --- a/src/Converter/Number/BigNumberConverter.php +++ b/src/Converter/Number/BigNumberConverter.php @@ -27,10 +27,7 @@ */ class BigNumberConverter implements NumberConverterInterface { - /** - * @var NumberConverterInterface - */ - private $converter; + private NumberConverterInterface $converter; public function __construct() { diff --git a/src/Converter/Number/GenericNumberConverter.php b/src/Converter/Number/GenericNumberConverter.php index 501eac0f..043c3c43 100644 --- a/src/Converter/Number/GenericNumberConverter.php +++ b/src/Converter/Number/GenericNumberConverter.php @@ -26,14 +26,8 @@ */ class GenericNumberConverter implements NumberConverterInterface { - /** - * @var CalculatorInterface - */ - private $calculator; - - public function __construct(CalculatorInterface $calculator) + public function __construct(private CalculatorInterface $calculator) { - $this->calculator = $calculator; } /** diff --git a/src/Converter/Time/BigNumberTimeConverter.php b/src/Converter/Time/BigNumberTimeConverter.php index 7390dad8..b6bca9ee 100644 --- a/src/Converter/Time/BigNumberTimeConverter.php +++ b/src/Converter/Time/BigNumberTimeConverter.php @@ -29,10 +29,7 @@ */ class BigNumberTimeConverter implements TimeConverterInterface { - /** - * @var TimeConverterInterface - */ - private $converter; + private TimeConverterInterface $converter; public function __construct() { diff --git a/src/Converter/Time/GenericTimeConverter.php b/src/Converter/Time/GenericTimeConverter.php index a8aa64b7..f6b60abb 100644 --- a/src/Converter/Time/GenericTimeConverter.php +++ b/src/Converter/Time/GenericTimeConverter.php @@ -50,14 +50,8 @@ class GenericTimeConverter implements TimeConverterInterface */ private const MICROSECOND_INTERVALS = '10'; - /** - * @var CalculatorInterface - */ - private $calculator; - - public function __construct(CalculatorInterface $calculator) + public function __construct(private CalculatorInterface $calculator) { - $this->calculator = $calculator; } public function calculateTime(string $seconds, string $microseconds): Hexadecimal diff --git a/src/Converter/Time/PhpTimeConverter.php b/src/Converter/Time/PhpTimeConverter.php index 538d2f2f..66009f14 100644 --- a/src/Converter/Time/PhpTimeConverter.php +++ b/src/Converter/Time/PhpTimeConverter.php @@ -58,20 +58,9 @@ class PhpTimeConverter implements TimeConverterInterface */ private const MICROSECOND_INTERVALS = 10; - /** - * @var CalculatorInterface - */ - private $calculator; - - /** - * @var TimeConverterInterface - */ - private $fallbackConverter; - - /** - * @var int - */ - private $phpPrecision; + private int $phpPrecision; + private CalculatorInterface $calculator; + private TimeConverterInterface $fallbackConverter; public function __construct( ?CalculatorInterface $calculator = null, @@ -132,11 +121,11 @@ public function convertTime(Hexadecimal $uuidTimestamp): Time } /** - * @param int|float $time The time to split into seconds and microseconds + * @param float|int $time The time to split into seconds and microseconds * * @return string[] */ - private function splitTime($time): array + private function splitTime(float | int $time): array { $split = explode('.', (string) $time, 2); diff --git a/src/Converter/Time/UnixTimeConverter.php b/src/Converter/Time/UnixTimeConverter.php index d94233fb..4d6d0a8a 100644 --- a/src/Converter/Time/UnixTimeConverter.php +++ b/src/Converter/Time/UnixTimeConverter.php @@ -36,11 +36,8 @@ class UnixTimeConverter implements TimeConverterInterface { private const MILLISECONDS = 1000; - private CalculatorInterface $calculator; - - public function __construct(CalculatorInterface $calculator) + public function __construct(private CalculatorInterface $calculator) { - $this->calculator = $calculator; } public function calculateTime(string $seconds, string $microseconds): Hexadecimal diff --git a/src/FeatureSet.php b/src/FeatureSet.php index 482a8de0..6c8ccb0d 100644 --- a/src/FeatureSet.php +++ b/src/FeatureSet.php @@ -63,94 +63,25 @@ */ class FeatureSet { - /** - * @var bool - */ - private $disableBigNumber = false; - - /** - * @var bool - */ - private $disable64Bit = false; - - /** - * @var bool - */ - private $ignoreSystemNode = false; - - /** - * @var bool - */ - private $enablePecl = false; - - /** - * @var UuidBuilderInterface - */ - private $builder; - - /** - * @var CodecInterface - */ - private $codec; - - /** - * @var DceSecurityGeneratorInterface - */ - private $dceSecurityGenerator; - - /** - * @var NameGeneratorInterface - */ - private $nameGenerator; - - /** - * @var NodeProviderInterface - */ - private $nodeProvider; - - /** - * @var NumberConverterInterface - */ - private $numberConverter; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; - - /** - * @var RandomGeneratorInterface - */ - private $randomGenerator; - - /** - * @var TimeGeneratorInterface - */ - private $timeGenerator; - - /** - * @var TimeProviderInterface|null - */ - private $timeProvider; - - /** - * @var ValidatorInterface - */ - private $validator; - - /** - * @var CalculatorInterface - */ - private $calculator; - + private ?TimeProviderInterface $timeProvider = null; + private CalculatorInterface $calculator; + private CodecInterface $codec; + private DceSecurityGeneratorInterface $dceSecurityGenerator; + private NameGeneratorInterface $nameGenerator; + private NodeProviderInterface $nodeProvider; + private NumberConverterInterface $numberConverter; + private RandomGeneratorInterface $randomGenerator; + private TimeConverterInterface $timeConverter; + private TimeGeneratorInterface $timeGenerator; private TimeGeneratorInterface $unixTimeGenerator; + private UuidBuilderInterface $builder; + private ValidatorInterface $validator; /** * @param bool $useGuids True build UUIDs using the GuidStringCodec * @param bool $force32Bit True to force the use of 32-bit functionality * (primarily for testing purposes) - * @param bool $forceNoBigNumber True to disable the use of moontoast/math - * (primarily for testing purposes) + * @param bool $forceNoBigNumber (obsolete) * @param bool $ignoreSystemNode True to disable attempts to check for the * system node ID (primarily for testing purposes) * @param bool $enablePecl True to enable the use of the PeclUuidTimeGenerator @@ -158,16 +89,11 @@ class FeatureSet */ public function __construct( bool $useGuids = false, - bool $force32Bit = false, + private bool $force32Bit = false, bool $forceNoBigNumber = false, - bool $ignoreSystemNode = false, - bool $enablePecl = false + private bool $ignoreSystemNode = false, + private bool $enablePecl = false ) { - $this->disableBigNumber = $forceNoBigNumber; - $this->disable64Bit = $force32Bit; - $this->ignoreSystemNode = $ignoreSystemNode; - $this->enablePecl = $enablePecl; - $this->randomGenerator = $this->buildRandomGenerator(); $this->setCalculator(new BrickMathCalculator()); $this->builder = $this->buildUuidBuilder($useGuids); @@ -474,6 +400,6 @@ private function buildUuidBuilder(bool $useGuids = false): UuidBuilderInterface */ private function is64BitSystem(): bool { - return PHP_INT_SIZE === 8 && !$this->disable64Bit; + return PHP_INT_SIZE === 8 && !$this->force32Bit; } } diff --git a/src/Fields/SerializableFieldsTrait.php b/src/Fields/SerializableFieldsTrait.php index a2a89c6a..3d36b6f1 100644 --- a/src/Fields/SerializableFieldsTrait.php +++ b/src/Fields/SerializableFieldsTrait.php @@ -56,22 +56,23 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $serialized The serialized string representation of the object + * @param string $data The serialized string representation of the object * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize($serialized): void + public function unserialize(string $data): void { - if (strlen($serialized) === 16) { - $this->__construct($serialized); + if (strlen($data) === 16) { + $this->__construct($data); } else { - $this->__construct(base64_decode($serialized)); + $this->__construct(base64_decode($data)); } } /** * @param array{bytes?: string} $data + * + * @psalm-suppress UnusedMethodCall */ public function __unserialize(array $data): void { diff --git a/src/Generator/CombGenerator.php b/src/Generator/CombGenerator.php index 25b7988e..0e887060 100644 --- a/src/Generator/CombGenerator.php +++ b/src/Generator/CombGenerator.php @@ -61,22 +61,10 @@ class CombGenerator implements RandomGeneratorInterface { public const TIMESTAMP_BYTES = 6; - /** - * @var RandomGeneratorInterface - */ - private $randomGenerator; - - /** - * @var NumberConverterInterface - */ - private $converter; - public function __construct( - RandomGeneratorInterface $generator, - NumberConverterInterface $numberConverter + private RandomGeneratorInterface $generator, + private NumberConverterInterface $numberConverter ) { - $this->converter = $numberConverter; - $this->randomGenerator = $generator; } /** @@ -95,11 +83,11 @@ public function generate(int $length): string $hash = ''; if (self::TIMESTAMP_BYTES > 0 && $length > self::TIMESTAMP_BYTES) { - $hash = $this->randomGenerator->generate($length - self::TIMESTAMP_BYTES); + $hash = $this->generator->generate($length - self::TIMESTAMP_BYTES); } $lsbTime = str_pad( - $this->converter->toHex($this->timestamp()), + $this->numberConverter->toHex($this->timestamp()), self::TIMESTAMP_BYTES * 2, '0', STR_PAD_LEFT diff --git a/src/Generator/DceSecurityGenerator.php b/src/Generator/DceSecurityGenerator.php index aca8c5db..37ba7813 100644 --- a/src/Generator/DceSecurityGenerator.php +++ b/src/Generator/DceSecurityGenerator.php @@ -52,29 +52,11 @@ class DceSecurityGenerator implements DceSecurityGeneratorInterface */ private const CLOCK_SEQ_LOW = 0; - /** - * @var NumberConverterInterface - */ - private $numberConverter; - - /** - * @var TimeGeneratorInterface - */ - private $timeGenerator; - - /** - * @var DceSecurityProviderInterface - */ - private $dceSecurityProvider; - public function __construct( - NumberConverterInterface $numberConverter, - TimeGeneratorInterface $timeGenerator, - DceSecurityProviderInterface $dceSecurityProvider + private NumberConverterInterface $numberConverter, + private TimeGeneratorInterface $timeGenerator, + private DceSecurityProviderInterface $dceSecurityProvider ) { - $this->numberConverter = $numberConverter; - $this->timeGenerator = $timeGenerator; - $this->dceSecurityProvider = $dceSecurityProvider; } public function generate( @@ -153,8 +135,7 @@ public function generate( // Replace bytes in the time-based UUID with DCE Security values. $bytes = substr_replace($bytes, $identifierBytes, 0, 4); - $bytes = substr_replace($bytes, $domainByte, 9, 1); - return $bytes; + return substr_replace($bytes, $domainByte, 9, 1); } } diff --git a/src/Generator/DefaultTimeGenerator.php b/src/Generator/DefaultTimeGenerator.php index d245c7bc..a1b39b04 100644 --- a/src/Generator/DefaultTimeGenerator.php +++ b/src/Generator/DefaultTimeGenerator.php @@ -40,29 +40,11 @@ */ class DefaultTimeGenerator implements TimeGeneratorInterface { - /** - * @var NodeProviderInterface - */ - private $nodeProvider; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; - - /** - * @var TimeProviderInterface - */ - private $timeProvider; - public function __construct( - NodeProviderInterface $nodeProvider, - TimeConverterInterface $timeConverter, - TimeProviderInterface $timeProvider + private NodeProviderInterface $nodeProvider, + private TimeConverterInterface $timeConverter, + private TimeProviderInterface $timeProvider ) { - $this->nodeProvider = $nodeProvider; - $this->timeConverter = $timeConverter; - $this->timeProvider = $timeProvider; } /** @@ -121,13 +103,13 @@ public function generate($node = null, ?int $clockSeq = null): string * Uses the node provider given when constructing this instance to get * the node ID (usually a MAC address) * - * @param string|int|null $node A node value that may be used to override the node provider + * @param int|string|null $node A node value that may be used to override the node provider * * @return string 6-byte binary string representation of the node * * @throws InvalidArgumentException */ - private function getValidNode($node): string + private function getValidNode(int | string | null $node): string { if ($node === null) { $node = $this->nodeProvider->getNode(); diff --git a/src/Generator/PeclUuidNameGenerator.php b/src/Generator/PeclUuidNameGenerator.php index 3780c5c6..6a6d1aec 100644 --- a/src/Generator/PeclUuidNameGenerator.php +++ b/src/Generator/PeclUuidNameGenerator.php @@ -33,21 +33,16 @@ class PeclUuidNameGenerator implements NameGeneratorInterface /** @psalm-pure */ public function generate(UuidInterface $ns, string $name, string $hashAlgorithm): string { - switch ($hashAlgorithm) { - case 'md5': - $uuid = uuid_generate_md5($ns->toString(), $name); - - break; - case 'sha1': - $uuid = uuid_generate_sha1($ns->toString(), $name); - - break; - default: - throw new NameException(sprintf( + $uuid = match ($hashAlgorithm) { + 'md5' => uuid_generate_md5($ns->toString(), $name), + 'sha1' => uuid_generate_sha1($ns->toString(), $name), + default => throw new NameException( + sprintf( 'Unable to hash namespace and name with algorithm \'%s\'', $hashAlgorithm - )); - } + ) + ), + }; return uuid_parse($uuid); } diff --git a/src/Generator/RandomLibAdapter.php b/src/Generator/RandomLibAdapter.php index 793ccd5a..fd0ccc8a 100644 --- a/src/Generator/RandomLibAdapter.php +++ b/src/Generator/RandomLibAdapter.php @@ -29,10 +29,7 @@ */ class RandomLibAdapter implements RandomGeneratorInterface { - /** - * @var Generator - */ - private $generator; + private Generator $generator; /** * Constructs a RandomLibAdapter diff --git a/src/Generator/TimeGeneratorFactory.php b/src/Generator/TimeGeneratorFactory.php index 3d55fc4d..8d06fc3a 100644 --- a/src/Generator/TimeGeneratorFactory.php +++ b/src/Generator/TimeGeneratorFactory.php @@ -24,29 +24,11 @@ */ class TimeGeneratorFactory { - /** - * @var NodeProviderInterface - */ - private $nodeProvider; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; - - /** - * @var TimeProviderInterface - */ - private $timeProvider; - public function __construct( - NodeProviderInterface $nodeProvider, - TimeConverterInterface $timeConverter, - TimeProviderInterface $timeProvider + private NodeProviderInterface $nodeProvider, + private TimeConverterInterface $timeConverter, + private TimeProviderInterface $timeProvider ) { - $this->nodeProvider = $nodeProvider; - $this->timeConverter = $timeConverter; - $this->timeProvider = $timeProvider; } /** diff --git a/src/Generator/UnixTimeGenerator.php b/src/Generator/UnixTimeGenerator.php index 74914ddd..1aef8699 100644 --- a/src/Generator/UnixTimeGenerator.php +++ b/src/Generator/UnixTimeGenerator.php @@ -25,18 +25,11 @@ */ class UnixTimeGenerator implements TimeGeneratorInterface { - private RandomGeneratorInterface $randomGenerator; - private TimeConverterInterface $timeConverter; - private TimeProviderInterface $timeProvider; - public function __construct( - TimeConverterInterface $timeConverter, - TimeProviderInterface $timeProvider, - RandomGeneratorInterface $randomGenerator + private TimeConverterInterface $timeConverter, + private TimeProviderInterface $timeProvider, + private RandomGeneratorInterface $randomGenerator ) { - $this->timeConverter = $timeConverter; - $this->timeProvider = $timeProvider; - $this->randomGenerator = $randomGenerator; } /** diff --git a/src/Guid/Fields.php b/src/Guid/Fields.php index 9e47aff9..0fc5d1c9 100644 --- a/src/Guid/Fields.php +++ b/src/Guid/Fields.php @@ -51,11 +51,6 @@ final class Fields implements FieldsInterface use VariantTrait; use VersionTrait; - /** - * @var string - */ - private $bytes; - /** * @param string $bytes A 16-byte binary string representation of a UUID * @@ -63,17 +58,15 @@ final class Fields implements FieldsInterface * @throws InvalidArgumentException if the byte string does not represent a GUID * @throws InvalidArgumentException if the byte string does not contain a valid version */ - public function __construct(string $bytes) + public function __construct(private string $bytes) { - if (strlen($bytes) !== 16) { + if (strlen($this->bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' - . 'received ' . strlen($bytes) . ' bytes' + . 'received ' . strlen($this->bytes) . ' bytes' ); } - $this->bytes = $bytes; - if (!$this->isCorrectVariant()) { throw new InvalidArgumentException( 'The byte string received does not conform to the RFC ' diff --git a/src/Guid/GuidBuilder.php b/src/Guid/GuidBuilder.php index 758dd6b7..c036bb20 100644 --- a/src/Guid/GuidBuilder.php +++ b/src/Guid/GuidBuilder.php @@ -31,16 +31,6 @@ */ class GuidBuilder implements UuidBuilderInterface { - /** - * @var NumberConverterInterface - */ - private $numberConverter; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; - /** * @param NumberConverterInterface $numberConverter The number converter to * use when constructing the Guid @@ -48,11 +38,9 @@ class GuidBuilder implements UuidBuilderInterface * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - NumberConverterInterface $numberConverter, - TimeConverterInterface $timeConverter + private NumberConverterInterface $numberConverter, + private TimeConverterInterface $timeConverter ) { - $this->numberConverter = $numberConverter; - $this->timeConverter = $timeConverter; } /** diff --git a/src/Lazy/LazyUuidFromString.php b/src/Lazy/LazyUuidFromString.php index d2a169f7..c0b47bbf 100644 --- a/src/Lazy/LazyUuidFromString.php +++ b/src/Lazy/LazyUuidFromString.php @@ -55,18 +55,14 @@ final class LazyUuidFromString implements UuidInterface { public const VALID_REGEX = '/\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/ms'; + + private ?UuidInterface $unwrapped = null; + /** - * @var string - * @psalm-var non-empty-string + * @psalm-param non-empty-string $uuid */ - private $uuid; - /** @var UuidInterface|null */ - private $unwrapped; - - /** @psalm-param non-empty-string $uuid */ - public function __construct(string $uuid) + public function __construct(private string $uuid) { - $this->uuid = $uuid; } /** @psalm-pure */ @@ -105,19 +101,20 @@ public function __serialize(): array /** * {@inheritDoc} * - * @param string $serialized + * @param string $data * - * @psalm-param non-empty-string $serialized + * @psalm-param non-empty-string $data */ - public function unserialize($serialized): void + public function unserialize(string $data): void { - $this->uuid = $serialized; + $this->uuid = $data; } /** * @param array{string?: string} $data * * @psalm-param array{string?: non-empty-string} $data + * @psalm-suppress UnusedMethodCall */ public function __unserialize(array $data): void { diff --git a/src/Nonstandard/Fields.php b/src/Nonstandard/Fields.php index d5b820f7..5dfe6107 100644 --- a/src/Nonstandard/Fields.php +++ b/src/Nonstandard/Fields.php @@ -47,26 +47,19 @@ final class Fields implements FieldsInterface use SerializableFieldsTrait; use VariantTrait; - /** - * @var string - */ - private $bytes; - /** * @param string $bytes A 16-byte binary string representation of a UUID * * @throws InvalidArgumentException if the byte string is not exactly 16 bytes */ - public function __construct(string $bytes) + public function __construct(private string $bytes) { - if (strlen($bytes) !== 16) { + if (strlen($this->bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' - . 'received ' . strlen($bytes) . ' bytes' + . 'received ' . strlen($this->bytes) . ' bytes' ); } - - $this->bytes = $bytes; } public function getBytes(): string diff --git a/src/Nonstandard/UuidBuilder.php b/src/Nonstandard/UuidBuilder.php index 0c892773..82efd402 100644 --- a/src/Nonstandard/UuidBuilder.php +++ b/src/Nonstandard/UuidBuilder.php @@ -29,16 +29,6 @@ */ class UuidBuilder implements UuidBuilderInterface { - /** - * @var NumberConverterInterface - */ - private $numberConverter; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; - /** * @param NumberConverterInterface $numberConverter The number converter to * use when constructing the Nonstandard\Uuid @@ -46,11 +36,9 @@ class UuidBuilder implements UuidBuilderInterface * for converting timestamps extracted from a UUID to Unix timestamps */ public function __construct( - NumberConverterInterface $numberConverter, - TimeConverterInterface $timeConverter + private NumberConverterInterface $numberConverter, + private TimeConverterInterface $timeConverter ) { - $this->numberConverter = $numberConverter; - $this->timeConverter = $timeConverter; } /** diff --git a/src/Provider/Dce/SystemDceSecurityProvider.php b/src/Provider/Dce/SystemDceSecurityProvider.php index c53b8397..d5b6cf0c 100644 --- a/src/Provider/Dce/SystemDceSecurityProvider.php +++ b/src/Provider/Dce/SystemDceSecurityProvider.php @@ -21,7 +21,6 @@ use function escapeshellarg; use function preg_split; use function str_getcsv; -use function strpos; use function strrpos; use function strtolower; use function strtoupper; @@ -106,15 +105,10 @@ private function getSystemUid(): string return ''; } - switch ($this->getOs()) { - case 'WIN': - return $this->getWindowsUid(); - case 'DAR': - case 'FRE': - case 'LIN': - default: - return trim((string) shell_exec('id -u')); - } + return match ($this->getOs()) { + 'WIN' => $this->getWindowsUid(), + default => trim((string) shell_exec('id -u')), + }; } /** @@ -126,15 +120,10 @@ private function getSystemGid(): string return ''; } - switch ($this->getOs()) { - case 'WIN': - return $this->getWindowsGid(); - case 'DAR': - case 'FRE': - case 'LIN': - default: - return trim((string) shell_exec('id -g')); - } + return match ($this->getOs()) { + 'WIN' => $this->getWindowsGid(), + default => trim((string) shell_exec('id -g')), + }; } /** @@ -144,7 +133,7 @@ private function hasShellExec(): bool { $disabledFunctions = strtolower((string) ini_get('disable_functions')); - return strpos($disabledFunctions, 'shell_exec') === false; + return !str_contains($disabledFunctions, 'shell_exec'); } /** diff --git a/src/Provider/Node/FallbackNodeProvider.php b/src/Provider/Node/FallbackNodeProvider.php index fe890cc4..d2eb20b7 100644 --- a/src/Provider/Node/FallbackNodeProvider.php +++ b/src/Provider/Node/FallbackNodeProvider.php @@ -24,24 +24,18 @@ */ class FallbackNodeProvider implements NodeProviderInterface { - /** - * @var iterable - */ - private $nodeProviders; - /** * @param iterable $providers Array of node providers */ - public function __construct(iterable $providers) + public function __construct(private iterable $providers) { - $this->nodeProviders = $providers; } public function getNode(): Hexadecimal { $lastProviderException = null; - foreach ($this->nodeProviders as $provider) { + foreach ($this->providers as $provider) { try { return $provider->getNode(); } catch (NodeException $exception) { diff --git a/src/Provider/Node/StaticNodeProvider.php b/src/Provider/Node/StaticNodeProvider.php index 51f1b02e..0f7536a8 100644 --- a/src/Provider/Node/StaticNodeProvider.php +++ b/src/Provider/Node/StaticNodeProvider.php @@ -32,10 +32,7 @@ */ class StaticNodeProvider implements NodeProviderInterface { - /** - * @var Hexadecimal - */ - private $node; + private Hexadecimal $node; /** * @param Hexadecimal $node The static node value to use diff --git a/src/Provider/Time/FixedTimeProvider.php b/src/Provider/Time/FixedTimeProvider.php index 90b1c6a6..526c8ff4 100644 --- a/src/Provider/Time/FixedTimeProvider.php +++ b/src/Provider/Time/FixedTimeProvider.php @@ -26,14 +26,8 @@ */ class FixedTimeProvider implements TimeProviderInterface { - /** - * @var Time - */ - private $fixedTime; - - public function __construct(Time $time) + public function __construct(private Time $time) { - $this->fixedTime = $time; } /** @@ -43,7 +37,7 @@ public function __construct(Time $time) */ public function setUsec($value): void { - $this->fixedTime = new Time($this->fixedTime->getSeconds(), $value); + $this->time = new Time($this->time->getSeconds(), $value); } /** @@ -53,11 +47,11 @@ public function setUsec($value): void */ public function setSec($value): void { - $this->fixedTime = new Time($value, $this->fixedTime->getMicroseconds()); + $this->time = new Time($value, $this->time->getMicroseconds()); } public function getTime(): Time { - return $this->fixedTime; + return $this->time; } } diff --git a/src/Rfc4122/Fields.php b/src/Rfc4122/Fields.php index 0a6ece5c..9acf810c 100644 --- a/src/Rfc4122/Fields.php +++ b/src/Rfc4122/Fields.php @@ -46,11 +46,6 @@ final class Fields implements FieldsInterface use VariantTrait; use VersionTrait; - /** - * @var string - */ - private $bytes; - /** * @param string $bytes A 16-byte binary string representation of a UUID * @@ -58,17 +53,15 @@ final class Fields implements FieldsInterface * @throws InvalidArgumentException if the byte string does not represent an RFC 4122 UUID * @throws InvalidArgumentException if the byte string does not contain a valid version */ - public function __construct(string $bytes) + public function __construct(private string $bytes) { - if (strlen($bytes) !== 16) { + if (strlen($this->bytes) !== 16) { throw new InvalidArgumentException( 'The byte string must be 16 bytes long; ' - . 'received ' . strlen($bytes) . ' bytes' + . 'received ' . strlen($this->bytes) . ' bytes' ); } - $this->bytes = $bytes; - if (!$this->isCorrectVariant()) { throw new InvalidArgumentException( 'The byte string received does not conform to the RFC 4122 variant' @@ -147,44 +140,34 @@ public function getTimeMid(): Hexadecimal */ public function getTimestamp(): Hexadecimal { - switch ($this->getVersion()) { - case Uuid::UUID_TYPE_DCE_SECURITY: - $timestamp = sprintf( - '%03x%04s%08s', - hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, - $this->getTimeMid()->toString(), - '' - ); - - break; - case Uuid::UUID_TYPE_REORDERED_TIME: - $timestamp = sprintf( - '%08s%04s%03x', - $this->getTimeLow()->toString(), - $this->getTimeMid()->toString(), - hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff - ); - - break; - case Uuid::UUID_TYPE_UNIX_TIME: - // The Unix timestamp in version 7 UUIDs is a 48-bit number, - // but for consistency, we will return a 60-bit number, padded - // to the left with zeros. - $timestamp = sprintf( - '%011s%04s', - $this->getTimeLow()->toString(), - $this->getTimeMid()->toString(), - ); - - break; - default: - $timestamp = sprintf( - '%03x%04s%08s', - hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, - $this->getTimeMid()->toString(), - $this->getTimeLow()->toString() - ); - } + $timestamp = match ($this->getVersion()) { + Uuid::UUID_TYPE_DCE_SECURITY => sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + '' + ), + Uuid::UUID_TYPE_REORDERED_TIME => sprintf( + '%08s%04s%03x', + $this->getTimeLow()->toString(), + $this->getTimeMid()->toString(), + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff + ), + // The Unix timestamp in version 7 UUIDs is a 48-bit number, + // but for consistency, we will return a 60-bit number, padded + // to the left with zeros. + Uuid::UUID_TYPE_UNIX_TIME => sprintf( + '%011s%04s', + $this->getTimeLow()->toString(), + $this->getTimeMid()->toString(), + ), + default => sprintf( + '%03x%04s%08s', + hexdec($this->getTimeHiAndVersion()->toString()) & 0x0fff, + $this->getTimeMid()->toString(), + $this->getTimeLow()->toString() + ), + }; return new Hexadecimal($timestamp); } @@ -195,10 +178,10 @@ public function getVersion(): ?int return null; } - /** @var array $parts */ + /** @var int[] $parts */ $parts = unpack('n*', $this->bytes); - return (int) $parts[4] >> 12; + return $parts[4] >> 12; } private function isCorrectVariant(): bool diff --git a/src/Rfc4122/UuidBuilder.php b/src/Rfc4122/UuidBuilder.php index 895524d1..859649fd 100644 --- a/src/Rfc4122/UuidBuilder.php +++ b/src/Rfc4122/UuidBuilder.php @@ -34,8 +34,6 @@ */ class UuidBuilder implements UuidBuilderInterface { - private NumberConverterInterface $numberConverter; - private TimeConverterInterface $timeConverter; private TimeConverterInterface $unixTimeConverter; /** @@ -51,12 +49,10 @@ class UuidBuilder implements UuidBuilderInterface * to Unix timestamps */ public function __construct( - NumberConverterInterface $numberConverter, - TimeConverterInterface $timeConverter, + private NumberConverterInterface $numberConverter, + private TimeConverterInterface $timeConverter, ?TimeConverterInterface $unixTimeConverter = null ) { - $this->numberConverter = $numberConverter; - $this->timeConverter = $timeConverter; $this->unixTimeConverter = $unixTimeConverter ?? new UnixTimeConverter(new BrickMathCalculator()); } diff --git a/src/Rfc4122/VariantTrait.php b/src/Rfc4122/VariantTrait.php index 74d12efe..1041de51 100644 --- a/src/Rfc4122/VariantTrait.php +++ b/src/Rfc4122/VariantTrait.php @@ -19,8 +19,8 @@ use function decbin; use function str_pad; +use function str_starts_with; use function strlen; -use function strpos; use function substr; use function unpack; @@ -64,7 +64,7 @@ public function getVariant(): int return Uuid::RFC_4122; } - /** @var array $parts */ + /** @var int[] $parts */ $parts = unpack('n*', $this->getBytes()); // $parts[5] is a 16-bit, unsigned integer containing the variant bits @@ -73,7 +73,7 @@ public function getVariant(): int // three characters (three most-significant bits) to determine the // variant. $binary = str_pad( - decbin((int) $parts[5]), + decbin($parts[5]), 16, '0', STR_PAD_LEFT @@ -82,15 +82,13 @@ public function getVariant(): int $msb = substr($binary, 0, 3); if ($msb === '111') { - $variant = Uuid::RESERVED_FUTURE; + return Uuid::RESERVED_FUTURE; } elseif ($msb === '110') { - $variant = Uuid::RESERVED_MICROSOFT; - } elseif (strpos($msb, '10') === 0) { - $variant = Uuid::RFC_4122; - } else { - $variant = Uuid::RESERVED_NCS; + return Uuid::RESERVED_MICROSOFT; + } elseif (str_starts_with($msb, '10')) { + return Uuid::RFC_4122; } - return $variant; + return Uuid::RESERVED_NCS; } } diff --git a/src/Rfc4122/VersionTrait.php b/src/Rfc4122/VersionTrait.php index fb3e3e5b..316f780c 100644 --- a/src/Rfc4122/VersionTrait.php +++ b/src/Rfc4122/VersionTrait.php @@ -49,17 +49,12 @@ private function isCorrectVersion(): bool return true; } - switch ($this->getVersion()) { - case Uuid::UUID_TYPE_TIME: - case Uuid::UUID_TYPE_DCE_SECURITY: - case Uuid::UUID_TYPE_HASH_MD5: - case Uuid::UUID_TYPE_RANDOM: - case Uuid::UUID_TYPE_HASH_SHA1: - case Uuid::UUID_TYPE_REORDERED_TIME: - case Uuid::UUID_TYPE_UNIX_TIME: - return true; - } - - return false; + return match ($this->getVersion()) { + Uuid::UUID_TYPE_TIME, Uuid::UUID_TYPE_DCE_SECURITY, + Uuid::UUID_TYPE_HASH_MD5, Uuid::UUID_TYPE_RANDOM, + Uuid::UUID_TYPE_HASH_SHA1, Uuid::UUID_TYPE_REORDERED_TIME, + Uuid::UUID_TYPE_UNIX_TIME => true, + default => false, + }; } } diff --git a/src/Type/Decimal.php b/src/Type/Decimal.php index 0c42e633..acc5e754 100644 --- a/src/Type/Decimal.php +++ b/src/Type/Decimal.php @@ -35,20 +35,10 @@ */ final class Decimal implements NumberInterface { - /** - * @var string - */ - private $value; - - /** - * @var bool - */ - private $isNegative = false; + private string $value; + private bool $isNegative = false; - /** - * @param int|float|string|self $value The decimal value to store - */ - public function __construct($value) + public function __construct(float | int | string | self $value) { $value = (string) $value; @@ -112,18 +102,19 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $serialized The serialized string representation of the object + * @param string $data The serialized string representation of the object * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize($serialized): void + public function unserialize(string $data): void { - $this->__construct($serialized); + $this->__construct($data); } /** * @param array{string?: string} $data + * + * @psalm-suppress UnusedMethodCall */ public function __unserialize(array $data): void { diff --git a/src/Type/Hexadecimal.php b/src/Type/Hexadecimal.php index fee0f85f..3c8f30ad 100644 --- a/src/Type/Hexadecimal.php +++ b/src/Type/Hexadecimal.php @@ -19,7 +19,7 @@ use function ctype_xdigit; use function sprintf; -use function strpos; +use function str_starts_with; use function strtolower; use function substr; @@ -34,10 +34,7 @@ */ final class Hexadecimal implements TypeInterface { - /** - * @var string - */ - private $value; + private string $value; /** * @param string $value The hexadecimal value to store @@ -46,7 +43,7 @@ public function __construct(string $value) { $value = strtolower($value); - if (strpos($value, '0x') === 0) { + if (str_starts_with($value, '0x')) { $value = substr($value, 2); } @@ -90,14 +87,13 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $serialized The serialized string representation of the object + * @param string $data The serialized string representation of the object * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize($serialized): void + public function unserialize(string $data): void { - $this->__construct($serialized); + $this->__construct($data); } /** diff --git a/src/Type/Integer.php b/src/Type/Integer.php index e786efeb..e41b3cad 100644 --- a/src/Type/Integer.php +++ b/src/Type/Integer.php @@ -40,17 +40,11 @@ final class Integer implements NumberInterface /** * @psalm-var numeric-string */ - private $value; + private string $value; - /** - * @var bool - */ - private $isNegative = false; + private bool $isNegative = false; - /** - * @param int|float|string|self $value The integer value to store - */ - public function __construct($value) + public function __construct(float | int | string | self $value) { $value = (string) $value; $sign = '+'; @@ -127,14 +121,13 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $serialized The serialized string representation of the object + * @param string $data The serialized string representation of the object * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize($serialized): void + public function unserialize(string $data): void { - $this->__construct($serialized); + $this->__construct($data); } /** diff --git a/src/Type/Time.php b/src/Type/Time.php index f9c72b57..745b5cca 100644 --- a/src/Type/Time.php +++ b/src/Type/Time.php @@ -33,22 +33,13 @@ */ final class Time implements TypeInterface { - /** - * @var IntegerObject - */ - private $seconds; - - /** - * @var IntegerObject - */ - private $microseconds; + private IntegerObject $seconds; + private IntegerObject $microseconds; - /** - * @param int|float|string|IntegerObject $seconds - * @param int|float|string|IntegerObject $microseconds - */ - public function __construct($seconds, $microseconds = 0) - { + public function __construct( + float | int | string | IntegerObject $seconds, + float | int | string | IntegerObject $microseconds = 0, + ) { $this->seconds = new IntegerObject($seconds); $this->microseconds = new IntegerObject($microseconds); } @@ -103,15 +94,14 @@ public function __serialize(): array /** * Constructs the object from a serialized string representation * - * @param string $serialized The serialized string representation of the object + * @param string $data The serialized string representation of the object * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint * @psalm-suppress UnusedMethodCall */ - public function unserialize($serialized): void + public function unserialize(string $data): void { /** @var array{seconds?: int|float|string, microseconds?: int|float|string} $time */ - $time = json_decode($serialized, true); + $time = json_decode($data, true); if (!isset($time['seconds']) || !isset($time['microseconds'])) { throw new UnsupportedOperationException( diff --git a/src/Uuid.php b/src/Uuid.php index 171d1263..6656aba0 100644 --- a/src/Uuid.php +++ b/src/Uuid.php @@ -216,38 +216,19 @@ class Uuid implements UuidInterface self::DCE_DOMAIN_ORG => 'org', ]; - /** - * @var UuidFactoryInterface|null - */ - private static $factory = null; - - /** - * @var bool flag to detect if the UUID factory was replaced internally, which disables all optimizations - * for the default/happy path internal scenarios - */ - private static $factoryReplaced = false; + private static ?UuidFactoryInterface $factory = null; /** - * @var CodecInterface + * @var bool flag to detect if the UUID factory was replaced internally, + * which disables all optimizations for the default/happy path internal + * scenarios */ - protected $codec; + private static bool $factoryReplaced = false; - /** - * The fields that make up this UUID - * - * @var Rfc4122FieldsInterface - */ - protected $fields; - - /** - * @var NumberConverterInterface - */ - protected $numberConverter; - - /** - * @var TimeConverterInterface - */ - protected $timeConverter; + protected CodecInterface $codec; + protected NumberConverterInterface $numberConverter; + protected Rfc4122FieldsInterface $fields; + protected TimeConverterInterface $timeConverter; /** * Creates a universally unique identifier (UUID) from an array of fields @@ -320,19 +301,17 @@ public function __serialize(): array /** * Re-constructs the object from its serialized form * - * @param string $serialized The serialized PHP string to unserialize into + * @param string $data The serialized PHP string to unserialize into * a UuidInterface instance - * - * @phpcsSuppress SlevomatCodingStandard.TypeHints.ParameterTypeHint.MissingNativeTypeHint */ - public function unserialize($serialized): void + public function unserialize(string $data): void { - if (strlen($serialized) === 16) { + if (strlen($data) === 16) { /** @var Uuid $uuid */ - $uuid = self::getFactory()->fromBytes($serialized); + $uuid = self::getFactory()->fromBytes($data); } else { /** @var Uuid $uuid */ - $uuid = self::getFactory()->fromString($serialized); + $uuid = self::getFactory()->fromString($data); } $this->codec = $uuid->codec; diff --git a/src/UuidFactory.php b/src/UuidFactory.php index f4fabdd5..ab730f74 100644 --- a/src/UuidFactory.php +++ b/src/UuidFactory.php @@ -48,63 +48,26 @@ class UuidFactory implements UuidFactoryInterface { - /** - * @var CodecInterface - */ - private $codec; - - /** - * @var DceSecurityGeneratorInterface - */ - private $dceSecurityGenerator; - - /** - * @var NameGeneratorInterface - */ - private $nameGenerator; - - /** - * @var NodeProviderInterface - */ - private $nodeProvider; - - /** - * @var NumberConverterInterface - */ - private $numberConverter; - - /** - * @var RandomGeneratorInterface - */ - private $randomGenerator; - - /** - * @var TimeConverterInterface - */ - private $timeConverter; - - /** - * @var TimeGeneratorInterface - */ - private $timeGenerator; - - /** - * @var UuidBuilderInterface - */ - private $uuidBuilder; + private CodecInterface $codec; + private DceSecurityGeneratorInterface $dceSecurityGenerator; + private NameGeneratorInterface $nameGenerator; + private NodeProviderInterface $nodeProvider; + private NumberConverterInterface $numberConverter; + private RandomGeneratorInterface $randomGenerator; + private TimeConverterInterface $timeConverter; + private TimeGeneratorInterface $timeGenerator; + private TimeGeneratorInterface $unixTimeGenerator; + private UuidBuilderInterface $uuidBuilder; + private ValidatorInterface $validator; /** - * @var ValidatorInterface + * @var bool whether the feature set was provided from outside, or we can + * operate under "default" assumptions */ - private $validator; - - /** @var bool whether the feature set was provided from outside, or we can operate under "default" assumptions */ - private $isDefaultFeatureSet; - - private TimeGeneratorInterface $unixTimeGenerator; + private bool $isDefaultFeatureSet; /** - * @param FeatureSet $features A set of available features in the current environment + * @param FeatureSet|null $features A set of available features in the current environment */ public function __construct(?FeatureSet $features = null) { @@ -484,8 +447,12 @@ public function uuid(string $bytes): UuidInterface * * @psalm-pure */ - private function uuidFromNsAndName($ns, string $name, int $version, string $hashAlgorithm): UuidInterface - { + private function uuidFromNsAndName( + UuidInterface | string $ns, + string $name, + int $version, + string $hashAlgorithm + ): UuidInterface { if (!($ns instanceof UuidInterface)) { $ns = $this->fromString($ns); } diff --git a/tests/Generator/RandomLibAdapterTest.php b/tests/Generator/RandomLibAdapterTest.php index 438f6f10..eec21763 100644 --- a/tests/Generator/RandomLibAdapterTest.php +++ b/tests/Generator/RandomLibAdapterTest.php @@ -5,6 +5,7 @@ namespace Ramsey\Uuid\Test\Generator; use Mockery; +use Mockery\MockInterface; use Ramsey\Uuid\Generator\RandomLibAdapter; use Ramsey\Uuid\Test\TestCase; use RandomLib\Factory as RandomLibFactory; @@ -34,8 +35,11 @@ public function testAdapterWithGeneratorDoesNotCreateGenerator(): void */ public function testAdapterWithoutGeneratorGreatesGenerator(): void { + $generator = Mockery::mock(Generator::class); + + /** @var RandomLibFactory&MockInterface $factory */ $factory = Mockery::mock('overload:' . RandomLibFactory::class); - $factory->shouldReceive('getHighStrengthGenerator')->once(); + $factory->expects()->getHighStrengthGenerator()->andReturns($generator); $this->assertInstanceOf(RandomLibAdapter::class, new RandomLibAdapter()); }