Passed
Push — master ( 8de557...73711b )
by Smoren
02:29
created

Rule   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Test Coverage

Coverage 54.17%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 11
eloc 23
c 1
b 0
f 0
dl 0
loc 78
ccs 13
cts 24
cp 0.5417
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A add() 0 4 1
A stopOnViolation() 0 3 1
A validate() 0 23 6
A check() 0 3 1
A stopOnAnyViolationBeforeNow() 0 6 2
1
<?php
2
3
namespace Smoren\Validator\Rules;
4
5
use Smoren\Validator\Exceptions\CheckError;
6
use Smoren\Validator\Exceptions\ValidationSuccessException;
7
use Smoren\Validator\Exceptions\ValidationError;
8
use Smoren\Validator\Interfaces\CheckInterface;
9
use Smoren\Validator\Interfaces\RuleInterface;
10
use Smoren\Validator\Structs\Check;
11
use Smoren\Validator\Structs\RetrospectiveCheck;
12
13
class Rule extends BaseRule implements RuleInterface
14
{
15
    /**
16
     * @var array<CheckInterface>
17
     */
18
    protected array $checks = [];
19
20
    /**
21
     * {@inheritDoc}
22
     */
23 47
    public function validate($value): void
24
    {
25
        try {
26 47
            parent::validate($value);
27 4
        } catch (ValidationSuccessException $e) {
28 3
            return;
29
        }
30
31 46
        $errors = [];
32
33 46
        foreach ($this->checks as $check) {
34
            try {
35 46
                $check->execute($value, $errors);
36 30
            } catch (CheckError $e) {
37 30
                $errors[] = $e;
38 30
                if ($check->isInterrupting()) {
39 10
                    throw ValidationError::fromCheckErrors($value, $errors);
40
                }
41
            }
42
        }
43
44 38
        if (\count($errors) > 0) {
45 19
            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 check(string $name, callable $predicate, array $params = [], bool $isBlocking = false): self
66
    {
67
        return $this->add(new Check($name, $predicate, $params, $isBlocking));
68
    }
69
70
    /**
71
     * {@inheritDoc}
72
     *
73
     * @return static
74
     */
75
    public function stopOnViolation(): self
76
    {
77
        return $this->add(new RetrospectiveCheck());
78
    }
79
80
    /**
81
     * {@inheritDoc}
82
     *
83
     * @return static
84
     */
85
    public function stopOnAnyViolationBeforeNow(): self
86
    {
87
        foreach ($this->checks as $check) {
88
            $check->setInterrupting();
89
        }
90
        return $this;
91
    }
92
}
93