Passed
Push — master ( a5c78b...c47e5f )
by Alexander
02:21
created

RulesDumper   A

Complexity

Total Complexity 7

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Test Coverage

Coverage 57.89%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 16
c 1
b 0
f 1
dl 0
loc 64
ccs 11
cts 19
cp 0.5789
rs 10
wmc 7

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A asArray() 0 17 5
A withFormatter() 0 5 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use InvalidArgumentException;
8
use function get_class;
9
use function is_array;
10
use function is_object;
11
12
/**
13
 * RulesDumper allows to get an array of rule names and corresponding settings from a set of rules.
14
 * The array is usually passed to the client to use it in client-side validation.
15
 *
16
 * * @see ParametrizedRuleInterface
17
 */
18
final class RulesDumper
19
{
20
    private ?FormatterInterface $formatter;
21
22 1
    public function __construct(?FormatterInterface $formatter)
23
    {
24 1
        $this->formatter = $formatter;
25 1
    }
26
27
    /**
28
     * Return all attribute rules as array.
29
     *
30
     * For example:
31
     *
32
     * ```php
33
     * [
34
     *    'amount' => [
35
     *        [
36
     *            'number',
37
     *            'integer' => true,
38
     *            'max' => 100,
39
     *            'notANumberMessage' => 'Value must be an integer.',
40
     *            'tooBigMessage' => 'Value must be no greater than 100.'
41
     *        ],
42
     *        ['callback'],
43
     *    ],
44
     *    'name' => [
45
     *        [
46
     *            'hasLength',
47
     *            'max' => 20,
48
     *            'message' => 'Value must contain at most 20 characters.'
49
     *        ],
50
     *    ],
51
     * ]
52
     * ```
53
     *
54
     * @param iterable $rules
55
     *
56
     * @return array
57
     */
58 1
    public function asArray(iterable $rules): array
59
    {
60 1
        $rulesOfArray = [];
61 1
        foreach ($rules as $attribute => $rulesSet) {
62 1
            if (is_array($rulesSet)) {
63 1
                $rulesSet = new Rules($rulesSet);
64
            }
65 1
            if (!$rulesSet instanceof Rules) {
66
                throw new InvalidArgumentException(sprintf(
67
                    'Value should be an instance of %s or an array of rules, %s given.',
68
                    Rules::class,
69
                    is_object($rulesSet) ? get_class($rulesSet) : gettype($rulesSet)
70
                ));
71
            }
72 1
            $rulesOfArray[$attribute] = $rulesSet->withFormatter($this->formatter)->asArray();
73
        }
74 1
        return $rulesOfArray;
75
    }
76
77
    public function withFormatter(?FormatterInterface $formatter): self
78
    {
79
        $new = clone $this;
80
        $new->formatter = $formatter;
81
        return $new;
82
    }
83
}
84