1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace LAG\SmokerBundle\Bridge\Doctrine\ORM\DataProvider; |
4
|
|
|
|
5
|
|
|
use Doctrine\ORM\EntityManager; |
6
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
7
|
|
|
use LAG\SmokerBundle\Contracts\DataProvider\DataProviderInterface; |
8
|
|
|
use Symfony\Component\OptionsResolver\Options; |
9
|
|
|
use Symfony\Component\OptionsResolver\OptionsResolver; |
10
|
|
|
use Traversable; |
11
|
|
|
|
12
|
|
|
class ORMDataProvider implements DataProviderInterface |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* @var EntityManagerInterface|EntityManager |
16
|
|
|
*/ |
17
|
|
|
private $entityManager; |
18
|
|
|
|
19
|
1 |
|
public function __construct(EntityManagerInterface $entityManager) |
20
|
|
|
{ |
21
|
1 |
|
$this->entityManager = $entityManager; |
22
|
1 |
|
} |
23
|
|
|
|
24
|
1 |
|
public function getData(string $class, array $options = []): Traversable |
25
|
|
|
{ |
26
|
1 |
|
$options = $this->resolveOptions($options); |
27
|
|
|
|
28
|
|
|
$queryBuilder = $this |
29
|
1 |
|
->entityManager |
30
|
1 |
|
->getRepository($class) |
31
|
1 |
|
->createQueryBuilder($options['alias']) |
32
|
|
|
; |
33
|
|
|
|
34
|
1 |
|
foreach ($options['where'] as $parameter => $value) { |
35
|
1 |
|
if (is_int($parameter)) { |
36
|
1 |
|
$queryBuilder->andWhere($value); |
37
|
|
|
} else { |
38
|
|
|
$clause = $options['alias'].'.'.$parameter.' = :'.$parameter; |
39
|
|
|
$queryBuilder |
40
|
|
|
->andWhere($clause) |
41
|
|
|
->setParameter($parameter, $value) |
42
|
|
|
; |
43
|
|
|
} |
44
|
|
|
} |
45
|
|
|
|
46
|
1 |
|
return $queryBuilder->getQuery()->iterate(); |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
public function getIdentifier(string $class): array |
50
|
|
|
{ |
51
|
|
|
return $this->entityManager->getClassMetadata($class)->getIdentifier(); |
52
|
|
|
} |
53
|
|
|
|
54
|
1 |
|
protected function resolveOptions(array $options) |
55
|
|
|
{ |
56
|
1 |
|
$resolver = new OptionsResolver(); |
57
|
|
|
$resolver |
58
|
1 |
|
->setDefaults([ |
59
|
1 |
|
'alias' => 'entity', |
60
|
|
|
'requirements' => [], |
61
|
|
|
'where' => [], |
62
|
|
|
]) |
63
|
1 |
|
->setAllowedTypes('alias', 'string') |
64
|
1 |
|
->setAllowedTypes('requirements', 'array') |
65
|
1 |
|
->setAllowedTypes('where', [ |
66
|
1 |
|
'array', |
67
|
|
|
'string', |
68
|
|
|
]) |
69
|
|
|
->setNormalizer('where', function (Options $options, $value) { |
70
|
|
|
// Allow the configuration "where: article.enabled" instead of |
71
|
|
|
// where: |
72
|
|
|
// - article.enabled |
73
|
1 |
|
if (is_string($value)) { |
74
|
|
|
$value = [ |
75
|
1 |
|
$value, |
76
|
|
|
]; |
77
|
|
|
} |
78
|
|
|
|
79
|
1 |
|
return $value; |
80
|
1 |
|
}) |
81
|
|
|
; |
82
|
|
|
|
83
|
1 |
|
return $resolver->resolve($options); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|