Passed
Pull Request — master (#314)
by Dmitriy
06:03 queued 03:28
created

AttributesRulesProvider::createAttributes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 2

Importance

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