1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Rb\Specification\Doctrine; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityRepository; |
6
|
|
|
use Doctrine\ORM\Query; |
7
|
|
|
use Doctrine\ORM\QueryBuilder; |
8
|
|
|
use Rb\Specification\Doctrine\Exception\LogicException; |
9
|
|
|
use Rb\Specification\Doctrine\Result\ModifierInterface; |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Class SpecificationRepository. |
13
|
|
|
*/ |
14
|
|
|
class SpecificationRepository extends EntityRepository |
15
|
|
|
{ |
16
|
|
|
/** |
17
|
|
|
* @var string |
18
|
|
|
*/ |
19
|
|
|
private $dqlAlias = 'e'; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* Get the query after matching with given specification. |
23
|
|
|
* |
24
|
|
|
* @param SpecificationInterface $specification |
25
|
|
|
* @param ModifierInterface $modifier |
26
|
|
|
* |
27
|
|
|
* @throws LogicException |
28
|
|
|
* |
29
|
|
|
* @return Query |
30
|
|
|
*/ |
31
|
|
|
public function match(SpecificationInterface $specification, ModifierInterface $modifier = null) |
32
|
|
|
{ |
33
|
|
|
if (! $specification->isSatisfiedBy($this->getEntityName())) { |
34
|
|
|
throw new LogicException(sprintf( |
35
|
|
|
'Specification "%s" not supported by this repository!', |
36
|
|
|
get_class($specification) |
37
|
|
|
)); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
$queryBuilder = $this->createQueryBuilder($this->dqlAlias); |
41
|
|
|
$this->modifyQueryBuilder($queryBuilder, $specification); |
42
|
|
|
|
43
|
|
|
return $this->modifyQuery($queryBuilder, $modifier); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Modifies the QueryBuilder according to the passed Specification. |
48
|
|
|
* Will also set the condition for this query if needed. |
49
|
|
|
* |
50
|
|
|
* @param QueryBuilder $queryBuilder |
51
|
|
|
* @param SpecificationInterface $specification |
52
|
|
|
* |
53
|
|
|
* @internal param string $dqlAlias |
54
|
|
|
*/ |
55
|
|
|
private function modifyQueryBuilder(QueryBuilder $queryBuilder, SpecificationInterface $specification) |
56
|
|
|
{ |
57
|
|
|
$condition = $specification->modify($queryBuilder, $this->dqlAlias); |
58
|
|
|
|
59
|
|
|
if (empty($condition)) { |
60
|
|
|
return; |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
$queryBuilder->where($condition); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* Modifies and returns a Query object according to the (optional) result modifier. |
68
|
|
|
* |
69
|
|
|
* @param QueryBuilder $queryBuilder |
70
|
|
|
* @param ModifierInterface|null $modifier |
71
|
|
|
* |
72
|
|
|
* @return Query |
73
|
|
|
*/ |
74
|
|
|
private function modifyQuery(QueryBuilder $queryBuilder, ModifierInterface $modifier = null) |
75
|
|
|
{ |
76
|
|
|
$query = $queryBuilder->getQuery(); |
77
|
|
|
|
78
|
|
|
if ($modifier) { |
79
|
|
|
$modifier->modify($query); |
80
|
|
|
} |
81
|
|
|
|
82
|
|
|
return $query; |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|