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 Hashids\Hashids; |
18
|
|
|
use Ramsey\Uuid\Exception\InvalidUuidStringException; |
19
|
|
|
use Ramsey\Uuid\Uuid; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Hashed UUID identity. |
23
|
|
|
*/ |
24
|
|
|
class HashUuidIdentity extends AbstractIdentity |
25
|
|
|
{ |
26
|
|
|
/** |
27
|
|
|
* {@inheritdoc} |
28
|
|
|
* |
29
|
|
|
* @throws InvalidIdentityException |
30
|
|
|
*/ |
31
|
|
|
final public static function fromString(string $value) |
32
|
|
|
{ |
33
|
|
|
try { |
34
|
|
|
$uuid = Uuid::fromString((new Hashids())->decodeHex($value)); |
35
|
|
|
} catch (InvalidUuidStringException $exception) { |
36
|
|
|
throw new InvalidIdentityException( |
37
|
|
|
\sprintf('Provided identity value "%s" is not a valid hashed UUID', $value), |
38
|
|
|
0, |
39
|
|
|
$exception |
40
|
|
|
); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) { |
44
|
|
|
throw new InvalidIdentityException( |
45
|
|
|
\sprintf('Provided identity value "%s" is not a valid hashed UUID', $value) |
46
|
|
|
); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return new static($value); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Get identity from UUID string. |
54
|
|
|
* |
55
|
|
|
* @param string $value |
56
|
|
|
* |
57
|
|
|
* @return mixed|static |
|
|
|
|
58
|
|
|
*/ |
59
|
|
|
final public static function fromUuid(string $value) |
60
|
|
|
{ |
61
|
|
|
try { |
62
|
|
|
$uuid = Uuid::fromString($value); |
63
|
|
|
} catch (InvalidUuidStringException $exception) { |
64
|
|
|
throw new InvalidIdentityException( |
65
|
|
|
\sprintf('Provided identity value "%s" is not a valid UUID', $value), |
66
|
|
|
0, |
67
|
|
|
$exception |
68
|
|
|
); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
if ($uuid->getVariant() !== Uuid::RFC_4122 || !\in_array($uuid->getVersion(), \range(1, 5), true)) { |
72
|
|
|
throw new InvalidIdentityException( |
73
|
|
|
\sprintf('Provided identity value "%s" is not a valid UUID', $value) |
74
|
|
|
); |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return new static((new Hashids())->encodeHex(\str_replace('-', '', $uuid->toString()))); |
|
|
|
|
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
This check looks for the generic type
array
as a return type and suggests a more specific type. This type is inferred from the actual code.