1
|
|
|
<?php declare(strict_types = 1); |
2
|
|
|
|
3
|
|
|
namespace Bukashk0zzz\FilterBundle\Service; |
4
|
|
|
|
5
|
|
|
use Bukashk0zzz\FilterBundle\Annotation\FilterAnnotation; |
6
|
|
|
use Doctrine\Common\Annotations\Reader; |
7
|
|
|
use Doctrine\Common\Util\ClassUtils; |
8
|
|
|
use Laminas\Filter\FilterChain; |
9
|
|
|
use ReflectionProperty; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class Filter. |
13
|
|
|
*/ |
14
|
|
|
class Filter |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var Reader Cached annotation reader |
18
|
|
|
*/ |
19
|
|
|
protected $annotationReader; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Filter constructor. |
23
|
|
|
*/ |
24
|
|
|
public function __construct(Reader $annotationReader) |
25
|
|
|
{ |
26
|
|
|
$this->annotationReader = $annotationReader; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function filterEntity(mixed $object): void |
30
|
|
|
{ |
31
|
|
|
if ($object === null) { |
32
|
|
|
return; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
$reflectionClass = ClassUtils::newReflectionClass($object::class); |
36
|
|
|
|
37
|
|
|
foreach ($reflectionClass->getProperties() as $property) { |
38
|
|
|
$attributes = $this->getAttributes($property); |
39
|
|
|
|
40
|
|
|
if (empty($attributes)) { |
41
|
|
|
continue; |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
$property->setAccessible(true); |
45
|
|
|
$value = $property->getValue($object); |
46
|
|
|
|
47
|
|
|
$filter = new FilterChain(); |
48
|
|
|
foreach ($attributes as $attribute) { |
49
|
|
|
$filter->attachByName($attribute->getFilter(), $attribute->getOptions()); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
$property->setValue($object, $filter->filter($value)); |
53
|
|
|
} |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Get Annotations of PHP Attributes. |
58
|
|
|
* |
59
|
|
|
* @return array<FilterAnnotation> |
60
|
|
|
*/ |
61
|
|
|
private function getAttributes(ReflectionProperty $property): array |
62
|
|
|
{ |
63
|
|
|
$annotations = $this->annotationReader->getPropertyAnnotations($property); |
64
|
|
|
|
65
|
|
|
$attributes = []; |
66
|
|
|
foreach ($annotations as $annotation) { |
67
|
|
|
if ($annotation instanceof FilterAnnotation) { |
68
|
|
|
$attributes[] = $annotation; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
// If we get an empty array with the annotations, we try PHP Attributes |
73
|
|
|
if (empty($attributes)) { |
74
|
|
|
$attrs = $property->getAttributes(FilterAnnotation::class); |
75
|
|
|
|
76
|
|
|
$attributes = []; |
77
|
|
|
foreach ($attrs as $attr) { |
78
|
|
|
$attributes[] = $attr->newInstance(); |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $attributes; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|