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

RulesDumper   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 62
Duplicated Lines 0 %

Test Coverage

Coverage 92.31%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 15
c 1
b 0
f 1
dl 0
loc 62
ccs 12
cts 13
cp 0.9231
rs 10
wmc 6

2 Methods

Rating   Name   Duplication   Size   Complexity  
A asArray() 0 3 1
A fetchOptions() 0 24 5
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