Completed
Push — master ( 2eb9e0...6fec5f )
by Daniel
02:30
created

MySQLiAdvancedOutput::getFieldOutputTime()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 0
Metric Value
c 4
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 2
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 MySQLiByDanielGPstructures;
40
41
    protected $advCache = null;
42
43
    /**
44
     * Establish Database and Table intended to work with
45
     * (in case the DB is ommited get the default one)
46
     *
47
     * @param string $tblSrc
48
     */
49
    private function establishDatabaseAndTable($tblSrc)
50
    {
51
        if (strpos($tblSrc, '.') === false) {
52
            if (!array_key_exists('workingDatabase', $this->advCache)) {
53
                $this->advCache['workingDatabase'] = $this->getMySqlCurrentDatabase();
54
            }
55
            return [$this->advCache['workingDatabase'], $tblSrc];
56
        }
57
        return explode('.', str_replace('`', '', $tblSrc));
58
    }
59
60
    /**
61
     * Establishes the defaults for ENUM or SET field
62
     *
63
     * @param string $fldType
64
     * @return array
65
     */
66
    private function establishDefaultEnumSet($fldType)
67
    {
68
        $dfltArray = [
69
            'enum' => ['additional' => ['size' => 1], 'suffix' => ''],
70
            'set'  => ['additional' => ['size' => 5, 'multiselect'], 'suffix' => '[]'],
71
        ];
72
        return $dfltArray[$fldType];
73
    }
74
75
    /**
76
     * Adjust table name with proper sufix and prefix
77
     *
78
     * @param string $refTbl
79
     * @return string
80
     */
81
    private function fixTableSource($refTbl)
82
    {
83
        $outS = [];
84
        if (substr($refTbl, 0, 1) !== '`') {
85
            $outS[] = '`';
86
        }
87
        $psT = strpos($refTbl, '.`');
88
        if ($psT !== false) {
89
            $refTbl = substr($refTbl, $psT + 2, strlen($refTbl) - $psT);
90
        }
91
        $outS[] = $refTbl;
92
        if (substr($refTbl, -1) !== '`') {
93
            $outS[] = '`';
94
        }
95
        return implode('', $outS);
96
    }
97
98
    /**
99
     * Creates a mask to differentiate between Mandatory and Optional fields
100
     *
101
     * @param array $details
102
     * @return string
103
     */
104
    private function getFieldCompletionType($details)
105
    {
106
        $inputFeatures = ['display' => '***', 'ftrs' => ['title' => 'Mandatory', 'class' => 'inputMandatory']];
107
        if ($details['IS_NULLABLE'] == 'YES') {
108
            $inputFeatures = ['display' => '~', 'ftrs' => ['title' => 'Optional', 'class' => 'inputOptional']];
109
        }
110
        return $this->setStringIntoTag($inputFeatures['display'], 'span', $inputFeatures['ftrs']);
111
    }
112
113
    /**
114
     * Returns the name of a field for displaying
115
     *
116
     * @param array $details
117
     * @return string
118
     */
119
    private function getFieldNameForDisplay($details)
120
    {
121
        $tableUniqueId = $details['TABLE_SCHEMA'] . '.' . $details['TABLE_NAME'];
122
        if ($details['COLUMN_COMMENT'] != '') {
123
            return $details['COLUMN_COMMENT'];
124
        } elseif (isset($this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']])) {
125
            return $this->advCache['tableStructureLocales'][$tableUniqueId][$details['COLUMN_NAME']];
126
        }
127
        return $details['COLUMN_NAME'];
128
    }
129
130
    /**
131
     * Returns a Date field 2 use in a form
132
     *
133
     * @param array $value
134
     * @return string
135
     */
136
    private function getFieldOutputDate($value)
137
    {
138
        $defaultValue = $this->getFieldValue($value);
139
        if (is_null($defaultValue)) {
140
            $defaultValue = date('Y-m-d');
141
        }
142
        $inA = [
143
            'type'      => 'text',
144
            'name'      => $value['Field'],
145
            'id'        => $value['Field'],
146
            'value'     => $defaultValue,
147
            'size'      => 10,
148
            'maxlength' => 10,
149
            'onfocus'   => implode('', [
150
                'javascript:NewCssCal(\'' . $value['Field'],
151
                '\',\'yyyyMMdd\',\'dropdown\',false,\'24\',false);',
152
            ]),
153
        ];
154
        return $this->setStringIntoShortTag('input', $inA) . $this->setCalendarControl($value['Field']);
155
    }
156
157
    /**
158
     * Returns a Enum or Set field to use in form
159
     *
160
     * @param string $tblSrc
161
     * @param string $fldType
162
     * @param array $val
163
     * @param array $iar
164
     * @return string
165
     */
166
    private function getFieldOutputEnumSet($tblSrc, $fldType, $val, $iar = [])
167
    {
168
        $adnlThings = $this->establishDefaultEnumSet($fldType);
169
        if (array_key_exists('readonly', $val)) {
170
            return $this->getFieldOutputEnumSetReadOnly($val, $adnlThings);
171
        }
172
        $inAdtnl = $adnlThings['additional'];
173
        if ($iar !== []) {
174
            $inAdtnl = array_merge($inAdtnl, $iar);
175
        }
176
        $vlSlct    = explode(',', $this->getFieldValue($val));
177
        $slctOptns = $this->getSetOrEnum2Array($tblSrc, $val['COLUMN_NAME']);
178
        return $this->setArrayToSelect($slctOptns, $vlSlct, $val['COLUMN_NAME'] . $adnlThings['suffix'], $inAdtnl);
179
    }
180
181
    /**
182
     * Creats an input for ENUM or SET if marked Read-Only
183
     *
184
     * @param array $val
185
     * @param array $adnlThings
186
     * @return string
187
     */
188
    private function getFieldOutputEnumSetReadOnly($val, $adnlThings)
189
    {
190
        $inputFeatures = [
191
            'name'     => $val['COLUMN_NAME'] . $adnlThings['suffix'],
192
            'id'       => $val['COLUMN_NAME'],
193
            'readonly' => 'readonly',
194
            'class'    => 'input_readonly',
195
            'size'     => 50,
196
            'value'    => $this->getFieldValue($val),
197
        ];
198
        return $this->setStringIntoShortTag('input', $inputFeatures);
199
    }
200
201
    /**
202
     * Returns a Numeric field 2 use in a form
203
     *
204
     * @param string $tblSrc
205
     * @param array $value
206
     * @param array $iar
207
     * @return string
208
     */
209
    private function getFieldOutputNumeric($tblSrc, $value, $iar = [])
210
    {
211
        if ($value['EXTRA'] == 'auto_increment') {
212
            return $this->getFieldOutputNumericAI($value, $iar);
213
        }
214
        $fkArray = $this->getForeignKeysToArray($this->advCache['workingDatabase'], $tblSrc, $value['COLUMN_NAME']);
215
        if (is_null($fkArray)) {
216
            $fldNos = $this->setFieldNumbers($value);
217
            return $this->getFieldOutputTT($value, min(50, $fldNos['l']), $iar);
218
        }
219
        return $this->getFieldOutputNumericNonFK($fkArray, $value, $iar);
220
    }
221
222
    /**
223
     * Handles creation of Auto Increment numeric field type output
224
     *
225
     * @param array $value
226
     * @param array $iar
227
     * @return string
228
     */
229
    private function getFieldOutputNumericAI($value, $iar = [])
230
    {
231
        if ($this->getFieldValue($value) == '') {
232
            $spF = ['id' => $value['COLUMN_NAME'], 'style' => 'font-style:italic;'];
233
            return $this->setStringIntoTag('auto-numar', 'span', $spF);
234
        }
235
        $inAdtnl = [
236
            'type'  => 'hidden',
237
            'name'  => $value['COLUMN_NAME'],
238
            'id'    => $value['COLUMN_NAME'],
239
            'value' => $this->getFieldValue($value),
240
        ];
241
        if ($iar !== []) {
242
            $inAdtnl = array_merge($inAdtnl, $iar);
243
        }
244
        return '<b>' . $this->getFieldValue($value) . '</b>' . $this->setStringIntoShortTag('input', $inAdtnl);
245
    }
246
247
    /**
248
     * Builds field output type for numeric types if not FK
249
     *
250
     * @param array $fkArray
251
     * @param array $value
252
     * @param array $iar
253
     * @return string
254
     */
255
    private function getFieldOutputNumericNonFK($fkArray, $value, $iar = [])
256
    {
257
        $query         = $this->sQueryGenericSelectKeyValue([
258
            $fkArray[$value['COLUMN_NAME']][1],
259
            $fkArray[$value['COLUMN_NAME']][2],
260
            $fkArray[$value['COLUMN_NAME']][0],
261
        ]);
262
        $selectOptions = $this->setMySQLquery2Server($query, 'array_key_value')['result'];
263
        $selectValue   = $this->getFieldValue($value);
264
        $inAdtnl       = ['size' => 1];
265
        if ($value['IS_NULLABLE'] == 'YES') {
266
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
267
        }
268
        if ($iar !== []) {
269
            $inAdtnl = array_merge($inAdtnl, $iar);
270
        }
271
        return $this->setArrayToSelect($selectOptions, $selectValue, $value['COLUMN_NAME'], $inAdtnl);
272
    }
273
274
    /**
275
     * Returns a Char field 2 use in a form
276
     *
277
     * @param string $tbl
278
     * @param string $fieldType
279
     * @param array $value
280
     * @param array $iar
281
     * @return string
282
     */
283
    private function getFieldOutputText($tbl, $fieldType, $value, $iar = [])
284
    {
285
        if (!in_array($fieldType, ['char', 'tinytext', 'varchar'])) {
286
            return '';
287
        }
288
        $foreignKeysArray = $this->getFieldOutputTextPrerequisites($tbl, $value);
289
        if (!is_null($foreignKeysArray)) {
290
            return $this->getFieldOutputTextFK($foreignKeysArray, $value, $iar);
291
        }
292
        return $this->getFieldOutputTextNonFK($value, $iar);
293
    }
294
295
    /**
296
     * Prepares the output of text fields defined w. FKs
297
     *
298
     * @param array $foreignKeysArray
299
     * @param array $value
300
     * @param array $iar
301
     * @return string
302
     */
303
    private function getFieldOutputTextFK($foreignKeysArray, $value, $iar)
304
    {
305
        $query   = $this->sQueryGenericSelectKeyValue([
306
            $foreignKeysArray[$value['COLUMN_NAME']][1],
307
            $foreignKeysArray[$value['COLUMN_NAME']][2],
308
            $foreignKeysArray[$value['COLUMN_NAME']][0]
309
        ]);
310
        echo '<hr/>' . $query . '<hr/>';
311
        $inAdtnl = ['size' => 1];
312
        if ($value['IS_NULLABLE'] == 'YES') {
313
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
314
        }
315
        if ($iar !== []) {
316
            $inAdtnl = array_merge($inAdtnl, $iar);
317
        }
318
        $slct = [
319
            'Options' => $this->setMySQLquery2Server($query, 'array_key_value'),
320
            'Value'   => $this->getFieldValue($value),
321
        ];
322
        return $this->setArrayToSelect($slct['Options'], $slct['Value'], $value['COLUMN_NAME'], $inAdtnl);
0 ignored issues
show
Bug introduced by
It seems like $slct['Options'] can also be of type string; however, danielgp\common_lib\DomC...lGP::setArrayToSelect() does only seem to accept array, 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...
323
    }
324
325
    /**
326
     * Returns a Text field 2 use in a form
327
     *
328
     * @param string $fieldType
329
     * @param array $value
330
     * @param array $iar
331
     * @return string
332
     */
333
    private function getFieldOutputTextLarge($fieldType, $value, $iar = [])
334
    {
335
        if (!in_array($fieldType, ['blob', 'text'])) {
336
            return '';
337
        }
338
        $inAdtnl = [
339
            'name' => $value['COLUMN_NAME'],
340
            'id'   => $value['COLUMN_NAME'],
341
            'rows' => 4,
342
            'cols' => 55,
343
        ];
344
        if ($iar !== []) {
345
            $inAdtnl = array_merge($inAdtnl, $iar);
346
        }
347
        return $this->setStringIntoTag($this->getFieldValue($value), 'textarea', $inAdtnl);
348
    }
349
350
    /**
351
     * Prepares the output of text fields w/o FKs
352
     *
353
     * @param array $value
354
     * @param array $iar
355
     * @return string
356
     */
357
    private function getFieldOutputTextNonFK($value, $iar)
358
    {
359
        $fldNos  = $this->setFieldNumbers($value);
360
        $inAdtnl = [
361
            'type'      => ($value['COLUMN_NAME'] == 'password' ? 'password' : 'text'),
362
            'name'      => $value['COLUMN_NAME'],
363
            'id'        => $value['COLUMN_NAME'],
364
            'size'      => min(30, $fldNos['M']),
365
            'maxlength' => min(255, $fldNos['M']),
366
            'value'     => $this->getFieldValue($value),
367
        ];
368
        if ($iar !== []) {
369
            $inAdtnl = array_merge($inAdtnl, $iar);
370
        }
371
        return $this->setStringIntoShortTag('input', $inAdtnl);
372
    }
373
374
    /**
375
     * Prepares the text output fields
376
     *
377
     * @param string $tbl
378
     * @param array $value
379
     * @return null|array
380
     */
381
    private function getFieldOutputTextPrerequisites($tbl, $value)
382
    {
383
        $foreignKeysArray = null;
384
        if (($tbl != 'user_rights') && ($value['COLUMN_NAME'] != 'eid')) {
385
            $database = $this->advCache['workingDatabase'];
386
            if (strpos($tbl, '`.`')) {
387
                $database = substr($tbl, 0, strpos($tbl, '`.`'));
388
            }
389
            $foreignKeysArray = $this->getForeignKeysToArray($database, $tbl, $value['COLUMN_NAME']);
390
        }
391
        return $foreignKeysArray;
392
    }
393
394
    /**
395
     * Builds output as text input type
396
     *
397
     * @param array $value
398
     * @param integer $szN
399
     * @param array $iar
400
     * @return string
401
     */
402
    private function getFieldOutputTT($value, $szN, $iar = [])
403
    {
404
        $inAdtnl = [
405
            'id'        => $value['COLUMN_NAME'],
406
            'maxlength' => $szN,
407
            'name'      => $value['COLUMN_NAME'],
408
            'size'      => $szN,
409
            'type'      => 'text',
410
            'value'     => $this->getFieldValue($value),
411
        ];
412
        if ($iar !== []) {
413
            $inAdtnl = array_merge($inAdtnl, $iar);
414
        }
415
        return $this->setStringIntoShortTag('input', $inAdtnl);
416
    }
417
418
    /**
419
     * Returns a Time field 2 use in a form
420
     *
421
     * @param array $value
422
     * @param array $iar
423
     * @return string
424
     */
425
    private function getFieldOutputTime($value, $iar = [])
426
    {
427
        return $this->getFieldOutputTT($value, 8, $iar);
428
    }
429
430
    /**
431
     * Returns a Timestamp field 2 use in a form
432
     *
433
     * @param array $dtl
434
     * @param array $iar
435
     * @return string
436
     */
437
    private function getFieldOutputTimestamp($dtl, $iar = [])
438
    {
439
        if (($dtl['COLUMN_DEFAULT'] == 'CURRENT_TIMESTAMP') || ($dtl['EXTRA'] == 'on update CURRENT_TIMESTAMP')) {
440
            return $this->getTimestamping($dtl)['input'];
441
        }
442
        $input = $this->getFieldOutputTT($dtl, 19, $iar);
443
        if (!array_key_exists('readonly', $iar)) {
444
            $input .= $this->setCalendarControlWithTime($dtl['COLUMN_NAME']);
445
        }
446
        return $input;
447
    }
448
449
    /**
450
     * Returns a Year field 2 use in a form
451
     *
452
     * @param array $details
453
     * @param array $iar
454
     * @return string
455
     */
456
    private function getFieldOutputYear($tblName, $details, $iar)
457
    {
458
        $listOfValues = [];
459
        for ($cntr = 1901; $cntr <= 2155; $cntr++) {
460
            $listOfValues[$cntr] = $cntr;
461
        }
462
        if ($iar == []) {
463
            $slDflt = $this->getFieldValue($details);
464
            return $this->setArrayToSelect($listOfValues, $slDflt, $details['COLUMN_NAME'], ['size' => 1]);
465
        }
466
        return $this->getFieldOutputText($tblName, 'varchar', $details, $iar);
467
    }
468
469
    /**
470
     * Returns an array with fields referenced by a Foreign key
471
     *
472
     * @param string $database
473
     * @param string $tblName
474
     * @param string|array $onlyCol
475
     * @return array
476
     */
477
    private function getForeignKeysToArray($database, $tblName, $onlyCol = '')
478
    {
479
        $this->setTableForeginKeyCache($database, $this->fixTableSource($tblName));
480
        $array2return = null;
481
        if (isset($this->advCache['tableFKs'][$database][$tblName])) {
482
            foreach ($this->advCache['tableFKs'][$database][$tblName] as $value) {
483
                if ($value['COLUMN_NAME'] == $onlyCol) {
484
                    $query                  = $this->getForeignKeysQuery($value);
485
                    $targetTblTxtFlds       = $this->setMySQLquery2Server($query, 'full_array_key_numbered')['result'];
486
                    $array2return[$onlyCol] = [
487
                        $this->glueDbTb($value['REFERENCED_TABLE_SCHEMA'], $value['REFERENCED_TABLE_NAME']),
488
                        $value['REFERENCED_COLUMN_NAME'],
489
                        '`' . $targetTblTxtFlds[0]['COLUMN_NAME'] . '`',
490
                    ];
491
                }
492
            }
493
        }
494
        return $array2return;
495
    }
496
497
    /**
498
     * Build label html tag
499
     *
500
     * @param array $details
501
     * @return string
502
     */
503
    private function getLabel($details)
504
    {
505
        return '<span class="fake_label">' . $this->getFieldNameForDisplay($details) . '</span>';
506
    }
507
508
    /**
509
     * Returns an array with possible values of a SET or ENUM column
510
     *
511
     * @param string $refTbl
512
     * @param string $refCol
513
     * @return array
514
     */
515
    protected function getSetOrEnum2Array($refTbl, $refCol)
516
    {
517
        $dat = $this->establishDatabaseAndTable($refTbl);
518
        foreach ($this->advCache['tableStructureCache'][$dat[0]][$dat[1]] as $value) {
519
            if ($value['COLUMN_NAME'] == $refCol) {
520
                $clndVls = explode(',', str_replace([$value['DATA_TYPE'], '(', "'", ')'], '', $value['COLUMN_TYPE']));
521
                $enmVls  = array_combine($clndVls, $clndVls);
522
                if ($value['IS_NULLABLE'] === 'YES') {
523
                    $enmVls['NULL'] = '';
524
                }
525
            }
526
        }
527
        ksort($enmVls);
528
        return $enmVls;
529
    }
530
531
    /**
532
     * Returns a timestamp field value
533
     *
534
     * @param array $dtl
535
     * @return array
536
     */
537
    private function getTimestamping($dtl)
538
    {
539
        $inM = $this->setStringIntoTag($this->getFieldValue($dtl), 'span');
540
        if (in_array($this->getFieldValue($dtl), ['', 'CURRENT_TIMESTAMP', 'NULL'])) {
541
            $mCN = [
542
                'InsertDateTime'        => 'data/timpul ad. informatiei',
543
                'ModificationDateTime'  => 'data/timpul modificarii inf.',
544
                'modification_datetime' => 'data/timpul modificarii inf.',
545
            ];
546
            if (array_key_exists($dtl['COLUMN_NAME'], $mCN)) {
547
                $inM = $this->setStringIntoTag($mCN[$dtl['COLUMN_NAME']], 'span', ['style' => 'font-style:italic;']);
548
            }
549
        }
550
        return ['label' => $this->getLabel($dtl), 'input' => $inM];
551
    }
552
553
    /**
554
     * Glues Database and Table into 1 single string
555
     *
556
     * @param string $dbName
557
     * @param string $tbName
558
     * @return string
559
     */
560
    private function glueDbTb($dbName, $tbName)
561
    {
562
        return '`' . $dbName . '`.`' . $tbName . '`';
563
    }
564
565
    /**
566
     * Manages features flag
567
     *
568
     * @param string $fieldName
569
     * @param array $features
570
     * @return string
571
     */
572
    private function handleFeatures($fieldName, $features)
573
    {
574
        $rOly  = $this->handleFeaturesSingle($fieldName, $features, 'readonly');
575
        $rDbld = $this->handleFeaturesSingle($fieldName, $features, 'disabled');
576
        $rNl   = [];
577
        if (isset($features['include_null']) && in_array($fieldName, $features['include_null'])) {
578
            $rNl = ['include_null'];
579
        }
580
        return array_merge([], $rOly, $rDbld, $rNl);
581
    }
582
583
    /**
584
     * Handles the features
585
     *
586
     * @param string $fieldName
587
     * @param array $features
588
     * @param string $featureKey
589
     * @return array
590
     */
591
    private function handleFeaturesSingle($fieldName, $features, $featureKey)
592
    {
593
        $fMap    = [
594
            'readonly' => ['readonly', 'class', 'input_readonly'],
595
            'disabled' => ['disabled']
596
        ];
597
        $aReturn = [];
598
        if (array_key_exists($featureKey, $features)) {
599
            if (array_key_exists($fieldName, $features[$featureKey])) {
600
                $aReturn[$featureKey][$fMap[$featureKey][0]] = $fMap[$featureKey][0];
601
                if (count($fMap[$featureKey]) > 1) {
602
                    $aReturn[$featureKey][$fMap[$featureKey][1]] = $fMap[$featureKey][2];
603
                }
604
            }
605
        }
606
        return $aReturn;
607
    }
608
609
    /**
610
     * Builds field output w. special column name
611
     *
612
     * @param string $tableSource
613
     * @param array $dtl
614
     * @param array $features
615
     * @param string $fieldLabel
616
     * @return array
617
     */
618
    private function setField($tableSource, $dtl, $features, $fieldLabel)
619
    {
620
        if ($dtl['COLUMN_NAME'] == 'host') {
621
            $inVl = gethostbyaddr($this->tCmnRequest->server->get('REMOTE_ADDR'));
622
            return [
623
                'label' => '<label for="' . $dtl['COLUMN_NAME'] . '">Numele calculatorului</label>',
624
                'input' => '<input type="text" name="host" size="15" readonly value="' . $inVl . '" />',
625
            ];
626
        }
627
        $result = $this->setFieldInput($tableSource, $dtl, $features);
628
        return ['label' => $this->setFieldLabel($dtl, $features, $fieldLabel), 'input' => $result];
629
    }
630
631
    /**
632
     * Builds field output w. another special column name
633
     *
634
     * @param string $tableSource
635
     * @param array $dtl
636
     * @param array $features
637
     * @return string
638
     */
639
    private function setFieldInput($tableSource, $dtl, $features)
640
    {
641
        if ($dtl['COLUMN_NAME'] == 'ChoiceId') {
642
            return '<input type="text" name="ChoiceId" value="'
643
                    . $this->tCmnRequest->request->get($dtl['COLUMN_NAME']) . '" />';
644
        }
645
        return $this->setNeededFieldByType($tableSource, $dtl, $features);
646
    }
647
648
    /**
649
     * Returns a generic form based on a given table
650
     *
651
     * @param string $tblSrc
652
     * @param array $feat
653
     * @param array $hdnInf
654
     *
655
     * @return string Form to add/modify detail for a single row within a table
656
     */
657
    protected function setFormGenericSingleRecord($tblSrc, $feat, $hdnInf = [])
658
    {
659
        echo $this->setStringIntoTag('', 'div', ['id' => 'loading']);
660
        $this->setTableCache($tblSrc);
661
        if (strpos($tblSrc, '.') !== false) {
662
            $tblSrc = explode('.', str_replace('`', '', $tblSrc))[1];
663
        }
664
        $sReturn = [];
665
        if (count($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc]) != 0) {
666
            foreach ($this->advCache['tableStructureCache'][$this->advCache['workingDatabase']][$tblSrc] as $value) {
667
                $sReturn[] = $this->setNeededField($tblSrc, $value, $feat);
668
            }
669
        }
670
        $frmFtrs = ['id' => $feat['id'], 'action' => $feat['action'], 'method' => $feat['method']];
671
        return $this->setStringIntoTag(implode('', $sReturn) . $this->setFormButtons($feat, $hdnInf), 'form', $frmFtrs)
672
                . $this->setFormJavascriptFinal($feat['id']);
673
    }
674
675
    /**
676
     * Analyse the field and returns the proper line 2 use in forms
677
     *
678
     * @param string $tableSource
679
     * @param array $details
680
     * @param array $features
681
     * @return string|array
682
     */
683
    private function setNeededField($tableSource, $details, $features)
684
    {
685
        if (isset($features['hidden'])) {
686
            if (in_array($details['COLUMN_NAME'], $features['hidden'])) {
687
                return null;
688
            }
689
        }
690
        $fieldLabel = $this->getFieldNameForDisplay($details);
691
        if ($fieldLabel == 'hidden') {
692
            return null;
693
        }
694
        return $this->setNeededFieldFinal($tableSource, $details, $features, $fieldLabel);
695
    }
696
697
    /**
698
     * Analyse the field type and returns the proper lines 2 use in forms
699
     *
700
     * @param string $tblName
701
     * @param array $dtls
702
     * @param array $features
703
     * @return string|array
704
     */
705
    private function setNeededFieldByType($tblName, $dtls, $features)
706
    {
707
        if (isset($features['special']) && isset($features['special'][$dtls['COLUMN_NAME']])) {
708
            $sOpt = $this->setMySQLquery2Server($features['special'][$dtls['COLUMN_NAME']], 'array_key_value');
709
            return $this->setArrayToSelect($sOpt, $this->getFieldValue($dtls), $dtls['COLUMN_NAME'], ['size' => 1]);
0 ignored issues
show
Bug introduced by
It seems like $sOpt defined by $this->setMySQLquery2Ser...']], 'array_key_value') on line 708 can also be of type string; however, danielgp\common_lib\DomC...lGP::setArrayToSelect() does only seem to accept array, 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...
710
        }
711
        return $this->setNeededFieldKnown($tblName, $dtls, $features);
712
    }
713
714
    private function setNeededFieldKnown($tblName, $dtls, $features)
715
    {
716
        $iar      = $this->handleFeatures($dtls['COLUMN_NAME'], $features);
717
        $sReturn  = '';
718
        $numTypes = ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'float', 'double', 'decimal', 'numeric'];
719
        if (in_array($dtls['DATA_TYPE'], $numTypes)) {
720
            $sReturn = $this->getFieldOutputNumeric($tblName, $dtls, $iar);
721
        } elseif (in_array($dtls['DATA_TYPE'], ['char', 'tinytext', 'varchar', 'enum', 'set', 'text', 'blob'])) {
722
            $sReturn = $this->setNeededFieldTextRelated($tblName, $dtls, $iar);
723
        } elseif (in_array($dtls['DATA_TYPE'], ['date', 'datetime', 'time', 'timestamp', 'year'])) {
724
            $sReturn = $this->setNeededFieldSingleType($tblName, $dtls, $iar);
725
        }
726
        return $this->getFieldCompletionType($dtls) . $sReturn;
727
    }
728
729
    private function setNeededFieldFinal($tableSource, $details, $features, $fieldLabel)
730
    {
731
        $sReturn = $this->setField($tableSource, $details, $features, $fieldLabel);
732
        $lmts    = $this->setFieldNumbers($details);
733
        return '<div>' . $sReturn['label']
734
                . $this->setStringIntoTag($sReturn['input'], 'span', ['class' => 'labell'])
735
                . '<span style="font-size:x-small;font-style:italic;">&nbsp;(max. '
736
                . $lmts['M'] . (isset($lmts['d']) ? ' w. ' . $lmts['d'] . ' decimals' : '') . ')</span>'
737
                . '</div>';
738
    }
739
740
    private function setNeededFieldSingleType($tblName, $dtls, $iar)
741
    {
742
        if ($dtls['DATA_TYPE'] == 'date') {
743
            return $this->getFieldOutputDate($dtls);
744
        } elseif ($dtls['DATA_TYPE'] == 'time') {
745
            return $this->getFieldOutputTime($dtls, $iar);
746
        } elseif (in_array($dtls['DATA_TYPE'], ['datetime', 'timestamp'])) {
747
            return $this->getFieldOutputTimestamp($dtls, $iar);
748
        }
749
        return $this->getFieldOutputYear($tblName, $dtls, $iar);
750
    }
751
752
    private function setNeededFieldTextRelated($tblName, $dtls, $iar)
753
    {
754
        if (in_array($dtls['DATA_TYPE'], ['char', 'tinytext', 'varchar'])) {
755
            return $this->getFieldOutputText($tblName, $dtls['DATA_TYPE'], $dtls, $iar);
756
        } elseif (in_array($dtls['DATA_TYPE'], ['text', 'blob'])) {
757
            return $this->getFieldOutputTextLarge($dtls['DATA_TYPE'], $dtls, $iar);
758
        }
759
        return $this->getFieldOutputEnumSet($tblName, $dtls['DATA_TYPE'], $dtls, $iar);
760
    }
761
762
    /**
763
     * create a Cache for given table to use it in many places
764
     *
765
     * @param string $tblSrc
766
     */
767
    private function setTableCache($tblSrc)
768
    {
769
        $dat = $this->establishDatabaseAndTable($tblSrc);
770
        if (!isset($this->advCache['tableStructureCache'][$dat[0]][$dat[1]])) {
771
            $this->advCache['workingDatabase']                       = $dat[0];
772
            $this->advCache['tableStructureCache'][$dat[0]][$dat[1]] = $this->getMySQLlistColumns([
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([
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