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

RulesDumper::fetchOptions()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.9256

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 14
c 1
b 0
f 0
dl 0
loc 20
ccs 8
cts 12
cp 0.6667
rs 9.4888
cc 5
nc 5
nop 1
crap 5.9256
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