Passed
Push — main ( 450654...a3bcd5 )
by Breno
01:48
created

Regex::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 3
dl 0
loc 7
rs 10
c 0
b 0
f 0
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 Throwable;
10
11
#[Attribute(Attribute::TARGET_PROPERTY)]
12
class Regex extends AbstractRule
13
{
14
    const MESSAGE = 'Value does not match pattern: %s';
15
16
    public function __construct(
17
        private string $pattern,
18
        ?string $message = null,
19
        int $stopOnFailure = StopSign::DONT_STOP
20
    ) {
21
        $message = $message ?? sprintf(self::MESSAGE, $this->pattern);
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 $exception) {
31
            return false;
32
        }
33
    }
34
}
35