Passed
Push — master ( 12a116...9129d6 )
by Smoren
02:21
created

Rule::add()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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