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

AttributeDataSet::handleAttributes()   C

Complexity

Conditions 14
Paths 51

Size

Total Lines 76
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 37
CRAP Score 14.0826

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 42
dl 0
loc 76
ccs 37
cts 40
cp 0.925
rs 6.2666
c 1
b 0
f 0
cc 14
nc 51
nop 1
crap 14.0826

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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