Passed
Pull Request — master (#270)
by Rustam
02:25
created

AttributeDataSet::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 4
c 1
b 0
f 0
dl 0
loc 6
ccs 4
cts 5
cp 0.8
rs 10
cc 3
nc 4
nop 2
crap 3.072
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 === [] && is_subclass_of($baseAnnotatedObject, DataSetInterface::class))
29
            ? $baseAnnotatedObject->getData()
30 7
            : $data;
31
    }
32
33 7
    public function getRules(): iterable
34
    {
35 7
        $classMeta = new ReflectionClass($this->baseAnnotatedObject);
36
37 7
        return $this->collectAttributes($classMeta);
38
    }
39
40
    // TODO: use Generator to collect attributes
41 7
    private function collectAttributes(ReflectionClass $classMeta): array
42
    {
43 7
        $rules = [];
44 7
        foreach ($classMeta->getProperties() as $property) {
45 6
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
46 6
            foreach ($attributes as $attribute) {
47 4
                $rules[$property->getName()][] = $attribute->newInstance();
48
            }
49
        }
50
51 7
        return $rules;
52
    }
53
}
54