Passed
Push — master ( e3afe2...5369ce )
by Smoren
02:31
created

Rule::check()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 1
c 1
b 0
f 0
dl 0
loc 3
ccs 0
cts 2
cp 0
rs 10
cc 1
nc 1
nop 4
crap 2
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 extends NullableRule implements UniformRuleInterface
12
{
13
    /**
14
     * @var array<CheckInterface>
15
     */
16
    protected array $checks = [];
17
18
    /**
19
     * {@inheritDoc}
20
     */
21 38
    public function validate($value): void
22
    {
23 38
        if ($value === null) {
24 4
            if ($this->isNullable) {
25 3
                return;
26
            }
27
28 1
            throw new ValidationError($value, [[self::ERROR_NULL, []]]);
29
        }
30
31 37
        $errors = [];
32
33 37
        foreach ($this->checks as $check) {
34
            try {
35 37
                $check->execute($value);
36 21
            } catch (CheckError $e) {
37 21
                if ($check->isBlocking()) {
38 4
                    throw ValidationError::fromCheckErrors($value, [$e]);
39
                }
40 17
                $errors[] = $e;
41
            }
42
        }
43
44 33
        if (\count($errors) > 0) {
45 17
            throw ValidationError::fromCheckErrors($value, $errors);
46
        }
47
    }
48
49
    /**
50
     * {@inheritDoc}
51
     *
52
     * @return static
53
     */
54
    public function add(CheckInterface $check): self
55
    {
56
        $this->checks[] = $check;
57
        return $this;
58
    }
59
60
    /**
61
     * {@inheritDoc}
62
     *
63
     * @return static
64
     */
65
    public function toBlocking(): self
66
    {
67
        foreach ($this->checks as $check) {
68
            $check->setBlocking();
69
        }
70
        return $this;
71
    }
72
73
    /**
74
     * {@inheritDoc}
75
     *
76
     * @return static
77
     */
78
    public function check(string $name, callable $predicate, array $params = [], bool $isBlocking = false): self
79
    {
80
        return $this->add(new Check($name, $predicate, $params, $isBlocking));
81
    }
82
}
83