Passed
Push — master ( fdabae...ac5352 )
by Sergei
15:30 queued 13:06
created

AttributesRulesProvider::getRules()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 6
ccs 4
cts 4
cp 1
rs 10
cc 2
nc 2
nop 0
crap 2
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 12
    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 12
    public function getRules(): array
34
    {
35 12
        if ($this->rules === null) {
36 12
            $this->rules = $this->parseRules();
37
        }
38 12
        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 12
    private function parseRules(): array
45
    {
46 12
        $rules = [];
47
48 12
        $reflection = is_object($this->source)
49 5
            ? new ReflectionObject($this->source)
50 7
            : new ReflectionClass($this->source);
51 12
        foreach ($reflection->getProperties() as $property) {
52 12
            if (!$this->isUseProperty($property)) {
53 7
                continue;
54
            }
55
56 12
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
57 12
            foreach ($attributes as $attribute) {
58 12
                $rules[$property->getName()][] = $attribute->newInstance();
59
            }
60
        }
61
62 12
        return $rules;
63
    }
64
65 12
    private function isUseProperty(ReflectionProperty $property): bool
66
    {
67 12
        return ($property->isPublic() && ($this->propertyVisibility & ReflectionProperty::IS_PUBLIC))
68 12
            || ($property->isPrivate() && ($this->propertyVisibility & ReflectionProperty::IS_PRIVATE))
69 12
            || ($property->isProtected() && ($this->propertyVisibility & ReflectionProperty::IS_PROTECTED));
70
    }
71
}
72