1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* identity (https://github.com/phpgears/identity). |
5
|
|
|
* Identity objects for PHP. |
6
|
|
|
* |
7
|
|
|
* @license MIT |
8
|
|
|
* @link https://github.com/phpgears/identity |
9
|
|
|
* @author Julián Gutiérrez <[email protected]> |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Gears\Identity; |
15
|
|
|
|
16
|
|
|
use Gears\Identity\Exception\InvalidIdentityException; |
17
|
|
|
use Ramsey\Uuid\Exception\InvalidUuidStringException; |
18
|
|
|
use Ramsey\Uuid\Uuid; |
19
|
|
|
use Ramsey\Uuid\UuidInterface; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Immutable UUID based identity. |
23
|
|
|
*/ |
24
|
|
|
abstract class AbstractUuidIdentity extends AbstractIdentity |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* @param string $uuidString |
28
|
|
|
* |
29
|
|
|
* @throws InvalidUuidStringException |
30
|
|
|
* |
31
|
|
|
* @return UuidInterface |
32
|
|
|
*/ |
33
|
|
|
final protected static function uuidFromString(string $uuidString): UuidInterface |
34
|
|
|
{ |
35
|
|
|
try { |
36
|
|
|
$uuid = Uuid::fromString($uuidString); |
37
|
|
|
} catch (InvalidUuidStringException $exception) { |
38
|
|
|
throw new InvalidIdentityException( |
39
|
|
|
\sprintf('Provided identity value "%s" is not a valid UUID', $uuidString), |
40
|
|
|
0, |
41
|
|
|
$exception |
42
|
|
|
); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
static::assertUuidVariant($uuid); |
46
|
|
|
|
47
|
|
|
return $uuid; |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
/** |
51
|
|
|
* Assert correct UUID variant. |
52
|
|
|
* |
53
|
|
|
* @param UuidInterface $uuid |
54
|
|
|
* |
55
|
|
|
* @throws InvalidUuidStringException |
56
|
|
|
*/ |
57
|
|
|
final protected static function assertUuidVariant(UuidInterface $uuid): void |
58
|
|
|
{ |
59
|
|
|
if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) { |
60
|
|
|
throw new InvalidIdentityException( |
61
|
|
|
\sprintf('Provided identity value "%s" is not a valid UUID', $uuid->toString()) |
62
|
|
|
); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
|