chore: clean up types and PHP 8-ify the code

This commit is contained in:
Ben Ramsey
2022-09-15 22:14:04 -05:00
parent ef842484ba
commit ae247f1dcd
39 changed files with 225 additions and 608 deletions
+1 -1
View File
@@ -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
+2 -11
View File
@@ -30,15 +30,7 @@ use Ramsey\Uuid\UuidInterface;
*/
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();
}
+1 -7
View File
@@ -27,17 +27,11 @@ use Ramsey\Uuid\UuidInterface;
*/
class FallbackBuilder implements UuidBuilderInterface
{
/**
* @var iterable<UuidBuilderInterface>
*/
private $builders;
/**
* @param iterable<UuidBuilderInterface> $builders An array of UUID builders
*/
public function __construct(iterable $builders)
public function __construct(private iterable $builders)
{
$this->builders = $builders;
}
/**
+1 -7
View File
@@ -36,19 +36,13 @@ use function substr;
*/
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
+1 -4
View File
@@ -27,10 +27,7 @@ use Ramsey\Uuid\Math\BrickMathCalculator;
*/
class BigNumberConverter implements NumberConverterInterface
{
/**
* @var NumberConverterInterface
*/
private $converter;
private NumberConverterInterface $converter;
public function __construct()
{
@@ -26,14 +26,8 @@ use Ramsey\Uuid\Type\Integer as IntegerObject;
*/
class GenericNumberConverter implements NumberConverterInterface
{
/**
* @var CalculatorInterface
*/
private $calculator;
public function __construct(CalculatorInterface $calculator)
public function __construct(private CalculatorInterface $calculator)
{
$this->calculator = $calculator;
}
/**
@@ -29,10 +29,7 @@ use Ramsey\Uuid\Type\Time;
*/
class BigNumberTimeConverter implements TimeConverterInterface
{
/**
* @var TimeConverterInterface
*/
private $converter;
private TimeConverterInterface $converter;
public function __construct()
{
+1 -7
View File
@@ -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
+5 -16
View File
@@ -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 @@ class PhpTimeConverter implements TimeConverterInterface
}
/**
* @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);
+1 -4
View File
@@ -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
+17 -91
View File
@@ -63,94 +63,25 @@ use const PHP_INT_SIZE;
*/
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 @@ class FeatureSet
*/
private function is64BitSystem(): bool
{
return PHP_INT_SIZE === 8 && !$this->disable64Bit;
return PHP_INT_SIZE === 8 && !$this->force32Bit;
}
}
+7 -6
View File
@@ -56,22 +56,23 @@ trait SerializableFieldsTrait
/**
* 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
{
+4 -16
View File
@@ -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 @@ class CombGenerator implements RandomGeneratorInterface
$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
+4 -23
View File
@@ -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 @@ class DceSecurityGenerator implements DceSecurityGeneratorInterface
// 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);
}
}
+5 -23
View File
@@ -40,29 +40,11 @@ use const STR_PAD_LEFT;
*/
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 @@ class DefaultTimeGenerator implements TimeGeneratorInterface
* 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();
+8 -13
View File
@@ -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);
}
+1 -4
View File
@@ -29,10 +29,7 @@ use RandomLib\Generator;
*/
class RandomLibAdapter implements RandomGeneratorInterface
{
/**
* @var Generator
*/
private $generator;
private Generator $generator;
/**
* Constructs a RandomLibAdapter
+3 -21
View File
@@ -24,29 +24,11 @@ use Ramsey\Uuid\Provider\TimeProviderInterface;
*/
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;
}
/**
+3 -10
View File
@@ -25,18 +25,11 @@ use function hex2bin;
*/
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;
}
/**
+3 -10
View File
@@ -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 '
+2 -14
View File
@@ -31,16 +31,6 @@ use Throwable;
*/
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;
}
/**
+11 -14
View File
@@ -55,18 +55,14 @@ use function substr;
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';
/**
* @var string
* @psalm-var non-empty-string
*/
private $uuid;
/** @var UuidInterface|null */
private $unwrapped;
/** @psalm-param non-empty-string $uuid */
public function __construct(string $uuid)
private ?UuidInterface $unwrapped = null;
/**
* @psalm-param non-empty-string $uuid
*/
public function __construct(private string $uuid)
{
$this->uuid = $uuid;
}
/** @psalm-pure */
@@ -105,19 +101,20 @@ final class LazyUuidFromString implements UuidInterface
/**
* {@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
{
+3 -10
View File
@@ -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
+2 -14
View File
@@ -29,16 +29,6 @@ use Throwable;
*/
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;
}
/**
+9 -20
View File
@@ -21,7 +21,6 @@ use Ramsey\Uuid\Type\Integer as IntegerObject;
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 @@ class SystemDceSecurityProvider implements DceSecurityProviderInterface
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 @@ class SystemDceSecurityProvider implements DceSecurityProviderInterface
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 @@ class SystemDceSecurityProvider implements DceSecurityProviderInterface
{
$disabledFunctions = strtolower((string) ini_get('disable_functions'));
return strpos($disabledFunctions, 'shell_exec') === false;
return !str_contains($disabledFunctions, 'shell_exec');
}
/**
+2 -8
View File
@@ -24,24 +24,18 @@ use Ramsey\Uuid\Type\Hexadecimal;
*/
class FallbackNodeProvider implements NodeProviderInterface
{
/**
* @var iterable<NodeProviderInterface>
*/
private $nodeProviders;
/**
* @param iterable<NodeProviderInterface> $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) {
+1 -4
View File
@@ -32,10 +32,7 @@ use const STR_PAD_LEFT;
*/
class StaticNodeProvider implements NodeProviderInterface
{
/**
* @var Hexadecimal
*/
private $node;
private Hexadecimal $node;
/**
* @param Hexadecimal $node The static node value to use
+4 -10
View File
@@ -26,14 +26,8 @@ use Ramsey\Uuid\Type\Time;
*/
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 @@ class FixedTimeProvider implements TimeProviderInterface
*/
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 @@ class FixedTimeProvider implements TimeProviderInterface
*/
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;
}
}
+33 -50
View File
@@ -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 @@ final class Fields implements FieldsInterface
*/
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 @@ final class Fields implements FieldsInterface
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
+2 -6
View File
@@ -34,8 +34,6 @@ use Throwable;
*/
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());
}
+8 -10
View File
@@ -19,8 +19,8 @@ use Ramsey\Uuid\Uuid;
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 @@ trait VariantTrait
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 @@ trait VariantTrait
// 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 @@ trait VariantTrait
$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;
}
}
+7 -12
View File
@@ -49,17 +49,12 @@ trait VersionTrait
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,
};
}
}
+8 -17
View File
@@ -35,20 +35,10 @@ use function str_starts_with;
*/
final class Decimal implements NumberInterface
{
/**
* @var string
*/
private $value;
private string $value;
private bool $isNegative = false;
/**
* @var bool
*/
private $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 @@ final class Decimal implements NumberInterface
/**
* 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
{
+6 -10
View File
@@ -19,7 +19,7 @@ use ValueError;
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 @@ use function substr;
*/
final class Hexadecimal implements TypeInterface
{
/**
* @var string
*/
private $value;
private string $value;
/**
* @param string $value The hexadecimal value to store
@@ -46,7 +43,7 @@ final class Hexadecimal implements TypeInterface
{
$value = strtolower($value);
if (strpos($value, '0x') === 0) {
if (str_starts_with($value, '0x')) {
$value = substr($value, 2);
}
@@ -90,14 +87,13 @@ final class Hexadecimal implements TypeInterface
/**
* 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);
}
/**
+6 -13
View File
@@ -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 @@ final class Integer implements NumberInterface
/**
* 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);
}
/**
+9 -19
View File
@@ -33,22 +33,13 @@ use function sprintf;
*/
final class Time implements TypeInterface
{
/**
* @var IntegerObject
*/
private $seconds;
private IntegerObject $seconds;
private IntegerObject $microseconds;
/**
* @var IntegerObject
*/
private $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 @@ final class Time implements TypeInterface
/**
* 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(
+14 -35
View File
@@ -216,38 +216,19 @@ class Uuid implements UuidInterface
self::DCE_DOMAIN_ORG => 'org',
];
/**
* @var UuidFactoryInterface|null
*/
private static $factory = null;
private static ?UuidFactoryInterface $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
* @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 bool $factoryReplaced = false;
/**
* @var CodecInterface
*/
protected $codec;
/**
* 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 @@ class Uuid implements UuidInterface
/**
* 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;
+23 -56
View File
@@ -48,63 +48,26 @@ use const STR_PAD_LEFT;
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;
/**
* @var ValidatorInterface
*/
private $validator;
/** @var bool whether the feature set was provided from outside, or we can operate under "default" assumptions */
private $isDefaultFeatureSet;
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;
/**
* @param FeatureSet $features A set of available features in the current environment
* @var bool whether the feature set was provided from outside, or we can
* operate under "default" assumptions
*/
private bool $isDefaultFeatureSet;
/**
* @param FeatureSet|null $features A set of available features in the current environment
*/
public function __construct(?FeatureSet $features = null)
{
@@ -484,8 +447,12 @@ class UuidFactory implements UuidFactoryInterface
*
* @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);
}
+5 -1
View File
@@ -5,6 +5,7 @@ declare(strict_types=1);
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 @@ class RandomLibAdapterTest extends TestCase
*/
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());
}