8000 Refactor Slug validation to use dynamic regex. · symfony/symfony@0193d0c · GitHub
[go: up one dir, main page]

Skip to content

Commit 0193d0c

Browse files
Refactor Slug validation to use dynamic regex.
Replaced the hardcoded SLUG_PATTERN with a dynamic regex property in the Slug constraint class. This allows greater flexibility by enabling customization of the slug validation pattern. Adjusted SlugValidator to use the new regex property.
1 parent 41712ac commit 0193d0c

File tree

2 files changed

+4
-2
lines changed

2 files changed

+4
-2
lines changed

src/Symfony/Component/Validator/Constraints/Slug.php

+3-1
Original file line numberDiff line numberDiff line change
@@ -22,18 +22,20 @@
2222
class Slug extends Constraint
2323
{
2424
public const NOT_SLUG_ERROR = '14e6df1e-c8ab-4395-b6ce-04b132a3765e';
25-
public const SLUG_PATTERN = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
2625

2726
public string $message = 'This value is not a valid slug.';
27+
public string $regex = '/^[a-z0-9]+(?:-[a-z0-9]+)*$/';
2828

2929
public function __construct(
3030
?array $options = null,
31+
?string $regex = null,
3132
?string $message = null,
3233
?array $groups = null,
3334
mixed $payload = null,
3435
) {
3536
parent::__construct($options, $groups, $payload);
3637

3738
$this->message = $message ?? $this->message;
39+
$this->regex = $regex ?? $this->regex;
3840
}
3941
}

src/Symfony/Component/Validator/Constraints/SlugValidator.php

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ public function validate(mixed $value, Constraint $constraint): void
3737

3838
$value = (string) $value;
3939

40-
if (0 === preg_match(Slug::SLUG_PATTERN, $value)) {
40+
if (0 === preg_match($constraint->regex, $value)) {
4141
$this->context->buildViolation($constraint->message)
4242
->setParameter('{{ value }}', $this->formatValue($value))
4343
->setCode(Slug::NOT_SLUG_ERROR)

0 commit comments

Comments
 (0)
0