Passed
Pull Request — master (#222)
by Alexander
04:32 queued 02:10
created

RulesDumper::fetchOptions()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.5069

Importance

Changes 1
Bugs 1 Features 0
Metric Value
eloc 13
c 1
b 1
f 0
dl 0
loc 19
ccs 8
cts 11
cp 0.7272
rs 9.5222
cc 5
nc 5
nop 1
crap 5.5069
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): array
50
    {
51 6
        return $this->fetchOptions($ruleSetMap);
52
    }
53
54 6
    private function fetchOptions(iterable $rules): 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);
60 6
            } elseif ($rule instanceof ParametrizedRuleInterface) {
61 6
                $result[$attribute] = array_merge([$rule->getName()], $rule->getOptions());
62
            } elseif ($rule instanceof RuleInterface) {
63
                $result[$attribute] = [$rule->getName()];
64
            } else {
65
                throw new InvalidArgumentException(sprintf(
66
                    'Rules should be an array of rules that implements %s.',
67
                    RuleInterface::class,
68
                ));
69
            }
70
        }
71
72 6
        return $result;
73
    }
74
}
75