Test Failed
Pull Request — master (#249)
by Dmitriy
02:18
created

AttributeDataSet::collectAttributes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.0416

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 12
rs 10
ccs 5
cts 6
cp 0.8333
cc 3
nc 3
nop 1
crap 3.0416
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\DataSet;
6
7
use ReflectionAttribute;
8
use ReflectionClass;
9
use Yiisoft\Validator\RuleInterface;
10
use Yiisoft\Validator\RulesProviderInterface;
11
12
/**
13
 * This data set makes use of attributes introduced in PHP 8. It simplifies rules configuration process, especially for
14
 * nested data and relations. Please refer to the guide for example.
15
 *
16
 * @link https://www.php.net/manual/en/language.attributes.overview.php
17
 */
18
final class AttributeDataSet implements RulesProviderInterface
19
{
20
    use ArrayDataTrait;
21
22
    private object $baseAnnotatedObject;
23
24
    public function __construct(object $baseAnnotatedObject, array $data = [])
25
    {
26
        $this->baseAnnotatedObject = $baseAnnotatedObject;
27
        $this->data = $data;
28
    }
29 2
30
    public function getRules(): iterable
31 2
    {
32 2
        $classMeta = new ReflectionClass($this->baseAnnotatedObject);
33
34
        return $this->collectAttributes($classMeta);
35 2
    }
36
37 2
    // TODO: use Generator to collect attributes
38
    private function collectAttributes(ReflectionClass $classMeta): array
39 2
    {
40
        $rules = [];
41
        foreach ($classMeta->getProperties() as $property) {
42 2
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
43
            foreach ($attributes as $attribute) {
44 2
                /** @psalm-suppress UndefinedMethod */
45 2
                $rules[$property->getName()][] = $attribute->newInstance();
46 2
            }
47
        }
48
49
        return $rules;
50 2
    }
51
}
52