Test Failed
Pull Request — master (#297)
by Sergei
02:26
created

AttributesRulesProvider::getRules()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
rs 10
cc 2
nc 2
nop 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\RulesProvider;
6
7
use ReflectionAttribute;
8
use ReflectionClass;
9
use ReflectionObject;
10
use ReflectionProperty;
11
use Yiisoft\Validator\RuleInterface;
12
use Yiisoft\Validator\RulesProviderInterface;
13
14
final class AttributesRulesProvider implements RulesProviderInterface
15
{
16
    /**
17
     * @var array<RuleInterface[]>|null
18
     */
19
    private ?array $rules = null;
20
21
    public function __construct(
22
        /**
23
         * @param class-string|object $class
24
         */
25
        private string|object $source,
26
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC
27
    ) {
28
    }
29
30
    /**
31
     * @return array<RuleInterface[]>
32
     */
33
    public function getRules(): array
34
    {
35
        if ($this->rules === null) {
36
            $this->rules = $this->parseRules();
37
        }
38
        return $this->rules;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->rules could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
39
    }
40
41
    /**
42
     * @return array<RuleInterface[]>
43
     */
44
    private function parseRules(): array
45
    {
46
        $rules = [];
47
48
        $reflection = is_object($this->source)
49
            ? new ReflectionObject($this->source)
50
            : new ReflectionClass($this->source);
51
        foreach ($reflection->getProperties() as $property) {
52
            if (!$this->isUseProperty($property)) {
53
                continue;
54
            }
55
56
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
57
            foreach ($attributes as $attribute) {
58
                $rules[$property->getName()][] = $attribute->newInstance();
59
            }
60
        }
61
62
        return $rules;
63
    }
64
65
    private function isUseProperty(ReflectionProperty $property): bool
66
    {
67
        return ($property->isPublic() && ($this->propertyVisibility & ReflectionProperty::IS_PUBLIC))
68
            || ($property->isPrivate() && ($this->propertyVisibility & ReflectionProperty::IS_PRIVATE))
69
            || ($property->isProtected() && ($this->propertyVisibility & ReflectionProperty::IS_PROTECTED));
70
    }
71
}
72