ORMRepository   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 254
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 7

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 20
lcom 1
cbo 7
dl 0
loc 254
ccs 65
cts 65
cp 1
rs 10
c 0
b 0
f 0

16 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A countBy() 0 21 4
A delete() 0 4 1
A deleteBy() 0 8 1
A find() 0 4 1
A findAll() 0 4 1
A findBy() 0 8 1
A findOneBy() 0 11 1
A getQueryBuilder() 0 8 1
A getEntityManager() 0 4 1
A getRepository() 0 8 2
A flush() 0 4 1
A persist() 0 4 1
A beginTransaction() 0 4 1
A commitTransaction() 0 4 1
A rollbackTransaction() 0 4 1
1
<?php
2
/**
3
 * Polder Knowledge / entityservice (https://polderknowledge.com)
4
 *
5
 * @link https://github.com/polderknowledge/entityservice for the canonical source repository
6
 * @copyright Copyright (c) 2016 Polder Knowledge (https://polderknowledge.com)
7
 * @license https://github.com/polderknowledge/entityservice/blob/master/LICENSE.md MIT
8
 */
9
10
namespace PolderKnowledge\EntityService\Repository\Doctrine;
11
12
use Doctrine\Common\Collections\Criteria;
13
use Doctrine\Common\Persistence\ObjectRepository;
14
use Doctrine\ORM\EntityManagerInterface;
15
use Doctrine\ORM\QueryBuilder;
16
use PolderKnowledge\EntityService\Repository\EntityRepositoryInterface;
17
use PolderKnowledge\EntityService\Repository\Feature\DeletableInterface;
18
use PolderKnowledge\EntityService\Repository\Feature\FlushableInterface;
19
use PolderKnowledge\EntityService\Repository\Feature\ReadableInterface;
20
use PolderKnowledge\EntityService\Repository\Feature\TransactionAwareInterface;
21
use PolderKnowledge\EntityService\Repository\Feature\WritableInterface;
22
use PolderKnowledge\EntityService\Repository\Util;
23
use UnexpectedValueException;
24
25
/**
26
 * Class ORMRepository is a default implementation for a repository using doctrine orm.
27
 */
28
class ORMRepository implements
29
    EntityRepositoryInterface,
30
    DeletableInterface,
31
    FlushableInterface,
32
    ReadableInterface,
33
    TransactionAwareInterface,
34
    WritableInterface
35
{
36
    /**
37
     * The Doctrine ORM entity manager that is used to retrieve and store data.
38
     *
39
     * @var EntityManagerInterface
40
     */
41
    protected $entityManager;
42
43
    /**
44
     * The FQCN of the entity to work with.
45
     *
46
     * @var string
47
     */
48
    protected $entityName;
49
50
    /**
51
     * The Doctrine ORM repository that is used to retrieve and store data.
52
     *
53
     * @var ObjectRepository
54
     */
55
    protected $repository;
56
57
    /**
58
     * Initializes the self::$entityManager and self::$entityName
59
     *
60
     * @param EntityManagerInterface $entityManager The Doctrine ORM entity manager used to retrieve and store data.
61
     * @param string $entityName The FQCN of the entity to work with.
62
     */
63 48
    public function __construct(EntityManagerInterface $entityManager, $entityName)
64
    {
65 48
        $this->entityManager = $entityManager;
66 48
        $this->entityName = $entityName;
67 48
    }
68
69
    /**
70
     * Counts entities by a set of criteria.
71
     *
72
     * Optionally sorting and limiting details can be passed. An implementation may throw an UnexpectedValueException
73
     * if certain values of the sorting or limiting details are not supported.
74
     *
75
     * @param array|Criteria $criteria The criteria to find entities by.
76
     * @return int Returns the amount of entities that are found.
77
     * @throws \Doctrine\ORM\Query\QueryException
78
     * @throws \Doctrine\ORM\NoResultException
79
     * @throws \Doctrine\ORM\NonUniqueResultException
80
     * @throws UnexpectedValueException
81
     */
82 6
    public function countBy($criteria)
83
    {
84
        /* @var $queryBuilder \Doctrine\ORM\QueryBuilder */
85 6
        $queryBuilder = $this->getRepository()->createQueryBuilder('e');
86 6
        $queryBuilder->select('count(e)');
87
88 6
        if ($criteria instanceof Criteria) {
89 3
            $clonedCriteria = clone $criteria;
90 3
            $clonedCriteria->setFirstResult(null);
91 3
            $clonedCriteria->setMaxResults(null);
92
93 3
            $queryBuilder->addCriteria($clonedCriteria);
94 3
        } elseif (!empty($criteria)) {
95 3
            foreach ($criteria as $field => $value) {
96 3
                $queryBuilder->andWhere($queryBuilder->expr()->eq('e.' . $field, ':' . $field));
97 3
                $queryBuilder->setParameter(':' . $field, $value);
98
            }
99
        }
100
101 6
        return $queryBuilder->getQuery()->getSingleScalarResult();
102
    }
103
104
    /**
105
     * Deletes the given object
106
     *
107
     * @param object $entity The entity to delete.
108
     */
109 3
    public function delete($entity)
110
    {
111 3
        $this->entityManager->remove($entity);
112 3
    }
113
114
    /**
115
     * Removes objects by a set of criteria.
116
     *
117
     * @param array|Criteria $criteria
118
     * @return void
119
     * @throws \Doctrine\ORM\Query\QueryException
120
     */
121 3
    public function deleteBy($criteria)
122
    {
123 3
        $criteria = Util::normalizeCriteria($criteria);
124
125 3
        $queryBuilder = $this->getQueryBuilder($criteria);
126 3
        $queryBuilder->delete($this->entityName, 'e');
127 3
        $queryBuilder->getQuery()->execute();
128 3
    }
129
130
    /**
131
     * Tries to find an entity in the repository by the given identifier.
132
     *
133
     * @param mixed $id The id of the entity which can be any type of object.
134
     * @return object|null Returns the entity that matches the identifier or null when no instance is found.
135
     */
136 3
    public function find($id)
137
    {
138 3
        return $this->entityManager->find($this->entityName, $id);
139
    }
140
141
    /**
142
     * Tries to find all entities in the repository.
143
     *
144
     * @return object[] Returns an array with entities that are found.
145
     */
146 3
    public function findAll()
147
    {
148 3
        return $this->getRepository()->findAll();
149
    }
150
151
    /**
152
     * Tries to find entities by a set of criteria.
153
     *
154
     * Optionally sorting and limiting details can be passed. An implementation may throw an UnexpectedValueException
155
     * if certain values of the sorting or limiting details are not supported.
156
     *
157
     * @param array|Criteria $criteria The criteria to find entities by.
158
     * @return array Returns an array with found entities. Returns an empty array when no entities are found.
159
     * @throws \Doctrine\ORM\Query\QueryException
160
     * @throws UnexpectedValueException Thrown when provided parameters are not supported.
161
     */
162 6
    public function findBy($criteria)
163
    {
164 6
        $criteria = Util::normalizeCriteria($criteria);
165
166 6
        $queryBuilder = $this->getQueryBuilder($criteria);
167
168 6
        return $queryBuilder->getQuery()->getResult();
169
    }
170
171
    /**
172
     * Tries to find a single entity by a set of criteria.
173
     *
174
     * @param array|Criteria $criteria The criteria. The criteria to find the entity by.
175
     * @return object|null Returns the entity that is found or null when no entity is found.
176
     * @throws \Doctrine\ORM\Query\QueryException
177
     * @throws \Doctrine\ORM\NonUniqueResultException
178
     */
179 6
    public function findOneBy($criteria)
180
    {
181 6
        $criteria = Util::normalizeCriteria($criteria);
182
183 6
        $criteria->setFirstResult(0);
184 6
        $criteria->setMaxResults(1);
185
186 6
        $queryBuilder = $this->getQueryBuilder($criteria);
187
188 6
        return $queryBuilder->getQuery()->getOneOrNullResult();
189
    }
190
191
    /**
192
     * Creates a new query builder using the $criteria.
193
     *
194
     * @param Criteria $criteria
195
     * @return \Doctrine\ORM\QueryBuilder
196
     * @throws \Doctrine\ORM\Query\QueryException
197
     */
198 15
    protected function getQueryBuilder(Criteria $criteria)
199
    {
200
        /** @var QueryBuilder $queryBuilder */
201 15
        $queryBuilder = $this->getRepository()->createQueryBuilder('e');
202 15
        $queryBuilder->addCriteria($criteria);
203
204 15
        return $queryBuilder;
205
    }
206
207
    /**
208
     * Gets the Doctrine EntityManager.
209
     *
210
     * @return EntityManagerInterface
211
     */
212 3
    public function getEntityManager()
213
    {
214 3
        return $this->entityManager;
215
    }
216
217
    /**
218
     * Returns the doctrine repository.
219
     *
220
     * @return ObjectRepository
221
     */
222 24
    public function getRepository()
223
    {
224 24
        if ($this->repository === null) {
225 24
            $this->repository = $this->entityManager->getRepository($this->entityName);
226
        }
227
228 24
        return $this->repository;
229
    }
230
231
    /**
232
     * Will flush the given entity. If non given all queued entities will be flushed.
233
     *
234
     * @param object $entity The entity to flush.
235
     * @return void
236
     */
237 3
    public function flush($entity = null)
238
    {
239 3
        $this->entityManager->flush($entity);
0 ignored issues
show
Unused Code introduced by
The call to EntityManagerInterface::flush() has too many arguments starting with $entity.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
240 3
    }
241
242
    /**
243
     * Persist the given entity.
244
     *
245
     * @param object $entity The entity to persist.
246
     */
247 3
    public function persist($entity)
248
    {
249 3
        $this->entityManager->persist($entity);
250 3
    }
251
252
    /**
253
     * Starts a new transaction.
254
     *
255
     * @return void
256
     */
257 3
    public function beginTransaction()
258
    {
259 3
        $this->entityManager->beginTransaction();
260 3
    }
261
262
    /**
263
     * Commits a started transaction.
264
     *
265
     * @return void
266
     */
267 3
    public function commitTransaction()
268
    {
269 3
        $this->entityManager->commit();
270 3
    }
271
272
    /**
273
     * Rolls back a started transaction.
274
     *
275
     * @return void
276
     */
277 3
    public function rollbackTransaction()
278
    {
279 3
        $this->entityManager->rollback();
280 3
    }
281
}
282