summaryrefslogtreecommitdiffstats
path: root/vendor/ipl/validator/src/ValidatorChain.php
blob: 2860a127eb3eb0b4a4ed75da31b15ca7ee009ab9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
<?php

namespace ipl\Validator;

use Countable;
use InvalidArgumentException;
use ipl\Stdlib\Contract\Validator;
use ipl\Stdlib\Messages;
use ipl\Stdlib\Plugins;
use ipl\Stdlib\PriorityQueue;
use IteratorAggregate;
use SplObjectStorage;
use Traversable;
use UnexpectedValueException;

use function ipl\Stdlib\get_php_type;

class ValidatorChain implements Countable, IteratorAggregate, Validator
{
    use Messages;
    use Plugins;

    /** Default priority at which validators are added */
    const DEFAULT_PRIORITY = 1;

    /** @var PriorityQueue Validator chain */
    protected $validators;

    /** @var SplObjectStorage Validators that break the chain on failure */
    protected $validatorsThatBreakTheChain;

    /**
     * Create a new validator chain
     */
    public function __construct()
    {
        $this->validators = new PriorityQueue();
        $this->validatorsThatBreakTheChain = new SplObjectStorage();

        $this->addDefaultPluginLoader('validator', __NAMESPACE__, 'Validator');
    }

    /**
     * Get the validators that break the chain
     *
     * @return SplObjectStorage
     */
    public function getValidatorsThatBreakTheChain()
    {
        return $this->validatorsThatBreakTheChain;
    }

    /**
     * Add a validator to the chain
     *
     * If $breakChainOnFailure is true and the validator fails, subsequent validators won't be executed.
     *
     * @param Validator $validator
     * @param bool      $breakChainOnFailure
     * @param int       $priority            Priority at which to add validator
     *
     * @return $this
     *
     */
    public function add(Validator $validator, $breakChainOnFailure = false, $priority = self::DEFAULT_PRIORITY)
    {
        $this->validators->insert($validator, $priority);

        if ($breakChainOnFailure) {
            $this->validatorsThatBreakTheChain->attach($validator);
        }

        return $this;
    }

    /**
     * Add the validators from the given validator specification to the chain
     *
     * @param iterable $validators
     *
     * @return $this
     *
     * @throws InvalidArgumentException If $validators is not iterable or if the validator specification is invalid
     */
    public function addValidators($validators)
    {
        if ($validators instanceof static) {
            return $this->merge($validators);
        }

        if (! is_iterable($validators)) {
            throw new InvalidArgumentException(sprintf(
                '%s expects parameter one to be iterable, got %s instead',
                __METHOD__,
                get_php_type($validators)
            ));
        }

        foreach ($validators as $name => $validator) {
            $breakChainOnFailure = false;

            if (! $validator instanceof Validator) {
                if (is_int($name)) {
                    if (! is_array($validator)) {
                        $name = $validator;
                        $validator = null;
                    } else {
                        if (! isset($validator['name'])) {
                            throw new InvalidArgumentException(
                                'Invalid validator array specification: Key "name" is missing'
                            );
                        }

                        $name = $validator['name'];
                        unset($validator['name']);
                    }
                }

                if (is_array($validator)) {
                    if (isset($validator['options'])) {
                        $options = $validator['options'];

                        unset($validator['options']);

                        $validator = array_merge($validator, $options);
                    }

                    if (isset($validator['break_chain_on_failure'])) {
                        $breakChainOnFailure = $validator['break_chain_on_failure'];

                        unset($validator['break_chain_on_failure']);
                    }
                }

                $validator = $this->createValidator($name, $validator);
            }

            $this->add($validator, $breakChainOnFailure);
        }

        return $this;
    }

    /**
     * Add a validator loader
     *
     * @param string $namespace Namespace of the validators
     * @param string $postfix   Validator name postfix, if any
     *
     * @return $this
     */
    public function addValidatorLoader($namespace, $postfix = null)
    {
        $this->addPluginLoader('validator', $namespace, $postfix);

        return $this;
    }

    /**
     * Remove all validators from the chain
     *
     * @return $this
     */
    public function clearValidators()
    {
        $this->validators = new PriorityQueue();
        $this->validatorsThatBreakTheChain = new SplObjectStorage();

        return $this;
    }

    /**
     * Create a validator from the given name and options
     *
     * @param string $name
     * @param mixed  $options
     *
     * @return Validator
     *
     * @throws InvalidArgumentException If the validator to load is unknown
     * @throws UnexpectedValueException If a validator loader did not return an instance of {@link Validator}
     */
    public function createValidator($name, $options = null)
    {
        $class = $this->loadPlugin('validator', $name);

        if (! $class) {
            throw new InvalidArgumentException(sprintf(
                "Can't load validator '%s'. Validator unknown",
                $name
            ));
        }

        if (empty($options)) {
            $validator = new $class();
        } else {
            $validator = new $class($options);
        }

        if (! $validator instanceof Validator) {
            throw new UnexpectedValueException(sprintf(
                "%s expects loader to return an instance of %s for validator '%s', got %s instead",
                __METHOD__,
                Validator::class,
                $name,
                get_php_type($validator)
            ));
        }

        return $validator;
    }

    /**
     * Merge all validators from the given chain into this one
     *
     * @param ValidatorChain $validatorChain
     *
     * @return $this
     */
    public function merge(ValidatorChain $validatorChain)
    {
        $validatorsThatBreakTheChain = $validatorChain->getValidatorsThatBreakTheChain();

        foreach ($validatorChain->validators->yieldAll() as $priority => $validator) {
            $this->add($validator, $validatorsThatBreakTheChain->contains($validator), $priority);
        }

        return $this;
    }

    public function __clone()
    {
        $this->validators = clone $this->validators;
    }

    /**
     * Export the chain as array
     *
     * @return array
     */
    public function toArray()
    {
        return array_values(iterator_to_array($this));
    }

    public function count(): int
    {
        return count($this->validators);
    }

    /**
     * Get an iterator for traversing the validators
     *
     * @return Validator[]|PriorityQueue
     */
    public function getIterator(): Traversable
    {
         // Clone validators because the PriorityQueue acts as a heap and thus items are removed upon iteration
        return clone $this->validators;
    }

    public function isValid($value)
    {
        $this->clearMessages();

        $valid = true;

        foreach ($this as $validator) {
            if ($validator->isValid($value)) {
                continue;
            }

            $valid = false;

            $this->addMessages($validator->getMessages());

            if ($this->validatorsThatBreakTheChain->contains($validator)) {
                break;
            }
        }

        return $valid;
    }
}