Completed
Push — master ( f70b57...5f6191 )
by Changwan
06:48
created

RuleNormalizer::normalize()   C

Complexity

Conditions 10
Paths 18

Size

Total Lines 23
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 10

Importance

Changes 0
Metric Value
cc 10
eloc 15
nc 18
nop 1
dl 0
loc 23
ccs 13
cts 13
cp 1
crap 10
rs 5.6534
c 0
b 0
f 0

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace Wandu\Validator;
3
4
use InvalidArgumentException;
5
use Wandu\Validator\Contracts\Rule;
6
7
class RuleNormalizer
8
{
9 10
    public function normalize($rule)
10
    {
11 10
        while (is_callable($rule) || (is_object($rule) && $rule instanceof Rule)) {
12 5
            if (is_callable($rule)) {
13 4
                $rule = call_user_func($rule);
14
            } else {
15 4
                $rule = $rule->rules();
16
            }
17
        }
18
        // string -> array
19 10
        if (!is_array($rule)) {
20 9
            $rule = [$rule];
21
        }
22 10
        $normalized = [];
23 10
        foreach ($rule as $key => $value) {
24 10
            if (is_int($key) || $key === '' || $key === null) {
25 10
                $normalized[''] = array_merge($normalized[''] ?? [], (array) $value);
26
            } else {
27 10
                $normalized[$key] = $this->normalize($value);
28
            }
29
        }
30 10
        return $normalized;
31
    }
32
}
33