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 iterable|null $rules = null; |
21
|
|
|
|
22
|
14 |
|
public function __construct( |
23
|
|
|
/** |
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
|
14 |
|
public function getRules(): iterable |
35
|
|
|
{ |
36
|
14 |
|
if ($this->rules === null) { |
37
|
14 |
|
$this->rules = $this->parseRules(); |
38
|
|
|
} |
39
|
|
|
|
40
|
14 |
|
yield from $this->rules; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* @throws ReflectionException |
45
|
|
|
*/ |
46
|
14 |
|
private function parseRules(): iterable |
47
|
|
|
{ |
48
|
14 |
|
$reflection = is_object($this->source) |
49
|
5 |
|
? new ReflectionObject($this->source) |
50
|
9 |
|
: new ReflectionClass($this->source); |
51
|
|
|
|
52
|
14 |
|
$reflectionProperties = $reflection->getProperties($this->propertyVisibility); |
53
|
14 |
|
if ($reflectionProperties === []) { |
54
|
|
|
return []; |
55
|
|
|
} |
56
|
14 |
|
foreach ($reflectionProperties as $property) { |
57
|
14 |
|
$attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF); |
58
|
14 |
|
if ($attributes === []) { |
59
|
|
|
continue; |
60
|
|
|
} |
61
|
|
|
|
62
|
14 |
|
yield $property->getName() => $this->createAttributes($attributes); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param array<array-key, ReflectionAttribute<RuleInterface>> $attributes |
|
|
|
|
68
|
|
|
*/ |
69
|
14 |
|
private function createAttributes(array $attributes): iterable |
70
|
|
|
{ |
71
|
14 |
|
foreach ($attributes as $attribute) { |
72
|
14 |
|
yield $attribute->newInstance(); |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
} |
76
|
|
|
|