Passed
Pull Request — master (#152)
by
unknown
02:10
created

AttributeTrait::rules()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 17
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 9
c 1
b 0
f 0
nc 4
nop 0
dl 0
loc 17
ccs 0
cts 10
cp 0
crap 20
rs 9.9666
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator;
6
7
use ReflectionClass;
8
use Yiisoft\Validator\Attribute\HasMany;
9
use Yiisoft\Validator\Attribute\HasOne;
10
use Yiisoft\Validator\Attribute\Validate;
11
use Yiisoft\Validator\Rule\Each;
12
use Yiisoft\Validator\Rule\Nested;
13
14
trait AttributeTrait
15
{
16
    public function getRule(): Rule
17
    {
18
        $class = new ReflectionClass($this);
19
20
        return $this->handleClass($class);
21
    }
22
23
    private function handleClass(ReflectionClass $class): Rule
24
    {
25
        $rules = [];
26
        foreach ($class->getProperties() as $property) {
27
            if ($property->isStatic()) {
28
                continue;
29
            }
30
31
            $attributes = $property->getAttributes(HasMany::class);
32
            if ($attributes) {
33
                $relatedClass = new ReflectionClass(new ($attributes[0]->getArguments()[0]));
0 ignored issues
show
Bug introduced by
A parse error occurred: Syntax error, unexpected '(', expecting ':' on line 33 at column 56
Loading history...
34
                $rules[$property->getName()] = Each::rule(new Rules([$this->handleClass($relatedClass)]));
35
            }
36
37
            $attributes = $property->getAttributes(HasOne::class);
38
            if ($attributes) {
39
                $relatedClass = new ReflectionClass(new ($attributes[0]->getArguments()[0]));
40
                $rules[$property->getName()] = $this->handleClass($relatedClass);
41
            }
42
43
            $useEach = false;
44
            $flatRules = [];
45
            $attributes = $property->getAttributes(Validate::class);
46
47
            foreach ($attributes as $index => $attribute) {
48
                if ($index ===0 && $attribute->getArguments()[0] === Each::class) {
49
                    $useEach = true;
50
51
                    continue;
52
                }
53
54
                $flatRules[] = $attribute->newInstance()->getRule();
55
            }
56
57
            if (!$flatRules) {
58
                continue;
59
            }
60
61
            if (!$useEach) {
62
                $rules[$property->getName()] = $flatRules;
63
            } else {
64
                $rules[$property->getName()] = Each::rule(new Rules($flatRules));
65
            }
66
        }
67
68
        return Nested::rule($rules)->skipOnError(false);
69
    }
70
}
71