Completed
Push — master ( 5247c6...b8f763 )
by Craig
10:35 queued 03:41
created

AbstractRouteRepository   F

Complexity

Total Complexity 126

Size/Duplication

Total Lines 997
Duplicated Lines 9.53 %

Coupling/Cohesion

Components 1
Dependencies 15

Importance

Changes 0
Metric Value
dl 95
loc 997
rs 1.0434
c 0
b 0
f 0
wmc 126
lcom 1
cbo 15

38 Methods

Rating   Name   Duplication   Size   Complexity  
B getAllowedSortingFields() 0 25 1
A getDefaultSortingField() 0 4 1
A setDefaultSortingField() 0 4 1
A getRequest() 0 4 1
A setRequest() 0 4 1
A getTitleFieldName() 0 6 1
A getDescriptionFieldName() 0 6 1
A getPreviewFieldName() 0 6 1
A getStartDateFieldName() 0 6 1
B getAdditionalTemplateParameters() 0 24 5
A getViewQuickNavParameters() 0 23 2
A truncateTable() 0 11 1
B updateCreator() 19 19 5
B updateLastEditor() 19 19 5
A deleteByCreator() 18 18 3
A deleteByLastEditor() 18 18 3
B addIdListFilter() 0 25 5
A selectById() 0 6 3
A selectByIdList() 11 11 2
A addExclusion() 0 9 2
A getListQueryBuilder() 0 9 3
A selectWhere() 0 8 1
A getSelectWherePaginatedQuery() 0 12 1
A selectWherePaginated() 10 10 1
D addCommonViewFilters() 0 47 18
A applyDefaultFilters() 0 5 1
A selectSearch() 0 13 2
F addSearchFilter() 0 73 30
A retrieveCollectionResult() 0 18 3
A getCountQuery() 0 21 3
A selectCount() 0 10 1
A detectUniqueState() 0 14 1
B genericBaseQuery() 0 36 4
B genericBaseQueryAddWhere() 0 63 4
B genericBaseQueryAddOrderBy() 0 21 5
A getQueryFromBuilder() 0 6 1
A addJoinsToSelection() 0 6 1
A addJoinsToFrom() 0 5 1

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like AbstractRouteRepository often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use AbstractRouteRepository, and based on these observations, apply Extract Interface, too.

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.1 (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 Symfony\Component\HttpFoundation\Request;
23
use Zikula\Component\FilterUtil\FilterUtil;
24
use Zikula\Component\FilterUtil\Config as FilterConfig;
25
use Zikula\Component\FilterUtil\PluginManager as FilterPluginManager;
26
use Psr\Log\LoggerInterface;
27
use ServiceUtil;
28
use Zikula\Common\Translator\TranslatorInterface;
29
use Zikula\UsersModule\Api\CurrentUserApi;
30
use Zikula\RoutesModule\Entity\RouteEntity;
31
32
/**
33
 * Repository class used to implement own convenience methods for performing certain DQL queries.
34
 *
35
 * This is the base repository class for route entities.
36
 */
37
abstract class AbstractRouteRepository extends SortableRepository
38
{
39
    
40
    /**
41
     * @var string The default sorting field/expression
42
     */
43
    protected $defaultSortingField = 'sort';
44
45
    /**
46
     * @var Request The request object given by the calling controller
47
     */
48
    protected $request;
49
    
50
51
    /**
52
     * Retrieves an array with all fields which can be used for sorting instances.
53
     *
54
     * @return array Sorting fields array
55
     */
56
    public function getAllowedSortingFields()
57
    {
58
        return [
59
            'routeType',
60
            'replacedRouteName',
61
            'bundle',
62
            'controller',
63
            'action',
64
            'path',
65
            'host',
66
            'schemes',
67
            'methods',
68
            'prependBundlePrefix',
69
            'translatable',
70
            'translationPrefix',
71
            'condition',
72
            'description',
73
            'sort',
74
            'group',
75
            'createdBy',
76
            'createdDate',
77
            'updatedBy',
78
            'updatedDate',
79
        ];
80
    }
81
82
    /**
83
     * Returns the default sorting field.
84
     *
85
     * @return string
86
     */
87
    public function getDefaultSortingField()
88
    {
89
        return $this->defaultSortingField;
90
    }
91
    
92
    /**
93
     * Sets the default sorting field.
94
     *
95
     * @param string $defaultSortingField
96
     *
97
     * @return void
98
     */
99
    public function setDefaultSortingField($defaultSortingField)
100
    {
101
        $this->defaultSortingField = $defaultSortingField;
102
    }
103
    
104
    /**
105
     * Returns the request.
106
     *
107
     * @return Request
108
     */
109
    public function getRequest()
110
    {
111
        return $this->request;
112
    }
113
    
114
    /**
115
     * Sets the request.
116
     *
117
     * @param Request $request
118
     *
119
     * @return void
120
     */
121
    public function setRequest($request)
0 ignored issues
show
Bug introduced by
You have injected the Request via parameter $request. This is generally not recommended as there might be multiple instances during a request cycle (f.e. when using sub-requests). Instead, it is recommended to inject the RequestStack and retrieve the current request each time you need it via getCurrentRequest().
Loading history...
122
    {
123
        $this->request = $request;
124
    }
125
    
126
127
    /**
128
     * Returns name of the field used as title / name for entities of this repository.
129
     *
130
     * @return string Name of field to be used as title
131
     */
132
    public function getTitleFieldName()
133
    {
134
        $fieldName = 'replacedRouteName';
135
    
136
        return $fieldName;
137
    }
138
    
139
    /**
140
     * Returns name of the field used for describing entities of this repository.
141
     *
142
     * @return string Name of field to be used as description
143
     */
144
    public function getDescriptionFieldName()
145
    {
146
        $fieldName = 'bundle';
147
    
148
        return $fieldName;
149
    }
150
    
151
    /**
152
     * Returns name of first upload field which is capable for handling images.
153
     *
154
     * @return string Name of field to be used for preview images
155
     */
156
    public function getPreviewFieldName()
157
    {
158
        $fieldName = '';
159
    
160
        return $fieldName;
161
    }
162
    
163
    /**
164
     * Returns name of the date(time) field to be used for representing the start
165
     * of this object. Used for providing meta data to the tag module.
166
     *
167
     * @return string Name of field to be used as date
168
     */
169
    public function getStartDateFieldName()
170
    {
171
        $fieldName = 'createdDate';
172
    
173
        return $fieldName;
174
    }
175
176
    /**
177
     * Returns an array of additional template variables which are specific to the object type treated by this repository.
178
     *
179
     * @param ImageHelper $imageHelper ImageHelper service instance
0 ignored issues
show
Bug introduced by
There is no parameter named $imageHelper. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

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

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

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

Loading history...
180
     * @param string      $context     Usage context (allowed values: controllerAction, api, actionHandler, block, contentType)
181
     * @param array       $args        Additional arguments
182
     *
183
     * @return array List of template variables to be assigned
184
     */
185
    public function getAdditionalTemplateParameters($context = '', $args = [])
186
    {
187
        if (!in_array($context, ['controllerAction', 'api', 'actionHandler', 'block', 'contentType'])) {
188
            $context = 'controllerAction';
189
        }
190
    
191
        $templateParameters = [];
192
    
193
        if ($context == 'controllerAction') {
194
            if (!isset($args['action'])) {
195
                $args['action'] = $this->getRequest()->query->getAlpha('func', 'index');
196
            }
197
            if (in_array($args['action'], ['index', 'view'])) {
198
                $templateParameters = $this->getViewQuickNavParameters($context, $args);
199
            }
200
        }
201
    
202
        // in the concrete child class you could do something like
203
        // $parameters = parent::getAdditionalTemplateParameters($context, $args);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
204
        // $parameters['myvar'] = 'myvalue';
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
205
        // return $parameters;
206
    
207
        return $templateParameters;
208
    }
209
    /**
210
     * Returns an array of additional template variables for view quick navigation forms.
211
     *
212
     * @param string $context Usage context (allowed values: controllerAction, api, actionHandler, block, contentType)
213
     * @param array  $args    Additional arguments
214
     *
215
     * @return array List of template variables to be assigned
216
     */
217
    protected function getViewQuickNavParameters($context = '', $args = [])
0 ignored issues
show
Unused Code introduced by
The parameter $args is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
218
    {
219
        if (!in_array($context, ['controllerAction', 'api', 'actionHandler', 'block', 'contentType'])) {
220
            $context = 'controllerAction';
0 ignored issues
show
Unused Code introduced by
$context is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
221
        }
222
    
223
        $parameters = [];
224
        $parameters['workflowState'] = $this->getRequest()->query->get('workflowState', '');
225
        $parameters['routeType'] = $this->getRequest()->query->get('routeType', '');
226
        $parameters['schemes'] = $this->getRequest()->query->get('schemes', '');
227
        $parameters['methods'] = $this->getRequest()->query->get('methods', '');
228
        $parameters['q'] = $this->getRequest()->query->get('q', '');
229
        
230
        $parameters['prependBundlePrefix'] = $this->getRequest()->query->get('prependBundlePrefix', '');
231
        $parameters['translatable'] = $this->getRequest()->query->get('translatable', '');
232
    
233
        // in the concrete child class you could do something like
234
        // $parameters = parent::getViewQuickNavParameters($context, $args);
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
235
        // $parameters['myvar'] = 'myvalue';
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
236
        // return $parameters;
237
    
238
        return $parameters;
239
    }
240
241
    /**
242
     * Helper method for truncating the table.
243
     * Used during installation when inserting default data.
244
     *
245
     * @param LoggerInterface $logger Logger service instance
246
     *
247
     * @return void
248
     */
249
    public function truncateTable(LoggerInterface $logger)
250
    {
251
        $qb = $this->getEntityManager()->createQueryBuilder();
252
        $qb->delete('Zikula\RoutesModule\Entity\RouteEntity', 'tbl');
253
        $query = $qb->getQuery();
254
    
255
        $query->execute();
256
    
257
        $logArgs = ['app' => 'ZikulaRoutesModule', 'entity' => 'route'];
258
        $logger->debug('{app}: Truncated the {entity} entity table.', $logArgs);
259
    }
260
    /**
261
     * Updates the creator of all objects created by a certain user.
262
     *
263
     * @param integer             $userId         The userid of the creator to be replaced
264
     * @param integer             $newUserId      The new userid of the creator as replacement
265
     * @param TranslatorInterface $translator     Translator service instance
266
     * @param LoggerInterface     $logger         Logger service instance
267
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
268
     *
269
     * @return void
270
     *
271
     * @throws InvalidArgumentException Thrown if invalid parameters are received
272
     */
273 View Code Duplication
    public function updateCreator($userId, $newUserId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApi $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...
274
    {
275
        // check id parameter
276
        if ($userId == 0 || !is_numeric($userId)
277
         || $newUserId == 0 || !is_numeric($newUserId)) {
278
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
279
        }
280
    
281
        $qb = $this->getEntityManager()->createQueryBuilder();
282
        $qb->update('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
283
           ->set('tbl.createdBy', $newUserId)
284
           ->where('tbl.createdBy= :creator')
285
           ->setParameter('creator', $userId);
286
        $query = $qb->getQuery();
287
        $query->execute();
288
    
289
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
290
        $logger->debug('{app}: User {user} updated {entities} created by user id {userid}.', $logArgs);
291
    }
292
    
293
    /**
294
     * Updates the last editor of all objects updated by a certain user.
295
     *
296
     * @param integer             $userId         The userid of the last editor to be replaced
297
     * @param integer             $newUserId      The new userid of the last editor as replacement
298
     * @param TranslatorInterface $translator     Translator service instance
299
     * @param LoggerInterface     $logger         Logger service instance
300
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
301
     *
302
     * @return void
303
     *
304
     * @throws InvalidArgumentException Thrown if invalid parameters are received
305
     */
306 View Code Duplication
    public function updateLastEditor($userId, $newUserId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApi $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...
307
    {
308
        // check id parameter
309
        if ($userId == 0 || !is_numeric($userId)
310
         || $newUserId == 0 || !is_numeric($newUserId)) {
311
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
312
        }
313
    
314
        $qb = $this->getEntityManager()->createQueryBuilder();
315
        $qb->update('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
316
           ->set('tbl.updatedBy', $newUserId)
317
           ->where('tbl.updatedBy = :editor')
318
           ->setParameter('editor', $userId);
319
        $query = $qb->getQuery();
320
        $query->execute();
321
    
322
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
323
        $logger->debug('{app}: User {user} updated {entities} edited by user id {userid}.', $logArgs);
324
    }
325
    
326
    /**
327
     * Deletes all objects created by a certain user.
328
     *
329
     * @param integer             $userId         The userid of the creator to be removed
330
     * @param TranslatorInterface $translator     Translator service instance
331
     * @param LoggerInterface     $logger         Logger service instance
332
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
333
     *
334
     * @return void
335
     *
336
     * @throws InvalidArgumentException Thrown if invalid parameters are received
337
     */
338 View Code Duplication
    public function deleteByCreator($userId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApi $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...
339
    {
340
        // check id parameter
341
        if ($userId == 0 || !is_numeric($userId)) {
342
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
343
        }
344
    
345
        $qb = $this->getEntityManager()->createQueryBuilder();
346
        $qb->delete('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
347
           ->where('tbl.createdBy = :creator')
348
           ->setParameter('creator', $userId);
349
        $query = $qb->getQuery();
350
    
351
        $query->execute();
352
    
353
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
354
        $logger->debug('{app}: User {user} deleted {entities} created by user id {userid}.', $logArgs);
355
    }
356
    
357
    /**
358
     * Deletes all objects updated by a certain user.
359
     *
360
     * @param integer             $userId         The userid of the last editor to be removed
361
     * @param TranslatorInterface $translator     Translator service instance
362
     * @param LoggerInterface     $logger         Logger service instance
363
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
364
     *
365
     * @return void
366
     *
367
     * @throws InvalidArgumentException Thrown if invalid parameters are received
368
     */
369 View Code Duplication
    public function deleteByLastEditor($userId, TranslatorInterface $translator, LoggerInterface $logger, CurrentUserApi $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...
370
    {
371
        // check id parameter
372
        if ($userId == 0 || !is_numeric($userId)) {
373
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
374
        }
375
    
376
        $qb = $this->getEntityManager()->createQueryBuilder();
377
        $qb->delete('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
378
           ->where('tbl.updatedBy = :editor')
379
           ->setParameter('editor', $userId);
380
        $query = $qb->getQuery();
381
    
382
        $query->execute();
383
    
384
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
385
        $logger->debug('{app}: User {user} deleted {entities} edited by user id {userid}.', $logArgs);
386
    }
387
388
    /**
389
     * Adds an array of id filters to given query instance.
390
     *
391
     * @param mixed        $idList The array of ids to use to retrieve the object
392
     * @param QueryBuilder $qb     Query builder to be enhanced
393
     *
394
     * @return QueryBuilder Enriched query builder instance
395
     */
396
    protected function addIdListFilter($idList, QueryBuilder $qb)
397
    {
398
        $orX = $qb->expr()->orX();
399
    
400
        foreach ($idList as $id) {
401
            // check id parameter
402
            if ($id == 0) {
403
                throw new InvalidArgumentException('Invalid identifier received.');
404
            }
405
    
406
            if (is_array($id)) {
407
                $andX = $qb->expr()->andX();
408
                foreach ($id as $fieldName => $fieldValue) {
409
                    $andX->add($qb->expr()->eq('tbl.' . $fieldName, $fieldValue));
410
                }
411
                $orX->add($andX);
412
            } else {
413
                $orX->add($qb->expr()->eq('tbl.id', $id));
414
            }
415
        }
416
    
417
        $qb->andWhere($orX);
418
    
419
        return $qb;
420
    }
421
    
422
    /**
423
     * Selects an object from the database.
424
     *
425
     * @param mixed   $id       The id (or array of ids) to use to retrieve the object (optional) (default=0)
426
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
427
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
428
     *
429
     * @return array|routeEntity retrieved data array or routeEntity instance
430
     *
431
     * @throws InvalidArgumentException Thrown if invalid parameters are received
432
     */
433
    public function selectById($id = 0, $useJoins = true, $slimMode = false)
434
    {
435
        $results = $this->selectByIdList(is_array($id) ? $id : [$id], $useJoins, $slimMode);
436
    
437
        return count($results) > 0 ? $results[0] : null;
438
    }
439
    
440
    /**
441
     * Selects a list of objects with an array of ids
442
     *
443
     * @param mixed   $idList   The array of ids to use to retrieve the objects (optional) (default=0)
444
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
445
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
446
     *
447
     * @return ArrayCollection collection containing retrieved routeEntity instances
448
     *
449
     * @throws InvalidArgumentException Thrown if invalid parameters are received
450
     */
451 View Code Duplication
    public function selectByIdList($idList = [0], $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...
452
    {
453
        $qb = $this->genericBaseQuery('', '', $useJoins, $slimMode);
454
        $qb = $this->addIdListFilter($idList, $qb);
455
    
456
        $query = $this->getQueryFromBuilder($qb);
457
    
458
        $results = $query->getResult();
459
    
460
        return (count($results) > 0) ? $results : null;
461
    }
462
463
    /**
464
     * Adds where clauses excluding desired identifiers from selection.
465
     *
466
     * @param QueryBuilder $qb        Query builder to be enhanced
467
     * @param integer      $excludeId The id to be excluded from selection
468
     *
469
     * @return QueryBuilder Enriched query builder instance
470
     */
471
    protected function addExclusion(QueryBuilder $qb, $excludeId)
472
    {
473
        if ($excludeId > 0) {
474
            $qb->andWhere('tbl.id != :excludeId')
475
               ->setParameter('excludeId', $excludeId);
476
        }
477
    
478
        return $qb;
479
    }
480
481
    /**
482
     * Returns query builder for selecting a list of objects with a given where clause.
483
     *
484
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
485
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
486
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
487
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
488
     *
489
     * @return QueryBuilder query builder for the given arguments
490
     */
491
    public function getListQueryBuilder($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
492
    {
493
        $qb = $this->genericBaseQuery($where, $orderBy, $useJoins, $slimMode);
494
        if (!$useJoins || !$slimMode) {
495
            $qb = $this->addCommonViewFilters($qb);
496
        }
497
    
498
        return $qb;
499
    }
500
    
501
    /**
502
     * Selects a list of objects with a given where clause.
503
     *
504
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
505
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
506
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
507
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
508
     *
509
     * @return ArrayCollection collection containing retrieved routeEntity instances
510
     */
511
    public function selectWhere($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
512
    {
513
        $qb = $this->getListQueryBuilder($where, $orderBy, $useJoins, $slimMode);
514
    
515
        $query = $this->getQueryFromBuilder($qb);
516
    
517
        return $this->retrieveCollectionResult($query, $orderBy, false);
518
    }
519
520
    /**
521
     * Returns query builder instance for retrieving a list of objects with a given where clause and pagination parameters.
522
     *
523
     * @param QueryBuilder $qb             Query builder to be enhanced
524
     * @param integer      $currentPage    Where to start selection
525
     * @param integer      $resultsPerPage Amount of items to select
526
     *
527
     * @return Query Created query instance
528
     */
529
    public function getSelectWherePaginatedQuery(QueryBuilder $qb, $currentPage = 1, $resultsPerPage = 25)
530
    {
531
        $qb = $this->addCommonViewFilters($qb);
532
    
533
        $query = $this->getQueryFromBuilder($qb);
534
        $offset = ($currentPage-1) * $resultsPerPage;
535
    
536
        $query->setFirstResult($offset)
537
              ->setMaxResults($resultsPerPage);
538
    
539
        return $query;
540
    }
541
    
542
    /**
543
     * Selects a list of objects with a given where clause and pagination parameters.
544
     *
545
     * @param string  $where          The where clause to use when retrieving the collection (optional) (default='')
546
     * @param string  $orderBy        The order-by clause to use when retrieving the collection (optional) (default='')
547
     * @param integer $currentPage    Where to start selection
548
     * @param integer $resultsPerPage Amount of items to select
549
     * @param boolean $useJoins       Whether to include joining related objects (optional) (default=true)
550
     * @param boolean $slimMode       If activated only some basic fields are selected without using any joins (optional) (default=false)
551
     *
552
     * @return array with retrieved collection and amount of total records affected by this query
553
     */
554 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...
555
    {
556
        $qb = $this->genericBaseQuery($where, $orderBy, $useJoins, $slimMode);
557
    
558
        $page = $currentPage;
559
        
560
        $query = $this->getSelectWherePaginatedQuery($qb, $page, $resultsPerPage);
561
    
562
        return $this->retrieveCollectionResult($query, $orderBy, true);
563
    }
564
    
565
    /**
566
     * Adds quick navigation related filter options as where clauses.
567
     *
568
     * @param QueryBuilder $qb Query builder to be enhanced
569
     *
570
     * @return QueryBuilder Enriched query builder instance
571
     */
572
    public function addCommonViewFilters(QueryBuilder $qb)
573
    {
574
        if (null === $this->getRequest()) {
575
            // if no request is set we return (#433)
576
            return $qb;
577
        }
578
    
579
        $currentFunc = $this->getRequest()->query->getAlpha('func', 'index');
580
        if ($currentFunc == 'edit') {
581
            return $qb;
582
        }
583
    
584
        $parameters = $this->getViewQuickNavParameters('', []);
585
        foreach ($parameters as $k => $v) {
586
            if (in_array($k, ['q', 'searchterm'])) {
587
                // quick search
588
                if (!empty($v)) {
589
                    $qb = $this->addSearchFilter($qb, $v);
590
                }
591
            } elseif (in_array($k, ['prependBundlePrefix', 'translatable'])) {
592
                // boolean filter
593
                if ($v == 'no') {
594
                    $qb->andWhere('tbl.' . $k . ' = 0');
595
                } elseif ($v == 'yes' || $v == '1') {
596
                    $qb->andWhere('tbl.' . $k . ' = 1');
597
                }
598
            } else if (!is_array($v)) {
599
                // field filter
600
                if ((!is_numeric($v) && $v != '') || (is_numeric($v) && $v > 0)) {
601
                    if ($k == 'workflowState' && substr($v, 0, 1) == '!') {
602
                        $qb->andWhere('tbl.' . $k . ' != :' . $k)
603
                           ->setParameter($k, substr($v, 1, strlen($v)-1));
604
                    } elseif (substr($v, 0, 1) == '%') {
605
                        $qb->andWhere('tbl.' . $k . ' LIKE :' . $k)
606
                           ->setParameter($k, '%' . $v . '%');
607
                    } else {
608
                        $qb->andWhere('tbl.' . $k . ' = :' . $k)
609
                           ->setParameter($k, $v);
610
                   }
611
                }
612
            }
613
        }
614
    
615
        $qb = $this->applyDefaultFilters($qb, $parameters);
616
    
617
        return $qb;
618
    }
619
    
620
    /**
621
     * Adds default filters as where clauses.
622
     *
623
     * @param QueryBuilder $qb         Query builder to be enhanced
624
     * @param array        $parameters List of determined filter options
625
     *
626
     * @return QueryBuilder Enriched query builder instance
627
     */
628
    protected function applyDefaultFilters(QueryBuilder $qb, $parameters = [])
0 ignored issues
show
Unused Code introduced by
The parameter $parameters is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
629
    {
630
    
631
        return $qb;
632
    }
633
634
    /**
635
     * Selects entities by a given search fragment.
636
     *
637
     * @param string  $fragment       The fragment to search for
638
     * @param array   $exclude        List with identifiers to be excluded from search
639
     * @param string  $orderBy        The order-by clause to use when retrieving the collection (optional) (default='')
640
     * @param integer $currentPage    Where to start selection
641
     * @param integer $resultsPerPage Amount of items to select
642
     * @param boolean $useJoins       Whether to include joining related objects (optional) (default=true)
643
     *
644
     * @return array with retrieved collection and amount of total records affected by this query
645
     */
646
    public function selectSearch($fragment = '', $exclude = [], $orderBy = '', $currentPage = 1, $resultsPerPage = 25, $useJoins = true)
647
    {
648
        $qb = $this->genericBaseQuery('', $orderBy, $useJoins);
649
        if (count($exclude) > 0) {
650
        	$qb = $this->addExclusion($qb, $exclude);
0 ignored issues
show
Documentation introduced by
$exclude is of type array, but the function expects a integer.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
651
        }
652
    
653
        $qb = $this->addSearchFilter($qb, $fragment);
654
    
655
        $query = $this->getSelectWherePaginatedQuery($qb, $currentPage, $resultsPerPage);
656
    
657
        return $this->retrieveCollectionResult($query, $orderBy, true);
658
    }
659
    
660
    /**
661
     * Adds where clause for search query.
662
     *
663
     * @param QueryBuilder $qb       Query builder to be enhanced
664
     * @param string       $fragment The fragment to search for
665
     *
666
     * @return QueryBuilder Enriched query builder instance
667
     */
668
    protected function addSearchFilter(QueryBuilder $qb, $fragment = '')
669
    {
670
        if ($fragment == '') {
671
            return $qb;
672
        }
673
    
674
        $fragment = str_replace('\'', '', \DataUtil::formatForStore($fragment));
675
        $fragmentIsNumeric = is_numeric($fragment);
676
    
677
        $where = '';
678
        if (!$fragmentIsNumeric) {
679
            $where .= ((!empty($where)) ? ' OR ' : '');
680
            $where .= 'tbl.routeType = \'' . $fragment . '\'';
681
            $where .= ((!empty($where)) ? ' OR ' : '');
682
            $where .= 'tbl.replacedRouteName LIKE \'%' . $fragment . '%\'';
683
            $where .= ((!empty($where)) ? ' OR ' : '');
684
            $where .= 'tbl.bundle LIKE \'%' . $fragment . '%\'';
685
            $where .= ((!empty($where)) ? ' OR ' : '');
686
            $where .= 'tbl.controller LIKE \'%' . $fragment . '%\'';
687
            $where .= ((!empty($where)) ? ' OR ' : '');
688
            $where .= 'tbl.action LIKE \'%' . $fragment . '%\'';
689
            $where .= ((!empty($where)) ? ' OR ' : '');
690
            $where .= 'tbl.path LIKE \'%' . $fragment . '%\'';
691
            $where .= ((!empty($where)) ? ' OR ' : '');
692
            $where .= 'tbl.host LIKE \'%' . $fragment . '%\'';
693
            $where .= ((!empty($where)) ? ' OR ' : '');
694
            $where .= 'tbl.schemes = \'' . $fragment . '\'';
695
            $where .= ((!empty($where)) ? ' OR ' : '');
696
            $where .= 'tbl.methods = \'' . $fragment . '\'';
697
            $where .= ((!empty($where)) ? ' OR ' : '');
698
            $where .= 'tbl.translationPrefix LIKE \'%' . $fragment . '%\'';
699
            $where .= ((!empty($where)) ? ' OR ' : '');
700
            $where .= 'tbl.condition LIKE \'%' . $fragment . '%\'';
701
            $where .= ((!empty($where)) ? ' OR ' : '');
702
            $where .= 'tbl.description LIKE \'%' . $fragment . '%\'';
703
            $where .= ((!empty($where)) ? ' OR ' : '');
704
            $where .= 'tbl.group LIKE \'%' . $fragment . '%\'';
705
        } else {
706
            $where .= ((!empty($where)) ? ' OR ' : '');
707
            $where .= 'tbl.routeType = \'' . $fragment . '\'';
708
            $where .= ((!empty($where)) ? ' OR ' : '');
709
            $where .= 'tbl.replacedRouteName LIKE \'%' . $fragment . '%\'';
710
            $where .= ((!empty($where)) ? ' OR ' : '');
711
            $where .= 'tbl.bundle LIKE \'%' . $fragment . '%\'';
712
            $where .= ((!empty($where)) ? ' OR ' : '');
713
            $where .= 'tbl.controller LIKE \'%' . $fragment . '%\'';
714
            $where .= ((!empty($where)) ? ' OR ' : '');
715
            $where .= 'tbl.action LIKE \'%' . $fragment . '%\'';
716
            $where .= ((!empty($where)) ? ' OR ' : '');
717
            $where .= 'tbl.path LIKE \'%' . $fragment . '%\'';
718
            $where .= ((!empty($where)) ? ' OR ' : '');
719
            $where .= 'tbl.host LIKE \'%' . $fragment . '%\'';
720
            $where .= ((!empty($where)) ? ' OR ' : '');
721
            $where .= 'tbl.schemes = \'' . $fragment . '\'';
722
            $where .= ((!empty($where)) ? ' OR ' : '');
723
            $where .= 'tbl.methods = \'' . $fragment . '\'';
724
            $where .= ((!empty($where)) ? ' OR ' : '');
725
            $where .= 'tbl.translationPrefix LIKE \'%' . $fragment . '%\'';
726
            $where .= ((!empty($where)) ? ' OR ' : '');
727
            $where .= 'tbl.condition LIKE \'%' . $fragment . '%\'';
728
            $where .= ((!empty($where)) ? ' OR ' : '');
729
            $where .= 'tbl.description LIKE \'%' . $fragment . '%\'';
730
            $where .= ((!empty($where)) ? ' OR ' : '');
731
            $where .= 'tbl.sort = \'' . $fragment . '\'';
732
            $where .= ((!empty($where)) ? ' OR ' : '');
733
            $where .= 'tbl.group LIKE \'%' . $fragment . '%\'';
734
        }
735
        $where = '(' . $where . ')';
736
    
737
        $qb->andWhere($where);
738
    
739
        return $qb;
740
    }
741
742
    /**
743
     * Performs a given database selection and post-processed the results.
744
     *
745
     * @param Query   $query       The Query instance to be executed
746
     * @param string  $orderBy     The order-by clause to use when retrieving the collection (optional) (default='')
747
     * @param boolean $isPaginated Whether the given query uses a paginator or not (optional) (default=false)
748
     *
749
     * @return array with retrieved collection and (for paginated queries) the amount of total records affected
750
     */
751
    public function retrieveCollectionResult(Query $query, $orderBy = '', $isPaginated = false)
0 ignored issues
show
Unused Code introduced by
The parameter $orderBy is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
752
    {
753
        $count = 0;
754
        if (!$isPaginated) {
755
            $result = $query->getResult();
756
        } else {
757
            $paginator = new Paginator($query, false);
758
    
759
            $count = count($paginator);
760
            $result = $paginator;
761
        }
762
    
763
        if (!$isPaginated) {
764
            return $result;
765
        }
766
    
767
        return [$result, $count];
768
    }
769
770
    /**
771
     * Returns query builder instance for a count query.
772
     *
773
     * @param string  $where    The where clause to use when retrieving the object count (optional) (default='')
774
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
775
     *
776
     * @return QueryBuilder Created query builder instance
777
     * @TODO fix usage of joins; please remove the first line and test
778
     */
779
    protected function getCountQuery($where = '', $useJoins = true)
0 ignored issues
show
Unused Code introduced by
The parameter $useJoins is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
780
    {
781
        $useJoins = false;
782
    
783
        $selection = 'COUNT(tbl.id) AS numRoutes';
784
        if (true === $useJoins) {
785
            $selection .= $this->addJoinsToSelection();
786
        }
787
    
788
        $qb = $this->getEntityManager()->createQueryBuilder();
789
        $qb->select($selection)
790
           ->from('Zikula\RoutesModule\Entity\RouteEntity', 'tbl');
791
    
792
        if (true === $useJoins) {
793
            $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...
794
        }
795
    
796
        $this->genericBaseQueryAddWhere($qb, $where);
797
    
798
        return $qb;
799
    }
800
    
801
    /**
802
     * Selects entity count with a given where clause.
803
     *
804
     * @param string  $where      The where clause to use when retrieving the object count (optional) (default='')
805
     * @param boolean $useJoins   Whether to include joining related objects (optional) (default=true)
806
     * @param array   $parameters List of determined filter options
807
     *
808
     * @return integer amount of affected records
809
     */
810
    public function selectCount($where = '', $useJoins = true, $parameters = [])
811
    {
812
        $qb = $this->getCountQuery($where, $useJoins);
813
    
814
        $qb = $this->applyDefaultFilters($qb, $parameters);
815
    
816
        $query = $qb->getQuery();
817
    
818
        return $query->getSingleScalarResult();
819
    }
820
821
822
    /**
823
     * Checks for unique values.
824
     *
825
     * @param string $fieldName  The name of the property to be checked
826
     * @param string $fieldValue The value of the property to be checked
827
     * @param int    $excludeId  Id of routes to exclude (optional)
828
     *
829
     * @return boolean result of this check, true if the given route does not already exist
830
     */
831
    public function detectUniqueState($fieldName, $fieldValue, $excludeId = 0)
832
    {
833
        $qb = $this->getCountQuery('', false);
834
        $qb->andWhere('tbl.' . $fieldName . ' = :' . $fieldName)
835
           ->setParameter($fieldName, $fieldValue);
836
    
837
        $qb = $this->addExclusion($qb, $excludeId);
838
    
839
        $query = $qb->getQuery();
840
    
841
        $count = $query->getSingleScalarResult();
842
    
843
        return ($count == 0);
844
    }
845
846
    /**
847
     * Builds a generic Doctrine query supporting WHERE and ORDER BY.
848
     *
849
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
850
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
851
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
852
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
853
     *
854
     * @return QueryBuilder query builder instance to be further processed
855
     */
856
    public function genericBaseQuery($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
857
    {
858
        // normally we select the whole table
859
        $selection = 'tbl';
860
    
861
        if (true === $slimMode) {
862
            // but for the slim version we select only the basic fields, and no joins
863
    
864
            $selection = 'tbl.id';
865
            
866
            
867
            $selection .= ', tbl.path';
868
            
869
            
870
            $selection .= ', tbl.sort';
871
            
872
            $useJoins = false;
873
        }
874
    
875
        if (true === $useJoins) {
876
            $selection .= $this->addJoinsToSelection();
877
        }
878
    
879
        $qb = $this->getEntityManager()->createQueryBuilder();
880
        $qb->select($selection)
881
           ->from('Zikula\RoutesModule\Entity\RouteEntity', 'tbl');
882
    
883
        if (true === $useJoins) {
884
            $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...
885
        }
886
    
887
        $this->genericBaseQueryAddWhere($qb, $where);
888
        $this->genericBaseQueryAddOrderBy($qb, $orderBy);
889
    
890
        return $qb;
891
    }
892
893
    /**
894
     * Adds WHERE clause to given query builder.
895
     *
896
     * @param QueryBuilder $qb    Given query builder instance
897
     * @param string       $where The where clause to use when retrieving the collection (optional) (default='')
898
     *
899
     * @return QueryBuilder query builder instance to be further processed
900
     */
901
    protected function genericBaseQueryAddWhere(QueryBuilder $qb, $where = '')
902
    {
903
        if (!empty($where)) {
904
            // Use FilterUtil to support generic filtering.
905
            //$qb->where($where);
0 ignored issues
show
Unused Code Comprehensibility introduced by
86% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
906
    
907
            // Create filter configuration.
908
            $filterConfig = new FilterConfig($qb);
909
    
910
            // Define plugins to be used during filtering.
911
            $filterPluginManager = new FilterPluginManager(
912
                $filterConfig,
913
    
914
                // Array of plugins to load.
915
                // If no plugin with default = true given the compare plugin is loaded and used for unconfigured fields.
916
                // Multiple objects of the same plugin with different configurations are possible.
917
                [
918
                ],
919
    
920
                // Allowed operators per field.
921
                // Array in the form "field name => operator array".
922
                // If a field is not set in this array all operators are allowed.
923
                []
924
            );
925
    
926
            // Request object to obtain the filter string (only needed if the filter is set via GET or it reads values from GET).
927
            // We do this not per default (for now) to prevent problems with explicite filters set by blocks or content types.
928
            // TODO readd automatic request processing (basically replacing applyDefaultFilters() and addCommonViewFilters()).
929
            $request = null;
930
    
931
            // Name of filter variable(s) (filterX).
932
            $filterKey = 'filter';
933
    
934
            // initialise FilterUtil and assign both query builder and configuration
935
            $filterUtil = new FilterUtil($filterPluginManager, $request, $filterKey);
936
    
937
            // set our given filter
938
            $filterUtil->setFilter($where);
939
    
940
            // you could add explicit filters at this point, something like
941
            // $filterUtil->addFilter('foo:eq:something,bar:gt:100');
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
942
            // read more at https://github.com/zikula/core/tree/1.4/src/docs/Core-2.0/FilterUtil
943
    
944
            // now enrich the query builder
945
            $filterUtil->enrichQuery();
946
        }
947
    
948
        if (null === $this->getRequest()) {
949
            // if no request is set we return (#783)
950
            return $qb;
951
        }
952
    
953
        
954
        $showOnlyOwnEntries = $this->getRequest()->query->getInt('own', 0);
955
        if ($showOnlyOwnEntries == 1) {
956
            
957
            $userId = $this->getRequest()->getSession()->get('uid');
958
            $qb->andWhere('tbl.createdBy = :creator')
959
               ->setParameter('creator', $userId);
960
        }
961
    
962
        return $qb;
963
    }
964
965
    /**
966
     * Adds ORDER BY clause to given query builder.
967
     *
968
     * @param QueryBuilder $qb      Given query builder instance
969
     * @param string       $orderBy The order-by clause to use when retrieving the collection (optional) (default='')
970
     *
971
     * @return QueryBuilder query builder instance to be further processed
972
     */
973
    protected function genericBaseQueryAddOrderBy(QueryBuilder $qb, $orderBy = '')
974
    {
975
        if ($orderBy == 'RAND()') {
976
            // random selection
977
            $qb->addSelect('MOD(tbl.id, ' . mt_rand(2, 15) . ') AS HIDDEN randomIdentifiers')
978
               ->add('orderBy', 'randomIdentifiers');
0 ignored issues
show
Documentation introduced by
'randomIdentifiers' is of type string, but the function expects a object<Doctrine\ORM\Query\Expr\Base>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
979
            $orderBy = '';
980
        } elseif (empty($orderBy)) {
981
            $orderBy = $this->defaultSortingField;
982
        }
983
    
984
        // add order by clause
985
        if (!empty($orderBy)) {
986
            if (false === strpos($orderBy, '.')) {
987
                $orderBy = 'tbl.' . $orderBy;
988
            }
989
            $qb->add('orderBy', $orderBy);
0 ignored issues
show
Documentation introduced by
$orderBy is of type string, but the function expects a object<Doctrine\ORM\Query\Expr\Base>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
990
        }
991
    
992
        return $qb;
993
    }
994
995
    /**
996
     * Retrieves Doctrine query from query builder, applying FilterUtil and other common actions.
997
     *
998
     * @param QueryBuilder $qb Query builder instance
999
     *
1000
     * @return Query query instance to be further processed
1001
     */
1002
    public function getQueryFromBuilder(QueryBuilder $qb)
1003
    {
1004
        $query = $qb->getQuery();
1005
    
1006
        return $query;
1007
    }
1008
1009
    /**
1010
     * Helper method to add join selections.
1011
     *
1012
     * @return String Enhancement for select clause
1013
     */
1014
    protected function addJoinsToSelection()
1015
    {
1016
        $selection = '';
1017
    
1018
        return $selection;
1019
    }
1020
    
1021
    /**
1022
     * Helper method to add joins to from clause.
1023
     *
1024
     * @param QueryBuilder $qb Query builder instance used to create the query
1025
     *
1026
     * @return QueryBuilder The query builder enriched by additional joins
1027
     */
1028
    protected function addJoinsToFrom(QueryBuilder $qb)
1029
    {
1030
    
1031
        return $qb;
1032
    }
1033
}
1034