Completed
Push — master ( e647cd...a0585d )
by Daniel
06:11
created

MySQLiAdvancedOutput::getFieldOutputNumeric()   B

Complexity

Conditions 8
Paths 9

Size

Total Lines 59
Code Lines 46

Duplication

Lines 0
Ratio 0 %

Importance

Changes 6
Bugs 0 Features 0
Metric Value
c 6
b 0
f 0
dl 0
loc 59
rs 7.132
cc 8
eloc 46
nc 9
nop 3

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
/**
4
 *
5
 * The MIT License (MIT)
6
 *
7
 * Copyright (c) 2015 Daniel Popiniuc
8
 *
9
 * Permission is hereby granted, free of charge, to any person obtaining a copy
10
 * of this software and associated documentation files (the "Software"), to deal
11
 * in the Software without restriction, including without limitation the rights
12
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13
 * copies of the Software, and to permit persons to whom the Software is
14
 * furnished to do so, subject to the following conditions:
15
 *
16
 * The above copyright notice and this permission notice shall be included in all
17
 * copies or substantial portions of the Software.
18
 *
19
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24
 *  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
25
 * SOFTWARE.
26
 *
27
 */
28
29
namespace danielgp\common_lib;
30
31
/**
32
 * usefull functions to get quick results
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiAdvancedOutput
37
{
38
39
    use DomComponentsByDanielGP;
40
41
    protected $advCache = null;
42
43
    /**
44
     *
45
     * @param type $tblSrc
46
     */
47
    private function establishDatabaseAndTable($tblSrc)
48
    {
49
        if (strpos($tblSrc, '.') === false) { // in case the DB is ommited get the default one
50
            if (!defined('MYSQL_DATABASE')) {
51
                define('MYSQL_DATABASE', 'information_schema');
52
            }
53
            return [$tblSrc, MYSQL_DATABASE];
54
        }
55
        return explode('.', str_replace('`', '', $tblSrc));
56
    }
57
58
    private function establishDefaultEnumSet($fldType)
59
    {
60
        $dfltArray = [
61
            'enum' => ['additional' => ['size' => 1], 'suffix' => ''],
62
            'set'  => ['additional' => ['size' => 5, 'multiselect'], 'suffix' => '[]'],
63
        ];
64
        return $dfltArray[$fldType];
65
    }
66
67
    private function getFieldCompletionType($details)
68
    {
69
        $inputFeatures = ['display' => '***', 'ftrs' => ['title' => 'Mandatory', 'class' => 'inputMandatory']];
70
        if ($details['IS_NULLABLE'] == 'YES') {
71
            $inputFeatures = ['display' => '~', 'ftrs' => ['title' => 'Optional', 'class' => 'inputOptional']];
72
        }
73
        return $this->setStringIntoTag($inputFeatures['display'], 'span', $inputFeatures['ftrs']);
74
    }
75
76
    /**
77
     * Returns the name of a field for displaying
78
     *
79
     * @param array $details
80
     * @return string
81
     */
82
    private function getFieldNameForDisplay($details)
83
    {
84
        $tableUniqueId = $details['TABLE_SCHEMA'] . '.' . $details['TABLE_NAME'];
85
        if ($details['COLUMN_COMMENT'] != '') {
86
            return $details['COLUMN_COMMENT'];
87
        } elseif (isset($this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']])) {
88
            return $this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']];
89
        }
90
        return $details['COLUMN_NAME'];
91
    }
92
93
    /**
94
     * Returns a Enum or Set field to use in form
95
     *
96
     * @param string $tblSrc
97
     * @param string $fldType
98
     * @param array $val
99
     * @param string $iar
100
     * @return string
101
     */
102
    private function getFieldOutputEnumSet($tblSrc, $fldType, $val, $iar = null)
103
    {
104
        $adnlThings = $this->establishDefaultEnumSet($fldType);
105
        if (isset($iar['readonly'])) {
106
            return $this->getFieldOutputEnumSetReadOnly($tblSrc, $fldType, $val, $iar, $adnlThings);
107
        }
108
        $inAdtnl = $adnlThings['additional'];
109
        if (!is_null($iar)) {
110
            $inAdtnl = array_merge($inAdtnl, $iar);
111
        }
112
        $vlSlct    = explode(',', $this->getFieldValue($val));
113
        $slctOptns = $this->getSetOrEnum2Array($tblSrc, $val['COLUMN_NAME']);
114
        return $this->setArrayToSelect($slctOptns, $vlSlct, $val['COLUMN_NAME'] . $adnlThings['suffix'], $inAdtnl);
115
    }
116
117
    private function getFieldOutputEnumSetReadOnly($tblSrc, $fldType, $val, $iar, $adnlThings)
0 ignored issues
show
Unused Code introduced by
The parameter $tblSrc is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $fldType is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $iar is not used and could be removed.

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

Loading history...
118
    {
119
        $inputFeatures = [
120
            'name'     => $val['COLUMN_NAME'] . $adnlThings['suffix'],
121
            'id'       => $val['COLUMN_NAME'],
122
            'readonly' => 'readonly',
123
            'class'    => 'input_readonly',
124
            'size'     => 50,
125
            'value'    => $this->getFieldValue($val),
126
        ];
127
        return $this->setStringIntoShortTag('input', $inputFeatures);
128
    }
129
130
    /**
131
     * Returns a Numeric field 2 use in a form
132
     *
133
     * @param string $tblSrc
134
     * @param array $value
135
     * @param array $features
0 ignored issues
show
Bug introduced by
There is no parameter named $features. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
136
     * @param string $iar
137
     * @return string
138
     */
139
    private function getFieldOutputNumeric($tblSrc, $value, $iar = null)
140
    {
141
        $input = null;
0 ignored issues
show
Unused Code introduced by
$input is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
142
        if ($value['EXTRA'] == 'auto_increment') {
143
            if ($this->getFieldValue($value) == '') {
144
                $input = $this->setStringIntoTag('auto-numar', 'span', [
145
                    'id'    => $value['COLUMN_NAME'],
146
                    'style' => 'font-style:italic;',
147
                ]);
148
            } else {
149
                $inAdtnl = [
150
                    'type'  => 'hidden',
151
                    'name'  => $value['COLUMN_NAME'],
152
                    'id'    => $value['COLUMN_NAME'],
153
                    'value' => $this->getFieldValue($value),
154
                ];
155
                if (!is_null($iar)) {
156
                    $inAdtnl = array_merge($inAdtnl, $iar);
157
                }
158
                $input = $this->setStringIntoTag($this->getFieldValue($value), 'b')
159
                        . $this->setStringIntoShortTag('input', $inAdtnl);
160
            }
161
        } else {
162
            $database = $this->advCache['workingDatabase'];
163
            $fkArray  = $this->getForeignKeysToArray($database, $tblSrc, $value['COLUMN_NAME']);
164
            if (is_null($fkArray)) {
165
                $fldNos  = $this->setFieldNumbers($value);
0 ignored issues
show
Bug introduced by
It seems like setFieldNumbers() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
166
                $inAdtnl = [
167
                    'type'      => 'text',
168
                    'name'      => $value['COLUMN_NAME'],
169
                    'id'        => $value['COLUMN_NAME'],
170
                    'value'     => $this->getFieldValue($value),
171
                    'size'      => min(50, $fldNos['l']),
172
                    'maxlength' => min(50, $fldNos['l'])
173
                ];
174
                if (isset($iar)) {
175
                    $inAdtnl = array_merge($inAdtnl, $iar);
176
                }
177
                $input = $this->setStringIntoShortTag('input', $inAdtnl);
178
            } else {
179
                $query         = $this->sQueryGenericSelectKeyValue([
0 ignored issues
show
Bug introduced by
It seems like sQueryGenericSelectKeyValue() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
180
                    $fkArray[$value['COLUMN_NAME']][1],
181
                    $fkArray[$value['COLUMN_NAME']][2],
182
                    $fkArray[$value['COLUMN_NAME']][0]
183
                ]);
184
                $selectOptions = $this->setMySQLquery2Server($query, 'array_key_value')['result'];
0 ignored issues
show
Bug introduced by
It seems like setMySQLquery2Server() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
185
                $selectValue   = $this->getFieldValue($value);
186
                $inAdtnl       = ['size' => 1];
187
                if ($value['IS_NULLABLE'] == 'YES') {
188
                    $inAdtnl = array_merge($inAdtnl, ['include_null']);
189
                }
190
                if (isset($iar)) {
191
                    $inAdtnl = array_merge($inAdtnl, $iar);
192
                }
193
                $input = $this->setArrayToSelect($selectOptions, $selectValue, $value['COLUMN_NAME'], $inAdtnl);
194
            }
195
        }
196
        return $input;
197
    }
198
199
    /**
200
     * Returns a Char field 2 use in a form
201
     *
202
     * @param string $tbl
203
     * @param string $fieldType
204
     * @param array $value
205
     * @param array $features
0 ignored issues
show
Bug introduced by
There is no parameter named $features. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
206
     * @param string $iar
207
     * @return string
208
     */
209
    private function getFieldOutputText($tbl, $fieldType, $value, $iar = null)
210
    {
211
        if (!in_array($fieldType, ['char', 'tinytext', 'varchar'])) {
212
            return '';
213
        }
214
        $input    = null;
0 ignored issues
show
Unused Code introduced by
$input is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
215
        $database = $this->advCache['workingDatabase'];
216
        if (strpos($tbl, '`.`')) {
217
            $database = substr($tbl, 0, strpos($tbl, '`.`'));
218
        }
219
        if (($tbl != 'user_rights') && ($value['COLUMN_NAME'] != 'eid')) {
220
            $foreignKeysArray = $this->getForeignKeysToArray($database, $tbl, $value['COLUMN_NAME']);
221
            if (is_null($foreignKeysArray)) {
222
                unset($foreignKeysArray);
223
            }
224
        }
225
        if (isset($foreignKeysArray)) {
226
            $query   = $this->storedQuery('generic_select_key_value', [
0 ignored issues
show
Bug introduced by
It seems like storedQuery() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
227
                $foreignKeysArray[$value['COLUMN_NAME']][1],
228
                $foreignKeysArray[$value['COLUMN_NAME']][2],
229
                $foreignKeysArray[$value['COLUMN_NAME']][0]
230
            ]);
231
            $inAdtnl = ['size' => 1];
232
            if ($value['IS_NULLABLE'] == 'YES') {
233
                $inAdtnl = array_merge($inAdtnl, ['include_null']);
234
            }
235
            if (!is_null($iar)) {
236
                $inAdtnl = array_merge($inAdtnl, $iar);
237
            }
238
            $slct  = [
239
                'Options' => $this->setQuery2Server($query, 'array_key_value'),
0 ignored issues
show
Bug introduced by
It seems like setQuery2Server() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
240
                'Value'   => $this->getFieldValue($value),
241
            ];
242
            $input = $this->setArrayToSelect($slct['Options'], $slct['Value'], $value['COLUMN_NAME'], $inAdtnl);
243
            unset($foreignKeysArray);
244
        } else {
245
            $fldNos  = $this->setFieldNumbers($value);
0 ignored issues
show
Bug introduced by
It seems like setFieldNumbers() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
246
            $inAdtnl = [
247
                'type'      => ($value['COLUMN_NAME'] == 'password' ? 'password' : 'text'),
248
                'name'      => $value['COLUMN_NAME'],
249
                'id'        => $value['COLUMN_NAME'],
250
                'size'      => min(30, $fldNos['l']),
251
                'maxlength' => min(255, $fldNos['l']),
252
                'value'     => $this->getFieldValue($value),
253
            ];
254
            if (!is_null($iar)) {
255
                $inAdtnl = array_merge($inAdtnl, $iar);
256
            }
257
            $input = $this->setStringIntoShortTag('input', $inAdtnl);
258
        }
259
        return $input;
260
    }
261
262
    /**
263
     * Returns a Text field 2 use in a form
264
     *
265
     * @param string $table_source
0 ignored issues
show
Bug introduced by
There is no parameter named $table_source. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
266
     * @param string $fieldType
267
     * @param array $value
268
     * @param array $features
0 ignored issues
show
Bug introduced by
There is no parameter named $features. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
269
     * @param string $iar
270
     * @return string
271
     */
272
    private function getFieldOutputTextLarge($fieldType, $value, $iar = null)
273
    {
274
        if (!in_array($fieldType, ['blob', 'text'])) {
275
            $sReturn = '';
276
        } else {
277
            $inAdtnl = [
278
                'name' => $value['COLUMN_NAME'],
279
                'id'   => $value['COLUMN_NAME'],
280
                'rows' => 4,
281
                'cols' => 55,
282
            ];
283
            if (isset($iar)) {
284
                $inAdtnl = array_merge($inAdtnl, $iar);
285
            }
286
            $sReturn = $this->setStringIntoTag($this->getFieldValue($value), 'textarea', $inAdtnl);
287
        }
288
        return $sReturn;
289
    }
290
291
    /**
292
     * Returns a Time field 2 use in a form
293
     *
294
     * @param string $table_source
0 ignored issues
show
Bug introduced by
There is no parameter named $table_source. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
295
     * @param string $fieldType
296
     * @param array $value
297
     * @param array $features
0 ignored issues
show
Bug introduced by
There is no parameter named $features. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
298
     * @param string $iar
299
     * @return string
300
     */
301
    private function getFieldOutputTime($fieldType, $value, $iar = null)
302
    {
303
        $input = null;
304
        switch ($fieldType) {
305
            case 'time':
306
                $inAdtnl = [
307
                    'type'      => 'text',
308
                    'size'      => 9,
309
                    'maxlength' => 9,
310
                    'name'      => $value['COLUMN_NAME'],
311
                    'id'        => $value['COLUMN_NAME'],
312
                    'value'     => $this->getFieldValue($value),
313
                ];
314
                if (isset($iar)) {
315
                    $inAdtnl = array_merge($inAdtnl, $iar);
316
                }
317
                $input = $this->setStringIntoShortTag('input', $inAdtnl);
318
                break;
319
        }
320
        return $input;
321
    }
322
323
    /**
324
     * Returns a Timestamp field 2 use in a form
325
     *
326
     * @param string $table_source
0 ignored issues
show
Bug introduced by
There is no parameter named $table_source. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
327
     * @param string $fieldType
328
     * @param array $value
329
     * @param array $features
0 ignored issues
show
Bug introduced by
There is no parameter named $features. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
330
     * @param string $iar
331
     * @return string
332
     */
333
    private function getFieldOutputTimestamp($fieldType, $value, $iar = null)
334
    {
335
        $input = null;
336
        switch ($fieldType) {
337
            case 'timestamp':
338
            // intentioanlly left open
339
            case 'datetime':
340
                $inAdtnl = [
341
                    'type'      => 'text',
342
                    'size'      => 19,
343
                    'maxlength' => 19,
344
                    'name'      => $value['COLUMN_NAME'],
345
                    'id'        => $value['COLUMN_NAME'],
346
                    'value'     => $this->getFieldValue($value),
347
                ];
348
                if (isset($iar)) {
349
                    $inAdtnl = array_merge($inAdtnl, $iar);
350
                }
351
                $input = $this->setStringIntoShortTag('input', $inAdtnl);
352
                if (!isset($iar['readonly'])) {
353
                    $input .= $this->setCalendarControlWithTime($value['COLUMN_NAME']);
354
                }
355
                break;
356
        }
357
        return $input;
358
    }
359
360
    /**
361
     * Returns a Year field 2 use in a form
362
     *
363
     * @param array $details
364
     * @param string $iar
365
     * @return string
366
     */
367
    private function getFieldOutputYear($details, $iar)
368
    {
369
        for ($c = 1901; $c <= 2155; $c++) {
370
            $listOfValues[$c] = $c;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$listOfValues was never initialized. Although not strictly required by PHP, it is generally a good practice to add $listOfValues = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
371
        }
372
        if (is_null($iar)) {
373
            $slDflt  = $this->getFieldValue($details);
374
            $sReturn = $this->setArrayToSelect($listOfValues, $slDflt, $details['COLUMN_NAME'], [
0 ignored issues
show
Bug introduced by
The variable $listOfValues does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
375
                'size' => 1
376
            ]);
377
        } else {
378
            $sReturn = $this->getFieldOutputText('varchar', $details, $iar);
0 ignored issues
show
Documentation introduced by
$details is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
Documentation introduced by
$iar is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
379
        }
380
        return $sReturn;
381
    }
382
383
    /**
384
     * Returns given value for a field from $_REQUEST
385
     *
386
     * @param array $details
387
     * @return string
388
     */
389
    private function getFieldValue($details)
390
    {
391
        $this->initializeSprGlbAndSession();
392
        $rqCN = $this->tCmnRequest->request->get($details['COLUMN_NAME']);
393 View Code Duplication
        if (!is_null($rqCN)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
394
            if (($details['IS_NULLABLE'] == 'YES') && ($rqCN == '')) {
395
                return 'NULL';
396
            }
397
            return $rqCN;
398
        }
399
        return $this->getFieldValueWithoutUserInput($details);
400
    }
401
402
    /**
403
     * Handles field value ignoring any input from the user
404
     *
405
     * @param array $details
406
     * @return string
407
     */
408
    private function getFieldValueWithoutUserInput($details)
409
    {
410 View Code Duplication
        if (is_null($details['COLUMN_DEFAULT'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
411
            if ($details['IS_NULLABLE'] == 'YES') {
412
                return 'NULL';
413
            }
414
            return '';
415
        }
416
        return $details['COLUMN_DEFAULT'];
417
    }
418
419
    /**
420
     * Returns an array with fields referenced by a Foreign key
421
     *
422
     * @param object $db
0 ignored issues
show
Bug introduced by
There is no parameter named $db. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
423
     * @param string $database
424
     * @param string $tblName
425
     * @param string $onlyCols
0 ignored issues
show
Documentation introduced by
There is no parameter named $onlyCols. Did you maybe mean $onlyCol?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function. It has, however, found a similar but not annotated parameter which might be a good fit.

Consider the following example. The parameter $ireland is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $ireland
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was changed, but the annotation was not.

Loading history...
426
     * @return array
427
     */
428
    private function getForeignKeysToArray($database, $tblName, $onlyCol = '')
429
    {
430
        if (strpos($tblName, '.`')) {
431
            $tblName = substr($tblName, strpos($tblName, '.`') + 2, 64);
432
        }
433
        $this->setTableForeginKeyCache($database, $tblName);
434
        $array2return = null;
435
        if (isset($this->advCache['tableFKs'][$database][$tblName])) {
436
            foreach ($this->advCache['tableFKs'][$database][$tblName] as $value) {
437
                if ($value['COLUMN_NAME'] == $onlyCol) {
438
                    $query                  = $this->sQueryMySqlColumns([
0 ignored issues
show
Bug introduced by
It seems like sQueryMySqlColumns() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
439
                        'TABLE_SCHEMA' => $value['REFERENCED_TABLE_SCHEMA'],
440
                        'TABLE_NAME'   => $value['REFERENCED_TABLE_NAME'],
441
                        'DATA_TYPE'    => [
442
                            'char',
443
                            'varchar',
444
                            'text',
445
                        ],
446
                    ]);
447
                    $targetTblTxtFlds       = $this->setMySQLquery2Server($query, 'full_array_key_numbered')['result'];
0 ignored issues
show
Bug introduced by
It seems like setMySQLquery2Server() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
448
                    $significance           = $targetTblTxtFlds[0]['COLUMN_NAME'];
449
                    unset($targetTblTxtFlds);
450
                    $array2return[$onlyCol] = [
451
                        '`' . implode('`.`', [
452
                            $value['REFERENCED_TABLE_SCHEMA'],
453
                            $value['REFERENCED_TABLE_NAME'],
454
                        ]) . '`',
455
                        $value['REFERENCED_COLUMN_NAME'],
456
                        '`' . $significance . '`',
457
                    ];
458
                }
459
            }
460
        }
461
        return $array2return;
462
    }
463
464
    private function getLabel($details)
465
    {
466
        return $this->setStringIntoTag($this->getFieldNameForDisplay($details), 'span', ['class' => 'fake_label']);
467
    }
468
469
    /**
470
     * Returns an array with possible values of a SET or ENUM column
471
     *
472
     * @param string $refTbl
473
     * @param string $refCol
474
     * @return array
475
     */
476
    protected function getSetOrEnum2Array($refTbl, $refCol)
477
    {
478
        if ((strpos($refTbl, '`') !== false) && (substr($refTbl, 0, 1) != '`')) {
479
            $refTbl = '`' . $refTbl . '`';
480
        }
481
        $dat = $this->establishDatabaseAndTable($refTbl);
0 ignored issues
show
Documentation introduced by
$refTbl is of type string, but the function expects a object<danielgp\common_lib\type>.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
482
        foreach ($this->advCache['tableStructureCache'][$dat[0]][$dat[1]] as $value) {
483
            if ($value['COLUMN_NAME'] == $refCol) {
484
                $clndVls = explode(',', str_replace([$value['DATA_TYPE'], '(', "'", ')'], '', $value['COLUMN_TYPE']));
485
                $enmVls  = array_combine($clndVls, $clndVls);
486
                if ($value['IS_NULLABLE'] == 'YES') {
487
                    $enmVls['NULL'] = '';
488
                }
489
            }
490
        }
491
        ksort($enmVls);
492
        return $enmVls;
493
    }
494
495
    /**
496
     * Returns a timestamp field value
497
     *
498
     * @param $details
499
     * @return unknown_type
500
     */
501
    private function getTimestamping($details)
502
    {
503
        $label = $this->getLabel($details);
504
        if (in_array($this->getFieldValue($details), ['', 'CURRENT_TIMESTAMP', 'NULL'])) {
505
            switch ($details['COLUMN_NAME']) {
506
                case 'InsertDateTime':
507
                    $input = $this->setStringIntoTag('data/timpul ad. informatiei', 'span', [
508
                        'style' => 'font-style:italic;'
509
                    ]);
510
                    break;
511
                case 'modification_datetime':
512
                case 'ModificationDateTime':
513
                    $input = $this->setStringIntoTag('data/timpul modificarii inf.', 'span', [
514
                        'style' => 'font-style:italic;'
515
                    ]);
516
                    break;
517
            }
518
        } else {
519
            $input = $this->setStringIntoTag($this->getFieldValue($details), 'span');
520
        }
521
        return ['label' => $label, 'input' => $input];
0 ignored issues
show
Bug introduced by
The variable $input does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
522
    }
523
524
    /**
525
     * Manages features flag
526
     *
527
     * @param string $fieldName
528
     * @param array $features
529
     * @return string
530
     */
531
    private function handleFeatures($fieldName, $features)
532
    {
533
        $iar = null;
534
        if (isset($features['readonly']) && in_array($fieldName, $features['readonly'])) {
535
            $iar = ['readonly' => 'readonly', 'class' => 'input_readonly'];
536
        }
537 View Code Duplication
        if (isset($features['disabled']) && in_array($fieldName, $features['disabled'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
538
            $iar = ['disabled' => 'disabled'];
539
        }
540 View Code Duplication
        if (isset($features['include_null']) && in_array($fieldName, $features['include_null'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
541
            $iar = ['include_null'];
542
        }
543
        return $iar;
544
    }
545
546
    private function handleFeaturesSingle($fieldName, $features)
0 ignored issues
show
Unused Code introduced by
The parameter $fieldName is not used and could be removed.

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

Loading history...
Unused Code introduced by
The parameter $features is not used and could be removed.

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

Loading history...
547
    {
548
549
    }
550
551
    /**
552
     * Returns a generic form based on a given table
553
     *
554
     * @param string $tblSrc Table Source
555
     * @param array $feat
556
     * @param string/array $hiddenInfo List of hidden fields
0 ignored issues
show
Documentation introduced by
The doc-type string/array could not be parsed: Unknown type name "string/array" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
557
     *
558
     * @return string Form to add/modify detail for a single row within a table
559
     */
560
    protected function setFormGenericSingleRecord($tblSrc, $feat, $hiddenInfo = '')
561
    {
562
        echo $this->setStringIntoTag('', 'div', [
563
            'id' => 'loading'
564
        ]); // Ajax container
565
        if (strpos($tblSrc, '.') !== false) {
566
            $tblSrc = explode('.', str_replace('`', '', $tblSrc))[1];
567
        }
568
        $this->setTableCache($tblSrc); // will populate $this->advCache['tableStructureCache'][$dt[0]][$dt[1]]
0 ignored issues
show
Unused Code Comprehensibility introduced by
74% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
569
        if (count($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc]) != 0) {
570
            foreach ($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc] as $value) {
571
                $sReturn[] = $this->setNeededField($tblSrc, $value, $feat);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sReturn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sReturn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
572
            }
573
        }
574
        $btn[]                = $this->setStringIntoShortTag('input', [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$btn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $btn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
575
            'type'  => 'submit',
576
            'id'    => 'submit',
577
            'style' => 'margin-left:220px;',
578
            'value' => $this->lclMsgCmn('i18n_Form_ButtonSave'),
579
        ]);
580
        $adtnlScriptAfterForm = $this->setJavascriptContent(implode('', [
581
            '$(document).ready(function(){',
582
            '$("form#' . $feat['id'] . '").submit(function(){',
583
            '$("input").attr("readonly", true);',
584
            '$("input[type=submit]").attr("disabled", "disabled");',
585
            '$("input[type=submit]").attr("value", "' . $this->lclMsgCmn('i18n_Form_ButtonSaving') . '");',
586
            '});',
587
            '});',
588
        ]));
589
        if (isset($feat['insertAndUpdate'])) {
590
            $btn[] = $this->setStringIntoShortTag('input', [
591
                'type'  => 'hidden',
592
                'id'    => 'insertAndUpdate',
593
                'name'  => 'insertAndUpdate',
594
                'value' => 'insertAndUpdate'
595
            ]);
596
        }
597
        $sReturn[] = $this->setStringIntoTag(implode('', $btn), 'div');
0 ignored issues
show
Bug introduced by
The variable $sReturn does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
598
        if (isset($hiddenInfo)) {
599
            if (is_array($hiddenInfo)) {
600
                foreach ($hiddenInfo as $key => $value) {
601
                    $hiddenInput = $this->setStringIntoShortTag('input', [
602
                        'type'  => 'hidden',
603
                        'name'  => $key,
604
                        'id'    => $key,
605
                        'value' => $value,
606
                    ]);
607
                    $sReturn[]   = $this->setStringIntoTag($hiddenInput, 'div');
608
                }
609
            }
610
        }
611
        return $this->setStringIntoTag(implode('', $sReturn), 'form', [
612
                    'id'     => $feat['id'],
613
                    'action' => $feat['action'],
614
                    'method' => $feat['method']
615
                ])
616
                . $adtnlScriptAfterForm;
617
    }
618
619
    protected function setTableLocaleFields($localizationStrings)
620
    {
621
        $this->advCache['tableStructureLocales'] = $localizationStrings;
622
    }
623
624
    /**
625
     * Analyse the field and returns the proper line 2 use in forms
626
     *
627
     * @param string $tableSource
628
     * @param array $details
629
     * @param array $features
630
     * @return string|array
631
     */
632
    private function setNeededField($tableSource, $details, $features)
0 ignored issues
show
Coding Style introduced by
setNeededField uses the super-global variable $_SERVER which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
setNeededField uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
633
    {
634
        if (isset($features['hidden'])) {
635
            if (in_array($details['COLUMN_NAME'], $features['hidden'])) {
636
                return null;
637
            }
638
        }
639
        $fieldLabel = $this->getFieldNameForDisplay($details);
640
        if ($fieldLabel == 'hidden') {
641
            return null;
642
        }
643
        switch ($details['COLUMN_NAME']) {
644
            case 'host':
645
                $sReturn['label'] = $this->setStringIntoTag('Numele calculatorului', 'label', [
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sReturn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sReturn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
646
                    'for' => $details['COLUMN_NAME']
647
                ]);
648
                $sReturn['input'] = $this->setStringIntoShortTag('input', [
649
                    'type'     => 'input',
650
                    'size'     => 15,
651
                    'readonly' => 'readonly',
652
                    'value'    => gethostbyaddr($_SERVER['REMOTE_ADDR'])
653
                ]);
654
                break;
655
            case 'InsertDateTime':
656
            case 'modification_datetime':
657
            case 'ModificationDateTime':
658
                $sReturn          = call_user_func_array([$this, 'getTimestamping'], [$details]);
659
                break;
660
            default:
661
                $aLabel           = [
662
                    'for' => $details['COLUMN_NAME'],
663
                    'id'  => $details['COLUMN_NAME'] . '_label'
664
                ];
665
                if (isset($features['disabled'])) {
666
                    if (in_array($details['COLUMN_NAME'], $features['disabled'])) {
667
                        $aLabel = array_merge($aLabel, ['style' => 'color: grey;']);
668
                    }
669
                }
670
                $sReturn['label'] = $this->setStringIntoTag($fieldLabel, 'label', $aLabel);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$sReturn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $sReturn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
671
                if ($details['COLUMN_NAME'] == 'ChoiceId') {
672
                    $result = $this->setStringIntoShortTag('input', [
673
                        'type'  => 'text',
674
                        'name'  => $details['COLUMN_NAME'],
675
                        'value' => $_REQUEST[$details['COLUMN_NAME']]
676
                    ]);
677
                } else {
678
                    $result = $this->setNeededFieldByType($tableSource, $details, $features);
679
                }
680
                $sReturn['input'] = $result;
681
                break;
682
        }
683
        $finalReturn[] = $sReturn['label'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$finalReturn was never initialized. Although not strictly required by PHP, it is generally a good practice to add $finalReturn = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
684
        $finalReturn[] = $this->setStringIntoTag($sReturn['input'], 'span', ['class' => 'labell']);
685
        $wrkDb         = $this->advCache['workingDatabase'];
686
        if (isset($this->tableFKsCache[$wrkDb][$tableSource])) {
0 ignored issues
show
Bug introduced by
The property tableFKsCache does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
687
            if (in_array($details['COLUMN_NAME'], $this->advCache['FKcol'][$wrkDb][$tableSource])) {
688
                $finalReturn[] = $this->getFieldLength($details);
0 ignored issues
show
Bug introduced by
It seems like getFieldLength() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
689
            }
690
        }
691
        return $this->setStringIntoTag(implode('', $finalReturn), 'div');
692
    }
693
694
    /**
695
     * Analyse the field type and returns the proper lines 2 use in forms
696
     *
697
     * @param string $tbl_src
698
     * @param array $details
699
     * @param array $features
700
     * @return string/array
0 ignored issues
show
Documentation introduced by
The doc-type string/array could not be parsed: Unknown type name "string/array" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
701
     */
702
    private function setNeededFieldByType($tbl_src, $details, $features)
703
    {
704
        $sReturn = null;
705
        if (isset($features['special']) && isset($features['special'][$details['COLUMN_NAME']])) {
706
            $slctOpt = $this->setQuery2Server($features['special'][$details['COLUMN_NAME']], 'array_key_value');
0 ignored issues
show
Bug introduced by
It seems like setQuery2Server() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
707
            $sReturn = $this->setArrayToSelect($slctOpt, $this->getFieldValue($details), $details['COLUMN_NAME'], [
708
                'size' => 1
709
            ]);
710
        } else {
711
            $iar = $this->handleFeatures($details['COLUMN_NAME'], $features);
712
            switch ($details['DATA_TYPE']) {
713
                case 'bigint':
714
                case 'int':
715
                case 'mediumint':
716
                case 'smallint':
717
                case 'tinyint':
718
                case 'float':
719
                case 'double':
720
                case 'decimal':
721
                case 'numeric':
722
                    $sReturn = $this->getFieldOutputNumeric($tbl_src, $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like $iar defined by $this->handleFeatures($d...LUMN_NAME'], $features) on line 711 can also be of type array<integer,string,{"0":"string"}> or array<string,string,{"disabled":"string"}> or array<string,string,{"re...ing","class":"string"}>; however, danielgp\common_lib\MySQ...getFieldOutputNumeric() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
723
                    break;
724
                case 'char':
725
                case 'tinytext':
726
                case 'varchar':
727
                    $sReturn = $this->getFieldOutputText($tbl_src, $details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like $iar defined by $this->handleFeatures($d...LUMN_NAME'], $features) on line 711 can also be of type array<integer,string,{"0":"string"}> or array<string,string,{"disabled":"string"}> or array<string,string,{"re...ing","class":"string"}>; however, danielgp\common_lib\MySQ...t::getFieldOutputText() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
728
                    break;
729
                case 'date':
730
                    $sReturn = $this->getFieldOutputDate($details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like getFieldOutputDate() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
731
                    break;
732
                case 'datetime':
733
                case 'timestamp':
734
                    $sReturn = $this->getFieldOutputTimestamp($details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like $iar defined by $this->handleFeatures($d...LUMN_NAME'], $features) on line 711 can also be of type array<integer,string,{"0":"string"}> or array<string,string,{"disabled":"string"}> or array<string,string,{"re...ing","class":"string"}>; however, danielgp\common_lib\MySQ...tFieldOutputTimestamp() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
735
                    break;
736
                case 'enum':
737
                case 'set':
738
                    $sReturn = $this->getFieldOutputEnumSet($tbl_src, $details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like $iar defined by $this->handleFeatures($d...LUMN_NAME'], $features) on line 711 can also be of type array<integer,string,{"0":"string"}> or array<string,string,{"disabled":"string"}> or array<string,string,{"re...ing","class":"string"}>; however, danielgp\common_lib\MySQ...getFieldOutputEnumSet() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
739
                    break;
740
                case 'text':
741
                case 'blob':
742
                    $sReturn = $this->getFieldOutputTextLarge($details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like $iar defined by $this->handleFeatures($d...LUMN_NAME'], $features) on line 711 can also be of type array<integer,string,{"0":"string"}> or array<string,string,{"disabled":"string"}> or array<string,string,{"re...ing","class":"string"}>; however, danielgp\common_lib\MySQ...tFieldOutputTextLarge() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
743
                    break;
744
                case 'time':
745
                    $sReturn = $this->getFieldOutputTime($details['DATA_TYPE'], $details, $iar);
0 ignored issues
show
Bug introduced by
It seems like $iar defined by $this->handleFeatures($d...LUMN_NAME'], $features) on line 711 can also be of type array<integer,string,{"0":"string"}> or array<string,string,{"disabled":"string"}> or array<string,string,{"re...ing","class":"string"}>; however, danielgp\common_lib\MySQ...t::getFieldOutputTime() does only seem to accept string|null, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
746
                    break;
747
                case 'year':
748
                    $sReturn = $this->getFieldOutputYear($details, $iar);
0 ignored issues
show
Documentation introduced by
$iar is of type array<string,string,{"re...,string,{"0":"string"}>, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
749
                    break;
750
            }
751
        }
752
        return $this->getFieldCompletionType($details) . $sReturn;
753
    }
754
755
    /**
756
     * create a Cache for given table to use it in many places
757
     *
758
     * @param type $tblSrc
759
     */
760
    private function setTableCache($tblSrc)
761
    {
762
        $dat = $this->establishDatabaseAndTable($tblSrc);
763
        if (!isset($this->advCache['tableStructureCache'][$dat[0]][$dat[1]])) {
764
            switch ($dat[1]) {
765
                case 'user_rights':
766
                    $this->advCache['workingDatabase'] = 'usefull_security';
767
                    break;
768
                default:
769
                    $this->advCache['workingDatabase'] = $dat[0];
770
                    break;
771
            }
772
            $this->advCache['tableStructureCache'][$dat[0]][$dat[1]] = $this->getMySQLlistColumns([
0 ignored issues
show
Bug introduced by
It seems like getMySQLlistColumns() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
773
                'TABLE_SCHEMA' => $dat[0],
774
                'TABLE_NAME'   => $dat[1],
775
            ]);
776
            $this->setTableForeginKeyCache($dat[0], $dat[1]);
777
        }
778
    }
779
780
    private function setTableForeginKeyCache($dbName, $tblName)
781
    {
782
        $frgnKs = $this->getMySQLlistIndexes([
0 ignored issues
show
Bug introduced by
It seems like getMySQLlistIndexes() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
783
            'TABLE_SCHEMA'          => $dbName,
784
            'TABLE_NAME'            => $tblName,
785
            'REFERENCED_TABLE_NAME' => 'NOT NULL',
786
        ]);
787
        if (!is_null($frgnKs)) {
788
            $this->advCache['tableFKs'][$dbName][$tblName] = $frgnKs;
789
            $this->advCache['FKcol'][$dbName][$tblName]    = array_column($frgnKs, 'COLUMN_NAME', 'CONSTRAINT_NAME');
790
        }
791
    }
792
793
    /**
794
     * Automatic handler for Record deletion
795
     *
796
     * @param string $tbl
797
     * @param string $identifier
798
     * @return string
799
     */
800
    protected function setViewModernDelete($tbl, $identifier)
0 ignored issues
show
Coding Style introduced by
setViewModernDelete uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
801
    {
802
        $sReturn = [];
803
        $tMsg    = [
804
            'Confirmation' => $this->lclMsgCmn('i18n_Action_Confirmation'),
805
            'Failed'       => $this->lclMsgCmn('i18n_ActionDelete_Failed'),
806
            'Impossible'   => $this->lclMsgCmn('i18n_ActionDelete_Impossible'),
807
            'Success'      => $this->lclMsgCmn('i18n_ActionDelete_Success'),
808
        ];
809
        if ($tbl == '') {
810
            $sReturn[] = $this->setFeedbackModern('error', $tMsg['Confirmation'], $tMsg['Impossible']);
811
        } else {
812
            $query = $this->sQueryToDeleteSingleIdentifier([
0 ignored issues
show
Bug introduced by
It seems like sQueryToDeleteSingleIdentifier() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
813
                $tbl,
814
                $identifier,
815
                $_REQUEST[$identifier]
816
            ]);
817
            $this->setMySQLquery2Server($query);
0 ignored issues
show
Bug introduced by
It seems like setMySQLquery2Server() must be provided by classes using this trait. How about adding it as abstract method to this trait?

This check looks for methods that are used by a trait but not required by it.

To illustrate, let’s look at the following code example

trait Idable {
    public function equalIds(Idable $other) {
        return $this->getId() === $other->getId();
    }
}

The trait Idable provides a method equalsId that in turn relies on the method getId(). If this method does not exist on a class mixing in this trait, the method will fail.

Adding the getId() as an abstract method to the trait will make sure it is available.

Loading history...
818
            if ($this->mySQLconnection->affected_rows != 0) {
819
                $sReturn[] = $this->setFeedbackModern('check', $tMsg['Confirmation'], $tMsg['Success']);
820
            } else {
821
                $sReturn[] = $this->setFeedbackModern('error', $tMsg['Confirmation'], $tMsg['Failed']);
822
                $sReturn[] = '(' . $this->mySQLconnection->error . ')';
0 ignored issues
show
Bug introduced by
The property mySQLconnection does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
823
            }
824
        }
825
        $finalJavascript = $this->setJavascriptContent(implode('', [
826
            '$("#DeleteFeedback").fadeOut(4000, function() {',
827
            '$(this).remove();',
828
            '});',
829
        ]));
830
        return '<div id="DeleteFeedback">' . implode('', $sReturn) . '</div>' . $finalJavascript;
831
    }
832
}
833