Passed
Push — master ( 580df1...6894ed )
by Daniel
02:27
created

MySQLiAdvancedOutput::getFieldNameForDisplay()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 1
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
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
 * useful functions to get quick results
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiAdvancedOutput
37
{
38
39
    use MySQLiByDanielGPstructures;
40
41
    /**
42
     * Returns a Enum or Set field to use in form
43
     *
44
     * @param string $tblSrc
45
     * @param string $fldType
46
     * @param array $val
47
     * @param array $iar
48
     * @return string
49
     */
50
    private function getFieldOutputEnumSet($tblSrc, $fldType, $val, $iar = [])
51
    {
52
        $adnlThings = $this->establishDefaultEnumSet($fldType);
53
        if (array_key_exists('readonly', $val)) {
54
            return $this->getFieldOutputEnumSetReadOnly($val, $adnlThings);
55
        }
56
        $inAdtnl = $adnlThings['additional'];
57
        if ($iar !== []) {
58
            $inAdtnl = array_merge($inAdtnl, $iar);
59
        }
60
        $vlSlct    = explode(',', $this->getFieldValue($val));
61
        $slctOptns = $this->getSetOrEnum2Array($tblSrc, $val['COLUMN_NAME']);
62
        return $this->setArrayToSelect($slctOptns, $vlSlct, $val['COLUMN_NAME'] . $adnlThings['suffix'], $inAdtnl);
63
    }
64
65
    /**
66
     * Returns a Numeric field 2 use in a form
67
     *
68
     * @param string $tblSrc
69
     * @param array $value
70
     * @param array $iar
71
     * @return string
72
     */
73
    private function getFieldOutputNumeric($tblSrc, $value, $iar = [])
74
    {
75
        if ($value['EXTRA'] == 'auto_increment') {
76
            return $this->getFieldOutputNumericAI($value, $iar);
77
        }
78
        $fkArray = $this->getForeignKeysToArray($this->advCache['workingDatabase'], $tblSrc, $value['COLUMN_NAME']);
79
        if ($fkArray === []) {
80
            $fldNos = $this->setFieldNumbers($value);
81
            return $this->getFieldOutputTT($value, min(50, (array_key_exists('l', $fldNos) ? $fldNos['l'] : 99)), $iar);
82
        }
83
        return $this->getFieldOutputNumericNonFK($fkArray, $value, $iar);
84
    }
85
86
    /**
87
     * Handles creation of Auto Increment numeric field type output
88
     *
89
     * @param array $value
90
     * @param array $iar
91
     * @return string
92
     */
93
    private function getFieldOutputNumericAI($value, $iar = [])
94
    {
95
        if ($this->getFieldValue($value) == '') {
96
            $spF = ['id' => $value['COLUMN_NAME'], 'style' => 'font-style:italic;'];
97
            return $this->setStringIntoTag('auto-numar', 'span', $spF);
98
        }
99
        $inAdtnl = [
100
            'type'  => 'hidden',
101
            'name'  => $value['COLUMN_NAME'],
102
            'id'    => $value['COLUMN_NAME'],
103
            'value' => $this->getFieldValue($value),
104
        ];
105
        if ($iar !== []) {
106
            $inAdtnl = array_merge($inAdtnl, $iar);
107
        }
108
        return '<b>' . $this->getFieldValue($value) . '</b>' . $this->setStringIntoShortTag('input', $inAdtnl);
109
    }
110
111
    /**
112
     * Builds field output type for numeric types if not FK
113
     *
114
     * @param array $fkArray
115
     * @param array $value
116
     * @param array $iar
117
     * @return string
118
     */
119
    private function getFieldOutputNumericNonFK($fkArray, $value, $iar = [])
120
    {
121
        $query         = $this->sQueryGenericSelectKeyValue([
122
            '`' . $value['COLUMN_NAME'] . '`',
123
            $fkArray[$value['COLUMN_NAME']][2],
124
            $fkArray[$value['COLUMN_NAME']][0],
125
        ]);
126
        $selectOptions = $this->setMySQLquery2Server($query, 'array_key_value')['result'];
127
        $selectValue   = $this->getFieldValue($value);
128
        $inAdtnl       = ['size' => 1];
129
        if ($value['IS_NULLABLE'] == 'YES') {
130
            $inAdtnl = array_merge($inAdtnl, ['include_null']);
131
        }
132
        if ($iar !== []) {
133
            $inAdtnl = array_merge($inAdtnl, $iar);
134
        }
135
        return $this->setArrayToSelect($selectOptions, $selectValue, $value['COLUMN_NAME'], $inAdtnl);
136
    }
137
138
    /**
139
     * Returns a Char field 2 use in a form
140
     *
141
     * @param string $tbl
142
     * @param string $fieldType
143
     * @param array $value
144
     * @param array $iar
145
     * @return string
146
     */
147
    private function getFieldOutputText($tbl, $fieldType, $value, $iar = [])
148
    {
149
        if (!in_array($fieldType, ['char', 'tinytext', 'varchar'])) {
150
            return '';
151
        }
152
        $foreignKeysArray = $this->getFieldOutputTextPrerequisites($tbl, $value);
153
        if ($foreignKeysArray !== []) {
154
            return $this->getFieldOutputTextFK($foreignKeysArray, $value, $iar);
155
        }
156
        return $this->getFieldOutputTextNonFK($value, $iar);
157
    }
158
159
    /**
160
     * Returns a Text field 2 use in a form
161
     *
162
     * @param string $fieldType
163
     * @param array $value
164
     * @param array $iar
165
     * @return string
166
     */
167
    protected function getFieldOutputTextLarge($fieldType, $value, $iar = [])
168
    {
169
        if (!in_array($fieldType, ['blob', 'text'])) {
170
            return '';
171
        }
172
        $inAdtnl = [
173
            'name' => $value['COLUMN_NAME'],
174
            'id'   => $value['COLUMN_NAME'],
175
            'rows' => 4,
176
            'cols' => 55,
177
        ];
178
        if ($iar !== []) {
179
            $inAdtnl = array_merge($inAdtnl, $iar);
180
        }
181
        return $this->setStringIntoTag($this->getFieldValue($value), 'textarea', $inAdtnl);
182
    }
183
184
    /**
185
     * Prepares the text output fields
186
     *
187
     * @param string $tbl
188
     * @param array $value
189
     * @return array
190
     */
191
    private function getFieldOutputTextPrerequisites($tbl, $value)
192
    {
193
        $foreignKeysArray = [];
194
        if (($tbl != 'user_rights') && ($value['COLUMN_NAME'] != 'eid')) {
195
            $database = $this->advCache['workingDatabase'];
196
            if (strpos($tbl, '`.`')) {
197
                $database = substr($tbl, 0, strpos($tbl, '`.`'));
198
            }
199
            $foreignKeysArray = $this->getForeignKeysToArray($database, $tbl, $value['COLUMN_NAME']);
200
        }
201
        return $foreignKeysArray;
202
    }
203
204
    /**
205
     * Returns a Timestamp field 2 use in a form
206
     *
207
     * @param array $dtl
208
     * @param array $iar
209
     * @return string
210
     */
211
    private function getFieldOutputTimestamp($dtl, $iar = [])
212
    {
213
        if (($dtl['COLUMN_DEFAULT'] == 'CURRENT_TIMESTAMP') || ($dtl['EXTRA'] == 'on update CURRENT_TIMESTAMP')) {
214
            return $this->getTimestamping($dtl)['input'];
215
        }
216
        $input = $this->getFieldOutputTT($dtl, 19, $iar);
217
        if (!array_key_exists('readonly', $iar)) {
218
            $input .= $this->setCalendarControlWithTime($dtl['COLUMN_NAME']);
219
        }
220
        return $input;
221
    }
222
223
    /**
224
     * Returns a Year field 2 use in a form
225
     *
226
     * @param array $details
227
     * @param array $iar
228
     * @return string
229
     */
230
    private function getFieldOutputYear($tblName, $details, $iar)
231
    {
232
        $listOfValues = [];
233
        for ($cntr = 1901; $cntr <= 2155; $cntr++) {
234
            $listOfValues[$cntr] = $cntr;
235
        }
236
        if ($iar == []) {
237
            $slDflt = $this->getFieldValue($details);
238
            return $this->setArrayToSelect($listOfValues, $slDflt, $details['COLUMN_NAME'], ['size' => 1]);
239
        }
240
        return $this->getFieldOutputText($tblName, 'varchar', $details, $iar);
241
    }
242
243
    /**
244
     * Returns an array with fields referenced by a Foreign key
245
     *
246
     * @param string $database
247
     * @param string $tblName
248
     * @param string|array $oCol Only column(s) considered
249
     * @return array
250
     */
251
    private function getForeignKeysToArray($database, $tblName, $oCol = '')
252
    {
253
        if (!isset($this->advCache['tableFKs'][$database][$tblName])) {
254
            $this->setTableForeignKeyCache($database, $this->fixTableSource($tblName));
255
        }
256
        $aRt = [];
257
        if (isset($this->advCache['tableFKs'][$database][$tblName])) {
258
            $cnm = ['COLUMN_NAME', 'full_array_key_numbered', 'REFERENCED_TABLE_SCHEMA', 'REFERENCED_TABLE_NAME'];
259
            foreach ($this->advCache['tableFKs'][$database][$tblName] as $val) {
260
                if ($val[$cnm[0]] == $oCol) {
261
                    $vlQ        = array_merge($val, ['LIMIT' => 2]);
262
                    $tFd        = $this->setMySQLquery2Server($this->getForeignKeysQuery($vlQ), $cnm[1])['result'];
263
                    $tgtFld     = '`' . ($tFd[0][$cnm[0]] == $val[$cnm[0]] ? $tFd[1][$cnm[0]] : $tFd[0][$cnm[0]]) . '`';
264
                    $aRt[$oCol] = [$this->glueDbTb($val[$cnm[2]], $val[$cnm[3]]), $val[$cnm[2]], $tgtFld];
265
                }
266
            }
267
        }
268
        return $aRt;
269
    }
270
271
    /**
272
     * Returns an array with possible values of a SET or ENUM column
273
     *
274
     * @param string $refTbl
275
     * @param string $refCol
276
     * @return array
277
     */
278
    protected function getSetOrEnum2Array($refTbl, $refCol)
279
    {
280
        $dat = $this->establishDatabaseAndTable($refTbl);
281
        foreach ($this->advCache['tableStructureCache'][$dat[0]][$dat[1]] as $vle) {
282
            if ($vle['COLUMN_NAME'] == $refCol) {
283
                $kVl = explode('\',\'', substr($vle['COLUMN_TYPE'], strlen($vle['DATA_TYPE']) + 2, -2));
284
                $fVl = array_combine($kVl, $kVl);
285
                if ($vle['IS_NULLABLE'] === 'YES') {
286
                    $fVl['NULL'] = '';
287
                }
288
            }
289
        }
290
        ksort($fVl);
291
        return $fVl;
292
    }
293
294
    /**
295
     * Returns a timestamp field value
296
     *
297
     * @param array $dtl
298
     * @return array
299
     */
300
    private function getTimestamping($dtl)
301
    {
302
        $fieldValue = $this->getFieldValue($dtl);
303
        $inM        = $this->setStringIntoTag($fieldValue, 'span');
304
        if (in_array($fieldValue, ['', 'CURRENT_TIMESTAMP', 'NULL'])) {
305
            $mCN = [
306
                'InsertDateTime'        => 'data/timpul ad. informatiei',
307
                'ModificationDateTime'  => 'data/timpul modificarii inf.',
308
                'modification_datetime' => 'data/timpul modificarii inf.',
309
            ];
310
            if (array_key_exists($dtl['COLUMN_NAME'], $mCN)) {
311
                $inM = $this->setStringIntoTag($mCN[$dtl['COLUMN_NAME']], 'span', ['style' => 'font-style:italic;']);
312
            }
313
        }
314
        $lbl = '<span class="fake_label">' . $this->getFieldNameForDisplay($dtl) . '</span>';
315
        return ['label' => $lbl, 'input' => $inM];
316
    }
317
318
    protected function setNeededFieldKnown($tblName, $dtls, $features)
319
    {
320
        $iar      = $this->handleFeatures($dtls['COLUMN_NAME'], $features);
321
        $sReturn  = '';
322
        $numTypes = ['bigint', 'int', 'mediumint', 'smallint', 'tinyint', 'float', 'double', 'decimal', 'numeric'];
323
        if (in_array($dtls['DATA_TYPE'], $numTypes)) {
324
            $sReturn = $this->getFieldOutputNumeric($tblName, $dtls, $iar);
325
        } elseif (in_array($dtls['DATA_TYPE'], ['char', 'tinytext', 'varchar', 'enum', 'set', 'text', 'blob'])) {
326
            $sReturn = $this->setNeededFieldTextRelated($tblName, $dtls, $iar);
327
        } elseif (in_array($dtls['DATA_TYPE'], ['date', 'datetime', 'time', 'timestamp', 'year'])) {
328
            $sReturn = $this->setNeededFieldSingleType($tblName, $dtls, $iar);
329
        }
330
        return $this->getFieldCompletionType($dtls) . $sReturn;
331
    }
332
333
    private function setNeededFieldSingleType($tblName, $dtls, $iar)
334
    {
335
        if ($dtls['DATA_TYPE'] == 'date') {
336
            return $this->getFieldOutputDate($dtls);
337
        } elseif ($dtls['DATA_TYPE'] == 'time') {
338
            return $this->getFieldOutputTime($dtls, $iar);
339
        } elseif (in_array($dtls['DATA_TYPE'], ['datetime', 'timestamp'])) {
340
            return $this->getFieldOutputTimestamp($dtls, $iar);
341
        }
342
        return $this->getFieldOutputYear($tblName, $dtls, $iar);
343
    }
344
345
    /**
346
     *
347
     * @param string $tblName
348
     * @param array $dtls
349
     * @param array $iar
350
     * @return string
351
     */
352
    private function setNeededFieldTextRelated($tblName, $dtls, $iar)
353
    {
354
        if (in_array($dtls['DATA_TYPE'], ['char', 'tinytext', 'varchar'])) {
355
            return $this->getFieldOutputText($tblName, $dtls['DATA_TYPE'], $dtls, $iar);
356
        } elseif (in_array($dtls['DATA_TYPE'], ['text', 'blob'])) {
357
            return $this->getFieldOutputTextLarge($dtls['DATA_TYPE'], $dtls, $iar);
358
        }
359
        return $this->getFieldOutputEnumSet($tblName, $dtls['DATA_TYPE'], $dtls, $iar);
360
    }
361
362
    /**
363
     * create a Cache for given table to use it in many places
364
     *
365
     * @param string $tblSrc
366
     */
367
    protected function setTableCache($tblSrc)
368
    {
369
        $dat = $this->establishDatabaseAndTable($tblSrc);
370
        if (!isset($this->advCache['tableStructureCache'][$dat[0]][$dat[1]])) {
371
            $this->advCache['workingDatabase']                       = $dat[0];
372
            $this->advCache['tableStructureCache'][$dat[0]][$dat[1]] = $this->getMySQLlistColumns([
373
                'TABLE_SCHEMA' => $dat[0],
374
                'TABLE_NAME'   => $dat[1],
375
            ]);
376
            $this->setTableForeignKeyCache($dat[0], $dat[1]);
377
        }
378
    }
379
380
    /**
381
     *
382
     * @param string $dbName
383
     * @param string $tblName
384
     */
385
    private function setTableForeignKeyCache($dbName, $tblName)
386
    {
387
        $frgnKs = $this->getMySQLlistIndexes([
388
            'TABLE_SCHEMA'          => $dbName,
389
            'TABLE_NAME'            => $tblName,
390
            'REFERENCED_TABLE_NAME' => 'NOT NULL',
391
        ]);
392
        if (!is_null($frgnKs)) {
0 ignored issues
show
introduced by
The condition is_null($frgnKs) is always false.
Loading history...
393
            $this->advCache['tableFKs'][$dbName][$tblName] = $frgnKs;
394
            $this->advCache['FKcol'][$dbName][$tblName]    = array_column($frgnKs, 'COLUMN_NAME', 'CONSTRAINT_NAME');
395
        }
396
    }
397
398
}
399