Passed
Pull Request — master (#222)
by Dmitriy
12:29
created

RulesDumper::fetchOptions()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.0187

Importance

Changes 0
Metric Value
cc 5
eloc 14
c 0
b 0
f 0
nc 5
nop 2
dl 0
loc 24
ccs 10
cts 11
cp 0.9091
crap 5.0187
rs 9.4888
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use InvalidArgumentException;
8
use function is_array;
9
10
/**
11
 * RulesDumper allows to get an array of rule names and corresponding settings from a set of rules.
12
 * The array is usually passed to the client to use it in client-side validation.
13
 *
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 $ruleSetMap
46
     *
47
     * @return array
48
     */
49 6
    public function asArray(iterable $ruleSetMap, bool $dumpRuleName): array
50
    {
51 6
        return $this->fetchOptions($ruleSetMap, $dumpRuleName);
52
    }
53
54 6
    private function fetchOptions(iterable $rules, bool $dumpRuleName): array
55
    {
56 6
        $result = [];
57 6
        foreach ($rules as $attribute => $rule) {
58 6
            if (is_array($rule)) {
59 2
                $result[$attribute] = $this->fetchOptions($rule, $dumpRuleName);
60 6
            } elseif ($rule instanceof RuleInterface) {
61 6
                if ($dumpRuleName) {
62 2
                    $result[$attribute] = array_merge([$rule->getName()], $rule->getOptions());
63
                } else {
64 6
                    $result[$attribute] = $rule->getOptions();
65
                }
66
            } else {
67
                // or ?
68
                // $result[$attribute] = [get_class($rule)];
69
70
                throw new InvalidArgumentException(sprintf(
71
                    'Rules should be an array of rules that implements %s.',
72
                    RuleInterface::class,
73
                ));
74
            }
75
        }
76
77 6
        return $result;
78
    }
79
}
80