Passed
Push — master ( 3e37f5...03f85f )
by Smoren
02:24
created

Check   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 62.5%

Importance

Changes 0
Metric Value
eloc 21
c 0
b 0
f 0
dl 0
loc 62
ccs 10
cts 16
cp 0.625
rs 10
wmc 5

2 Methods

Rating   Name   Duplication   Size   Complexity  
A execute() 0 15 4
A __construct() 0 12 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Smoren\Validator\Checks;
6
7
use Smoren\Validator\Exceptions\CheckError;
8
use Smoren\Validator\Exceptions\ValidationError;
9
use Smoren\Validator\Interfaces\CheckInterface;
10
use Smoren\Validator\Structs\Param;
11
12
class Check implements CheckInterface
13
{
14
    /**
15
     * @var string
16
     */
17
    protected string $name;
18
    /**
19
     * @var string
20
     */
21
    protected string $errorName;
22
    /**
23
     * @var callable
24
     */
25
    protected $predicate;
26
    /**
27
     * @var array<string, mixed>
28
     */
29
    protected array $params;
30
    /**
31
     * @var array<CheckInterface>
32
     */
33
    protected array $dependsOnChecks;
34
35
    /**
36
     * @param string $name
37
     * @param string $errorName
38
     * @param callable $predicate
39
     * @param array<string, mixed> $params
40
     * @param array<CheckInterface> $dependsOnChecks
41
     */
42
    public function __construct(
43
        string $name,
44
        string $errorName,
45
        callable $predicate,
46
        array $params = [],
47
        array $dependsOnChecks = []
48
    ) {
49
        $this->name = $name;
50
        $this->errorName = $errorName;
51
        $this->predicate = $predicate;
52
        $this->params = $params;
53
        $this->dependsOnChecks = $dependsOnChecks;
54
    }
55
56
    /**
57
     * {@inheritDoc}
58
     */
59 65
    public function execute($value, array $previousErrors): void
60
    {
61 65
        foreach ($this->dependsOnChecks as $check) {
62 11
            $check->execute($value, $previousErrors);
63
        }
64
65
        try {
66 65
            if (($this->predicate)($value, ...array_values($this->params)) === false) {
67 65
                throw new CheckError($this->errorName, $value, $this->params);
68
            }
69 39
        } catch (ValidationError $e) {
70 3
            $params = $this->params;
71 3
            $params[Param::RULE] = $e->getName();
72 3
            $params[Param::VIOLATIONS] = $e->getSummary();
73 3
            throw new CheckError($this->errorName, $value, $params);
74
        }
75
    }
76
}
77