Passed
Pull Request — master (#222)
by Rustam
02:32
created

RulesDumper::asArray()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 2
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 1
c 1
b 0
f 1
dl 0
loc 3
ccs 2
cts 2
cp 1
rs 10
cc 1
nc 1
nop 1
crap 1
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 ParametrizedRuleInterface
15
 * * @see RuleInterface
16
 */
17
final class RulesDumper
18
{
19
    /**
20
     * Return all attribute rules as array.
21
     *
22
     * For example:
23
     *
24
     * ```php
25
     * [
26
     *    'amount' => [
27
     *        [
28
     *            'number',
29
     *            'integer' => true,
30
     *            'max' => 100,
31
     *            'notANumberMessage' => 'Value must be an integer.',
32
     *            'tooBigMessage' => 'Value must be no greater than 100.'
33
     *        ],
34
     *        ['callback'],
35
     *    ],
36
     *    'name' => [
37
     *        [
38
     *            'hasLength',
39
     *            'max' => 20,
40
     *            'message' => 'Value must contain at most 20 characters.'
41
     *        ],
42
     *    ],
43
     * ]
44
     * ```
45
     *
46
     * @param iterable $ruleSetMap
47
     *
48
     * @return array
49
     */
50 6
    public function asArray(iterable $ruleSetMap): array
51
    {
52 6
        return $this->fetchOptions($ruleSetMap);
53
    }
54
55 6
    private function fetchOptions(iterable $rules): array
56
    {
57 6
        $result = [];
58 6
        foreach ($rules as $attribute => $rule) {
59 6
            if (is_array($rule)) {
60 2
                $result[$attribute] = $this->fetchOptions($rule);
61 6
            } elseif ($rule instanceof ParametrizedRuleInterface) {
62 6
                $result[$attribute] = array_merge([$rule->getName()], $rule->getOptions());
63
            } elseif ($rule instanceof RuleInterface) {
64
                $result[$attribute] = [$rule->getName()];
65
            } else {
66
                throw new InvalidArgumentException(sprintf(
67
                    'Rules should be a rule or an array of rules that implements %s.',
68
                    RuleInterface::class,
69
                ));
70
            }
71
        }
72
73 6
        return $result;
74
    }
75
}
76