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