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
|
|
|
/** |
22
|
|
|
* @psalm-param Closure(mixed, ValidationContext):bool|null $when |
23
|
|
|
*/ |
24
|
|
|
public function __construct( |
25
|
|
|
private string $referenceClassName, |
26
|
|
|
string $message = 'This value is not a valid.', |
27
|
|
|
bool $skipOnEmpty = false, |
28
|
|
|
bool $skipOnError = false, |
29
|
|
|
?Closure $when = null, |
30
|
|
|
) { |
31
|
|
|
parent::__construct($message, $skipOnEmpty, $skipOnError, $when); |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
public function getRuleSet(): iterable |
35
|
|
|
{ |
36
|
|
|
$classMeta = new ReflectionClass($this->referenceClassName); |
37
|
|
|
|
38
|
|
|
return $this->collectAttributes($classMeta); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
private function collectAttributes(ReflectionClass $classMeta): iterable |
42
|
|
|
{ |
43
|
|
|
$reflectionProperties = $classMeta->getProperties(); |
44
|
|
|
if ($reflectionProperties === []) { |
45
|
|
|
return []; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
foreach ($reflectionProperties as $property) { |
49
|
|
|
$attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF); |
50
|
|
|
if ($attributes === []) { |
51
|
|
|
continue; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
yield $property->getName() => $this->createAttributes($attributes); |
55
|
|
|
} |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* @param ReflectionAttribute[] $attributes |
60
|
|
|
* |
61
|
|
|
* @return iterable |
62
|
|
|
*/ |
63
|
|
|
private function createAttributes(array $attributes): iterable |
64
|
|
|
{ |
65
|
|
|
foreach ($attributes as $attribute) { |
66
|
|
|
yield $attribute->newInstance(); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
|