Completed
Push — master ( a7cf71...06c6ea )
by Craig
06:43
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 3
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.0 (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
use Doctrine\ORM\Query;
18
use Doctrine\ORM\QueryBuilder;
19
use Doctrine\ORM\Tools\Pagination\Paginator;
20
use InvalidArgumentException;
21
use Symfony\Component\HttpFoundation\Request;
22
use Zikula\Component\FilterUtil\FilterUtil;
23
use Zikula\Component\FilterUtil\Config as FilterConfig;
24
use Zikula\Component\FilterUtil\PluginManager as FilterPluginManager;
25
use ModUtil;
26
use Psr\Log\LoggerInterface;
27
use ServiceUtil;
28
use System;
29
use Zikula\Common\Translator\TranslatorInterface;
30
use Zikula\UsersModule\Api\CurrentUserApi;
31
use Zikula\RoutesModule\Entity\RouteEntity;
32
33
/**
34
 * Repository class used to implement own convenience methods for performing certain DQL queries.
35
 *
36
 * This is the base repository class for route entities.
37
 */
38
abstract class AbstractRouteRepository extends SortableRepository
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
     * 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
            'createdUserId',
75
            'updatedUserId',
76
            'createdDate',
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
        $this->defaultSortingField = $defaultSortingField;
101
    }
102
    
103
    /**
104
     * Returns the request.
105
     *
106
     * @return Request
107
     */
108
    public function getRequest()
109
    {
110
        return $this->request;
111
    }
112
    
113
    /**
114
     * Sets the request.
115
     *
116
     * @param Request $request
117
     *
118
     * @return void
119
     */
120
    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...
121
    {
122
        $this->request = $request;
123
    }
124
    
125
126
    /**
127
     * Returns name of the field used as title / name for entities of this repository.
128
     *
129
     * @return string Name of field to be used as title
130
     */
131
    public function getTitleFieldName()
132
    {
133
        $fieldName = 'replacedRouteName';
134
    
135
        return $fieldName;
136
    }
137
    
138
    /**
139
     * Returns name of the field used for describing entities of this repository.
140
     *
141
     * @return string Name of field to be used as description
142
     */
143
    public function getDescriptionFieldName()
144
    {
145
        $fieldName = 'bundle';
146
    
147
        return $fieldName;
148
    }
149
    
150
    /**
151
     * Returns name of first upload field which is capable for handling images.
152
     *
153
     * @return string Name of field to be used for preview images
154
     */
155
    public function getPreviewFieldName()
156
    {
157
        $fieldName = '';
158
    
159
        return $fieldName;
160
    }
161
    
162
    /**
163
     * Returns name of the date(time) field to be used for representing the start
164
     * of this object. Used for providing meta data to the tag module.
165
     *
166
     * @return string Name of field to be used as date
167
     */
168
    public function getStartDateFieldName()
169
    {
170
        $fieldName = 'createdDate';
171
    
172
        return $fieldName;
173
    }
174
175
    /**
176
     * Returns an array of additional template variables which are specific to the object type treated by this repository.
177
     *
178
     * @param string $context Usage context (allowed values: controllerAction, api, actionHandler, block, contentType)
179
     * @param array  $args    Additional arguments
180
     *
181
     * @return array List of template variables to be assigned
182
     */
183
    public function getAdditionalTemplateParameters($context = '', $args = [])
184
    {
185
        if (!in_array($context, ['controllerAction', 'api', 'actionHandler', 'block', 'contentType'])) {
186
            $context = 'controllerAction';
187
        }
188
    
189
        $templateParameters = [];
190
    
191
        if ($context == 'controllerAction') {
192
            if (!isset($args['action'])) {
193
                $args['action'] = $this->getRequest()->query->getAlpha('func', 'index');
194
            }
195
            if (in_array($args['action'], ['index', 'view'])) {
196
                $templateParameters = $this->getViewQuickNavParameters($context, $args);
197
            }
198
        }
199
    
200
        // in the concrete child class you could do something like
201
        // $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...
202
        // $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...
203
        // return $parameters;
204
    
205
        return $templateParameters;
206
    }
207
    /**
208
     * Returns an array of additional template variables for view quick navigation forms.
209
     *
210
     * @param string $context Usage context (allowed values: controllerAction, api, actionHandler, block, contentType)
211
     * @param array  $args    Additional arguments
212
     *
213
     * @return array List of template variables to be assigned
214
     */
215
    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...
216
    {
217
        if (!in_array($context, ['controllerAction', 'api', 'actionHandler', 'block', 'contentType'])) {
218
            $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...
219
        }
220
    
221
        $parameters = [];
222
        $parameters['workflowState'] = $this->getRequest()->query->get('workflowState', '');
223
        $parameters['routeType'] = $this->getRequest()->query->get('routeType', '');
224
        $parameters['schemes'] = $this->getRequest()->query->get('schemes', '');
225
        $parameters['methods'] = $this->getRequest()->query->get('methods', '');
226
        $parameters['q'] = $this->getRequest()->query->get('q', '');
227
        
228
        $parameters['prependBundlePrefix'] = $this->getRequest()->query->get('prependBundlePrefix', '');
229
        $parameters['translatable'] = $this->getRequest()->query->get('translatable', '');
230
    
231
        // in the concrete child class you could do something like
232
        // $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...
233
        // $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...
234
        // return $parameters;
235
    
236
        return $parameters;
237
    }
238
239
    /**
240
     * Helper method for truncating the table.
241
     * Used during installation when inserting default data.
242
     *
243
     * @param LoggerInterface $logger Logger service instance
244
     *
245
     * @return void
246
     */
247
    public function truncateTable(LoggerInterface $logger)
248
    {
249
        $qb = $this->getEntityManager()->createQueryBuilder();
250
        $qb->delete('Zikula\RoutesModule\Entity\RouteEntity', 'tbl');
251
        $query = $qb->getQuery();
252
    
253
        $query->execute();
254
    
255
        $logArgs = ['app' => 'ZikulaRoutesModule', 'entity' => 'route'];
256
        $logger->debug('{app}: Truncated the {entity} entity table.', $logArgs);
257
    }
258
    /**
259
     * Updates the creator of all objects created by a certain user.
260
     *
261
     * @param integer             $userId         The userid of the creator to be replaced
262
     * @param integer             $newUserId      The new userid of the creator as replacement
263
     * @param TranslatorInterface $translator     Translator service instance
264
     * @param LoggerInterface     $logger         Logger service instance
265
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
266
     *
267
     * @return void
268
     *
269
     * @throws InvalidArgumentException Thrown if invalid parameters are received
270
     */
271 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...
272
    {
273
        // check id parameter
274
        if ($userId == 0 || !is_numeric($userId)
275
         || $newUserId == 0 || !is_numeric($newUserId)) {
276
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
277
        }
278
    
279
        $qb = $this->getEntityManager()->createQueryBuilder();
280
        $qb->update('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
281
           ->set('tbl.createdUserId', $newUserId)
282
           ->where('tbl.createdUserId = :creator')
283
           ->setParameter('creator', $userId);
284
        $query = $qb->getQuery();
285
        $query->execute();
286
    
287
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
288
        $logger->debug('{app}: User {user} updated {entities} created by user id {userid}.', $logArgs);
289
    }
290
    
291
    /**
292
     * Updates the last editor of all objects updated by a certain user.
293
     *
294
     * @param integer             $userId         The userid of the last editor to be replaced
295
     * @param integer             $newUserId      The new userid of the last editor as replacement
296
     * @param TranslatorInterface $translator     Translator service instance
297
     * @param LoggerInterface     $logger         Logger service instance
298
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
299
     *
300
     * @return void
301
     *
302
     * @throws InvalidArgumentException Thrown if invalid parameters are received
303
     */
304 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...
305
    {
306
        // check id parameter
307
        if ($userId == 0 || !is_numeric($userId)
308
         || $newUserId == 0 || !is_numeric($newUserId)) {
309
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
310
        }
311
    
312
        $qb = $this->getEntityManager()->createQueryBuilder();
313
        $qb->update('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
314
           ->set('tbl.updatedUserId', $newUserId)
315
           ->where('tbl.updatedUserId = :editor')
316
           ->setParameter('editor', $userId);
317
        $query = $qb->getQuery();
318
        $query->execute();
319
    
320
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
321
        $logger->debug('{app}: User {user} updated {entities} edited by user id {userid}.', $logArgs);
322
    }
323
    
324
    /**
325
     * Deletes all objects created by a certain user.
326
     *
327
     * @param integer             $userId         The userid of the creator to be removed
328
     * @param TranslatorInterface $translator     Translator service instance
329
     * @param LoggerInterface     $logger         Logger service instance
330
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
331
     *
332
     * @return void
333
     *
334
     * @throws InvalidArgumentException Thrown if invalid parameters are received
335
     */
336 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...
337
    {
338
        // check id parameter
339
        if ($userId == 0 || !is_numeric($userId)) {
340
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
341
        }
342
    
343
        $qb = $this->getEntityManager()->createQueryBuilder();
344
        $qb->delete('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
345
           ->where('tbl.createdUserId = :creator')
346
           ->setParameter('creator', $userId);
347
        $query = $qb->getQuery();
348
    
349
        $query->execute();
350
    
351
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
352
        $logger->debug('{app}: User {user} deleted {entities} created by user id {userid}.', $logArgs);
353
    }
354
    
355
    /**
356
     * Deletes all objects updated by a certain user.
357
     *
358
     * @param integer             $userId         The userid of the last editor to be removed
359
     * @param TranslatorInterface $translator     Translator service instance
360
     * @param LoggerInterface     $logger         Logger service instance
361
     * @param CurrentUserApi      $currentUserApi CurrentUserApi service instance
362
     *
363
     * @return void
364
     *
365
     * @throws InvalidArgumentException Thrown if invalid parameters are received
366
     */
367 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...
368
    {
369
        // check id parameter
370
        if ($userId == 0 || !is_numeric($userId)) {
371
            throw new InvalidArgumentException($translator->__('Invalid user identifier received.'));
372
        }
373
    
374
        $qb = $this->getEntityManager()->createQueryBuilder();
375
        $qb->delete('Zikula\RoutesModule\Entity\RouteEntity', 'tbl')
376
           ->where('tbl.updatedUserId = :editor')
377
           ->setParameter('editor', $userId);
378
        $query = $qb->getQuery();
379
    
380
        $query->execute();
381
    
382
        $logArgs = ['app' => 'ZikulaRoutesModule', 'user' => $currentUserApi->get('uname'), 'entities' => 'routes', 'userid' => $userId];
383
        $logger->debug('{app}: User {user} deleted {entities} edited by user id {userid}.', $logArgs);
384
    }
385
386
    /**
387
     * Adds an array of id filters to given query instance.
388
     *
389
     * @param mixed        $idList The array of ids to use to retrieve the object
390
     * @param QueryBuilder $qb     Query builder to be enhanced
391
     *
392
     * @return QueryBuilder Enriched query builder instance
393
     */
394
    protected function addIdListFilter($idList, QueryBuilder $qb)
395
    {
396
        $orX = $qb->expr()->orX();
397
    
398
        foreach ($idList as $id) {
399
            // check id parameter
400
            if ($id == 0) {
401
                throw new InvalidArgumentException('Invalid identifier received.');
402
            }
403
    
404
            if (is_array($id)) {
405
                $andX = $qb->expr()->andX();
406
                foreach ($id as $fieldName => $fieldValue) {
407
                    $andX->add($qb->expr()->eq('tbl.' . $fieldName, $fieldValue));
408
                }
409
                $orX->add($andX);
410
            } else {
411
                $orX->add($qb->expr()->eq('tbl.id', $id));
412
            }
413
        }
414
    
415
        $qb->andWhere($orX);
416
    
417
        return $qb;
418
    }
419
    
420
    /**
421
     * Selects an object from the database.
422
     *
423
     * @param mixed   $id       The id (or array of ids) to use to retrieve the object (optional) (default=0)
424
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
425
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
426
     *
427
     * @return array|routeEntity retrieved data array or routeEntity instance
428
     *
429
     * @throws InvalidArgumentException Thrown if invalid parameters are received
430
     */
431
    public function selectById($id = 0, $useJoins = true, $slimMode = false)
432
    {
433
        $results = $this->selectByIdList([$id], $useJoins, $slimMode);
434
    
435
        return (count($results) > 0) ? $results[0] : null;
436
    }
437
    
438
    /**
439
     * Selects a list of objects with an array of ids
440
     *
441
     * @param mixed   $idList   The array of ids to use to retrieve the objects (optional) (default=0)
442
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
443
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
444
     *
445
     * @return ArrayCollection collection containing retrieved routeEntity instances
446
     *
447
     * @throws InvalidArgumentException Thrown if invalid parameters are received
448
     */
449
    public function selectByIdList($idList = [0], $useJoins = true, $slimMode = false)
450
    {
451
        $qb = $this->genericBaseQuery('', '', $useJoins, $slimMode);
452
        $qb = $this->addIdListFilter($idList, $qb);
453
    
454
        $query = $this->getQueryFromBuilder($qb);
455
    
456
        $results = $query->getResult();
457
    
458
        return (count($results) > 0) ? $results : null;
459
    }
460
461
    /**
462
     * Adds where clauses excluding desired identifiers from selection.
463
     *
464
     * @param QueryBuilder $qb        Query builder to be enhanced
465
     * @param integer      $excludeId The id (or array of ids) to be excluded from selection
466
     *
467
     * @return QueryBuilder Enriched query builder instance
468
     */
469
    protected function addExclusion(QueryBuilder $qb, $excludeId)
470
    {
471
        if ($excludeId > 0) {
472
            $qb->andWhere('tbl.id != :excludeId')
473
               ->setParameter('excludeId', $excludeId);
474
        }
475
    
476
        return $qb;
477
    }
478
479
    /**
480
     * Returns query builder for selecting a list of objects with a given where clause.
481
     *
482
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
483
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
484
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
485
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
486
     *
487
     * @return QueryBuilder query builder for the given arguments
488
     */
489
    public function getListQueryBuilder($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
490
    {
491
        $qb = $this->genericBaseQuery($where, $orderBy, $useJoins, $slimMode);
492
        if (!$useJoins || !$slimMode) {
493
            $qb = $this->addCommonViewFilters($qb);
494
        }
495
    
496
        return $qb;
497
    }
498
    
499
    /**
500
     * Selects a list of objects with a given where clause.
501
     *
502
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
503
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
504
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
505
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
506
     *
507
     * @return ArrayCollection collection containing retrieved routeEntity instances
508
     */
509
    public function selectWhere($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
510
    {
511
        $qb = $this->getListQueryBuilder($where, $orderBy, $useJoins, $slimMode);
512
    
513
        $query = $this->getQueryFromBuilder($qb);
514
    
515
        return $this->retrieveCollectionResult($query, $orderBy, false);
516
    }
517
518
    /**
519
     * Returns query builder instance for retrieving a list of objects with a given where clause and pagination parameters.
520
     *
521
     * @param QueryBuilder $qb             Query builder to be enhanced
522
     * @param integer      $currentPage    Where to start selection
523
     * @param integer      $resultsPerPage Amount of items to select
524
     *
525
     * @return array Created query instance and amount of affected items
526
     */
527
    public function getSelectWherePaginatedQuery(QueryBuilder $qb, $currentPage = 1, $resultsPerPage = 25)
528
    {
529
        $qb = $this->addCommonViewFilters($qb);
530
    
531
        $query = $this->getQueryFromBuilder($qb);
532
        $offset = ($currentPage-1) * $resultsPerPage;
533
    
534
        $query->setFirstResult($offset)
535
              ->setMaxResults($resultsPerPage);
536
        $count = 0; // will be set at a later stage (in calling method)
537
        
538
    
539
        return [$query, $count];
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
    public function selectWherePaginated($where = '', $orderBy = '', $currentPage = 1, $resultsPerPage = 25, $useJoins = true, $slimMode = false)
555
    {
556
        $qb = $this->genericBaseQuery($where, $orderBy, $useJoins, $slimMode);
557
    
558
        $page = $currentPage;
559
    
560
        // check if we have any filters set
561
        $parameters = $this->getViewQuickNavParameters('', []);
562
        $hasFilters = false;
0 ignored issues
show
Unused Code introduced by
$hasFilters 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...
563
        foreach ($parameters as $k => $v) {
564
            if ((!is_numeric($v) && $v != '') || (is_numeric($v) && $v > 0)) {
565
                $hasFilters = true;
0 ignored issues
show
Unused Code introduced by
$hasFilters 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...
566
                break;
567
            }
568
        }
569
    
570
        
571
        list($query, $count) = $this->getSelectWherePaginatedQuery($qb, $page, $resultsPerPage);
0 ignored issues
show
Unused Code introduced by
The assignment to $count is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
572
    
573
        return $this->retrieveCollectionResult($query, $orderBy, true);
574
    }
575
    
576
    /**
577
     * Adds quick navigation related filter options as where clauses.
578
     *
579
     * @param QueryBuilder $qb Query builder to be enhanced
580
     *
581
     * @return QueryBuilder Enriched query builder instance
582
     */
583
    public function addCommonViewFilters(QueryBuilder $qb)
584
    {
585
        if (null === $this->getRequest()) {
586
            // if no request is set we return (#433)
587
            return $qb;
588
        }
589
    
590
        $currentFunc = $this->getRequest()->query->getAlpha('func', 'index');
591
        if ($currentFunc == 'edit') {
592
            return $qb;
593
        }
594
    
595
        $parameters = $this->getViewQuickNavParameters('', []);
596
        foreach ($parameters as $k => $v) {
597
            if (in_array($k, ['q', 'searchterm'])) {
598
                // quick search
599
                if (!empty($v)) {
600
                    $qb = $this->addSearchFilter($qb, $v);
601
                }
602
            } elseif (in_array($k, ['prependBundlePrefix', 'translatable'])) {
603
                // boolean filter
604
                if ($v == 'no') {
605
                    $qb->andWhere('tbl.' . $k . ' = 0');
606
                } elseif ($v == 'yes' || $v == '1') {
607
                    $qb->andWhere('tbl.' . $k . ' = 1');
608
                }
609
            } else if (!is_array($v)) {
610
                // field filter
611
                if ((!is_numeric($v) && $v != '') || (is_numeric($v) && $v > 0)) {
612
                    if ($k == 'workflowState' && substr($v, 0, 1) == '!') {
613
                        $qb->andWhere('tbl.' . $k . ' != :' . $k)
614
                           ->setParameter($k, substr($v, 1, strlen($v)-1));
615
                    } elseif (substr($v, 0, 1) == '%') {
616
                        $qb->andWhere('tbl.' . $k . ' LIKE :' . $k)
617
                           ->setParameter($k, '%' . $v . '%');
618
                    } else {
619
                        $qb->andWhere('tbl.' . $k . ' = :' . $k)
620
                           ->setParameter($k, $v);
621
                   }
622
                }
623
            }
624
        }
625
    
626
        $qb = $this->applyDefaultFilters($qb, $parameters);
627
    
628
        return $qb;
629
    }
630
    
631
    /**
632
     * Adds default filters as where clauses.
633
     *
634
     * @param QueryBuilder $qb         Query builder to be enhanced
635
     * @param array        $parameters List of determined filter options
636
     *
637
     * @return QueryBuilder Enriched query builder instance
638
     */
639
    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...
640
    {
641
    
642
        return $qb;
643
    }
644
645
    /**
646
     * Selects entities by a given search fragment.
647
     *
648
     * @param string  $fragment       The fragment to search for
649
     * @param array   $exclude        Comma separated list with ids to be excluded from search
650
     * @param string  $orderBy        The order-by clause to use when retrieving the collection (optional) (default='')
651
     * @param integer $currentPage    Where to start selection
652
     * @param integer $resultsPerPage Amount of items to select
653
     * @param boolean $useJoins       Whether to include joining related objects (optional) (default=true)
654
     *
655
     * @return array with retrieved collection and amount of total records affected by this query
656
     */
657
    public function selectSearch($fragment = '', $exclude = [], $orderBy = '', $currentPage = 1, $resultsPerPage = 25, $useJoins = true)
658
    {
659
        $qb = $this->genericBaseQuery('', $orderBy, $useJoins);
660
        if (count($exclude) > 0) {
661
            $qb->andWhere('tbl.id NOT IN (:excludeList)')
662
               ->setParameter('excludeList', $exclude);
663
        }
664
    
665
        $qb = $this->addSearchFilter($qb, $fragment);
666
    
667
        list($query, $count) = $this->getSelectWherePaginatedQuery($qb, $currentPage, $resultsPerPage);
0 ignored issues
show
Unused Code introduced by
The assignment to $count is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
668
    
669
        return $this->retrieveCollectionResult($query, $orderBy, true);
670
    }
671
    
672
    /**
673
     * Adds where clause for search query.
674
     *
675
     * @param QueryBuilder $qb       Query builder to be enhanced
676
     * @param string       $fragment The fragment to search for
677
     *
678
     * @return QueryBuilder Enriched query builder instance
679
     */
680
    protected function addSearchFilter(QueryBuilder $qb, $fragment = '')
681
    {
682
        if ($fragment == '') {
683
            return $qb;
684
        }
685
    
686
        $fragment = str_replace('\'', '', \DataUtil::formatForStore($fragment));
687
        $fragmentIsNumeric = is_numeric($fragment);
688
    
689
        $where = '';
690
        if (!$fragmentIsNumeric) {
691
            $where .= ((!empty($where)) ? ' OR ' : '');
692
            $where .= 'tbl.routeType = \'' . $fragment . '\'';
693
            $where .= ((!empty($where)) ? ' OR ' : '');
694
            $where .= 'tbl.replacedRouteName LIKE \'%' . $fragment . '%\'';
695
            $where .= ((!empty($where)) ? ' OR ' : '');
696
            $where .= 'tbl.bundle LIKE \'%' . $fragment . '%\'';
697
            $where .= ((!empty($where)) ? ' OR ' : '');
698
            $where .= 'tbl.controller LIKE \'%' . $fragment . '%\'';
699
            $where .= ((!empty($where)) ? ' OR ' : '');
700
            $where .= 'tbl.action LIKE \'%' . $fragment . '%\'';
701
            $where .= ((!empty($where)) ? ' OR ' : '');
702
            $where .= 'tbl.path LIKE \'%' . $fragment . '%\'';
703
            $where .= ((!empty($where)) ? ' OR ' : '');
704
            $where .= 'tbl.host LIKE \'%' . $fragment . '%\'';
705
            $where .= ((!empty($where)) ? ' OR ' : '');
706
            $where .= 'tbl.schemes = \'' . $fragment . '\'';
707
            $where .= ((!empty($where)) ? ' OR ' : '');
708
            $where .= 'tbl.methods = \'' . $fragment . '\'';
709
            $where .= ((!empty($where)) ? ' OR ' : '');
710
            $where .= 'tbl.translationPrefix LIKE \'%' . $fragment . '%\'';
711
            $where .= ((!empty($where)) ? ' OR ' : '');
712
            $where .= 'tbl.condition LIKE \'%' . $fragment . '%\'';
713
            $where .= ((!empty($where)) ? ' OR ' : '');
714
            $where .= 'tbl.description LIKE \'%' . $fragment . '%\'';
715
            $where .= ((!empty($where)) ? ' OR ' : '');
716
            $where .= 'tbl.group LIKE \'%' . $fragment . '%\'';
717
        } else {
718
            $where .= ((!empty($where)) ? ' OR ' : '');
719
            $where .= 'tbl.routeType = \'' . $fragment . '\'';
720
            $where .= ((!empty($where)) ? ' OR ' : '');
721
            $where .= 'tbl.replacedRouteName LIKE \'%' . $fragment . '%\'';
722
            $where .= ((!empty($where)) ? ' OR ' : '');
723
            $where .= 'tbl.bundle LIKE \'%' . $fragment . '%\'';
724
            $where .= ((!empty($where)) ? ' OR ' : '');
725
            $where .= 'tbl.controller LIKE \'%' . $fragment . '%\'';
726
            $where .= ((!empty($where)) ? ' OR ' : '');
727
            $where .= 'tbl.action LIKE \'%' . $fragment . '%\'';
728
            $where .= ((!empty($where)) ? ' OR ' : '');
729
            $where .= 'tbl.path LIKE \'%' . $fragment . '%\'';
730
            $where .= ((!empty($where)) ? ' OR ' : '');
731
            $where .= 'tbl.host LIKE \'%' . $fragment . '%\'';
732
            $where .= ((!empty($where)) ? ' OR ' : '');
733
            $where .= 'tbl.schemes = \'' . $fragment . '\'';
734
            $where .= ((!empty($where)) ? ' OR ' : '');
735
            $where .= 'tbl.methods = \'' . $fragment . '\'';
736
            $where .= ((!empty($where)) ? ' OR ' : '');
737
            $where .= 'tbl.translationPrefix LIKE \'%' . $fragment . '%\'';
738
            $where .= ((!empty($where)) ? ' OR ' : '');
739
            $where .= 'tbl.condition LIKE \'%' . $fragment . '%\'';
740
            $where .= ((!empty($where)) ? ' OR ' : '');
741
            $where .= 'tbl.description LIKE \'%' . $fragment . '%\'';
742
            $where .= ((!empty($where)) ? ' OR ' : '');
743
            $where .= 'tbl.sort = \'' . $fragment . '\'';
744
            $where .= ((!empty($where)) ? ' OR ' : '');
745
            $where .= 'tbl.group LIKE \'%' . $fragment . '%\'';
746
        }
747
        $where = '(' . $where . ')';
748
    
749
        $qb->andWhere($where);
750
    
751
        return $qb;
752
    }
753
754
    /**
755
     * Performs a given database selection and post-processed the results.
756
     *
757
     * @param Query   $query       The Query instance to be executed
758
     * @param string  $orderBy     The order-by clause to use when retrieving the collection (optional) (default='')
759
     * @param boolean $isPaginated Whether the given query uses a paginator or not (optional) (default=false)
760
     *
761
     * @return array with retrieved collection and (for paginated queries) the amount of total records affected
762
     */
763
    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...
764
    {
765
        $count = 0;
766
        if (!$isPaginated) {
767
            $result = $query->getResult();
768
        } else {
769
            $paginator = new Paginator($query, false);
770
    
771
            $count = count($paginator);
772
            $result = $paginator;
773
        }
774
    
775
        if (!$isPaginated) {
776
            return $result;
777
        }
778
    
779
        return [$result, $count];
780
    }
781
782
    /**
783
     * Returns query builder instance for a count query.
784
     *
785
     * @param string  $where    The where clause to use when retrieving the object count (optional) (default='')
786
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
787
     *
788
     * @return QueryBuilder Created query builder instance
789
     * @TODO fix usage of joins; please remove the first line and test
790
     */
791
    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...
792
    {
793
        $useJoins = false;
794
    
795
        $selection = 'COUNT(tbl.id) AS numRoutes';
796
        if (true === $useJoins) {
797
            $selection .= $this->addJoinsToSelection();
798
        }
799
    
800
        $qb = $this->getEntityManager()->createQueryBuilder();
801
        $qb->select($selection)
802
           ->from('Zikula\RoutesModule\Entity\RouteEntity', 'tbl');
803
    
804
        if (true === $useJoins) {
805
            $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...
806
        }
807
    
808
        $this->genericBaseQueryAddWhere($qb, $where);
809
    
810
        return $qb;
811
    }
812
    
813
    /**
814
     * Selects entity count with a given where clause.
815
     *
816
     * @param string  $where      The where clause to use when retrieving the object count (optional) (default='')
817
     * @param boolean $useJoins   Whether to include joining related objects (optional) (default=true)
818
     * @param array   $parameters List of determined filter options
819
     *
820
     * @return integer amount of affected records
821
     */
822
    public function selectCount($where = '', $useJoins = true, $parameters = [])
823
    {
824
        $qb = $this->getCountQuery($where, $useJoins);
825
    
826
        $qb = $this->applyDefaultFilters($qb, $parameters);
827
    
828
        $query = $qb->getQuery();
829
    
830
        return $query->getSingleScalarResult();
831
    }
832
833
834
    /**
835
     * Checks for unique values.
836
     *
837
     * @param string $fieldName  The name of the property to be checked
838
     * @param string $fieldValue The value of the property to be checked
839
     * @param int    $excludeId  Id of routes to exclude (optional)
840
     *
841
     * @return boolean result of this check, true if the given route does not already exist
842
     */
843
    public function detectUniqueState($fieldName, $fieldValue, $excludeId = 0)
844
    {
845
        $qb = $this->getCountQuery('', false);
846
        $qb->andWhere('tbl.' . $fieldName . ' = :' . $fieldName)
847
           ->setParameter($fieldName, $fieldValue);
848
    
849
        $qb = $this->addExclusion($qb, $excludeId);
850
    
851
        $query = $qb->getQuery();
852
    
853
        $count = $query->getSingleScalarResult();
854
    
855
        return ($count == 0);
856
    }
857
858
    /**
859
     * Builds a generic Doctrine query supporting WHERE and ORDER BY.
860
     *
861
     * @param string  $where    The where clause to use when retrieving the collection (optional) (default='')
862
     * @param string  $orderBy  The order-by clause to use when retrieving the collection (optional) (default='')
863
     * @param boolean $useJoins Whether to include joining related objects (optional) (default=true)
864
     * @param boolean $slimMode If activated only some basic fields are selected without using any joins (optional) (default=false)
865
     *
866
     * @return QueryBuilder query builder instance to be further processed
867
     */
868
    public function genericBaseQuery($where = '', $orderBy = '', $useJoins = true, $slimMode = false)
869
    {
870
        // normally we select the whole table
871
        $selection = 'tbl';
872
    
873
        if (true === $slimMode) {
874
            // but for the slim version we select only the basic fields, and no joins
875
    
876
            $selection = 'tbl.id';
877
            
878
            
879
            $selection .= ', tbl.path';
880
            
881
            
882
            $selection .= ', tbl.sort';
883
            
884
            $useJoins = false;
885
        }
886
    
887
        if (true === $useJoins) {
888
            $selection .= $this->addJoinsToSelection();
889
        }
890
    
891
        $qb = $this->getEntityManager()->createQueryBuilder();
892
        $qb->select($selection)
893
           ->from('Zikula\RoutesModule\Entity\RouteEntity', 'tbl');
894
    
895
        if (true === $useJoins) {
896
            $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...
897
        }
898
    
899
        $this->genericBaseQueryAddWhere($qb, $where);
900
        $this->genericBaseQueryAddOrderBy($qb, $orderBy);
901
    
902
        return $qb;
903
    }
904
905
    /**
906
     * Adds WHERE clause to given query builder.
907
     *
908
     * @param QueryBuilder $qb    Given query builder instance
909
     * @param string       $where The where clause to use when retrieving the collection (optional) (default='')
910
     *
911
     * @return QueryBuilder query builder instance to be further processed
912
     */
913
    protected function genericBaseQueryAddWhere(QueryBuilder $qb, $where = '')
914
    {
915
        if (!empty($where)) {
916
        // Use FilterUtil to support generic filtering.
917
        //$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...
918
    
919
        // Create filter configuration.
920
        $filterConfig = new FilterConfig($qb);
921
    
922
        // Define plugins to be used during filtering.
923
        $filterPluginManager = new FilterPluginManager(
924
            $filterConfig,
925
    
926
            // Array of plugins to load.
927
            // If no plugin with default = true given the compare plugin is loaded and used for unconfigured fields.
928
            // Multiple objects of the same plugin with different configurations are possible.
929
            [
930
            ],
931
    
932
            // Allowed operators per field.
933
            // Array in the form "field name => operator array".
934
            // If a field is not set in this array all operators are allowed.
935
            []
936
        );
937
    
938
        // Request object to obtain the filter string (only needed if the filter is set via GET or it reads values from GET).
939
        // We do this not per default (for now) to prevent problems with explicite filters set by blocks or content types.
940
        // TODO readd automatic request processing (basically replacing applyDefaultFilters() and addCommonViewFilters()).
941
        $request = null;
942
    
943
        // Name of filter variable(s) (filterX).
944
        $filterKey = 'filter';
945
    
946
        // initialise FilterUtil and assign both query builder and configuration
947
        $filterUtil = new FilterUtil($filterPluginManager, $request, $filterKey);
948
    
949
        // set our given filter
950
        $filterUtil->setFilter($where);
951
    
952
        // you could add explicit filters at this point, something like
953
        // $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...
954
        // read more at
955
        // https://github.com/zikula/core/blob/master/src/lib/Zikula/Component/FilterUtil/README.md
956
        // https://github.com/zikula/core/blob/master/src/lib/Zikula/Component/FilterUtil/Resources/docs/users.md
957
    
958
        // now enrich the query builder
959
        $filterUtil->enrichQuery();
960
        }
961
    
962
        if (null === $this->getRequest()) {
963
            // if no request is set we return (#783)
964
            return $qb;
965
        }
966
    
967
        
968
        $showOnlyOwnEntries = $this->getRequest()->query->getDigits('own', 0);
969
        if ($showOnlyOwnEntries == 1) {
970
            
971
            $uid = $this->getRequest()->getSession()->get('uid');
972
            $qb->andWhere('tbl.createdUserId = :creator')
973
               ->setParameter('creator', $uid);
974
        }
975
    
976
        return $qb;
977
    }
978
979
    /**
980
     * Adds ORDER BY clause to given query builder.
981
     *
982
     * @param QueryBuilder $qb      Given query builder instance
983
     * @param string       $orderBy The order-by clause to use when retrieving the collection (optional) (default='')
984
     *
985
     * @return QueryBuilder query builder instance to be further processed
986
     */
987
    protected function genericBaseQueryAddOrderBy(QueryBuilder $qb, $orderBy = '')
988
    {
989
        if ($orderBy == 'RAND()') {
990
            // random selection
991
            $qb->addSelect('MOD(tbl.id, ' . mt_rand(2, 15) . ') AS HIDDEN randomIdentifiers')
992
               ->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...
993
            $orderBy = '';
994
        } elseif (empty($orderBy)) {
995
            $orderBy = $this->defaultSortingField;
996
        }
997
    
998
        // add order by clause
999
        if (!empty($orderBy)) {
1000
            if (false === strpos($orderBy, '.')) {
1001
                $orderBy = 'tbl.' . $orderBy;
1002
            }
1003
            $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...
1004
        }
1005
    
1006
        return $qb;
1007
    }
1008
1009
    /**
1010
     * Retrieves Doctrine query from query builder, applying FilterUtil and other common actions.
1011
     *
1012
     * @param QueryBuilder $qb Query builder instance
1013
     *
1014
     * @return Query query instance to be further processed
1015
     */
1016
    public function getQueryFromBuilder(QueryBuilder $qb)
1017
    {
1018
        $query = $qb->getQuery();
1019
    
1020
        return $query;
1021
    }
1022
1023
    /**
1024
     * Helper method to add join selections.
1025
     *
1026
     * @return String Enhancement for select clause
1027
     */
1028
    protected function addJoinsToSelection()
1029
    {
1030
        $selection = '';
1031
    
1032
        return $selection;
1033
    }
1034
    
1035
    /**
1036
     * Helper method to add joins to from clause.
1037
     *
1038
     * @param QueryBuilder $qb query builder instance used to create the query
1039
     *
1040
     * @return String Enhancement for from clause
1041
     */
1042
    protected function addJoinsToFrom(QueryBuilder $qb)
1043
    {
1044
    
1045
        return $qb;
1046
    }
1047
}
1048