Passed
Pull Request — master (#344)
by Dmitriy
23:44 queued 21:04
created

RulesDumper   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 56
Duplicated Lines 0 %

Test Coverage

Coverage 71.43%

Importance

Changes 2
Bugs 0 Features 1
Metric Value
wmc 6
eloc 16
c 2
b 0
f 1
dl 0
loc 56
ccs 10
cts 14
cp 0.7143
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A asArray() 0 3 1
A fetchOptions() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use InvalidArgumentException;
8
9
/**
10
 * RulesDumper allows to get an array of rule names and corresponding settings from a set of rules.
11
 * The array is usually passed to the client to use it in client-side validation.
12
 *
13
 * * @see SerializableRuleInterface
14
 * * @see RuleInterface
15
 */
16
final class RulesDumper
17
{
18
    /**
19
     * Return all attribute rules as array.
20
     *
21
     * For example:
22
     *
23
     * ```php
24
     * [
25
     *    'amount' => [
26
     *        [
27
     *            'number',
28
     *            'integer' => true,
29
     *            'max' => 100,
30
     *            'notANumberMessage' => 'Value must be an integer.',
31
     *            'tooBigMessage' => 'Value must be no greater than 100.'
32
     *        ],
33
     *        ['callback'],
34
     *    ],
35
     *    'name' => [
36
     *        [
37
     *            'hasLength',
38
     *            'max' => 20,
39
     *            'message' => 'Value must contain at most 20 characters.'
40
     *        ],
41
     *    ],
42
     * ]
43
     * ```
44
     *
45
     * @param iterable $rules
46
     */
47 6
    public function asArray(iterable $rules): array
48
    {
49 6
        return $this->fetchOptions($rules);
50
    }
51
52 6
    private function fetchOptions(iterable $rules): array
53
    {
54 6
        $result = [];
55 6
        foreach ($rules as $attribute => $rule) {
56 6
            if (is_iterable($rule)) {
57 3
                $result[$attribute] = $this->fetchOptions($rule);
58 6
            } elseif ($rule instanceof SerializableRuleInterface) {
59 6
                $result[$attribute] = array_merge([$rule->getName()], $rule->getOptions());
60
            } elseif ($rule instanceof RuleInterface) {
61
                $result[$attribute] = [$rule->getName()];
62
            } else {
63
                throw new InvalidArgumentException(sprintf(
64
                    'Rules should be a rule or an array of rules that implements "%s". Type "%s" given.',
65
                    RuleInterface::class,
66
                    get_debug_type($rule),
67
                ));
68
            }
69
        }
70
71 6
        return $result;
72
    }
73
}
74