|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Nip\Utility; |
|
4
|
|
|
|
|
5
|
|
|
use Ramsey\Uuid\Uuid as RamseyUuid; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Class Uuid |
|
9
|
|
|
* @package Nip\Utility |
|
10
|
|
|
*/ |
|
11
|
|
|
class Uuid |
|
12
|
|
|
{ |
|
13
|
|
|
|
|
14
|
|
|
/** |
|
15
|
|
|
* The callback that should be used to generate UUIDs. |
|
16
|
|
|
* |
|
17
|
|
|
* @var callable |
|
18
|
|
|
*/ |
|
19
|
|
|
protected static $uuidFactory; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* Generate a UUID (version 4). |
|
23
|
|
|
* |
|
24
|
|
|
* @return \Ramsey\Uuid\UuidInterface |
|
25
|
|
|
*/ |
|
26
|
1 |
|
public static function uuid() |
|
27
|
|
|
{ |
|
28
|
1 |
|
return static::$uuidFactory |
|
29
|
|
|
? call_user_func(static::$uuidFactory) |
|
30
|
1 |
|
: RamseyUuid::uuid4(); |
|
31
|
|
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* Generate a UUID (version 4). |
|
35
|
|
|
* |
|
36
|
|
|
* @return \Ramsey\Uuid\UuidInterface |
|
37
|
|
|
*/ |
|
38
|
|
|
public static function v4() |
|
39
|
|
|
{ |
|
40
|
|
|
return RamseyUuid::uuid4(); |
|
41
|
|
|
} |
|
42
|
|
|
|
|
43
|
|
|
/** |
|
44
|
|
|
* Generate a UUID (version 5). |
|
45
|
|
|
* |
|
46
|
|
|
* @return \Ramsey\Uuid\UuidInterface |
|
47
|
|
|
*/ |
|
48
|
|
|
public static function v5($ns, string $name) |
|
49
|
|
|
{ |
|
50
|
|
|
return RamseyUuid::uuid5($ns, $name); |
|
51
|
|
|
} |
|
52
|
|
|
|
|
53
|
|
|
/** |
|
54
|
|
|
* @param $uuid |
|
55
|
|
|
* @return mixed |
|
56
|
|
|
*/ |
|
57
|
|
|
public function fromString($uuid) |
|
58
|
|
|
{ |
|
59
|
|
|
return Uuid::fromString($uuid); |
|
|
|
|
|
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
/** |
|
63
|
|
|
* @param $uuid |
|
64
|
|
|
* @return mixed |
|
65
|
|
|
*/ |
|
66
|
|
|
public function fromBinary($uuid) |
|
67
|
|
|
{ |
|
68
|
|
|
return Uuid::fromBinary($uuid); |
|
|
|
|
|
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* @param $uuid |
|
73
|
|
|
* @return bool |
|
74
|
|
|
*/ |
|
75
|
21 |
|
public static function isValid($uuid) |
|
76
|
|
|
{ |
|
77
|
21 |
|
if (!is_string($uuid)) { |
|
78
|
|
|
return false; |
|
79
|
|
|
} |
|
80
|
|
|
|
|
81
|
21 |
|
return preg_match('/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iD', $uuid) > 0; |
|
82
|
|
|
} |
|
83
|
|
|
|
|
84
|
|
|
/** |
|
85
|
|
|
* Set the callable that will be used to generate UUIDs. |
|
86
|
|
|
* |
|
87
|
|
|
* @param callable|null $factory |
|
88
|
|
|
* @return void |
|
89
|
|
|
*/ |
|
90
|
|
|
public static function createUsing(callable $factory = null) |
|
91
|
|
|
{ |
|
92
|
|
|
static::$uuidFactory = $factory; |
|
93
|
|
|
} |
|
94
|
|
|
|
|
95
|
|
|
/** |
|
96
|
|
|
* Indicate that UUIDs should be created normally and not using a custom factory. |
|
97
|
|
|
* |
|
98
|
|
|
* @return void |
|
99
|
|
|
*/ |
|
100
|
|
|
public static function createNormally() |
|
101
|
|
|
{ |
|
102
|
|
|
static::$uuidFactory = null; |
|
103
|
|
|
} |
|
104
|
|
|
} |
|
105
|
|
|
|