Completed
Pull Request — master (#5)
by Philip
02:31
created

Collection   A

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Importance

Changes 0
Metric Value
wmc 9
lcom 1
cbo 2
dl 0
loc 58
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A isValidCollection() 0 15 4
A isValid() 0 10 4
A getInvalidDetails() 0 3 1
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 $rule
36
     * the rule 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 $rule) {
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' => [$rule]], ['value' => $value]);
50
            if (!$elementValidation['valid']) {
51
                $this->invalidDetails[$key] = $elementValidation['errors']['value'][0];
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