Passed
Pull Request — master (#249)
by Dmitriy
02:46
created

AttributeDataSet::collectAttributes()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3

Importance

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