Passed
Push — master ( 89f940...819311 )
by Alexander
02:27
created

Embedded::getRules()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 2
c 0
b 0
f 0
dl 0
loc 5
ccs 0
cts 3
cp 0
rs 10
cc 1
nc 1
nop 0
crap 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Validator\Attribute;
6
7
use Attribute;
8
use Closure;
9
use ReflectionAttribute;
10
use ReflectionClass;
11
use Yiisoft\Validator\Rule\Composite;
12
use Yiisoft\Validator\RuleInterface;
13
use Yiisoft\Validator\ValidationContext;
14
15
/**
16
 * Collects all attributes from the reference and represents it as its own.
17
 */
18
#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
19
final class Embedded extends Composite
20
{
21
    /**
22
     * @psalm-param Closure(mixed, ValidationContext):bool|null $when
23
     */
24
    public function __construct(
25
        private string $referenceClassName,
26
        bool $skipOnEmpty = false,
27
        bool $skipOnError = false,
28
        ?Closure $when = null,
29
    ) {
30
        parent::__construct([], $skipOnEmpty, $skipOnError, $when);
31
    }
32
33
    public function getRules(): array
34
    {
35
        $classMeta = new ReflectionClass($this->referenceClassName);
36
37
        return $this->collectAttributes($classMeta);
38
    }
39
40
    // TODO: use Generator to collect attributes
41
    private function collectAttributes(ReflectionClass $classMeta): array
42
    {
43
        $rules = [];
44
        foreach ($classMeta->getProperties() as $property) {
45
            $attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF);
46
            foreach ($attributes as $attribute) {
47
                $rules[$property->getName()][] = $attribute->newInstance();
48
            }
49
        }
50
51
        return $rules;
52
    }
53
}
54