ValidationProcessImpl::validate()   A
last analyzed

Complexity

Conditions 6
Paths 9

Size

Total Lines 23
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 12
c 1
b 0
f 0
dl 0
loc 23
rs 9.2222
cc 6
nc 9
nop 0
1
<?php
2
/**
3
 * @author    Nurlan Mukhanov <[email protected]>
4
 * @copyright 2022 Nurlan Mukhanov
5
 * @license   https://en.wikipedia.org/wiki/MIT_License MIT License
6
 * @link      https://github.com/Falseclock/service-layer
7
 */
8
9
declare(strict_types=1);
10
11
namespace Falseclock\Service\Validation;
12
13
use Closure;
14
15
class ValidationProcessImpl implements ValidationProcess
16
{
17
    /** @var ValidatorError[] */
18
    protected $errors = [];
19
    /** @var ValidationElement[] */
20
    protected $elements = [];
21
22
    /**
23
     * @return ValidatorError[]
24
     */
25
    public function getErrors(): array
26
    {
27
        return $this->errors;
28
    }
29
30
    /**
31
     * Добавление новой проверки значения
32
     *
33
     * @param string|array|callable $valueOrEnclosure
34
     * @param Validator[] $validators
35
     *
36
     * @return ValidationProcess
37
     */
38
    public function add($valueOrEnclosure, Validator ...$validators): ValidationProcess
39
    {
40
        foreach ($validators as $validator)
41
            $this->elements[] = new ValidationElement($valueOrEnclosure, $validator);
42
43
        return $this;
44
    }
45
46
    /**
47
     * @return ValidatorError[]
48
     */
49
    public function validate(): array
50
    {
51
        foreach ($this->elements as $element) {
52
53
            if ($element->valueOrEnclosure instanceof Closure && is_callable($element->valueOrEnclosure)) {
54
                $checkingValue = ($element->valueOrEnclosure)();
55
            } else {
56
                $checkingValue = $element->valueOrEnclosure;
57
            }
58
59
            /** @see ValidatorImpl::$value */
60
            $element->validator->value = $checkingValue;
0 ignored issues
show
Bug introduced by
Accessing value on the interface Falseclock\Service\Validation\Validator suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
61
62
            try {
63
                if ($element->validator->check($checkingValue) === false) {
64
                    $this->saveMessage($element->validator->getMessage());
65
                }
66
            } catch (ValidationException $t) {
67
                $this->saveMessage(new ValidatorError($t->getMessage()));
68
            }
69
        }
70
71
        return $this->errors;
72
    }
73
74
    /**
75
     * @param ValidatorError $message
76
     */
77
    private function saveMessage(ValidatorError $message): void
78
    {
79
        $this->errors[] = $message;
80
    }
81
}
82