SwitchValidator   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 2

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 2
dl 0
loc 44
ccs 12
cts 12
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 1
A iterate() 0 12 4
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Caridea
5
 *
6
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
7
 * use this file except in compliance with the License. You may obtain a copy of
8
 * the License at
9
 *
10
 * http://www.apache.org/licenses/LICENSE-2.0
11
 *
12
 * Unless required by applicable law or agreed to in writing, software
13
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15
 * License for the specific language governing permissions and limitations under
16
 * the License.
17
 *
18
 * @copyright 2015-2018 LibreWorks contributors
19
 * @license   Apache-2.0
20
 */
21
namespace Caridea\Validate;
22
23
/**
24
 * Chooses between validators based on object field value.
25
 *
26
 * @copyright 2015-2018 LibreWorks contributors
27
 * @license   Apache-2.0
28
 */
29
class SwitchValidator extends Validator
30
{
31
    /**
32
     * @var string Field name to inspect
33
     */
34
    protected $field;
35
    /**
36
     * @var Validator[] Associative array of field value to validator
37
     */
38
    protected $validators;
39
    
40
    /**
41
     * Creates a new switch validator.
42
     *
43
     * @param string Field name to inspect
44
     * @param array $validators Associative array of field value to validator
45
     */
46 3
    public function __construct(string $field, array $validators)
47
    {
48 3
        parent::__construct([]);
49 3
        $this->field = $field;
50 3
        $this->validators = $validators;
51 3
    }
52
    
53
    /**
54
     * Iterates over the ruleset and collects any error codes.
55
     *
56
     * @param object|array $values An object or associative array to validate
57
     * @return array Associative array of field name to error
58
     * @throws \InvalidArgumentException if `$values` is null or matching validator
59
     */
60 3
    protected function iterate($values): array
61
    {
62 3
        if (!is_object($values) && !is_array($values)) {
63 1
            throw new \InvalidArgumentException("Unable to validate provided object");
64
        }
65 2
        $value = $this->access($values, $this->field);
66 2
        if (!isset($this->validators[$value])) {
67 1
            throw new \InvalidArgumentException("No validator found for [{$this->field}] of '$value'");
68
        } else {
69 1
            return $this->validators[$value]->validate($values)->getErrors();
70
        }
71
    }
72
}
73