AbstractValidationRuleSet::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the core-library package.
5
 *
6
 * (c) 2018 WEBEWEB
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace WBW\Library\Core\Validator\RuleSet;
13
14
use WBW\Library\Core\Validator\API\ValidationRuleInterface;
15
use WBW\Library\Core\Validator\API\ValidationRuleSetInterface;
16
17
/**
18
 * Abstract validation rule set.
19
 *
20
 * @author webeweb <https://github.com/webeweb/>
21
 * @package WBW\Library\Core\Validator\RuleSet
22
 * @abstract
23
 */
24
abstract class AbstractValidationRuleSet implements ValidationRuleSetInterface {
25
26
    /**
27
     * Rules.
28
     *
29
     * @var ValidationRuleInterface[]
30
     */
31
    private $rules;
32
33
    /**
34
     * Constructor.
35
     */
36
    protected function __construct() {
37
        $this->setRules([]);
38
    }
39
40
    /**
41
     * {@inheritDoc}
42
     */
43
    public function addRule(ValidationRuleInterface $rule): ValidationRuleSetInterface {
44
        $this->rules[] = $rule;
45
        return $this;
46
    }
47
48
    /**
49
     * {@inheritDoc}
50
     */
51
    public function getRules(): array {
52
        return $this->rules;
53
    }
54
55
    /**
56
     * {@inheritDoc}
57
     */
58
    public function removeRule(ValidationRuleInterface $rule): ValidationRuleSetInterface {
59
60
        for ($i = count($this->rules) - 1; 0 <= $i; --$i) {
61
62
            if ($rule !== $this->rules[$i]) {
63
                continue;
64
            }
65
66
            unset($this->rules[$i]);
67
        }
68
69
        return $this;
70
    }
71
72
    /**
73
     * Set the rules.
74
     *
75
     * @param ValidationRuleInterface[] $rules The rules.
76
     * @return ValidationRuleSetInterface Returns this validation rule set.
77
     */
78
    public function setRules(array $rules): ValidationRuleSetInterface {
79
        $this->rules = $rules;
80
        return $this;
81
    }
82
83
    /**
84
     * {@inheritDoc}
85
     */
86
    public function validate($object): array {
87
88
        $result = [];
89
90
        foreach ($this->rules as $current) {
91
92
            $status = $current->validate($object);
93
            if (null === $status->getRuleName()) {
94
                $status->setRuleName($current->getName());
95
            }
96
97
            $result [] = $status;
98
        }
99
100
        return $result;
101
    }
102
}
103