Passed
Push — master ( 385352...0dcc76 )
by Smoren
02:42
created

Rule::stopOnAnyPriorViolation()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 6
ccs 0
cts 4
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Smoren\Validator\Rules;
6
7
use Smoren\Validator\Exceptions\CheckError;
8
use Smoren\Validator\Exceptions\ValidationSuccessException;
9
use Smoren\Validator\Exceptions\ValidationError;
10
use Smoren\Validator\Interfaces\CheckInterface;
11
use Smoren\Validator\Interfaces\RuleInterface;
12
use Smoren\Validator\Structs\Check;
13
use Smoren\Validator\Structs\RetrospectiveCheck;
14
15
class Rule extends BaseRule implements RuleInterface
16
{
17
    /**
18
     * @var array<CheckInterface>
19
     */
20
    protected array $checks = [];
21
22
    /**
23
     * {@inheritDoc}
24
     */
25 47
    public function validate($value): void
26
    {
27
        try {
28 47
            parent::validate($value);
29 4
        } catch (ValidationSuccessException $e) {
30 3
            return;
31
        }
32
33 46
        $errors = [];
34
35 46
        foreach ($this->checks as $check) {
36
            try {
37 46
                $check->execute($value, $errors);
38 30
            } catch (CheckError $e) {
39 30
                $errors[] = $e;
40 30
                if ($check->isInterrupting()) {
41 10
                    throw ValidationError::fromCheckErrors($value, $errors);
42
                }
43
            }
44
        }
45
46 38
        if (\count($errors) > 0) {
47 19
            throw ValidationError::fromCheckErrors($value, $errors);
48
        }
49
    }
50
51
    /**
52
     * {@inheritDoc}
53
     *
54
     * @return static
55
     */
56
    public function add(CheckInterface $check): self
57
    {
58
        $this->checks[] = $check;
59
        return $this;
60
    }
61
62
    /**
63
     * {@inheritDoc}
64
     *
65
     * @return static
66
     */
67
    public function check(string $name, callable $predicate, array $params = [], bool $isInterrupting = false): self
68
    {
69
        return $this->add(new Check($name, $predicate, $params, $isInterrupting));
70
    }
71
72
    /**
73
     * {@inheritDoc}
74
     *
75
     * @return static
76
     */
77
    public function stopOnViolation(): self
78
    {
79
        return $this->add(new RetrospectiveCheck());
80
    }
81
82
    /**
83
     * {@inheritDoc}
84
     *
85
     * @return static
86
     */
87
    public function stopOnAnyPriorViolation(): self
88
    {
89
        foreach ($this->checks as $check) {
90
            $check->setInterrupting();
91
        }
92
        return $this;
93
    }
94
}
95