Completed
Push — master ( e3c15e...53c727 )
by Philip
10s
created

Collection::getInvalidDetails()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
/*
4
 * This file is part of the Valdi package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
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 Valdi\Validator;
13
14
use Valdi\ValidationException;
15
use Valdi\Validator;
16
17
/**
18
 * Validator for array values fulfilling a rule.
19
 */
20
class Collection implements ValidatorInterface {
21
22
23
    /**
24
     * Holds the invalid array values.
25
     */
26
    protected $invalidDetails;
27
28
    /**
29
     * Checks whether the given values are of the expected array.
30
     *
31
     * @param mixed $values
32
     * the potential array values to check
33
     * @param Validator $validator
34
     * the validator to check with
35
     * @param array $rules
36
     * the rules which each element must fulfill
37
     *
38
     * @return boolean
39
     * true if all the $values are a valid array, else false with the invalid details set
40
     */
41
    protected function isValidCollection($values, Validator $validator, array $rules) {
42
        if (!is_array($values)) {
43
            $this->invalidDetails = $values;
44
            return false;
45
        }
46
47
        $this->invalidDetails = [];
48
        foreach ($values as $key => $value) {
49
            $elementValidation = $validator->isValid(['value' => $rules], ['value' => $value]);
50
            if (!$elementValidation['valid']) {
51
                $this->invalidDetails[$key] = $elementValidation['errors']['value'];
52
            }
53
        }
54
        return count($this->invalidDetails) === 0;
55
    }
56
57
    /**
58
     * {@inheritdoc}
59
     */
60
    public function isValid($value, array $parameters) {
61
        if (count($parameters) !== 2) {
62
            throw new ValidationException('"collection" expects two parameters.');
63
        }
64
        if (!($parameters[0] instanceof Validator)) {
65
            throw new ValidationException('"collection" expects the first parameter to be an instance of a Validator.');
66
        }
67
        return in_array($value, ['', null], true) ||
68
            $this->isValidCollection($value, $parameters[0], $parameters[1]);
69
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    public function getInvalidDetails() {
75
        return ['collection' => $this->invalidDetails];
76
    }
77
}
78