1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Yiisoft\Validator\DataSet; |
6
|
|
|
|
7
|
|
|
use ReflectionAttribute; |
8
|
|
|
use ReflectionClass; |
9
|
|
|
use Yiisoft\Validator\DataSetInterface; |
10
|
|
|
use Yiisoft\Validator\RuleInterface; |
11
|
|
|
use Yiisoft\Validator\RulesProviderInterface; |
12
|
|
|
|
13
|
|
|
/** |
14
|
|
|
* This data set makes use of attributes introduced in PHP 8. It simplifies rules configuration process, especially for |
15
|
|
|
* nested data and relations. Please refer to the guide for example. |
16
|
|
|
* |
17
|
|
|
* @link https://www.php.net/manual/en/language.attributes.overview.php |
18
|
|
|
*/ |
19
|
|
|
final class AttributeDataSet implements RulesProviderInterface, DataSetInterface |
20
|
|
|
{ |
21
|
|
|
use ArrayDataTrait; |
22
|
|
|
|
23
|
|
|
private object $baseAnnotatedObject; |
24
|
|
|
|
25
|
7 |
|
public function __construct(object $baseAnnotatedObject, array $data = []) |
26
|
|
|
{ |
27
|
7 |
|
$this->baseAnnotatedObject = $baseAnnotatedObject; |
28
|
7 |
|
$this->data = $data; |
29
|
|
|
} |
30
|
|
|
|
31
|
7 |
|
public function getRules(): iterable |
32
|
|
|
{ |
33
|
7 |
|
$classMeta = new ReflectionClass($this->baseAnnotatedObject); |
34
|
|
|
|
35
|
7 |
|
return $this->collectAttributes($classMeta); |
36
|
|
|
} |
37
|
|
|
|
38
|
7 |
|
private function collectAttributes(ReflectionClass $classMeta): iterable |
39
|
|
|
{ |
40
|
7 |
|
$reflectionProperties = $classMeta->getProperties(); |
41
|
7 |
|
if ($reflectionProperties === []) { |
42
|
1 |
|
return []; |
43
|
|
|
} |
44
|
|
|
|
45
|
6 |
|
foreach ($reflectionProperties as $property) { |
46
|
6 |
|
$attributes = $property->getAttributes(RuleInterface::class, ReflectionAttribute::IS_INSTANCEOF); |
47
|
6 |
|
if ($attributes === []) { |
48
|
2 |
|
continue; |
49
|
|
|
} |
50
|
|
|
|
51
|
4 |
|
yield $property->getName() => $this->createAttributes($attributes); |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
/** |
56
|
|
|
* @param ReflectionAttribute[] $attributes |
57
|
|
|
* |
58
|
|
|
* @return iterable |
59
|
|
|
*/ |
60
|
4 |
|
private function createAttributes(array $attributes): iterable |
61
|
|
|
{ |
62
|
4 |
|
foreach ($attributes as $attribute) { |
63
|
4 |
|
yield $attribute->newInstance(); |
64
|
|
|
} |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|