Filter   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 69
Duplicated Lines 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
eloc 27
c 5
b 0
f 0
dl 0
loc 69
rs 10
wmc 11

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A filterEntity() 0 24 5
A getAttributes() 0 22 5
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