| 1 |
<?php |
| 2 |
|
| 3 |
namespace ipl\Validator; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
|
| 7 |
/** |
| 8 |
* Validate a value against a given regex pattern |
| 9 |
* |
| 10 |
* Available options: |
| 11 |
* - pattern: (string) Regex pattern |
| 12 |
* - notMatchMessage: (string) Message to show when the value isn't valid. If not set, a default message will be used |
| 13 |
*/ |
| 14 |
class RegexMatchValidator extends BaseValidator |
| 15 |
{ |
| 16 |
/** @var string Regex pattern */ |
| 17 |
protected string $pattern; |
| 18 |
|
| 19 |
/** @var ?string Message to show when the value isn't valid. If not set, a default message will be used */ |
| 20 |
protected ?string $notMatchMessage = null; |
| 21 |
|
| 22 |
/** |
| 23 |
* Create a new RegexMatchValidator |
| 24 |
* |
| 25 |
* @param string|array{pattern: string, notMatchMessage?: string|null} $pattern |
| 26 |
* |
| 27 |
* @throws InvalidArgumentException If the notMatchMessage consists only of whitespace |
| 28 |
* @throws InvalidArgumentException If the pattern is missing or invalid |
| 29 |
*/ |
| 30 |
public function __construct(string|array $pattern) |
| 31 |
{ |
| 32 |
if (is_array($pattern)) { |
| 33 |
$this->pattern = $pattern['pattern'] ?? throw new InvalidArgumentException("Missing option 'pattern'"); |
| 34 |
$this->notMatchMessage = $pattern['notMatchMessage'] ?? null; |
| 35 |
|
| 36 |
if ($this->notMatchMessage !== null && trim($this->notMatchMessage) === '') { |
| 37 |
throw new InvalidArgumentException( |
| 38 |
"Option 'notMatchMessage' must not be an empty or whitespace-only string" |
| 39 |
); |
| 40 |
} |
| 41 |
} else { |
| 42 |
$this->pattern = $pattern; |
| 43 |
} |
| 44 |
|
| 45 |
$syntax = new RegexSyntaxValidator(); |
| 46 |
if (! $syntax->isValid($this->pattern)) { |
| 47 |
throw new InvalidArgumentException($syntax->getMessages()[0]); |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
/** |
| 52 |
* Check whether the value matches the pattern |
| 53 |
* |
| 54 |
* @param string $value |
| 55 |
* |
| 56 |
* @return bool |
| 57 |
*/ |
| 58 |
public function isValid($value): bool |
| 59 |
{ |
| 60 |
// Reset messages from a previous isValid() call. |
| 61 |
$this->clearMessages(); |
| 62 |
|
| 63 |
$result = preg_match($this->pattern, $value); |
| 64 |
|
| 65 |
if ($result === false) { |
| 66 |
$this->addMessage(preg_last_error_msg()); |
| 67 |
|
| 68 |
return false; |
| 69 |
} |
| 70 |
|
| 71 |
if (! $result) { |
| 72 |
if ($this->notMatchMessage === null) { |
| 73 |
$this->addMessage(sprintf( |
| 74 |
$this->translate("'%s' does not match against pattern '%s'"), |
| 75 |
$value, |
| 76 |
$this->pattern |
| 77 |
)); |
| 78 |
} else { |
| 79 |
$this->addMessage($this->notMatchMessage); |
| 80 |
} |
| 81 |
|
| 82 |
return false; |
| 83 |
} |
| 84 |
|
| 85 |
return true; |
| 86 |
} |
| 87 |
} |