OrCombine::isValid()   A
last analyzed

Complexity

Conditions 4
Paths 5

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 11
CRAP Score 4

Importance

Changes 2
Bugs 1 Features 1
Metric Value
cc 4
eloc 10
nc 5
nop 2
dl 0
loc 17
ccs 11
cts 11
cp 1
crap 4
rs 9.9332
c 2
b 1
f 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\Validator;
15
use Valdi\ValidationException;
16
17
/**
18
 * Validator to combine other validators with a logical "or".
19
 */
20
class OrCombine implements ValidatorInterface
21
{
22
23
    /**
24
     * Holds the invalid validators.
25
     */
26
    protected $invalidDetails;
27
28
    /**
29
     * Checks whether the given parameters fulfil:
30
     * - At least three given
31
     * - The first one is a Validator or a subclass of it
32
     *
33
     * @param array $parameters the validation parameters
34
     *
35
     * @throws ValidationException - thrown if the amount of parameters is less than three or the first parameter is not a Validator
36
     */
37 4
    protected function checkParameters($parameters)
38
    {
39 4
        if (count($parameters) < 3) {
40 1
            throw new ValidationException('"or" expects at least 3 parameters.');
41
        }
42 4
        if (!($parameters[0] instanceof Validator)) {
43 1
            throw new ValidationException('"or" expects the first parameter to be a Validator or a subclass of it.');
44
        }
45 4
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50 4
    public function isValid($value, array $parameters)
51
    {
52
53 4
        $this->checkParameters($parameters);
54
55 4
        $validator = array_shift($parameters);
56 4
        $this->invalidDetails = [];
57 4
        $valid = false;
58 4
        foreach ($parameters as $rules) {
59 4
            $failedValidations = $validator->isValidValue($rules, $value);
60 4
            foreach ($failedValidations as $failedValidation) {
61 4
                $this->invalidDetails[] = $failedValidation;
62
            }
63 4
            $valid = $valid || empty($failedValidations);
64
        }
65
66 4
        return $valid;
67
    }
68
69
    /**
70
     * {@inheritdoc}
71
     */
72 2
    public function getInvalidDetails()
73
    {
74 2
        return ['or' => $this->invalidDetails];
75
    }
76
77
}
78