1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of Zenify |
7
|
|
|
* Copyright (c) 2012 Tomas Votruba (http://tomasvotruba.cz) |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Zenify\DoctrineFilters; |
11
|
|
|
|
12
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
13
|
|
|
use ReflectionClass; |
14
|
|
|
use Zenify\DoctrineFilters\Contract\ConditionalFilterInterface; |
15
|
|
|
use Zenify\DoctrineFilters\Contract\FilterInterface; |
16
|
|
|
use Zenify\DoctrineFilters\Contract\FilterManagerInterface; |
17
|
|
|
|
18
|
|
|
|
19
|
|
|
final class FilterManager implements FilterManagerInterface |
20
|
|
|
{ |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @var FilterInterface[] |
24
|
|
|
*/ |
25
|
|
|
private $filters = []; |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* @var EntityManagerInterface |
29
|
|
|
*/ |
30
|
|
|
private $entityManager; |
31
|
|
|
|
32
|
|
|
/** |
33
|
|
|
* @var bool |
34
|
|
|
*/ |
35
|
|
|
private $areFiltersEnabled = FALSE; |
36
|
|
|
|
37
|
|
|
|
38
|
5 |
|
public function __construct(EntityManagerInterface $entityManager) |
39
|
|
|
{ |
40
|
5 |
|
$this->entityManager = $entityManager; |
41
|
5 |
|
} |
42
|
|
|
|
43
|
|
|
|
44
|
5 |
|
public function addFilter(string $name, FilterInterface $filter) |
45
|
|
|
{ |
46
|
5 |
|
$this->filters[$name] = $filter; |
47
|
5 |
|
} |
48
|
|
|
|
49
|
|
|
|
50
|
3 |
|
public function enableFilters() |
51
|
|
|
{ |
52
|
3 |
|
if ($this->areFiltersEnabled) { |
53
|
|
|
return; |
54
|
|
|
} |
55
|
|
|
|
56
|
3 |
|
foreach ($this->filters as $name => $filter) { |
57
|
3 |
|
if ($filter instanceof ConditionalFilterInterface && ! $filter->isEnabled()) { |
58
|
3 |
|
continue; |
59
|
|
|
} |
60
|
|
|
|
61
|
3 |
|
$this->addFilterToEnabledInFilterCollection($name, $filter); |
62
|
|
|
} |
63
|
|
|
|
64
|
3 |
|
$this->areFiltersEnabled = TRUE; |
65
|
3 |
|
} |
66
|
|
|
|
67
|
|
|
|
68
|
3 |
|
private function addFilterToEnabledInFilterCollection(string $name, FilterInterface $filter) |
69
|
|
|
{ |
70
|
3 |
|
$filterCollection = $this->entityManager->getFilters(); |
71
|
|
|
|
72
|
3 |
|
$filterCollectionReflection = new ReflectionClass($filterCollection); |
73
|
3 |
|
$enabledFiltersReflection = $filterCollectionReflection->getProperty('enabledFilters'); |
74
|
3 |
|
$enabledFiltersReflection->setAccessible(TRUE); |
75
|
|
|
|
76
|
3 |
|
$enabledFilters = $enabledFiltersReflection->getValue($filterCollection); |
77
|
3 |
|
$enabledFilters[$name] = $filter; |
78
|
3 |
|
$enabledFiltersReflection->setValue($filterCollection, $enabledFilters); |
79
|
3 |
|
} |
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|