Passed
Push — main ( 954523...045e26 )
by Breno
01:54
created

Regex   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 26
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 26
rs 10
wmc 4

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValid() 0 7 2
A translatedMessage() 0 3 1
A __construct() 0 6 1
1
<?php
2
declare(strict_types=1);
3
4
namespace BrenoRoosevelt\Validation\Rules;
5
6
use Attribute;
7
use BrenoRoosevelt\Validation\AbstractRule;
8
use BrenoRoosevelt\Validation\StopSign;
9
use BrenoRoosevelt\Validation\Translation\Translator;
10
use Throwable;
11
12
#[Attribute(Attribute::TARGET_PROPERTY)]
13
class Regex extends AbstractRule
14
{
15
    const MESSAGE = 'Value does not match pattern: %s';
16
17
    public function __construct(
18
        private string $pattern,
19
        ?string $message = null,
20
        int $stopOnFailure = StopSign::DONT_STOP
21
    ) {
22
        parent::__construct($message, $stopOnFailure);
23
    }
24
25
    public function isValid($input, array $context = []): bool
26
    {
27
        try {
28
            $subject = (string) $input;
29
            return preg_match($this->pattern, $subject) === 1;
30
        } catch (Throwable) {
31
            return false;
32
        }
33
    }
34
35
    public function translatedMessage(): ?string
36
    {
37
        return Translator::translate(self::MESSAGE, $this->pattern);
38
    }
39
}
40