| Total Complexity | 8 |
| Total Lines | 50 |
| Duplicated Lines | 0 % |
| Changes | 1 | ||
| Bugs | 0 | Features | 0 |
| 1 | <?php |
||
| 20 | #[Attribute(Attribute::TARGET_PROPERTY)] |
||
| 21 | final class Regex extends Rule |
||
| 22 | { |
||
| 23 | public function __construct( |
||
| 24 | /** |
||
| 25 | * @var string the regular expression to be matched with |
||
| 26 | */ |
||
| 27 | private string $pattern, |
||
| 28 | /** |
||
| 29 | * @var bool whether to invert the validation logic. Defaults to `false`. If set to `true`, the regular |
||
| 30 | * expression defined via {@see $pattern} should NOT match the value. |
||
| 31 | */ |
||
| 32 | private bool $not = false, |
||
| 33 | private string $incorrectInputMessage = 'Value should be string.', |
||
| 34 | private string $message = 'Value is invalid.', |
||
| 35 | ?FormatterInterface $formatter = null, |
||
| 36 | bool $skipOnEmpty = false, |
||
| 37 | bool $skipOnError = false, |
||
| 38 | $when = null |
||
| 39 | ) { |
||
| 40 | parent::__construct(formatter: $formatter, skipOnEmpty: $skipOnEmpty, skipOnError: $skipOnError, when: $when); |
||
| 41 | } |
||
| 42 | |||
| 43 | protected function validateValue($value, ?ValidationContext $context = null): Result |
||
| 44 | { |
||
| 45 | $result = new Result(); |
||
| 46 | |||
| 47 | if (!is_string($value)) { |
||
| 48 | $result->addError($this->formatMessage($this->incorrectInputMessage)); |
||
| 49 | |||
| 50 | return $result; |
||
| 51 | } |
||
| 52 | |||
| 53 | if ( |
||
| 54 | (!$this->not && !preg_match($this->pattern, $value)) || |
||
| 55 | ($this->not && preg_match($this->pattern, $value)) |
||
| 56 | ) { |
||
| 57 | $result->addError($this->formatMessage($this->message)); |
||
| 58 | } |
||
| 59 | |||
| 60 | return $result; |
||
| 61 | } |
||
| 62 | |||
| 63 | public function getOptions(): array |
||
| 70 | ]); |
||
| 71 | } |
||
| 72 | } |
||
| 73 |