Passed
Push — master ( 7a3887...17dfad )
by
unknown
02:21
created

AttributesRulesProvider::isUseProperty()   A

Complexity

Conditions 6
Paths 11

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
ccs 4
cts 4
cp 1
rs 9.2222
cc 6
nc 11
nop 1
crap 6
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
use function is_object;
15
16
final class AttributesRulesProvider implements RulesProviderInterface
17
{
18
    /**
19
     * @var array<RuleInterface[]>|null
20
     */
21
    private ?array $rules = null;
22
23 14
    public function __construct(
24
        /**
25
         * @param class-string|object $class
26
         */
27
        private string|object $source,
28
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC
29
    ) {
30
    }
31
32
    /**
33
     * @return array<RuleInterface[]>
34
     */
35 14
    public function getRules(): array
36
    {
37 14
        if ($this->rules === null) {
38 14
            $this->rules = $this->parseRules();
39
        }
40 14
        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...
41
    }
42
43
    /**
44
     * @return array<RuleInterface[]>
45
     */
46 14
    private function parseRules(): array
47
    {
48 14
        $rules = [];
49
50 14
        $reflection = is_object($this->source)
51 5
            ? new ReflectionObject($this->source)
52 9
            : new ReflectionClass($this->source);
53 14
        foreach ($reflection->getProperties($this->propertyVisibility) as $property) {
54 14
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
55 14
            foreach ($attributes as $attribute) {
56 14
                $rules[$property->getName()][] = $attribute->newInstance();
57
            }
58
        }
59
60 14
        return $rules;
61
    }
62
}
63