1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/* |
4
|
|
|
* This file is part of Respect/Validation. |
5
|
|
|
* |
6
|
|
|
* (c) Alexandre Gomes Gaigalas <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the "LICENSE.md" |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
declare(strict_types=1); |
13
|
|
|
|
14
|
|
|
namespace Respect\Validation\Rules; |
15
|
|
|
|
16
|
|
|
use Respect\Validation\Exceptions\ComponentException; |
17
|
|
|
use function is_scalar; |
18
|
|
|
use function preg_match; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* This class validates UUIDs. |
22
|
|
|
* |
23
|
|
|
* Henrique Moody <[email protected]> |
24
|
|
|
* Michael Weimann <[email protected]> |
25
|
|
|
*/ |
26
|
|
|
class Uuid extends AbstractRule |
27
|
|
|
{ |
28
|
|
|
public const VERSION_ALL = '[1-5]'; |
29
|
|
|
public const VERSION_1 = '1'; |
30
|
|
|
public const VERSION_2 = '2'; |
31
|
|
|
public const VERSION_3 = '3'; |
32
|
|
|
public const VERSION_4 = '4'; |
33
|
|
|
public const VERSION_5 = '5'; |
34
|
|
|
|
35
|
|
|
public const VERSIONS = [ |
36
|
|
|
self::VERSION_ALL, |
37
|
|
|
self::VERSION_1, |
38
|
|
|
self::VERSION_2, |
39
|
|
|
self::VERSION_3, |
40
|
|
|
self::VERSION_4, |
41
|
|
|
self::VERSION_5, |
42
|
|
|
]; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Uuid regex pattern with sprint version placeholder. |
46
|
|
|
*/ |
47
|
|
|
private const PATTERN = '/^[0-9a-f]{8}-[0-9a-f]{4}-%s[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i'; |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* The UUID version to validate for. |
51
|
|
|
* |
52
|
|
|
* string |
53
|
|
|
*/ |
54
|
|
|
private $version; |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Uuid constructor. |
58
|
|
|
* |
59
|
|
|
* @param string $version use one of the Uuid class constants |
60
|
|
|
* |
61
|
|
|
* @throws ComponentException |
62
|
|
|
*/ |
63
|
4 |
|
public function __construct(string $version = self::VERSION_ALL) |
64
|
|
|
{ |
65
|
4 |
|
if (false === in_array($version, self::VERSIONS)) { |
66
|
3 |
|
$message = sprintf('invalid version %s given, possible: %s', $version, join(', ', self::VERSIONS)); |
67
|
3 |
|
throw new ComponentException($message); |
68
|
|
|
} |
69
|
|
|
|
70
|
1 |
|
$this->version = $version; |
71
|
1 |
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Validates whether input is an UUID. |
75
|
|
|
* |
76
|
|
|
* @param mixed $input the value to test |
77
|
|
|
* |
78
|
|
|
* @return bool |
79
|
|
|
*/ |
80
|
59 |
|
public function validate($input): bool |
81
|
|
|
{ |
82
|
59 |
|
if (!is_scalar($input)) { |
83
|
|
|
return false; |
84
|
|
|
} |
85
|
|
|
|
86
|
59 |
|
$pattern = sprintf(self::PATTERN, $this->version); |
87
|
|
|
|
88
|
59 |
|
return preg_match($pattern, (string) $input) > 0; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|