This repository has been archived by the owner on Nov 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEntityRepositoryHelperTrait.php
211 lines (171 loc) · 6.34 KB
/
EntityRepositoryHelperTrait.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
<?php
/**
* This file is part of the Orbitale DoctrineTools package.
*
* (c) Alexandre Rock Ancelet <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Orbitale\Component\DoctrineTools;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
use Symfony\Component\PropertyAccess\PropertyAccess;
/**
* This trait is a tool to be used with the Doctrine ORM.
* It adds many useful methods to the default EntityRepository, and can be used in any ORM environment.
*
* Many methods accept a "$indexBy" parameter. This parameter is used to modify the returned collection index.
* If you specify the $indexBy parameter, the returned array will be indexed by the specified field.
* For instance, if you want to index by "id", you can have something similar to this:
* [ '1' => ['id': 1, 'slug': 'object'] , '12' => ['id': '12', 'slug' => 'another-object'] ]
* This is great to be sure that primary/unique indexes garantee unique objects in the returned array.
*/
trait EntityRepositoryHelperTrait
{
/**
* Finds all objects and retrieve only "root" objects, without their associated relatives.
* This prevends potential "fetch=EAGER" to be thrown.
*/
public function findAllRoot($indexBy = null): iterable
{
$this->checkRepository();
$data = $this->createQueryBuilder('object')
->getQuery()
->getResult()
;
if ($data && $indexBy) {
$data = $this->sortCollection($data, $indexBy);
}
return $data;
}
/**
* Finds all objects and fetches them as array.
*/
public function findAllArray($indexBy = null): array
{
$this->checkRepository();
$data = $this->createQueryBuilder('object', $indexBy)->getQuery()->getArrayResult();
if ($data && $indexBy) {
$data = $this->sortCollection($data, $indexBy);
}
return $data;
}
/**
* Alias for findBy, but adding the $indexBy argument.
*
* {@inheritdoc}
*/
public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, $indexBy = null)
{
$this->checkRepository();
$data = parent::findBy($criteria, $orderBy, $limit, $offset);
if ($data && $indexBy) {
$data = $this->sortCollection($data, $indexBy);
}
return $data;
}
/**
* Alias for findAll, but adding the $indexBy argument.
* If you do not want the associated elements to be fetched at the same time, please {@see EntityRepositoryHelperTrait::findAllRoot}
*
* {@inheritdoc}
*/
public function findAll($indexBy = null)
{
$this->checkRepository();
$data = $this->findBy([]);
if ($data && $indexBy) {
$data = $this->sortCollection($data, $indexBy);
}
return $data;
}
/**
* Gets current AUTO_INCREMENT value from table.
* Useful to see get the maximum ID of the table.
* NOTE: Not compatible with every platform.
*/
public function getAutoIncrement(): int
{
$this->checkRepository();
$table = $this->getClassMetadata()->getTableName();
$connection = $this->getEntityManager()->getConnection();
$statement = $connection->prepare('SHOW TABLE STATUS LIKE "'.$table.'" ');
$statement->execute();
$data = $statement->fetch();
return (int) $data['Auto_increment'];
}
/**
* Gets total number of elements in the table.
*/
public function getNumberOfElements(): ?int
{
$this->checkRepository();
return $this->_em->createQueryBuilder()
->select('count(a)')
->from($this->getEntityName(), 'a')
->getQuery()
->getSingleScalarResult()
;
}
/**
* Sorts a collection by a specific key, usually the primary key one,
* but you can specify any key.
* For "cleanest" uses, you'd better use a primary or unique key.
*/
public function sortCollection(iterable $collection, $indexBy = null): iterable
{
$this->checkRepository();
$finalCollection = [];
$currentObject = current($collection);
$accessor = class_exists('Symfony\Component\PropertyAccess\PropertyAccess') ? PropertyAccess::createPropertyAccessor() : null;
if ('_primary' === $indexBy || true === $indexBy) {
$indexBy = $this->getClassMetadata()->getSingleIdentifierFieldName();
}
if (is_object($currentObject) && property_exists($currentObject, $indexBy) && method_exists($currentObject, 'get'.ucfirst($indexBy))) {
// Sorts a list of objects only if the property and its getter exist
foreach ($collection as $entity) {
$id = $accessor ? $accessor->getValue($entity, $indexBy) : $entity->{'get'.ucFirst($indexBy)};
$finalCollection[$id] = $entity;
}
return $finalCollection;
}
if (is_array($currentObject) && array_key_exists($indexBy, $currentObject)) {
// Sorts a list of arrays only if the key exists
foreach ($collection as $array) {
$finalCollection[$array[$indexBy]] = $array;
}
return $finalCollection;
}
if ($collection) {
throw new \InvalidArgumentException('The collection to sort by index seems to be invalid.');
}
return $collection;
}
/**
* Gets the list of all single identifiers (id) from table
*/
public function getIds(): iterable
{
$this->checkRepository();
$primaryKey = $this->getClassMetadata()->getSingleIdentifierFieldName();
$result = $this->_em
->createQueryBuilder()
->select('entity.'.$primaryKey)
->from($this->_entityName, 'entity')
->getQuery()
->getResult(Query::HYDRATE_ARRAY)
;
$array = [];
foreach ($result as $id) {
$array[] = $id[$primaryKey];
}
return $array;
}
private function checkRepository(): void
{
if (!$this instanceof EntityRepository) {
throw new \RuntimeException(sprintf('This trait can only be used by %s classes.', EntityRepository::class));
}
}
}