Completed
Push — master ( aaa9e1...ecddc5 )
by Daniel
02:15
created

MySQLiAdvancedOutput::getFieldOutputNumericNonFK()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 18
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

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