Passed
Push — master ( 92054b...6deecb )
by Smoren
02:27
created

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