| Total Complexity | 8 |
| Total Lines | 41 |
| Duplicated Lines | 0 % |
| Coverage | 100% |
| Changes | 0 | ||
| 1 | <?php |
||
| 17 | class MatchRegularExpression extends Rule |
||
| 18 | { |
||
| 19 | use HasValidationMessage; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var string the regular expression to be matched with |
||
| 23 | */ |
||
| 24 | private string $pattern; |
||
| 25 | /** |
||
| 26 | * @var bool whether to invert the validation logic. Defaults to false. If set to true, |
||
| 27 | * the regular expression defined via [[pattern]] should NOT match the attribute value. |
||
| 28 | */ |
||
| 29 | private bool $not = false; |
||
| 30 | |||
| 31 | private string $message = 'Value is invalid.'; |
||
| 32 | |||
| 33 | 1 | public function __construct(string $pattern) |
|
| 34 | { |
||
| 35 | 1 | $this->pattern = $pattern; |
|
| 36 | } |
||
| 37 | |||
| 38 | 1 | protected function validateValue($value, DataSetInterface $dataSet = null): Result |
|
| 39 | { |
||
| 40 | 1 | $result = new Result(); |
|
| 41 | |||
| 42 | 1 | $valid = !is_array($value) && |
|
| 43 | 1 | ((!$this->not && preg_match($this->pattern, $value)) |
|
| 44 | 1 | || ($this->not && !preg_match($this->pattern, $value))); |
|
| 45 | |||
| 46 | 1 | if (!$valid) { |
|
| 47 | 1 | $result->addError($this->translateMessage($this->message)); |
|
| 48 | } |
||
| 49 | |||
| 50 | 1 | return $result; |
|
| 51 | } |
||
| 52 | |||
| 53 | 1 | public function not(): self |
|
| 58 | } |
||
| 59 | } |
||
| 60 |