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\GroupRule; |
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 GroupRule |
20
|
|
|
{ |
21
|
|
|
public function __construct( |
22
|
|
|
private string $referenceClassName, |
23
|
|
|
string $message = 'This value is not a valid.', |
24
|
|
|
bool $skipOnEmpty = false, |
25
|
|
|
bool $skipOnError = false, |
26
|
|
|
/** |
27
|
|
|
* @var Closure(mixed, ValidationContext):bool|null |
28
|
|
|
*/ |
29
|
|
|
?Closure $when = null, |
30
|
|
|
) { |
31
|
|
|
parent::__construct($message, $skipOnEmpty, $skipOnError, $when); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getRuleSet(): array |
35
|
|
|
{ |
36
|
|
|
$classMeta = new ReflectionClass($this->referenceClassName); |
37
|
|
|
|
38
|
|
|
return $this->collectAttributes($classMeta); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
// TODO: use Generator to collect attributes |
42
|
|
|
private function collectAttributes(ReflectionClass $classMeta): array |
43
|
|
|
{ |
44
|
|
|
$rules = []; |
45
|
|
|
foreach ($classMeta->getProperties() as $property) { |
46
|
|
|
$attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF); |
47
|
|
|
foreach ($attributes as $attribute) { |
48
|
|
|
/** @psalm-suppress UndefinedMethod */ |
49
|
|
|
$rules[$property->getName()][] = $attribute->newInstance(); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
return $rules; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|