Completed
Push — master ( 60399b...890f86 )
by Craig
06:15
created

retrieveCollectionResult()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 11
nc 4
nop 2
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
1
<?php
2
/**
3
 * Routes.
4
 *
5
 * @copyright Zikula contributors (Zikula)
6
 * @license http://www.gnu.org/licenses/lgpl.html GNU Lesser General Public License
7
 * @author Zikula contributors <[email protected]>.
8
 * @link http://www.zikula.org
9
 * @link http://zikula.org
10
 * @version Generated by ModuleStudio 0.7.5 (http://modulestudio.de).
11
 */
12
13
namespace Zikula\RoutesModule\Entity\Repository\Base;
14
15
use Doctrine\Common\Collections\ArrayCollection;
16
use Gedmo\Sortable\Entity\Repository\SortableRepository;
17
18
use Doctrine\ORM\Query;
19
use Doctrine\ORM\QueryBuilder;
20
use Doctrine\ORM\Tools\Pagination\Paginator;
21
use InvalidArgumentException;
22
use Psr\Log\LoggerInterface;
23
use Zikula\Common\Translator\TranslatorInterface;
24
use Zikula\UsersModule\Api\ApiInterface\CurrentUserApiInterface;
25
use Zikula\RoutesModule\Entity\RouteEntity;
26
use Zikula\RoutesModule\Helper\CollectionFilterHelper;
27
28
/**
29
 * Repository class used to implement own convenience methods for performing certain DQL queries.
30
 *
31
 * This is the base repository class for route entities.
32
 */
33
abstract class AbstractRouteRepository extends SortableRepository
34
{
35
    /**
36
     * @var string The main entity class
37
     */
38
    protected $mainEntityClass = 'Zikula\RoutesModule\Entity\RouteEntity';
39
40
    /**
41
     * @var string The default sorting field/expression
42
     */
43
    protected $defaultSortingField = 'sort';
44
45
    /**
46
     * @var CollectionFilterHelper
47
     */
48
    protected $collectionFilterHelper = null;
49
50
    /**
51
     * Retrieves an array with all fields which can be used for sorting instances.
52
     *
53
     * @return array Sorting fields array
54
     */
55
    public function getAllowedSortingFields()
56
    {
57
        return [
58
            'routeType',
59
            'replacedRouteName',
60
            'bundle',
61
            'controller',
62
            'action',
63
            'path',
64
            'host',
65
            'schemes',
66
            'methods',
67
            'prependBundlePrefix',
68
            'translatable',
69
            'translationPrefix',
70
            'condition',
71
            'description',
72
            'sort',
73
            'group',
74
            'createdBy',
75
            'createdDate',
76
            'updatedBy',
77
            'updatedDate',
78
        ];
79
    }
80
81
    /**
82
     * Returns the default sorting field.
83
     *
84
     * @return string
85
     */
86
    public function getDefaultSortingField()
87
    {
88
        return $this->defaultSortingField;
89
    }
90
    
91
    /**
92
     * Sets the default sorting field.
93
     *
94
     * @param string $defaultSortingField
95
     *
96
     * @return void
97
     */
98
    public function setDefaultSortingField($defaultSortingField)
99
    {
100
        if ($this->defaultSortingField != $defaultSortingField) {
101
            $this->defaultSortingField = $defaultSortingField;
102
        }
103
    }
104
    
105
    /**
106
     * Returns the collection filter helper.
107
     *
108
     * @return CollectionFilterHelper
109
     */
110
    public function getCollectionFilterHelper()
111
    {
112
        return $this->collectionFilterHelper;
113
    }
114
    
115
    /**
116
     * Sets the collection filter helper.
117
     *
118
     * @param CollectionFilterHelper $collectionFilterHelper
119
     *
120
     * @return void
121
     */
122
    public function setCollectionFilterHelper($collectionFilterHelper)
123
    {
124
        if ($this->collectionFilterHelper != $collectionFilterHelper) {
125
            $this->collectionFilterHelper = $collectionFilterHelper;
126
        }
127
    }
128
    
129
130
    /**
131
     * Updates the creator of all objects created by a certain user.
132
     *
133
     * @param integer             $userId         The userid of the creator to be replaced
134
     * @param integer             $newUserId      The new userid of the creator as replacement
135
     * @param TranslatorInterface $translator     Translator service instance
136
     * @param LoggerInterface     $logger         Logger service instance
137
     * @param CurrentUserApiInterface $currentUserApi CurrentUserApi service instance
138
     *
139
     * @return void
140
     *
141
     * @throws InvalidArgumentException Thrown if invalid parameters are received
142
     */
143 View Code Duplication
    public function updateCreator($userId, $newUserId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApiInterface $currentUserApi)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
144
    {
145
        // check id parameter
146
        if ($userId == 0 || !is_numeric($userId)
147
         || $newUserId == 0 || !is_numeric($newUserId)) {
148
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
149
        }
150
    
151
        $qb = $this->getEntityManager()->createQueryBuilder();
152
        $qb->update($this->mainEntityClass, 'tbl')
153
           ->set('tbl.createdBy', $newUserId)
154
           ->where('tbl.createdBy = :creator')
155
           ->setParameter('creator', $userId);
156
        $query = $qb->getQuery();
157
        $query->execute();
158
    
159
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
160
        $logger->debug('{app}: User {user} updated {entities} created by user id {userid}.', $logArgs);
161
    }
162
    
163
    /**
164
     * Updates the last editor of all objects updated by a certain user.
165
     *
166
     * @param integer             $userId         The userid of the last editor to be replaced
167
     * @param integer             $newUserId      The new userid of the last editor as replacement
168
     * @param TranslatorInterface $translator     Translator service instance
169
     * @param LoggerInterface     $logger         Logger service instance
170
     * @param CurrentUserApiInterface $currentUserApi CurrentUserApi service instance
171
     *
172
     * @return void
173
     *
174
     * @throws InvalidArgumentException Thrown if invalid parameters are received
175
     */
176 View Code Duplication
    public function updateLastEditor($userId, $newUserId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApiInterface $currentUserApi)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
    {
178
        // check id parameter
179
        if ($userId == 0 || !is_numeric($userId)
180
         || $newUserId == 0 || !is_numeric($newUserId)) {
181
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
182
        }
183
    
184
        $qb = $this->getEntityManager()->createQueryBuilder();
185
        $qb->update($this->mainEntityClass, 'tbl')
186
           ->set('tbl.updatedBy', $newUserId)
187
           ->where('tbl.updatedBy = :editor')
188
           ->setParameter('editor', $userId);
189
        $query = $qb->getQuery();
190
        $query->execute();
191
    
192
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
193
        $logger->debug('{app}: User {user} updated {entities} edited by user id {userid}.', $logArgs);
194
    }
195
    
196
    /**
197
     * Deletes all objects created by a certain user.
198
     *
199
     * @param integer             $userId         The userid of the creator to be removed
200
     * @param TranslatorInterface $translator     Translator service instance
201
     * @param LoggerInterface     $logger         Logger service instance
202
     * @param CurrentUserApiInterface $currentUserApi CurrentUserApi service instance
203
     *
204
     * @return void
205
     *
206
     * @throws InvalidArgumentException Thrown if invalid parameters are received
207
     */
208 View Code Duplication
    public function deleteByCreator($userId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApiInterface $currentUserApi)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
209
    {
210
        // check id parameter
211
        if ($userId == 0 || !is_numeric($userId)) {
212
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
213
        }
214
    
215
        $qb = $this->getEntityManager()->createQueryBuilder();
216
        $qb->delete($this->mainEntityClass, 'tbl')
217
           ->where('tbl.createdBy = :creator')
218
           ->setParameter('creator', $userId);
219
        $query = $qb->getQuery();
220
        $query->execute();
221
    
222
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
223
        $logger->debug('{app}: User {user} deleted {entities} created by user id {userid}.', $logArgs);
224
    }
225
    
226
    /**
227
     * Deletes all objects updated by a certain user.
228
     *
229
     * @param integer             $userId         The userid of the last editor to be removed
230
     * @param TranslatorInterface $translator     Translator service instance
231
     * @param LoggerInterface     $logger         Logger service instance
232
     * @param CurrentUserApiInterface $currentUserApi CurrentUserApi service instance
233
     *
234
     * @return void
235
     *
236
     * @throws InvalidArgumentException Thrown if invalid parameters are received
237
     */
238 View Code Duplication
    public function deleteByLastEditor($userId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApiInterface $currentUserApi)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
239
    {
240
        // check id parameter
241
        if ($userId == 0 || !is_numeric($userId)) {
242
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
243
        }
244
    
245
        $qb = $this->getEntityManager()->createQueryBuilder();
246
        $qb->delete($this->mainEntityClass, 'tbl')
247
           ->where('tbl.updatedBy = :editor')
248
           ->setParameter('editor', $userId);
249
        $query = $qb->getQuery();
250
        $query->execute();
251
    
252
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
253
        $logger->debug('{app}: User {user} deleted {entities} edited by user id {userid}.', $logArgs);
254
    }
255
256
    /**
257
     * Adds an array of id filters to given query instance.
258
     *
259
     * @param array        $idList The array of ids to use to retrieve the object
260
     * @param QueryBuilder $qb     Query builder to be enhanced
261
     *
262
     * @return QueryBuilder Enriched query builder instance
263
     *
264
     * @throws InvalidArgumentException Thrown if invalid parameters are received
265
     */
266
    protected function addIdListFilter($idList, QueryBuilder $qb)
267
    {
268
        $orX = $qb->expr()->orX();
269
    
270
        foreach ($idList as $id) {
271
            // check id parameter
272
            if ($id == 0) {
273
                throw new InvalidArgumentException('Invalid identifier received.');
274
            }
275
    
276
            $orX->add($qb->expr()->eq('tbl.id', $id));
277
        }
278
    
279
        $qb->andWhere($orX);
280
    
281
        return $qb;
282
    }
283
    
284
    /**
285
     * Selects an object from the database.
286
     *
287
     * @param mixed   $id       The id (or array of ids) to use to retrieve the object (optional) (default=0)
288
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
289
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
290
     *
291
     * @return array|routeEntity Retrieved data array or routeEntity instance
292
     */
293
    public function selectById($id = 0, $useJoins = true, $slimMode = false)
294
    {
295
        $results = $this->selectByIdList(is_array($id) ? $id : [$id], $useJoins, $slimMode);
296
    
297
        return count($results) > 0 ? $results[0] : null;
298
    }
299
    
300
    /**
301
     * Selects a list of objects with an array of ids
302
     *
303
     * @param mixed   $idList   The array of ids to use to retrieve the objects (optional) (default=0)
304
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
305
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
306
     *
307
     * @return ArrayCollection Collection containing retrieved routeEntity instances
308
     */
309
    public function selectByIdList($idList = [0], $useJoins = true, $slimMode = false)
310
    {
311
        $qb = $this->genericBaseQuery('', '', $useJoins, $slimMode);
312
        $qb = $this->addIdListFilter($idList, $qb);
313
    
314
        $query = $this->getQueryFromBuilder($qb);
315
    
316
        $results = $query->getResult();
317
    
318
        return count($results) > 0 ? $results : null;
319
    }
320
321
    /**
322
     * Adds where clauses excluding desired identifiers from selection.
323
     *
324
     * @param QueryBuilder $qb           Query builder to be enhanced
325
     * @param array        $excludesions Array of ids to be excluded from selection
0 ignored issues
show
Documentation introduced by
There is no parameter named $excludesions. Did you maybe mean $exclusions?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
326
     *
327
     * @return QueryBuilder Enriched query builder instance
328
     */
329
    protected function addExclusion(QueryBuilder $qb, array $exclusions = [])
330
    {
331
        if (count($exclusions) > 0) {
332
            $qb->andWhere('tbl.id NOT IN (:excludedIdentifiers)')
333
               ->setParameter('excludedIdentifiers', $exclusions);
334
        }
335
    
336
        return $qb;
337
    }
338
339
    /**
340
     * Returns query builder for selecting a list of objects with a given where clause.
341
     *
342
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
343
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
344
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
345
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
346
     *
347
     * @return QueryBuilder Query builder for the given arguments
348
     */
349
    public function getListQueryBuilder($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
350
    {
351
        $qb = $this->genericBaseQuery($where, $orderBy, $useJoins, $slimMode);
352
        if ((!$useJoins || !$slimMode) && null !== $this->collectionFilterHelper) {
353
            $qb = $this->collectionFilterHelper->addCommonViewFilters('route', $qb);
354
        }
355
    
356
        return $qb;
357
    }
358
    
359
    /**
360
     * Selects a list of objects with a given where clause.
361
     *
362
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
363
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
364
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
365
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
366
     *
367
     * @return ArrayCollection Collection containing retrieved routeEntity instances
368
     */
369 View Code Duplication
    public function selectWhere($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
370
    {
371
        $qb = $this->getListQueryBuilder($where, $orderBy, $useJoins, $slimMode);
372
    
373
        $query = $this->getQueryFromBuilder($qb);
374
    
375
        return $this->retrieveCollectionResult($query, false);
376
    }
377
378
    /**
379
     * Returns query builder instance for retrieving a list of objects with a given where clause and pagination parameters.
380
     *
381
     * @param QueryBuilder $qb             Query builder to be enhanced
382
     * @param integer      $currentPage    Where to start selection
383
     * @param integer      $resultsPerPage Amount of items to select
384
     *
385
     * @return Query Created query instance
386
     */
387
    public function getSelectWherePaginatedQuery(QueryBuilder $qb, $currentPage = 1, $resultsPerPage = 25)
388
    {
389
        $query = $this->getQueryFromBuilder($qb);
390
        $offset = ($currentPage-1) * $resultsPerPage;
391
    
392
        $query->setFirstResult($offset)
393
              ->setMaxResults($resultsPerPage);
394
    
395
        return $query;
396
    }
397
    
398
    /**
399
     * Selects a list of objects with a given where clause and pagination parameters.
400
     *
401
     * @param string  $where          The where clause to use when retrieving the collection (optional) (default='')
402
     * @param string  $orderBy        The order-by clause to use when retrieving the collection (optional) (default='')
403
     * @param integer $currentPage    Where to start selection
404
     * @param integer $resultsPerPage Amount of items to select
405
     * @param boolean $useJoins       Whether to include joining related objects (optional) (default=true)
406
     * @param boolean $slimMode       If activated only some basic fields are selected without using any joins (optional) (default=false)
407
     *
408
     * @return array Retrieved collection and amount of total records affected by this query
409
     */
410 View Code Duplication
    public function selectWherePaginated($where = '', $orderBy = '', $currentPage = 1, $resultsPerPage = 25, $useJoins = true, $slimMode = false)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
411
    {
412
        $qb = $this->getListQueryBuilder($where, $orderBy, $useJoins, $slimMode);
413
        $query = $this->getSelectWherePaginatedQuery($qb, $currentPage, $resultsPerPage);
414
    
415
        return $this->retrieveCollectionResult($query, true);
416
    }
417
418
    /**
419
     * Selects entities by a given search fragment.
420
     *
421
     * @param string  $fragment       The fragment to search for
422
     * @param array   $exclude        List with identifiers to be excluded from search
423
     * @param string  $orderBy        The order-by clause to use when retrieving the collection (optional) (default='')
424
     * @param integer $currentPage    Where to start selection
425
     * @param integer $resultsPerPage Amount of items to select
426
     * @param boolean $useJoins       Whether to include joining related objects (optional) (default=true)
427
     *
428
     * @return array Retrieved collection and amount of total records affected by this query
429
     */
430
    public function selectSearch($fragment = '', $exclude = [], $orderBy = '', $currentPage = 1, $resultsPerPage = 25, $useJoins = true)
431
    {
432
        $qb = $this->getListQueryBuilder('', $orderBy, $useJoins);
433
        if (count($exclude) > 0) {
434
            $qb = $this->addExclusion($qb, $exclude);
435
        }
436
    
437
        if (null !== $this->collectionFilterHelper) {
438
            $qb = $this->collectionFilterHelper->addSearchFilter('route', $qb, $fragment);
439
        }
440
    
441
        $query = $this->getSelectWherePaginatedQuery($qb, $currentPage, $resultsPerPage);
442
    
443
        return $this->retrieveCollectionResult($query, true);
444
    }
445
446
    /**
447
     * Performs a given database selection and post-processed the results.
448
     *
449
     * @param Query   $query       The Query instance to be executed
450
     * @param boolean $isPaginated Whether the given query uses a paginator or not (optional) (default=false)
451
     *
452
     * @return array Retrieved collection and (for paginated queries) the amount of total records affected
453
     */
454
    public function retrieveCollectionResult(Query $query, $isPaginated = false)
455
    {
456
        $count = 0;
457
        if (!$isPaginated) {
458
            $result = $query->getResult();
459
        } else {
460
            $paginator = new Paginator($query, false);
461
    
462
            $count = count($paginator);
463
            $result = $paginator;
464
        }
465
    
466
        if (!$isPaginated) {
467
            return $result;
468
        }
469
    
470
        return [$result, $count];
471
    }
472
473
    /**
474
     * Returns query builder instance for a count query.
475
     *
476
     * @param string  $where    The where clause to use when retrieving the object count (optional) (default='')
477
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=false)
478
     *
479
     * @return QueryBuilder Created query builder instance
480
     */
481
    public function getCountQuery($where = '', $useJoins = false)
482
    {
483
        $selection = 'COUNT(tbl.id) AS numRoutes';
484
        if (true === $useJoins) {
485
            $selection .= $this->addJoinsToSelection();
486
        }
487
    
488
        $qb = $this->getEntityManager()->createQueryBuilder();
489
        $qb->select($selection)
490
           ->from($this->mainEntityClass, 'tbl');
491
    
492
        if (!empty($where)) {
493
            $qb->andWhere($where);
494
        }
495
    
496
        if (true === $useJoins) {
497
            $this->addJoinsToFrom($qb);
0 ignored issues
show
Unused Code introduced by
The call to the method Zikula\RoutesModule\Enti...itory::addJoinsToFrom() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
498
        }
499
    
500
        return $qb;
501
    }
502
503
    /**
504
     * Selects entity count with a given where clause.
505
     *
506
     * @param string  $where      The where clause to use when retrieving the object count (optional) (default='')
507
     * @param boolean $useJoins   Whether to include joining related objects (optional) (default=false)
508
     * @param array   $parameters List of determined filter options
509
     *
510
     * @return integer Amount of affected records
511
     */
512
    public function selectCount($where = '', $useJoins = false, $parameters = [])
513
    {
514
        $qb = $this->getCountQuery($where, $useJoins);
515
    
516
        if (null !== $this->collectionFilterHelper) {
517
            $qb = $this->collectionFilterHelper->applyDefaultFilters('route', $qb, $parameters);
518
        }
519
    
520
        $query = $qb->getQuery();
521
    
522
        return $query->getSingleScalarResult();
523
    }
524
525
526
    /**
527
     * Checks for unique values.
528
     *
529
     * @param string  $fieldName  The name of the property to be checked
530
     * @param string  $fieldValue The value of the property to be checked
531
     * @param integer $excludeId  Id of routes to exclude (optional)
532
     *
533
     * @return boolean Result of this check, true if the given route does not already exist
534
     */
535
    public function detectUniqueState($fieldName, $fieldValue, $excludeId = 0)
536
    {
537
        $qb = $this->getCountQuery('', false);
538
        $qb->andWhere('tbl.' . $fieldName . ' = :' . $fieldName)
539
           ->setParameter($fieldName, $fieldValue);
540
    
541
        if ($excludeId > 0) {
542
            $qb = $this->addExclusion($qb, [$excludeId]);
543
        }
544
    
545
        $query = $qb->getQuery();
546
    
547
        $count = $query->getSingleScalarResult();
548
    
549
        return ($count == 0);
550
    }
551
552
    /**
553
     * Builds a generic Doctrine query supporting WHERE and ORDER BY.
554
     *
555
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
556
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
557
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
558
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
559
     *
560
     * @return QueryBuilder Query builder instance to be further processed
561
     */
562
    public function genericBaseQuery($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
563
    {
564
        // normally we select the whole table
565
        $selection = 'tbl';
566
    
567
        if (true === $slimMode) {
568
            // but for the slim version we select only the basic fields, and no joins
569
    
570
            $selection = 'tbl.id';
571
            $selection .= ', tbl.path';
572
            $selection .= ', tbl.sort';
573
            $useJoins = false;
574
        }
575
    
576
        if (true === $useJoins) {
577
            $selection .= $this->addJoinsToSelection();
578
        }
579
    
580
        $qb = $this->getEntityManager()->createQueryBuilder();
581
        $qb->select($selection)
582
           ->from($this->mainEntityClass, 'tbl');
583
    
584
        if (true === $useJoins) {
585
            $this->addJoinsToFrom($qb);
0 ignored issues
show
Unused Code introduced by
The call to the method Zikula\RoutesModule\Enti...itory::addJoinsToFrom() seems un-needed as the method has no side-effects.

PHP Analyzer performs a side-effects analysis of your code. A side-effect is basically anything that might be visible after the scope of the method is left.

Let’s take a look at an example:

class User
{
    private $email;

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }
}

If we look at the getEmail() method, we can see that it has no side-effect. Whether you call this method or not, no future calls to other methods are affected by this. As such code as the following is useless:

$user = new User();
$user->getEmail(); // This line could safely be removed as it has no effect.

On the hand, if we look at the setEmail(), this method _has_ side-effects. In the following case, we could not remove the method call:

$user = new User();
$user->setEmail('email@domain'); // This line has a side-effect (it changes an
                                 // instance variable).
Loading history...
586
        }
587
    
588
        if (!empty($where)) {
589
            $qb->andWhere($where);
590
        }
591
    
592
        $this->genericBaseQueryAddOrderBy($qb, $orderBy);
593
    
594
        return $qb;
595
    }
596
597
    /**
598
     * Adds ORDER BY clause to given query builder.
599
     *
600
     * @param QueryBuilder $qb      Given query builder instance
601
     * @param string       $orderBy The order-by clause to use when retrieving the collection (optional) (default='')
602
     *
603
     * @return QueryBuilder Query builder instance to be further processed
604
     */
605
    protected function genericBaseQueryAddOrderBy(QueryBuilder $qb, $orderBy = '')
606
    {
607
        if ($orderBy == 'RAND()') {
608
            // random selection
609
            $qb->addSelect('MOD(tbl.id, ' . mt_rand(2, 15) . ') AS HIDDEN randomIdentifiers')
610
               ->add('orderBy', 'randomIdentifiers');
611
    
612
            return $qb;
613
        }
614
    
615
        if (empty($orderBy)) {
616
            $orderBy = $this->defaultSortingField;
617
        }
618
    
619
        if (empty($orderBy)) {
620
            return $qb;
621
        }
622
    
623
        // add order by clause
624
        if (false === strpos($orderBy, '.')) {
625
            $orderBy = 'tbl.' . $orderBy;
626
        }
627
        if (false !== strpos($orderBy, 'tbl.createdBy')) {
628
            $qb->addSelect('tblCreator')
629
               ->leftJoin('tbl.createdBy', 'tblCreator');
630
            $orderBy = str_replace('tbl.createdBy', 'tblCreator.uname', $orderBy);
631
        }
632
        if (false !== strpos($orderBy, 'tbl.updatedBy')) {
633
            $qb->addSelect('tblUpdater')
634
               ->leftJoin('tbl.updatedBy', 'tblUpdater');
635
            $orderBy = str_replace('tbl.updatedBy', 'tblUpdater.uname', $orderBy);
636
        }
637
        $qb->add('orderBy', $orderBy);
638
    
639
        return $qb;
640
    }
641
642
    /**
643
     * Retrieves Doctrine query from query builder.
644
     *
645
     * @param QueryBuilder $qb Query builder instance
646
     *
647
     * @return Query Query instance to be further processed
648
     */
649
    public function getQueryFromBuilder(QueryBuilder $qb)
650
    {
651
        $query = $qb->getQuery();
652
    
653
        return $query;
654
    }
655
656
    /**
657
     * Helper method to add join selections.
658
     *
659
     * @return String Enhancement for select clause
660
     */
661
    protected function addJoinsToSelection()
662
    {
663
        $selection = '';
664
    
665
        return $selection;
666
    }
667
    
668
    /**
669
     * Helper method to add joins to from clause.
670
     *
671
     * @param QueryBuilder $qb Query builder instance used to create the query
672
     *
673
     * @return QueryBuilder The query builder enriched by additional joins
674
     */
675
    protected function addJoinsToFrom(QueryBuilder $qb)
676
    {
677
    
678
        return $qb;
679
    }
680
}
681