GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Passed
Pull Request — master (#52)
by Simone
03:32
created

BaseRepository::setRouteName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Mado\QueryBundle\Repositories;
4
5
use Doctrine\ORM\EntityRepository;
6
use Hateoas\Configuration\Route;
0 ignored issues
show
Bug introduced by
The type Hateoas\Configuration\Route was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
use Hateoas\Representation\Factory\PagerfantaFactory;
0 ignored issues
show
Bug introduced by
The type Hateoas\Representation\Factory\PagerfantaFactory was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
use Pagerfanta\Adapter\DoctrineORMAdapter;
0 ignored issues
show
Bug introduced by
The type Pagerfanta\Adapter\DoctrineORMAdapter was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
use Pagerfanta\Pagerfanta;
0 ignored issues
show
Bug introduced by
The type Pagerfanta\Pagerfanta was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
10
use Symfony\Component\HttpFoundation\Request;
11
use Mado\QueryBundle\Queries\QueryBuilderOptions;
12
use Mado\QueryBundle\Queries\QueryBuilderFactory;
13
14
class BaseRepository extends EntityRepository
15
{
16
    protected $fields;
17
18
    protected $request;
19
20
    protected $use_result_cache = false;
21
22
    protected $entityAlias;
23
24
    protected $route_name;
25
26
    protected $currentEntityAlias;
27
28
    protected $embeddedFields;
29
30
    protected $joins = [];
31
32
    protected $queryBuilderFactory;
33
34
    protected $queryOptions;
35
36 9
    public function __construct($manager, $class)
37
    {
38 9
        parent::__construct($manager, $class);
39
40 9
        $this->fields = array_keys($this->getClassMetadata()->fieldMappings);
41
42 9
        $entityName = explode('\\', strtolower($this->getEntityName()) );
43 9
        $entityName = $entityName[count($entityName)-1];
44 9
        $entityAlias = $entityName[0];
45 9
        $this->entityAlias = $entityAlias;
46
47 9
        $this->queryBuilderFactory = new QueryBuilderFactory($this->getEntityManager());
48 9
    }
49
50 4
    public function initFromQueryBuilderOptions(QueryBuilderOptions $options)
51
    {
52 4
        $this->queryBuilderFactory->createQueryBuilder($this->getEntityName(), $this->entityAlias);
53
54 4
        $fieldMappings = $this->getClassMetadata()->fieldMappings;
55 4
        $this->fields = array_keys($fieldMappings);
56
57 4
        $this->queryBuilderFactory->setFields($this->fields ?? []);
58 4
        $this->queryBuilderFactory->setFilters($options->getFilters());
59 4
        $this->queryBuilderFactory->setOrFilters($options->getOrFilters());
60 4
        $this->queryBuilderFactory->setSorting($options->getSorting());
61 4
        $this->queryBuilderFactory->setRel($options->getRel());
62 4
        $this->queryBuilderFactory->setPrinting($options->getPrinting());
63 4
        $this->queryBuilderFactory->setSelect($options->getSelect());
64
65 4
        return $this;
66
    }
67
68 4
    public function getQueryBuilderFactory()
69
    {
70 4
        $this->initFromQueryBuilderOptions($this->queryOptions);
71
72 4
        return $this->queryBuilderFactory;
73
    }
74
75
    public function useResultCache($bool)
76
    {
77
        $this->use_result_cache = $bool;
78
    }
79
80 1
    public function setRequest(Request $request)
81
    {
82 1
        return $this->setQueryOptionsFromRequest($request);
83
    }
84
85
    public function setRequestWithFilter(Request $request, $filter)
86
    {
87
        return $this->setQueryOptionsFromRequestWithCustomFilter($request, $filter);
88
    }
89
90
    public function setRequestWithOrFilter(Request $request, $orFilter)
91
    {
92
        return $this->setQueryOptionsFromRequestWithCustomOrFilter($request, $orFilter);
93
    }
94
95 4
    public function setQueryOptions(QueryBuilderOptions $options)
96
    {
97 4
        $this->queryOptions = $options;
98
99 4
        return $this;
100
    }
101
102 3
    public function setQueryOptionsFromRequest(Request $request = null)
103
    {
104 3
        $requestAttributes = self::getRequestAttributes($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type null; however, parameter $request of Mado\QueryBundle\Reposit...:getRequestAttributes() does only seem to accept Symfony\Component\HttpFoundation\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

104
        $requestAttributes = self::getRequestAttributes(/** @scrutinizer ignore-type */ $request);
Loading history...
105
106 3
        $filters     = $request->query->get('filtering', []);
107 3
        $orFilters   = $request->query->get('filtering_or', []);
108 3
        $sorting     = $request->query->get('sorting', []);
109 3
        $printing    = $request->query->get('printing', []);
110 3
        $rel         = $request->query->get('rel', '');
111 3
        $page        = $request->query->get('page', '');
112 3
        $select      = $request->query->get('select', $this->entityAlias);
113 3
        $filtering   = $request->query->get('filtering', '');
114 3
        $limit       = $request->query->get('limit', '');
115
116 3
        $filterOrCorrected = [];
117
118 3
        $count = 0;
119 3
        foreach ($orFilters as $key => $filter) {
120
            if (is_array($filter)) {
121
                foreach ($filter as $keyInternal => $internal) {
122
                    $filterOrCorrected[$keyInternal .'|' . $count] = $internal;
123
                    $count = $count + 1;
124
                }
125
            } else {
126
                $filterOrCorrected[$key] = $filter;
127
            }
128
        }
129
130
        $requestProperties = [
131 3
            'filtering'   => $filtering,
132 3
            'orFiltering' => $filterOrCorrected,
133 3
            'limit'       => $limit,
134 3
            'page'        => $page,
135 3
            'filters'     => $filters,
136 3
            'orFilters'   => $filterOrCorrected,
137 3
            'sorting'     => $sorting,
138 3
            'rel'         => $rel,
139 3
            'printing'    => $printing,
140 3
            'select'      => $select,
141
        ];
142
143 3
        $options = array_merge(
144 3
            $requestAttributes,
145 3
            $requestProperties
146
        );
147
148 3
        $this->queryOptions = QueryBuilderOptions::fromArray($options);
149
150 3
        return $this;
151
    }
152
153 4
    public static function getRequestAttributes(Request $request)
154
    {
155 4
        $requestAttributes = [];
156
157 4
        foreach ($request->attributes->all() as $attributeName => $attributeValue) {
158
            $requestAttributes[$attributeName] = $request->attributes->get(
159
                $attributeName,
160
                $attributeValue
161
            );
162
        }
163
164 4
        return $requestAttributes;
165
    }
166
167 View Code Duplication
    public function setQueryOptionsFromRequestWithCustomFilter(Request $request = null, $filter)
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...
168
    {
169
        $requestAttributes = self::getRequestAttributes($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type null; however, parameter $request of Mado\QueryBundle\Reposit...:getRequestAttributes() does only seem to accept Symfony\Component\HttpFoundation\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

169
        $requestAttributes = self::getRequestAttributes(/** @scrutinizer ignore-type */ $request);
Loading history...
170
171
        $filters = $request->query->get('filtering', []);
172
        $orFilters = $request->query->get('filtering_or', []);
173
        $sorting = $request->query->get('sorting', []);
174
        $printing = $request->query->get('printing', []);
175
        $rel = $request->query->get('rel', '');
176
        $page = $request->query->get('page', '');
177
        $select = $request->query->get('select', $this->entityAlias);
178
        $filtering = $request->query->get('filtering', '');
179
        $limit = $request->query->get('limit', '');
180
181
        $filters = array_merge($filters, $filter);
182
183
        $filterOrCorrected = [];
184
185
        $count = 0;
186
        foreach ($orFilters as $key => $filter) {
187
            if (is_array($filter)) {
188
                foreach ($filter as $keyInternal => $internal) {
189
                    $filterOrCorrected[$keyInternal .'|' . $count] = $internal;
190
                    $count = $count + 1;
191
                }
192
            } else {
193
                $filterOrCorrected[$key] = $filter;
194
            }
195
        }
196
197
        $requestProperties = [
198
            '_route' => $request->attributes->get('_route'),
199
            'customer_id' => $request->attributes->get('customer_id'),
200
            'id' => $request->attributes->get('id'),
201
            'filtering' => $filtering,
202
            'limit' => $limit,
203
            'page' => $page,
204
            'filters' => $filters,
205
            'orFilters' => $filterOrCorrected,
206
            'sorting' => $sorting,
207
            'rel' => $rel,
208
            'printing' => $printing,
209
            'select' => $select,
210
        ];
211
212
        $options = array_merge(
213
            $requestAttributes,
214
            $requestProperties
215
        );
216
217
        $this->queryOptions = QueryBuilderOptions::fromArray($options);
218
219
        return $this;
220
    }
221
222 1 View Code Duplication
    public function setQueryOptionsFromRequestWithCustomOrFilter(Request $request = null, $orFilter)
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...
223
    {
224 1
        $requestAttributes = self::getRequestAttributes($request);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type null; however, parameter $request of Mado\QueryBundle\Reposit...:getRequestAttributes() does only seem to accept Symfony\Component\HttpFoundation\Request, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

224
        $requestAttributes = self::getRequestAttributes(/** @scrutinizer ignore-type */ $request);
Loading history...
225
226 1
        $filters = $request->query->get('filtering', []);
227 1
        $orFilters = $request->query->get('filtering_or', []);
228 1
        $sorting = $request->query->get('sorting', []);
229 1
        $printing = $request->query->get('printing', []);
230 1
        $rel = $request->query->get('rel', '');
231 1
        $page = $request->query->get('page', '');
232 1
        $select = $request->query->get('select', $this->entityAlias);
233 1
        $filtering = $request->query->get('filtering', '');
234 1
        $limit = $request->query->get('limit', '');
235
236 1
        $orFilters = array_merge($orFilters, $orFilter);
237
238 1
        $filterOrCorrected = [];
239
240 1
        $count = 0;
241 1
        foreach ($orFilters as $key => $filter) {
242
            if (is_array($filter)) {
243
                foreach ($filter as $keyInternal => $internal) {
244
                    $filterOrCorrected[$keyInternal .'|' . $count] = $internal;
245
                    $count = $count + 1;
246
                }
247
            } else {
248
                $filterOrCorrected[$key] = $filter;
249
            }
250
        }
251
252
        $requestProperties = [
253 1
            '_route' => $request->attributes->get('_route'),
254 1
            'customer_id' => $request->attributes->get('customer_id'),
255 1
            'id' => $request->attributes->get('id'),
256 1
            'filtering' => $filtering,
257 1
            'limit' => $limit,
258 1
            'page' => $page,
259 1
            'filters' => $filters,
260 1
            'orFilters' => $filterOrCorrected,
261 1
            'sorting' => $sorting,
262 1
            'rel' => $rel,
263 1
            'printing' => $printing,
264 1
            'select' => $select,
265
        ];
266
267 1
        $options = array_merge(
268 1
            $requestAttributes,
269 1
            $requestProperties
270
        );
271
272 1
        $this->queryOptions = QueryBuilderOptions::fromArray($options);
273
274 1
        return $this;
275
    }
276
277 4
    public function getQueryBuilderOptions()
278
    {
279 4
        return $this->queryOptions;
280
    }
281
282
    public function getRequest()
283
    {
284
        return $this->request;
285
    }
286
287
    public function setRouteName($route_name = '')
288
    {
289
        $this->route_name = $route_name;
290
        return $this;
291
    }
292
293
    public function findAllPaginated()
294
    {
295
        $this->initFromQueryBuilderOptions($this->queryOptions);
296
297
        $this->queryBuilderFactory->filter();
298
        $this->queryBuilderFactory->sort();
299
300
        return $this->paginateResults($this->queryBuilderFactory->getQueryBuilder());
301
    }
302
303
    protected function paginateResults(
304
        \Doctrine\ORM\QueryBuilder $queryBuilder
305
    ) {
306
        $limit = $this->queryOptions->get('limit', 10);
307
        $page = $this->queryOptions->get('page', 1);
308
309
310
        $pagerAdapter = new DoctrineORMAdapter($queryBuilder);
311
312
        $query = $pagerAdapter->getQuery();
313
        if(isset($this->use_result_cache) and $this->use_result_cache){
314
            $query->useResultCache(true, 600);
315
        }
316
317
        $pager = new Pagerfanta($pagerAdapter);
318
        $pager->setNormalizeOutOfRangePages(true);
319
        $pager->setMaxPerPage($limit);
320
        $pager->setCurrentPage($page);
321
322
        $pagerFactory = new PagerfantaFactory();
323
324
        $router = $this->createRouter();
325
326
        $results = $pagerFactory->createRepresentation($pager, $router);
327
328
        return $results;
329
    }
330
331
    protected function customQueryStringValues()
332
    {
333
        return [];
334
    }
335
336
    protected function createRouter()
337
    {
338
        $params = [];
339
340
        $list = array_merge([
341
            'filtering',
342
            'limit',
343
            'page',
344
            'sorting',
345
        ], $this->customQueryStringValues());
346
347
        foreach ($list as $itemKey => $itemValue) {
348
            $params[$itemValue] = $this->queryOptions->get($itemValue);
349
        }
350
351
        if(!isset($this->route_name)){
352
            $this->route_name = $this->queryOptions->get('_route');
353
        }
354
355
        return new Route($this->route_name, $params);
356
    }
357
358
    /** @deprecate use QueryBuilderFactory instead */
359
    public function noExistsJoin($prevEntityAlias, $currentEntityAlias)
360
    {
361
        $needle = $prevEntityAlias . "_" . $currentEntityAlias;
362
        return ! in_array($needle, $this->joins);
363
    }
364
365
    /** @deprecate use QueryBuilderFactory instead */
366
    public function storeJoin($prevEntityAlias, $currentEntityAlias)
367
    {
368
        $needle = $prevEntityAlias . "_" . $currentEntityAlias;
369
        $this->joins[$needle] = $needle;
370
    }
371
372
    /** @deprecate use QueryBuilderFactory instead */
373
    public function join($queryBuilder, $key, $val) 
0 ignored issues
show
Unused Code introduced by
The parameter $val is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

373
    public function join($queryBuilder, $key, /** @scrutinizer ignore-unused */ $val) 

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

Loading history...
374
    {
375
        if (strstr($key, '_embedded.')) {
376
            $embeddedFields = explode('.', $key);
377
            $numFields = count($embeddedFields);
378
379
            $prevEntityAlias = $this->entityAlias;
380
            $prevEntityName = $this->getEntityName();
381
382
            for ($i = 1; $i < $numFields - 1; $i++) {
383
                $metadata = $this->getEntityManager()->getClassMetadata($prevEntityName);
384
385
                $currentRelation = $embeddedFields[$i];
386
387
                if ($metadata->hasAssociation($currentRelation)) {
388
389
                    $association = $metadata->getAssociationMapping($currentRelation);
390
391
                    $currentEntityAlias = $this->getEntityAlias($association['targetEntity']);
392
393
                    if ($this->noExistsJoin($prevEntityAlias, $currentRelation)) {
394
                        if ($association['isOwningSide']) {
395
                            $queryBuilder->join($association['targetEntity'], "$currentEntityAlias", "WITH", "$currentEntityAlias.id = " . "$prevEntityAlias.$currentRelation");
396
                        } else {
397
                            $mappedBy = $association['mappedBy'];
398
                            $queryBuilder->join($association['targetEntity'], "$currentEntityAlias", "WITH", "$currentEntityAlias.$mappedBy = " . "$prevEntityAlias.id");
399
                        }
400
401
                        $this->storeJoin($prevEntityAlias, $currentRelation);
402
                    }
403
                }
404
405
                $prevEntityAlias = $currentEntityAlias;
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $currentEntityAlias does not seem to be defined for all execution paths leading up to this point.
Loading history...
406
                $prevEntityName = $association['targetEntity'];
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $association does not seem to be defined for all execution paths leading up to this point.
Loading history...
407
            }
408
409
            $this->setEmbeddedFields($embeddedFields);
410
            $this->setCurrentEntityAlias($currentEntityAlias);
411
        }
412
413
        return $queryBuilder;
414
    }
415
416
    protected function getCurrentEntityAlias() : string
417
    {
418
        return $this->currentEntityAlias;
419
    }
420
421
    protected function setCurrentEntityAlias(string $currentEntityAlias) 
422
    {
423
        $this->currentEntityAlias = $currentEntityAlias;
424
    }
425
426
    protected function getEmbeddedFields() : array
427
    {
428
        return $this->embeddedFields;
429
    }
430
431
    protected function setEmbeddedFields(array $embeddedFields) 
432
    {
433
        $this->embeddedFields = $embeddedFields;
434
    }    
435
436 1
    public function getEntityAlias(string $entityName) : string
437
    {
438 1
        $arrayEntityName = explode('\\', strtolower($entityName) );
439 1
        $entityAlias = $arrayEntityName[count($arrayEntityName)-1];
440 1
        return $entityAlias;
441
    }
442
443
    protected function relationship($queryBuilder)
444
    {
445
        return $queryBuilder;
446
    }
447
448
    /**
449
     *
450
     * @param type $insertFields
0 ignored issues
show
Bug introduced by
The type Mado\QueryBundle\Repositories\type was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
451
     * @param type $updateFields
452
     *
453
     * USE:
454
     *
455
     * $this->getEntityManager()
456
     *      ->getRepository('User')
457
     *      ->onDuplicateUpdate(['column1' => 'user_reminder_1', 'column2' => 235], ['column2' => 255]);
458
     */
459
    public function onDuplicateUpdate($insertFields, $updateFields)
460
    {
461
        $array_keys = array_keys($insertFields);
0 ignored issues
show
Bug introduced by
$insertFields of type Mado\QueryBundle\Repositories\type is incompatible with the type array expected by parameter $input of array_keys(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

461
        $array_keys = array_keys(/** @scrutinizer ignore-type */ $insertFields);
Loading history...
462
        $list_keys = '`' . implode('`,`', $array_keys) . '`';
463
464
        $list_values = "'" . implode("', '", $insertFields) . "'";
0 ignored issues
show
Bug introduced by
$insertFields of type Mado\QueryBundle\Repositories\type is incompatible with the type array expected by parameter $pieces of implode(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

464
        $list_values = "'" . implode("', '", /** @scrutinizer ignore-type */ $insertFields) . "'";
Loading history...
465
466
        $table = $this->getEntityManager()->getClassMetadata($this->getEntityName())->getTableName();
467
468
        $sql = 'INSERT INTO '.$table;
469
        $sql .= '('. $list_keys . ') ';
470
        $sql .= "VALUES(". $list_values.") ";
471
        $sql .= 'ON DUPLICATE KEY UPDATE ';
472
473
        $c = 0;
474
        foreach($updateFields as $column => $value) {
475
            if ($c > 0) {
476
                $sql .= ", ";
477
            }
478
479
            $sql .= '`'.$column . "` = '". $value."'";
480
            $c++;
481
        }
482
483
        $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
484
        $stmt->execute();
485
    }
486
487
    public function getQueryBuilderFactoryWithoutInitialization()
488
    {
489
        return $this->queryBuilderFactory;
490
    }
491
}
492