Passed
Push — develop ( 78bdd2...c3c905 )
by Andrea
21:45 queued 11s
created

TabellaQueryTrait::getRecordstabella()   A

Complexity

Conditions 5
Paths 10

Size

Total Lines 37
Code Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 5.0026

Importance

Changes 0
Metric Value
cc 5
eloc 21
nc 10
nop 0
dl 0
loc 37
ccs 20
cts 21
cp 0.9524
crap 5.0026
rs 9.2728
c 0
b 0
f 0
1
<?php
2
3
namespace Cdf\BiCoreBundle\Utils\Tabella;
4
5
use Doctrine\ORM\Tools\Pagination\Paginator;
6
use Doctrine\Common\Collections\Expr\Comparison;
7
use Cdf\BiCoreBundle\Utils\FieldType\FieldTypeUtils;
8
use function count;
9
10
trait TabellaQueryTrait
11
{
12 12
    protected function biQueryBuilder()
13
    {
14 12
        $nometabellaalias = $this->generaAlias($this->tablename);
0 ignored issues
show
Bug introduced by
It seems like generaAlias() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

14
        /** @scrutinizer ignore-call */ 
15
        $nometabellaalias = $this->generaAlias($this->tablename);
Loading history...
15 12
        $qb = $this->em->createQueryBuilder()
16 12
                ->select(array($nometabellaalias))
17 12
                ->from($this->entityname, $nometabellaalias);
18 12
        $campi = array_keys($this->em->getMetadataFactory()->getMetadataFor($this->entityname)->reflFields);
19 12
        $this->recursiveJoin($qb, $campi, $this->tablename, $nometabellaalias);
20 12
        $this->buildWhere($qb);
21 12
        $this->orderByBuilder($qb);
22
23 12
        return $qb;
24
    }
25
26 12
    protected function recursiveJoin(&$qb, $campi, $nometabella, $alias, $ancestors = array())
27
    {
28 12
        foreach ($campi as $campo) {
29 12
            if (false !== strpos(strtolower($campo), 'relatedby')) {
30
                continue;
31
            }
32 12
            if (!in_array($nometabella, $ancestors)) {
33 12
                $ancestors[] = $nometabella;
34
            }
35
36 12
            $configurazionecampo = isset($this->configurazionecolonnetabella[ucfirst(implode('.', $ancestors)).'.'.$campo]) ?
37 12
                    $this->configurazionecolonnetabella[ucfirst(implode('.', $ancestors)).'.'.$campo] : false;
38 12
            if ($configurazionecampo && true === $configurazionecampo['association']) {
39
                // crea la relazione con $padre = $nometabella in corso e figlio = $nomecampo con $alias generato
40 6
                if ((isset($configurazionecampo['sourceentityclass'])) && (null !== $configurazionecampo['sourceentityclass'])) {
41 6
                    $entitysrc = $configurazionecampo['sourceentityclass'];
42 6
                    $nometabellasrc = $this->em->getClassMetadata($entitysrc)->getTableName();
43
                } else {
44
                    $nometabellasrc = $nometabella;
45
                }
46
47 6
                $entitytarget = $configurazionecampo['associationtable']['targetEntity'];
48 6
                $nometabellatarget = $this->em->getClassMetadata($entitytarget)->getTableName();
49 6
                $aliastarget = $this->generaAlias($nometabellatarget, $nometabellasrc, $ancestors);
50
                //$qb->leftJoin($alias . "." . $configurazionecampo["nomecampo"], $aliastarget);
51
                //$camporelazionejoin = strtolower(substr($configurazionecampo["nomecampo"], strpos($configurazionecampo["nomecampo"], ".") + 1));
52 6
                $parti = explode('.', $configurazionecampo['nomecampo']);
53
54 6
                $camporelazionejoin = strtolower($parti[count($parti) - 1]);
55 6
                $qb->leftJoin($alias.'.'.$camporelazionejoin, $aliastarget);
56 6
                $campitarget = array_keys($this->em->getMetadataFactory()->getMetadataFor($entitytarget)->reflFields);
57 6
                $this->recursiveJoin($qb, $campitarget, $nometabellatarget, $aliastarget, $ancestors);
58
59
                // lancia rescursiveJoin su questo campo con padre = $aliasgenerato
60
                // --- figlio = $nomecampo
61
                // --- alias = alias generato nuovo
62
            }
63
        }
64 12
    }
65
66 12
    protected function buildWhere(&$qb)
67
    {
68
69 12
        $filtro = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $filtro is dead and can be removed.
Loading history...
70 12
        $prefiltro = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $prefiltro is dead and can be removed.
Loading history...
71 12
        foreach ($this->prefiltri as $key => $prefiltro) {
72 2
            $this->prefiltri[$key]['prefiltro'] = true;
0 ignored issues
show
Bug Best Practice introduced by
The property prefiltri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
73
        }
74 12
        foreach ($this->filtri as $key => $filtro) {
75 2
            $this->filtri[$key]['prefiltro'] = false;
0 ignored issues
show
Bug Best Practice introduced by
The property filtri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
76
        }
77 12
        $tuttifiltri = array_merge($this->filtri, $this->prefiltri);
78 12
        $parametribag = array();
79 12
        if (count($tuttifiltri)) {
80 3
            $descrizionefiltri = '';
81 3
            foreach ($tuttifiltri as $num => $filtrocorrente) {
82 3
                $tablename = substr($filtrocorrente['nomecampo'], 0, strripos($filtrocorrente['nomecampo'], '.'));
83 3
                $alias = $this->findAliasByTablename($tablename);
0 ignored issues
show
Bug introduced by
It seems like findAliasByTablename() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

83
                /** @scrutinizer ignore-call */ 
84
                $alias = $this->findAliasByTablename($tablename);
Loading history...
84 3
                $fieldname = $alias.'.'.(substr($filtrocorrente['nomecampo'], strripos($filtrocorrente['nomecampo'], '.') + 1));
85 3
                $fieldvalue = $this->getFieldValue($filtrocorrente['valore']);
0 ignored issues
show
Bug introduced by
It seems like getFieldValue() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

85
                /** @scrutinizer ignore-call */ 
86
                $fieldvalue = $this->getFieldValue($filtrocorrente['valore']);
Loading history...
86 3
                $fieldoperator = $this->getOperator($filtrocorrente['operatore']);
0 ignored issues
show
Bug introduced by
The method getOperator() does not exist on Cdf\BiCoreBundle\Utils\Tabella\TabellaQueryTrait. Did you maybe mean getApiOperator()? ( Ignorable by Annotation )

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

86
                /** @scrutinizer ignore-call */ 
87
                $fieldoperator = $this->getOperator($filtrocorrente['operatore']);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
87 3
                $fitrocorrenteqp = 'fitrocorrente'.$num;
88 3
                $filtronomecampocorrente = $this->findFieldnameByAlias($filtrocorrente['nomecampo']);
0 ignored issues
show
Bug introduced by
It seems like findFieldnameByAlias() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

88
                /** @scrutinizer ignore-call */ 
89
                $filtronomecampocorrente = $this->findFieldnameByAlias($filtrocorrente['nomecampo']);
Loading history...
89 2
                $criteria = new ParametriQueryTabellaDecoder(
90 2
                    $fieldname,
91
                    $fieldoperator,
92
                    $fieldvalue,
93
                    $fitrocorrenteqp,
94
                    $filtronomecampocorrente
95
                );
96
97 2
                $querycriteria = $criteria->getQueryCriteria();
98 2
                $queryparameter = $criteria->getQueryParameters();
99
100 2
                if ($querycriteria) {
101 2
                    $qb->andWhere($querycriteria);
102 2
                    $parametribag = array_merge($queryparameter, $parametribag);
103
                } else {
104 2
                    $qb->andWhere($fieldname.' '.$fieldoperator.' '.":$fitrocorrenteqp");
105 2
                    $parametribag = array_merge(array($fitrocorrenteqp => $fieldvalue), $parametribag);
106
                }
107 2
                $this->getDescrizioneFiltro($descrizionefiltri, $filtrocorrente, $criteria);
0 ignored issues
show
Bug introduced by
It seems like getDescrizioneFiltro() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

107
                $this->/** @scrutinizer ignore-call */ 
108
                       getDescrizioneFiltro($descrizionefiltri, $filtrocorrente, $criteria);
Loading history...
108
            }
109 2
            $this->traduzionefiltri = substr($descrizionefiltri, 2);
0 ignored issues
show
Bug Best Practice introduced by
The property traduzionefiltri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
110
        }
111 12
        $qb->setParameters($parametribag);
112
113 12
        if (isset($this->wheremanuale)) {
114
            $qb->andWhere($this->wheremanuale);
115
        }
116 12
    }
117
118 12
    protected function orderByBuilder(&$qb)
119
    {
120 12
        foreach ($this->colonneordinamento as $nomecampo => $tipoordinamento) {
121 10
            $tablename = substr($nomecampo, 0, strripos($nomecampo, '.'));
122 10
            $alias = $this->getAliasGenerato($tablename);
0 ignored issues
show
Bug introduced by
It seems like getAliasGenerato() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

122
            /** @scrutinizer ignore-call */ 
123
            $alias = $this->getAliasGenerato($tablename);
Loading history...
123 10
            $fieldname = $alias.'.'.(substr($nomecampo, strripos($nomecampo, '.') + 1));
124 10
            $qb->addOrderBy($fieldname, $tipoordinamento);
125
        }
126 12
    }
127
128
129
    /**
130
     * Attempt to translate the user given value into a boolean valid field
131
     */
132
    private function translateBoolValue($fieldvalue)
133
    {
134
        switch (strtoupper($fieldvalue)) {
135
            case 'SI':
136
                $fieldvalue = 'true';
137
                break;
138
            case '1':
139
                $fieldvalue = 'true';
140
                break;
141
            case 'NO':
142
                $fieldvalue = 'false';
143
                break;
144
            case '0':
145
                $fieldvalue = 'false';
146
                break;
147
            default:
148
                $fieldvalue = 'false';
149
                break;
150
        }
151
        return $fieldvalue;
152
    }
153
154
    /**
155
     * It appends the new filter string part to the given filter string ($filterString)
156
     */
157
    private function appendFilterString(String &$filterString, $swaggerType, $swaggerKind, $fieldvalue)
158
    {
159
        if ($swaggerKind == 'bool') {
160
            $filterString .= $this->translateBoolValue($fieldvalue);
161
        } elseif ($swaggerType == null /*|| $swaggerFormats[ $nomeCampo ] == 'datetime'*/) {
162
            $filterString .= '"%'.$fieldvalue.'%"';
163
        } elseif ($swaggerType == 'datetime' || $swaggerType == 'date') {
164
            $fieldvalue = \str_replace("/", "-", $fieldvalue);
165
            //does it contain an hour ?
166
            $hour = strpos($fieldvalue, ":");
167
            $time = strtotime($fieldvalue);
168
            $backend_format = FieldTypeUtils::getEnvVar("BE_DATETIME_FORMAT", "Y-m-d\TH:i:sP");
169
            if ($hour === false) {
170
                $backend_format = FieldTypeUtils::getEnvVar("BE_DATE_FORMAT", "Y-m-d");
171
            }
172
            $filter = date($backend_format, $time);
173
            $filterString .= $filter;
174
        } else {
175
            $filterString .= $fieldvalue;
176
        }
177
    }
178
179
    /**
180
     * It composes filtering string to be used with api rest services
181
     */
182
    protected function filterByApiBuilder(): ?String
183
    {
184
        $filterString = null;
185
        $filtro = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $filtro is dead and can be removed.
Loading history...
186
        $prefiltro = '';
0 ignored issues
show
Unused Code introduced by
The assignment to $prefiltro is dead and can be removed.
Loading history...
187
        foreach ($this->prefiltri as $key => $prefiltro) {
188
            $this->prefiltri[$key]['prefiltro'] = true;
0 ignored issues
show
Bug Best Practice introduced by
The property prefiltri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
189
        }
190
        foreach ($this->filtri as $key => $filtro) {
191
            $this->filtri[$key]['prefiltro'] = false;
0 ignored issues
show
Bug Best Practice introduced by
The property filtri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
192
        }
193
        $tuttifiltri = array_merge($this->filtri, $this->prefiltri);
194
        //$parametribag = array();
195
        if (count($tuttifiltri)) {
196
            $attributeMap = $this->entityname::attributeMap();
197
            $swaggerFormats = $this->entityname::swaggerFormats();
198
            $swaggerTypes = $this->entityname::swaggerTypes();
199
            //compose the string
200
            $descrizionefiltri = '';
201
            foreach ($tuttifiltri as $num => $filtrocorrente) {
202
                $nomeCampo = substr($filtrocorrente['nomecampo'], strripos($filtrocorrente['nomecampo'], '.') + 1);
203
                $fieldname = ' '.$nomeCampo;
204
                $filteringValues = $this->getFieldValue($filtrocorrente['valore']);
205
                $fieldoperator = $this->getOperator($filtrocorrente['operatore']);
206
                $fitrocorrenteqp = 'fitrocorrente'.$num;
207
                $filtronomecampocorrente = $this->findFieldnameByAlias($filtrocorrente['nomecampo']);
208
209
                $criteria = new ParametriQueryTabellaDecoder(
210
                    $fieldname,
211
                    $fieldoperator,
212
                    $filteringValues,
213
                    $fitrocorrenteqp,
214
                    $filtronomecampocorrente
215
                );
216
217
                if (is_array($filteringValues)) {
218
                    $fieldstring =  '( ';
219
                    foreach ($filteringValues as $num => $filterValue) {
0 ignored issues
show
Comprehensibility Bug introduced by
$num is overwriting a variable from outer foreach loop.
Loading history...
220
                        $fieldstring .= $attributeMap[ $nomeCampo ];
221
                        $fieldstring .= ' '.$this->getApiOperator($filtrocorrente['operatore']).' ';
222
                        $fieldvalue = urldecode($filterValue);
223
                        $this->appendFilterString($fieldstring, $swaggerFormats[ $nomeCampo ], $swaggerTypes[ $nomeCampo ], $fieldvalue);
224
                        if ($num < count($filteringValues)-1) {
225
                            $fieldstring .= ' OR ';
226
                        }
227
                    }
228
                    $fieldstring .=  ' )';
229
                } else {
230
                    $fieldstring = $attributeMap[ $nomeCampo ];
231
                    $fieldstring .= ' '.$this->getApiOperator($filtrocorrente['operatore']).' ';
232
                    $fieldvalue = urldecode($filteringValues);
0 ignored issues
show
Unused Code introduced by
The assignment to $fieldvalue is dead and can be removed.
Loading history...
233
                    $this->appendFilterString($fieldstring, $swaggerFormats[ $nomeCampo ], $swaggerTypes[ $nomeCampo ], $filteringValues);
234
                }
235
236
                if ($filterString != null) {
237
                    $filterString .= ' AND ';
238
                }
239
                $filterString .= $fieldstring;
240
                $this->getDescrizioneFiltro($descrizionefiltri, $filtrocorrente, $criteria);
241
            }
242
            $this->traduzionefiltri = substr($descrizionefiltri, 2);
0 ignored issues
show
Bug Best Practice introduced by
The property traduzionefiltri does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
243
        }
244
        return $filterString;
245
    }
246
247
    /**
248
     * Return the operator to be used
249
     */
250
    private function getApiOperator($operator)
251
    {
252
        switch (strtoupper($operator)) {
253
            case Comparison::CONTAINS:
254
                $operator = '~';
255
                break;
256
            /*case 'IN':
257
                $operator = Comparison::IN;
258
                break;
259
            case 'NOT IN':
260
                $operator = Comparison::NIN;
261
                break;*/
262
            default:
263
                $operator = '=';
264
                break;
265
        }
266
267
        return $operator;
268
    }
269
270
    /**
271
     * Build the ordering string compliant with API REST services
272
     */
273
    protected function orderByApiBuilder(): ?String
274
    {
275
        $attributeMap = $this->entityname::attributeMap();
276
        $orderingString = null;
277
        foreach ($this->colonneordinamento as $nomecampo => $tipoordinamento) {
278
            $fieldname = $attributeMap[ substr($nomecampo, strripos($nomecampo, '.') + 1) ];
279
            $fieldname .= ':'.$tipoordinamento;
280
            if ($orderingString != null) {
281
                $orderingString .= ',';
282
            }
283
            $orderingString .= $fieldname;
284
        }
285
        return $orderingString;
286
    }
287
288 12
    public function getRecordstabella()
289
    {
290
        //Look for all tables
291 12
        $qb = $this->biQueryBuilder();
292
293 12
        if (false === $this->estraituttirecords) {
0 ignored issues
show
Bug introduced by
The property estraituttirecords does not exist on Cdf\BiCoreBundle\Utils\Tabella\TabellaQueryTrait. Did you mean records?
Loading history...
294 12
            $paginator = new Paginator($qb, true);
295 12
            $this->righetotali = count($paginator);
0 ignored issues
show
Bug Best Practice introduced by
The property righetotali does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
296 12
            $this->paginetotali = (int) $this->calcolaPagineTotali($this->getRigheperpagina());
0 ignored issues
show
Bug Best Practice introduced by
The property paginetotali does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
Bug introduced by
It seems like getRigheperpagina() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

296
            $this->paginetotali = (int) $this->calcolaPagineTotali($this->/** @scrutinizer ignore-call */ getRigheperpagina());
Loading history...
Bug introduced by
It seems like calcolaPagineTotali() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

296
            $this->paginetotali = (int) $this->/** @scrutinizer ignore-call */ calcolaPagineTotali($this->getRigheperpagina());
Loading history...
297
            /* imposta l'offset, ovvero il record dal quale iniziare a visualizzare i dati */
298 12
            $offsetrecords = ($this->getRigheperpagina() * ($this->getPaginacorrente() - 1));
0 ignored issues
show
Bug introduced by
It seems like getPaginacorrente() must be provided by classes using this trait. How about adding it as abstract method to this trait? ( Ignorable by Annotation )

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

298
            $offsetrecords = ($this->getRigheperpagina() * ($this->/** @scrutinizer ignore-call */ getPaginacorrente() - 1));
Loading history...
299
300
            /* Imposta il limite ai record da estrarre */
301 12
            if ($this->getRigheperpagina()) {
302 12
                $qb = $qb->setMaxResults($this->getRigheperpagina());
303
            }
304
            /* E imposta il primo record da visualizzare (per la paginazione) */
305 12
            if ($offsetrecords) {
306
                $qb = $qb->setFirstResult($offsetrecords);
307
            }
308
            /* Dall'oggetto querybuilder si ottiene la query da eseguire */
309 12
            $recordsets = $qb->getQuery()->getResult();
310
        } else {
311
            /* Dall'oggetto querybuilder si ottiene la query da eseguire */
312 4
            $recordsets = $qb->getQuery()->getResult();
313 4
            $this->righetotali = count($recordsets);
314 4
            $this->paginetotali = 1;
315
        }
316
317 12
        $this->records = array();
0 ignored issues
show
Bug Best Practice introduced by
The property records does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
318 12
        $rigatabellahtml = array();
319 12
        foreach ($recordsets as $record) {
320 12
            $this->records[$record->getId()] = $record;
321 12
            unset($rigatabellahtml);
322
        }
323
324 12
        return $this->records;
325
    }
326
327
    /**
328
     * Read the API in order to obtains the pages features
329
     */
330
    public function getApiRecordstabella()
331
    {
332
        $newApi = $this->apiController;
333
        $apiController = new $newApi();
334
335
        if (false === $this->estraituttirecords) {
0 ignored issues
show
Bug introduced by
The property estraituttirecords does not exist on Cdf\BiCoreBundle\Utils\Tabella\TabellaQueryTrait. Did you mean records?
Loading history...
336
            $countMethod = $this->apiBook->getCount();
337
            
338
            $count = $apiController->$countMethod();
339
            $this->righetotali = $count;
0 ignored issues
show
Bug Best Practice introduced by
The property righetotali does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
340
            $this->paginetotali = (int) $this->calcolaPagineTotali($this->getRigheperpagina());
0 ignored issues
show
Bug Best Practice introduced by
The property paginetotali does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
341
            /* imposta l'offset, ovvero il record dal quale iniziare a visualizzare i dati */
342
            $offsetrecords = ($this->getRigheperpagina() * ($this->getPaginacorrente() - 1));
343
344
            /*$offset = null, $limit = null, $sort = null, $condition = null*/
345
            $paginationMethod = $this->apiBook->getAll();
346
            //dump($this->filterByApiBuilder());
347
348
            $recordsets = $apiController->$paginationMethod(
349
                $offsetrecords,
350
                $this->getRigheperpagina(),
351
                $this->orderByApiBuilder(),
352
                $this->filterByApiBuilder()
353
            );
354
        //dump($recordsets);
355
        } else {
356
            /* Dall'oggetto querybuilder si ottiene la query da eseguire */
357
            $paginationMethod = $this->apiBook->getAll();
358
            $recordsets = $apiController->$paginationMethod(0, null, $this->orderByApiBuilder(), $this->filterByApiBuilder());
359
            $this->paginetotali = 1;
360
            $this->righetotali = count($recordsets);
361
        }
362
        $this->records = array();
0 ignored issues
show
Bug Best Practice introduced by
The property records does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
363
        $rigatabellahtml = array();
364
        foreach ($recordsets as $record) {
365
            $this->records[$record->getId()] = $record;
366
            unset($rigatabellahtml);
367
        }
368
369
        return $this->records;
370
    }
371
}
372