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.
Test Failed
Pull Request — master (#33)
by Alessandro
07:05
created

BaseRepository::getRequestAttributes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 1
dl 0
loc 12
ccs 0
cts 5
cp 0
crap 6
rs 9.4285
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
    public function __construct($manager, $class)
37
    {
38
        parent::__construct($manager, $class);
39
40
        $this->fields = array_keys($this->getClassMetadata()->fieldMappings);
41
42
        $entityName = explode('\\', strtolower($this->getEntityName()) );
43
        $entityName = $entityName[count($entityName)-1];
44
        $entityAlias = $entityName[0];
45
        $this->entityAlias = $entityAlias;
46
47
        $this->queryBuilderFactory = new QueryBuilderFactory($this->getEntityManager());
48
    }
49
50
    public function initFromQueryBuilderOptions(QueryBuilderOptions $options)
51
    {
52
        $this->queryBuilderFactory->createQueryBuilder($this->getEntityName(), $this->entityAlias);
53
54
        $fieldMappings = $this->getClassMetadata()->fieldMappings;
55
        $this->fields = array_keys($fieldMappings);
56
57
        $this->queryBuilderFactory->setFields($this->fields ?? []);
58
        $this->queryBuilderFactory->setFilters($options->getFilters());
59
        $this->queryBuilderFactory->setOrFilters($options->getOrFilters());
60
        $this->queryBuilderFactory->setSorting($options->getSorting());
61
        $this->queryBuilderFactory->setRel($options->getRel());
62
        $this->queryBuilderFactory->setPrinting($options->getPrinting());
63
        $this->queryBuilderFactory->setSelect($options->getSelect());
64
    }
65
66
    public function getQueryBuilderFactory()
67
    {
68
        $this->initFromQueryBuilderOptions($this->queryOptions);
69
70
        return $this->queryBuilderFactory;
71
    }
72
73
    public function useResultCache($bool)
74
    {
75
        $this->use_result_cache = $bool;
76
    }
77
78
    public function setRequest(Request $request)
79
    {
80
        return $this->setQueryOptionsFromRequest($request);
81
    }
82
83
    public function setRequestWithFilter(Request $request, $filter)
84
    {
85
        return $this->setQueryOptionsFromRequestWithCustomFilter($request, $filter);
86
    }
87
88
    public function setRequestWithOrFilter(Request $request, $orFilter)
89
    {
90
        return $this->setQueryOptionsFromRequestWithCustomOrFilter($request, $orFilter);
91
    }
92
93
    public function setQueryOptions(QueryBuilderOptions $options)
94
    {
95
        $this->queryOptions = $options;
96
    }
97
98
    public function setQueryOptionsFromRequest(Request $request = null)
99
    {
100
        $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

100
        $requestAttributes = self::getRequestAttributes(/** @scrutinizer ignore-type */ $request);
Loading history...
101
102
        $requestOption = self::setRequestOption($request, $this->entityAlias);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type null; however, parameter $request of Mado\QueryBundle\Reposit...ory::setRequestOption() 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

102
        $requestOption = self::setRequestOption(/** @scrutinizer ignore-type */ $request, $this->entityAlias);
Loading history...
103
104
        $filterOrCorrected = [];
105
106
        $count = 0;
107
        foreach ($requestOption['orFilters'] as $key => $filter) {
108
            if (is_array($filter)) {
109
                foreach ($filter as $keyInternal => $internal) {
110
                    $filterOrCorrected[$keyInternal .'|' . $count] = $internal;
111
                    $count = $count + 1;
112
                }
113
            } else {
114
                $filterOrCorrected[$key] = $filter;
115
            }
116
        }
117
118
        $requestProperties = [
119
            'filtering'   => $requestOption['filtering'],
120
            'orFiltering' => $requestOption['filterOrCorrected'],
121
            'limit'       => $requestOption['limit'],
122
            'page'        => $requestOption['page'],
123
            'filters'     => $requestOption['filters'],
124
            'orFilters'   => $requestOption['filterOrCorrected'],
125
            'sorting'     => $requestOption['sorting'],
126
            'rel'         => $requestOption['rel'],
127
            'printing'    => $requestOption['printing'],
128
            'select'      => $requestOption['select'],
129
        ];
130
131
        $options = array_merge(
132
            $requestAttributes,
133
            $requestProperties
134
        );
135
136
        $this->queryOptions = QueryBuilderOptions::fromArray($options);
137
138
        return $this;
139
    }
140
141
    public static function getRequestAttributes(Request $request)
142
    {
143
        $requestAttributes = [];
144
145
        foreach ($request->attributes->all() as $attributeName => $attributeValue) {
146
            $requestAttributes[$attributeName] = $request->attributes->get(
147
                $attributeName,
148
                $attributeValue
149
            );
150
        }
151
152
        return $requestAttributes;
153
    }
154
155
    private static function setRequestOption(Request $request, $entityAlias)
156
    {
157
        $requestOption = [];
158
159
        $requestOption['filters']     = $request->query->get('filtering', []);
160
        $requestOption['orFilters']    = $request->query->get('filtering_or', []);
161
        $requestOption['sorting ']     = $request->query->get('sorting', []);
162
        $requestOption['printing']     = $request->query->get('printing', []);
163
        $requestOption['rel']          = $request->query->get('rel', '');
164
        $requestOption['page']         = $request->query->get('page', '');
165
        $requestOption['select']       = $request->query->get('select', $entityAlias);
166
        $requestOption['filtering']    = $request->query->get('filtering', '');
167
        $requestOption['limit']        = $request->query->get('limit', '');
168
169
        return $requestOption;
170
    }
171
172 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...
173
    {
174
        $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

174
        $requestAttributes = self::getRequestAttributes(/** @scrutinizer ignore-type */ $request);
Loading history...
175
176
        $requestOption = self::setRequestOption($request, $this->entityAlias);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type null; however, parameter $request of Mado\QueryBundle\Reposit...ory::setRequestOption() 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

176
        $requestOption = self::setRequestOption(/** @scrutinizer ignore-type */ $request, $this->entityAlias);
Loading history...
177
178
        $filters = array_merge($requestOption['filters'], $filter);
179
180
        $filterOrCorrected = [];
181
182
        $count = 0;
183
        foreach ($requestOption['orFilters'] as $key => $filter) {
184
            if (is_array($filter)) {
185
                foreach ($filter as $keyInternal => $internal) {
186
                    $filterOrCorrected[$keyInternal .'|' . $count] = $internal;
187
                    $count = $count + 1;
188
                }
189
            } else {
190
                $filterOrCorrected[$key] = $filter;
191
            }
192
        }
193
194
        $requestProperties = [
195
            '_route' => $request->attributes->get('_route'),
196
            'customer_id' => $request->attributes->get('customer_id'),
197
            'id' => $request->attributes->get('id'),
198
            'filtering' => $requestOption['filtering'],
199
            'limit' => $requestOption['limit'],
200
            'page' => $requestOption['page'],
201
            'filters' => $filters,
202
            'orFilters' => $filterOrCorrected,
203
            'sorting' => $requestOption['sorting'],
204
            'rel' => $requestOption['rel'],
205
            'printing' => $requestOption['printing'],
206
            'select' => $requestOption['select'],
207
        ];
208
209
        $options = array_merge(
210
            $requestAttributes,
211
            $requestProperties
212
        );
213
214
        $this->queryOptions = QueryBuilderOptions::fromArray($options);
215
216
        return $this;
217
    }
218
219 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...
220
    {
221
        $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

221
        $requestAttributes = self::getRequestAttributes(/** @scrutinizer ignore-type */ $request);
Loading history...
222
223
        $requestOption = self::setRequestOption($request, $this->entityAlias);
0 ignored issues
show
Bug introduced by
It seems like $request can also be of type null; however, parameter $request of Mado\QueryBundle\Reposit...ory::setRequestOption() 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

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

362
    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...
363
    {
364
        if (strstr($key, '_embedded.')) {
365
            $embeddedFields = explode('.', $key);
366
            $numFields = count($embeddedFields);
367
368
            $prevEntityAlias = $this->entityAlias;
369
            $prevEntityName = $this->getEntityName();
370
371
            for ($i = 1; $i < $numFields - 1; $i++) {
372
                $metadata = $this->getEntityManager()->getClassMetadata($prevEntityName);
373
374
                $currentRelation = $embeddedFields[$i];
375
376
                if ($metadata->hasAssociation($currentRelation)) {
377
378
                    $association = $metadata->getAssociationMapping($currentRelation);
379
380
                    $currentEntityAlias = $this->getEntityAlias($association['targetEntity']);
381
382
                    if ($this->noExistsJoin($prevEntityAlias, $currentRelation)) {
383
                        if ($association['isOwningSide']) {
384
                            $queryBuilder->join($association['targetEntity'], "$currentEntityAlias", "WITH", "$currentEntityAlias.id = " . "$prevEntityAlias.$currentRelation");
385
                        } else {
386
                            $mappedBy = $association['mappedBy'];
387
                            $queryBuilder->join($association['targetEntity'], "$currentEntityAlias", "WITH", "$currentEntityAlias.$mappedBy = " . "$prevEntityAlias.id");
388
                        }
389
390
                        $this->storeJoin($prevEntityAlias, $currentRelation);
391
                    }
392
                }
393
394
                $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...
395
                $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...
396
            }
397
398
            $this->setEmbeddedFields($embeddedFields);
399
            $this->setCurrentEntityAlias($currentEntityAlias);
400
        }
401
402
        return $queryBuilder;
403
    }
404
405
    protected function getCurrentEntityAlias() : string
406
    {
407
        return $this->currentEntityAlias;
408
    }
409
410
    protected function setCurrentEntityAlias(string $currentEntityAlias) 
411
    {
412
        $this->currentEntityAlias = $currentEntityAlias;
413
    }
414
415
    protected function getEmbeddedFields() : array
416
    {
417
        return $this->embeddedFields;
418
    }
419
420
    protected function setEmbeddedFields(array $embeddedFields) 
421
    {
422
        $this->embeddedFields = $embeddedFields;
423
    }    
424
425
    public function getEntityAlias(string $entityName) : string
426
    {
427
        $arrayEntityName = explode('\\', strtolower($entityName) );
428
        $entityAlias = $arrayEntityName[count($arrayEntityName)-1];
429
        return $entityAlias;
430
    }
431
432
    protected function relationship($queryBuilder)
433
    {
434
        return $queryBuilder;
435
    }
436
437
    /**
438
     *
439
     * @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...
440
     * @param type $updateFields
441
     *
442
     * USE:
443
     *
444
     * $this->getEntityManager()
445
     *      ->getRepository('User')
446
     *      ->onDuplicateUpdate(['column1' => 'user_reminder_1', 'column2' => 235], ['column2' => 255]);
447
     */
448
    public function onDuplicateUpdate($insertFields, $updateFields)
449
    {
450
        $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

450
        $array_keys = array_keys(/** @scrutinizer ignore-type */ $insertFields);
Loading history...
451
        $list_keys = '`' . implode('`,`', $array_keys) . '`';
452
453
        $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

453
        $list_values = "'" . implode("', '", /** @scrutinizer ignore-type */ $insertFields) . "'";
Loading history...
454
455
        $table = $this->getEntityManager()->getClassMetadata($this->getEntityName())->getTableName();
456
457
        $sql = 'INSERT INTO '.$table;
458
        $sql .= '('. $list_keys . ') ';
459
        $sql .= "VALUES(". $list_values.") ";
460
        $sql .= 'ON DUPLICATE KEY UPDATE ';
461
462
        $c = 0;
463
        foreach($updateFields as $column => $value) {
464
            if ($c > 0) {
465
                $sql .= ", ";
466
            }
467
468
            $sql .= '`'.$column . "` = '". $value."'";
469
            $c++;
470
        }
471
472
        $stmt = $this->getEntityManager()->getConnection()->prepare($sql);
473
        $stmt->execute();
474
    }
475
476
    public function getQueryBuilderFactoryWithoutInitialization()
477
    {
478
        return $this->queryBuilderFactory;
479
    }
480
}
481