-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegex.php
More file actions
206 lines (179 loc) · 6.36 KB
/
Copy pathRegex.php
File metadata and controls
206 lines (179 loc) · 6.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php
namespace Quatrevieux\Form\Validator\Constraint;
use Attribute;
use InvalidArgumentException;
use Quatrevieux\Form\Util\Code;
use Quatrevieux\Form\Validator\FieldError;
use Quatrevieux\Form\Validator\Generator\ConstraintValidatorGeneratorInterface;
use Quatrevieux\Form\Validator\Generator\FieldErrorExpression;
use Quatrevieux\Form\Validator\Generator\FieldErrorExpressionInterface;
use Quatrevieux\Form\Validator\Generator\ValidatorGenerator;
use Quatrevieux\Form\View\Provider\FieldViewAttributesProviderInterface;
use function addcslashes;
use function ctype_alpha;
use function is_scalar;
use function preg_last_error_msg;
use function preg_match;
use function str_contains;
use function strlen;
use function strtolower;
use function strtoupper;
use function substr;
/**
* Check if the field value match the given regular expression
* Use the PCRE syntax (https://www.php.net/manual/en/pcre.pattern.php)
*
* Note: HTML5 "pattern" attribute will be generated if possible (only supports case-insensitive flag)
*
* Usage:
* <code>
* class MyForm
* {
* #[Regex('^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$')]
* public ?string $uuid;
*
* // Use flags parameter to pass the flags (here, case insensitive)
* #[Regex('^[a-z]+$', flags: 'i')]
* public string $foo;
* }
* </code>
*
* @implements ConstraintValidatorGeneratorInterface<Regex>
*
* @see preg_match() Used to validate the value
*/
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
final class Regex extends SelfValidatedConstraint implements FieldViewAttributesProviderInterface, ConstraintValidatorGeneratorInterface
{
public const CODE = '4ba73c60-bba8-58cc-a92b-7f572ecaaf1f';
public function __construct(
/**
* Regular expression pattern, following the PCRE syntax
*
* Unlike the PHP preg_match() function, the pattern must not be enclosed by delimiters
* and flags must be passed as a separate argument
*/
public readonly string $pattern,
/**
* Regular expression flags / pattern modifiers
*
* Note: Usage of flags other than i (case-insensitive) will disable HTML5 "pattern" attribute generation
*
* @see https://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
*/
public readonly string $flags = '',
/**
* Error message to display if the value does not match the pattern
*/
public readonly string $message = 'This value is not valid.',
) {
if (@preg_match($this->getGrepPattern(), '') === false) {
throw new InvalidArgumentException(sprintf('The regular expression "%s" is not valid : %s', $this->pattern, preg_last_error_msg()));
}
}
/**
* {@inheritdoc}
*/
public function validate(ConstraintInterface $constraint, mixed $value, object $data): ?FieldError
{
if (!is_scalar($value)) {
return null;
}
$pattern = $constraint->getGrepPattern();
if (!preg_match($pattern, (string) $value)) {
return new FieldError($constraint->message, code: self::CODE);
}
return null;
}
/**
* {@inheritdoc}
*/
public function generate(ConstraintInterface $constraint, ValidatorGenerator $generator): FieldErrorExpressionInterface
{
return FieldErrorExpression::single(fn(string $accessor) => (string) Code::expr($accessor)->format(
'is_scalar({}) && !preg_match({pattern}, (string) {}) ? {error} : null',
pattern: $constraint->getGrepPattern(),
error: new FieldError($constraint->message, code: self::CODE),
));
}
/**
* {@inheritdoc}
*/
public function getAttributes(): array
{
// HTML5 does not support regex flags
if ($this->flags !== '' && $this->flags !== 'i') {
return [];
}
// Convert the pattern to a valid HTML5 regex
// Inspired by Symfony\Component\Validator\Constraints\Regex::getHtmlPattern()
$pattern = $this->pattern;
// Trim leading ^, otherwise prepend .*
$pattern = $pattern[0] === '^' ? substr($pattern, 1) : '.*' . $pattern;
// Trim trailing $, otherwise append .*
$pattern = $pattern[-1] === '$' ? substr($pattern, 0, -1) : $pattern . '.*';
// Handle case-insensitive flag
if (str_contains($this->flags, 'i')) {
$pattern = self::toCaseInsensitive($pattern);
}
return [
'pattern' => $pattern,
];
}
/**
* Compile the regex pattern.
*/
private function getGrepPattern(): string
{
return '#' . addcslashes($this->pattern, '#') . '#' . $this->flags;
}
/**
* Explicitly convert a regex pattern to a case-insensitive one.
*
* @param string $pattern The pattern to convert
* @return string
*/
private static function toCaseInsensitive(string $pattern): string
{
$converted = '';
$inRange = false;
$rangeContent = '';
$escapeNext = false;
for ($i = 0, $length = strlen($pattern); $i < $length; ++$i) {
$char = $pattern[$i];
if ($escapeNext) {
$converted .= $char;
$escapeNext = false;
continue;
}
switch ($char) {
case '[':
$converted .= '[';
$inRange = true;
$rangeContent = '';
break;
case ']':
$converted .= strtoupper($rangeContent) . ']';
$rangeContent = '';
$inRange = false;
break;
case '\\':
$converted .= '\\';
$escapeNext = true;
break;
default:
if ($inRange) {
$char = strtolower($char);
$converted .= $char;
$rangeContent .= $char;
} elseif (!ctype_alpha($char)) {
$converted .= $char;
} else {
$converted .= '[' . strtolower($char) . strtoupper($char) . ']';
}
break;
}
}
return $converted;
}
}