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

AttributeDataSet   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 5
eloc 13
c 2
b 0
f 0
dl 0
loc 31
ccs 13
cts 13
cp 1
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getRules() 0 5 1
A collectAttributes() 0 11 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