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_string; |
18
|
|
|
use function preg_match; |
19
|
|
|
use function sprintf; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Validates whether the input is a valid UUID. |
23
|
|
|
* |
24
|
|
|
* It also supports validation of specific versions 1, 3, 4 and 5. |
25
|
|
|
* |
26
|
|
|
* @author Dick van der Heiden <[email protected]> |
27
|
|
|
* @author Henrique Moody <[email protected]> |
28
|
|
|
* @author Michael Weimann <[email protected]> |
29
|
|
|
*/ |
30
|
|
|
final class Uuid extends AbstractRule |
31
|
|
|
{ |
32
|
|
|
/** |
33
|
|
|
* Placeholder in "sprintf()" format used to create the REGEX that validates inputs. |
34
|
|
|
*/ |
35
|
|
|
private const PATTERN_FORMAT = '/^[0-9a-f]{8}-[0-9a-f]{4}-%s[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i'; |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* The UUID version to validate for. |
39
|
|
|
* |
40
|
|
|
* @var int|null |
41
|
|
|
*/ |
42
|
|
|
private $version; |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Initializes the rule with the desired version. |
46
|
|
|
* |
47
|
|
|
* @param int|null $version |
48
|
|
|
* |
49
|
|
|
* @throws ComponentException when the version is not valid |
50
|
|
|
*/ |
51
|
4 |
|
public function __construct(int $version = null) |
52
|
|
|
{ |
53
|
4 |
|
if (null !== $version && !$this->isSupportedVersion($version)) { |
54
|
3 |
|
throw new ComponentException(sprintf('Only versions 1, 3, 4, and 5 are supported: %d given', $version)); |
55
|
|
|
} |
56
|
|
|
|
57
|
1 |
|
$this->version = $version; |
58
|
1 |
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* {@inheritdoc} |
62
|
|
|
*/ |
63
|
30 |
|
public function validate($input): bool |
64
|
|
|
{ |
65
|
30 |
|
if (!is_string($input)) { |
66
|
4 |
|
return false; |
67
|
|
|
} |
68
|
|
|
|
69
|
26 |
|
return preg_match($this->getPattern(), $input) > 0; |
70
|
|
|
} |
71
|
|
|
|
72
|
4 |
|
private function isSupportedVersion(int $version): bool |
73
|
|
|
{ |
74
|
4 |
|
return $version >= 1 && $version <= 5 && 2 !== $version; |
75
|
|
|
} |
76
|
|
|
|
77
|
26 |
|
private function getPattern(): string |
78
|
|
|
{ |
79
|
26 |
|
if (null !== $this->version) { |
80
|
17 |
|
return sprintf(self::PATTERN_FORMAT, $this->version); |
81
|
|
|
} |
82
|
|
|
|
83
|
10 |
|
return sprintf(self::PATTERN_FORMAT, '[13-5]'); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|