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 (#37)
by Simone
07:10
created

BaseRepository::setEmbeddedFields()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
ccs 0
cts 2
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 5
    public function __construct($manager, $class)
37
    {
38 5
        parent::__construct($manager, $class);
39
40 5
        $this->fields = array_keys($this->getClassMetadata()->fieldMappings);
41
42 5
        $entityName = explode('\\', strtolower($this->getEntityName()) );
43 5
        $entityName = $entityName[count($entityName)-1];
44 5
        $entityAlias = $entityName[0];
45 5
        $this->entityAlias = $entityAlias;
46
47 5
        $this->queryBuilderFactory = new QueryBuilderFactory($this->getEntityManager());
48 5
    }
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 1
    public function setRequest(Request $request)
79
    {
80 1
        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 3
    public function setQueryOptionsFromRequest(Request $request = null)
99
    {
100 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

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

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

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

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

457
        $array_keys = array_keys(/** @scrutinizer ignore-type */ $insertFields);
Loading history...
458
        $list_keys = '`' . implode('`,`', $array_keys) . '`';
459
460
        $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

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