|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\RulesProvider; |
|
6
|
|
|
|
|
7
|
|
|
use Generator; |
|
8
|
|
|
use ReflectionAttribute; |
|
9
|
|
|
use ReflectionClass; |
|
10
|
|
|
use ReflectionException; |
|
11
|
|
|
use ReflectionObject; |
|
12
|
|
|
use ReflectionProperty; |
|
13
|
|
|
use Yiisoft\Validator\RuleInterface; |
|
14
|
|
|
use Yiisoft\Validator\RulesProviderInterface; |
|
15
|
|
|
|
|
16
|
|
|
use function is_object; |
|
17
|
|
|
|
|
18
|
|
|
final class AttributesRulesProvider implements RulesProviderInterface |
|
19
|
|
|
{ |
|
20
|
|
|
private Generator|iterable|null $rules = null; |
|
21
|
|
|
|
|
22
|
|
|
public function __construct( |
|
23
|
14 |
|
/** |
|
24
|
|
|
* @param class-string|object $class |
|
25
|
|
|
*/ |
|
26
|
|
|
private string|object $source, |
|
27
|
|
|
private int $propertyVisibility = ReflectionProperty::IS_PRIVATE | ReflectionProperty::IS_PROTECTED | ReflectionProperty::IS_PUBLIC |
|
28
|
|
|
) { |
|
29
|
|
|
} |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @throws ReflectionException |
|
33
|
|
|
* |
|
34
|
|
|
* @return iterable |
|
35
|
14 |
|
*/ |
|
36
|
|
|
public function getRules(): iterable |
|
37
|
14 |
|
{ |
|
38
|
14 |
|
if ($this->rules === null) { |
|
39
|
|
|
$this->rules = $this->parseRules(); |
|
40
|
14 |
|
} |
|
41
|
|
|
|
|
42
|
|
|
yield from $this->rules; |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
|
|
/** |
|
46
|
14 |
|
* @throws ReflectionException |
|
47
|
|
|
* |
|
48
|
14 |
|
* @return Generator |
|
49
|
|
|
*/ |
|
50
|
14 |
|
private function parseRules(): iterable |
|
51
|
5 |
|
{ |
|
52
|
9 |
|
$reflection = is_object($this->source) |
|
53
|
14 |
|
? new ReflectionObject($this->source) |
|
54
|
14 |
|
: new ReflectionClass($this->source); |
|
55
|
14 |
|
|
|
56
|
14 |
|
$reflectionProperties = $reflection->getProperties($this->propertyVisibility); |
|
57
|
|
|
if ($reflectionProperties === []) { |
|
58
|
|
|
return []; |
|
59
|
|
|
} |
|
60
|
14 |
|
foreach ($reflectionProperties as $property) { |
|
61
|
|
|
$attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF); |
|
62
|
|
|
if ($attributes === []) { |
|
63
|
|
|
continue; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
yield $property->getName() => $this->createAttributes($attributes); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
/** |
|
71
|
|
|
* @param array<array-key, ReflectionAttribute<RuleInterface>> $attributes |
|
|
|
|
|
|
72
|
|
|
* |
|
73
|
|
|
* @return iterable |
|
74
|
|
|
*/ |
|
75
|
|
|
private function createAttributes(array $attributes): iterable |
|
76
|
|
|
{ |
|
77
|
|
|
foreach ($attributes as $attribute) { |
|
78
|
|
|
yield $attribute->newInstance(); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
} |
|
82
|
|
|
|