Passed
Pull Request — master (#376)
by
unknown
02:38
created

AttributesRulesProvider::parseRules()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 17
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 12
CRAP Score 5

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 11
c 2
b 0
f 0
dl 0
loc 17
ccs 12
cts 12
cp 1
rs 9.6111
cc 5
nc 8
nop 0
crap 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\RulesProvider;
6
7
use ReflectionAttribute;
8
use ReflectionClass;
9
use ReflectionException;
10
use ReflectionObject;
11
use ReflectionProperty;
12
use Yiisoft\Validator\RuleInterface;
13
use Yiisoft\Validator\RulesProviderInterface;
14
15
use function is_object;
16
17
final class AttributesRulesProvider implements RulesProviderInterface
18
{
19
    private iterable|null $rules = null;
20
21 16
    public function __construct(
22
        /**
23
         * @var class-string|object
24
         */
25
        private string|object $source,
26
        private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC
27
    ) {
28
    }
29
30
    /**
31
     * @throws ReflectionException
32
     */
33 16
    public function getRules(): iterable
34
    {
35 16
        if ($this->rules === null) {
36 16
            $this->rules = $this->parseRules();
37
        }
38
39 16
        yield from $this->rules;
40
    }
41
42
    /**
43
     * @throws ReflectionException
44
     */
45 16
    private function parseRules(): iterable
46
    {
47 16
        $reflection = is_object($this->source)
48 7
            ? new ReflectionObject($this->source)
49 9
            : new ReflectionClass($this->source);
50
51 16
        $reflectionProperties = $reflection->getProperties($this->propertyVisibility);
52 16
        if ($reflectionProperties === []) {
53 1
            return [];
54
        }
55 15
        foreach ($reflectionProperties as $property) {
56 15
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
57 15
            if ($attributes === []) {
58 1
                continue;
59
            }
60
61 15
            yield $property->getName() => $this->createAttributes($attributes);
62
        }
63
    }
64
65
    /**
66
     * @param array<array-key, ReflectionAttribute<RuleInterface>> $attributes
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<array-key, Reflect...tribute<RuleInterface>> at position 2 could not be parsed: Unknown type name 'array-key' at position 2 in array<array-key, ReflectionAttribute<RuleInterface>>.
Loading history...
67
     */
68 15
    private function createAttributes(array $attributes): iterable
69
    {
70 15
        foreach ($attributes as $attribute) {
71 15
            yield $attribute->newInstance();
72
        }
73
    }
74
}
75