Passed
Pull Request — master (#376)
by
unknown
03:18
created

AttributesRulesProvider   A

Complexity

Total Complexity 10

Size/Duplication

Total Lines 55
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 10
eloc 17
c 2
b 0
f 0
dl 0
loc 55
ccs 20
cts 20
cp 1
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A createAttributes() 0 4 2
A getRules() 0 7 2
A parseRules() 0 17 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 18
    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 18
    public function getRules(): iterable
34
    {
35 18
        if ($this->rules === null) {
36 18
            $this->rules = $this->parseRules();
37
        }
38
39 18
        yield from $this->rules;
40
    }
41
42
    /**
43
     * @throws ReflectionException
44
     */
45 18
    private function parseRules(): iterable
46
    {
47 18
        $reflection = is_object($this->source)
48 8
            ? new ReflectionObject($this->source)
49 10
            : new ReflectionClass($this->source);
50
51 18
        $reflectionProperties = $reflection->getProperties($this->propertyVisibility);
52 18
        if ($reflectionProperties === []) {
53 1
            return [];
54
        }
55 17
        foreach ($reflectionProperties as $property) {
56 17
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
57 17
            if ($attributes === []) {
58 1
                continue;
59
            }
60
61 17
            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 17
    private function createAttributes(array $attributes): iterable
69
    {
70 17
        foreach ($attributes as $attribute) {
71 17
            yield $attribute->newInstance();
72
        }
73
    }
74
}
75