Completed
Push — master ( a26bed...c8fc06 )
by Daniel
02:25
created

MySQLiByDanielGP::stFldLmts()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 8
rs 9.4285
cc 2
eloc 5
nc 2
nop 5
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 MySQL content
33
 *
34
 * @author Daniel Popiniuc
35
 */
36
trait MySQLiByDanielGP
37
{
38
39
    use DomComponentsByDanielGP,
40
        MySQLiMultiple,
41
        MySQLiByDanielGPqueries;
42
43
    /**
44
     * Intiates connection to MySQL
45
     *
46
     * @param array $mySQLconfig
47
     *
48
     * $mySQLconfig           = [
49
     * 'host'     => MYSQL_HOST,
50
     * 'port'     => MYSQL_PORT,
51
     * 'username' => MYSQL_USERNAME,
52
     * 'password' => MYSQL_PASSWORD,
53
     * 'database' => MYSQL_DATABASE,
54
     * ];
55
     */
56
    protected function connectToMySql($mySQLconfig)
57
    {
58
        if (is_null($this->mySQLconnection)) {
59
            extract($mySQLconfig);
60
            $this->mySQLconnection = new \mysqli($host, $username, $password, $database, $port);
61
            if (is_null($this->mySQLconnection->connect_error)) {
62
                return '';
63
            }
64
            $erNo                  = $this->mySQLconnection->connect_errno;
65
            $erMsg                 = $this->mySQLconnection->connect_error;
66
            $this->mySQLconnection = null;
67
            $msg                   = $this->lclMsgCmn('i18n_Feedback_ConnectionError');
68
            return sprintf($msg, $erNo, $erMsg, $host, $port, $username, $database);
69
        }
70
    }
71
72
    /**
73
     * returns a list of MySQL databases
74
     *
75
     * @return array
76
     */
77
    protected function getMySQLactiveDatabases()
78
    {
79
        return $this->getMySQLlistDatabases(true);
80
    }
81
82
    /**
83
     * returns a list of active MySQL engines
84
     *
85
     * @return array
86
     */
87
    protected function getMySQLactiveEngines()
88
    {
89
        return $this->getMySQLlistEngines(true);
90
    }
91
92
    /**
93
     * returns the list of all MySQL generic informations
94
     *
95
     * @return array
96
     */
97
    protected function getMySQLgenericInformations()
98
    {
99
        if (is_null($this->mySQLconnection)) {
100
            $line = [];
101
        } else {
102
            $line = [
103
                'Info'    => $this->mySQLconnection->server_info,
104
                'Version' => $this->mySQLconnection->server_version
105
            ];
106
        }
107
        return $line;
108
    }
109
110
    /**
111
     * returns the list of all MySQL global variables
112
     *
113
     * @return array
114
     */
115
    protected function getMySQLglobalVariables()
116
    {
117
        return $this->getMySQLlistMultiple('VariablesGlobal', 'array_key_value');
118
    }
119
120
    /**
121
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
122
     *
123
     * @return array
124
     */
125
    protected function getMySQLlistColumns($filterArray = null)
126
    {
127
        return $this->getMySQLlistMultiple('Columns', 'full_array_key_numbered', $filterArray);
128
    }
129
130
    /**
131
     * returns a list of MySQL databases (w. choice of exclude/include the system ones)
132
     *
133
     * @return array
134
     */
135
    protected function getMySQLlistDatabases($excludeSystemDbs = true)
136
    {
137
        return $this->getMySQLlistMultiple('Databases', 'array_first_key_rest_values', $excludeSystemDbs);
138
    }
139
140
    /**
141
     * returns a list of MySQL engines (w. choice of return only the active ones)
142
     *
143
     * @return array
144
     */
145
    protected function getMySQLlistEngines($onlyActiveOnes = true)
146
    {
147
        return $this->getMySQLlistMultiple('Engines', 'array_first_key_rest_values', $onlyActiveOnes);
148
    }
149
150
    /**
151
     * returns a list of MySQL indexes (w. choice of to choose any combination of db/table/column)
152
     *
153
     * @return array
154
     */
155
    protected function getMySQLlistIndexes($filterArray = null)
156
    {
157
        return $this->getMySQLlistMultiple('Indexes', 'full_array_key_numbered', $filterArray);
158
    }
159
160
    /**
161
     * Return various informations (from predefined list) from the MySQL server
162
     *
163
     * @return string
164
     */
165
    private function getMySQLlistMultiple($returnChoice, $returnType, $additionalFeatures = null)
166
    {
167
        if (is_null($this->mySQLconnection)) {
168
            switch ($returnType) {
169
                case 'value':
170
                    $line = null;
171
                    break;
172
                default:
173
                    $line = [];
174
                    break;
175
            }
176
        } else {
177
            $query = '';
178
            switch ($returnChoice) {
179
                case 'Columns':
180
                    $query = $this->sQueryMySqlColumns($additionalFeatures);
181
                    break;
182
                case 'Databases':
183
                    $query = $this->sQueryMySqlActiveDatabases($additionalFeatures);
184
                    break;
185
                case 'Engines':
186
                    $query = $this->sQueryMySqlActiveEngines($additionalFeatures);
187
                    break;
188
                case 'Indexes':
189
                    $query = $this->sQueryMySqlIndexes($additionalFeatures);
190
                    break;
191
                case 'ServerTime':
192
                    $query = $this->sQueryMySqlServerTime();
193
                    break;
194
                case 'Statistics':
195
                    $query = $this->sQueryMySqlStatistics($additionalFeatures);
196
                    break;
197
                case 'Tables':
198
                    $query = $this->sQueryMySqlTables($additionalFeatures);
199
                    break;
200
                case 'VariablesGlobal':
201
                    $query = $this->sQueryMySqlGlobalVariables();
202
                    break;
203
            }
204
            $line = $this->setMySQLquery2Server($query, $returnType)[
205
                    'result'
206
            ];
207
        }
208
        return $line;
209
    }
210
211
    /**
212
     * Return the list of Tables from the MySQL server
213
     *
214
     * @return string
215
     */
216
    protected function getMySQLStatistics($filterArray = null)
217
    {
218
        return $this->getMySQLlistMultiple('Statistics', 'full_array_key_numbered', $filterArray);
219
    }
220
221
    /**
222
     * Return the list of Tables from the MySQL server
223
     *
224
     * @return string
225
     */
226
    protected function getMySQLlistTables($filterArray = null)
227
    {
228
        return $this->getMySQLlistMultiple('Tables', 'full_array_key_numbered', $filterArray);
229
    }
230
231
    /**
232
     * Returns the Query language type by scanning the 1st keyword from a given query
233
     *
234
     * @param input $sQuery
235
     */
236
    protected function getMySQLqueryType($sQuery)
237
    {
238
        $queryPieces    = explode(' ', $sQuery);
239
        $statementTypes = $this->getMySQLqueryStatementType();
0 ignored issues
show
Bug introduced by
It seems like getMySQLqueryStatementType() 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
        if (in_array($queryPieces[0], array_keys($statementTypes))) {
241
            $type    = $statementTypes[$queryPieces[0]]['Type'];
242
            $sReturn = array_merge([
243
                'detected1stKeywordWithinQuery' => $queryPieces[0],
244
                $type                           => $this->getMySQLqueryLanguageType()[$type],
0 ignored issues
show
Bug introduced by
It seems like getMySQLqueryLanguageType() 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...
245
                    ], $statementTypes[$queryPieces[0]]);
246
        } else {
247
            $sReturn = [
248
                'detected1stKeywordWithinQuery' => $queryPieces[0],
249
                'unknown'                       => [
250
                    'standsFor'   => 'unknown',
251
                    'description' => 'unknown',
252
                ],
253
                'Type'                          => 'unknown',
254
                'Description'                   => 'unknown',
255
            ];
256
        }
257
        return $sReturn;
258
    }
259
260
    /**
261
     * Provides a detection if given Query does contain a Parameter
262
     * that may require statement processing later on
263
     *
264
     * @param string $sQuery
265
     * @param string $paramIdentifier
266
     * @return boolean
267
     */
268
    protected function getMySQLqueryWithParameterIdentifier($sQuery, $paramIdentifier)
269
    {
270
        $sReturn = true;
271
        if (strpos($sQuery, $paramIdentifier) === false) {
272
            $sReturn = false;
273
        }
274
        return $sReturn;
275
    }
276
277
    /**
278
     * Return the time from the MySQL server
279
     *
280
     * @return string
281
     */
282
    protected function getMySQLserverTime()
283
    {
284
        return $this->getMySQLlistMultiple('ServerTime', 'value');
285
    }
286
287
    /**
288
     * Reads data from table into $_REQUEST
289
     *
290
     * @param string $tableName
291
     * @param array $filtersArray
292
     */
293
    protected function getRowDataFromTable($tableName, $filtersArray)
0 ignored issues
show
Coding Style introduced by
getRowDataFromTable 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...
294
    {
295
        $query   = $this->sQueryRowsFromTable([
296
            $tableName,
297
            $this->setArrayToFilterValues($filtersArray),
298
        ]);
299
        $rawData = $this->setMySQLquery2Server($query, 'array_pairs_key_value')['result'];
300
        if (!is_null($rawData)) {
301
            foreach ($rawData as $key => $value) {
302
                $_REQUEST[$key] = str_replace(['\\\\"', '\\"', "\\\\'", "\\'"], ['"', '"', "'", "'"], $value);
303
            }
304
        }
305
    }
306
307
    /**
308
     * Just to keep a list of type of language as array
309
     *
310
     * @return array
311
     */
312
    private static function listOfMySQLqueryLanguageType()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
313
    {
314
        return [
315
            'DCL' => [
316
                'standsFor'   => 'Data Control Language',
317
                'description' => implode(', ', [
318
                    'includes commands such as GRANT',
319
                    'and mostly concerned with rights',
320
                    'permissions and other controls of the database system',
321
                ]),
322
            ],
323
            'DDL' => [
324
                'standsFor'   => 'Data Definition Language',
325
                'description' => implode(', ', [
326
                    'deals with database schemas and descriptions',
327
                    'of how the data should reside in the database',
328
                ]),
329
            ],
330
            'DML' => [
331
                'standsFor'   => 'Data Manipulation Language',
332
                'description' => implode(', ', [
333
                    'deals with data manipulation',
334
                    'and includes most common SQL statements such as SELECT, INSERT, UPDATE, DELETE etc',
335
                    'and it is used to store, modify, retrieve, delete and update data in database',
336
                ]),
337
            ],
338
            'DQL' => [
339
                'standsFor'   => 'Data Query Language',
340
                'description' => 'deals with data/structure retrieval',
341
            ],
342
            'DTL' => [
343
                'standsFor'   => 'Data Transaction Language',
344
                'description' => implode('. ', [
345
                    'statements are used to manage changes made by DML statements',
346
                    'It allows statements to be grouped together into logical transactions',
347
                ]),
348
            ],
349
        ];
350
    }
351
352
    /**
353
     * Just to keep a list of statement types as array
354
     *
355
     * @return array
356
     */
357
    private static function listOfMySQLqueryStatementType()
0 ignored issues
show
Unused Code introduced by
This method is not used, and could be removed.
Loading history...
358
    {
359
        return [
360
            'ALTER'     => [
361
                'Type'        => 'DDL',
362
                'Description' => 'create objects in the database',
363
            ],
364
            'CALL'      => [
365
                'Type'        => 'DML',
366
                'Description' => 'call a stored procedure',
367
            ],
368
            'COMMENT'   => [
369
                'Type'        => 'DDL',
370
                'Description' => 'add comments to the data dictionary',
371
            ],
372
            'COMMIT'    => [
373
                'Type'        => 'DTL',
374
                'Description' => 'sends a signal to MySQL to save all un-commited statements',
375
            ],
376
            'CREATE'    => [
377
                'Type'        => 'DDL',
378
                'Description' => 'create objects within a database',
379
            ],
380
            'DELETE'    => [
381
                'Type'        => 'DML',
382
                'Description' => 'deletes records from a table (all or partial depending on potential conditions)',
383
            ],
384
            'DESC'      => [
385
                'Type'        => 'DML',
386
                'Description' => 'interpretation of the data access path (synonym of EXPLAIN)',
387
            ],
388
            'DESCRIBE'  => [
389
                'type'        => 'DML',
390
                'Description' => 'interpretation of the data access path (synonym of EXPLAIN)',
391
            ],
392
            'DO'        => [
393
                'Type'        => 'DML',
394
                'Description' => 'executes an expression without returning any result',
395
            ],
396
            'DROP'      => [
397
                'Type'        => 'DDL',
398
                'Description' => 'delete objects from a database',
399
            ],
400
            'EXPLAIN'   => [
401
                'Type'        => 'DML',
402
                'Description' => 'interpretation of the data access path',
403
            ],
404
            'GRANT'     => [
405
                'Type'        => 'DCL',
406
                'Description' => 'allow users access privileges to database',
407
            ],
408
            'HANDLER'   => [
409
                'Type'        => 'DML',
410
                'Description' => 'statement provides direct access to table storage engine interfaces',
411
            ],
412
            'HELP'      => [
413
                'Type'        => 'DQL',
414
                'Description' => implode(' ', [
415
                    'The HELP statement returns online information from the MySQL Reference manual.',
416
                    'Its proper operation requires that the help tables in the mysql database',
417
                    'be initialized with help topic information',
418
                ]),
419
            ],
420
            'INSERT'    => [
421
                'Type'        => 'DML',
422
                'Description' => 'insert data into a table',
423
            ],
424
            'LOAD'      => [
425
                'Type'        => 'DML',
426
                'Description' => implode(' ', [
427
                    'The LOAD DATA INFILE statement reads rows from a text file',
428
                    'into a table at a very high speed',
429
                    'or LOAD XML statement reads data from an XML file into a table',
430
                ]),
431
            ],
432
            'LOCK'      => [
433
                'Type'        => 'DML',
434
                'Description' => 'concurrency control',
435
            ],
436
            'MERGE'     => [
437
                'Type'        => 'DML',
438
                'Description' => 'UPSERT operation (insert or update)',
439
            ],
440
            'RELEASE'   => [
441
                'Type'        => 'DTL',
442
                'Description' => implode(' ', [
443
                    'The RELEASE SAVEPOINT statement removes the named savepoint',
444
                    'from the set of savepoints of the current transaction.',
445
                    'No commit or rollback occurs. It is an error if the savepoint does not exist.',
446
                ]),
447
            ],
448
            'RENAME'    => [
449
                'Type'        => 'DDL',
450
                'Description' => 'rename objects from a database',
451
            ],
452
            'REPLACE'   => [
453
                'Type'        => 'DML',
454
                'Description' => implode(' ', [
455
                    'REPLACE works exactly like INSERT, except that if an old row in the table',
456
                    'has the same value as a new row for a PRIMARY KEY or a UNIQUE index,',
457
                    'the old row is deleted before the new row is inserted',
458
                ]),
459
            ],
460
            'REVOKE'    => [
461
                'Type'        => 'DCL',
462
                'description' => 'withdraw users access privileges given by using the GRANT command',
463
            ],
464
            'ROLLBACK'  => [
465
                'Type'        => 'DTL',
466
                'Description' => 'restore database to original since the last COMMIT',
467
            ],
468
            'SELECT'    => [
469
                'Type'        => 'DQL',
470
                'Description' => 'retrieve data from the a database',
471
            ],
472
            'SAVEPOINT' => [
473
                'Type'        => 'DTL',
474
                'Description' => 'identify a point in a transaction to which you can later roll back',
475
            ],
476
            'SET'       => [
477
                'Type'        => 'DTL',
478
                'Description' => 'change values of global/session variables or transaction characteristics',
479
            ],
480
            'SHOW'      => [
481
                'Type'        => 'DQL',
482
                'Description' => implode(' ', [
483
                    'has many forms that provide information about databases, tables, columns,',
484
                    'or status information about the server',
485
                ]),
486
            ],
487
            'START'     => [
488
                'Type'        => 'DTL',
489
                'Description' => 'marks the starting point for a transaction',
490
            ],
491
            'TRUNCATE'  => [
492
                'Type'        => 'DDL',
493
                'Description' => implode(', ', [
494
                    'remove all records from a table',
495
                    'including all spaces allocated for the records are removed'
496
                ]),
497
            ],
498
            'UPDATE'    => [
499
                'Type'        => 'DML',
500
                'Description' => 'updates existing data within a table',
501
            ],
502
            'USE'       => [
503
                'Type'        => 'DML',
504
                'Description' => implode(' ', [
505
                    'The USE db_name statement tells MySQL to use the db_name database',
506
                    'as the default (current) database for subsequent statements.',
507
                ]),
508
            ],
509
        ];
510
    }
511
512
    /**
513
     * Transforms an array into usable filters
514
     *
515
     * @param array $entryArray
516
     * @param string $referenceTable
517
     * @return array
518
     */
519
    private function setArrayToFilterValues($entryArray, $referenceTable = '')
520
    {
521
        $filters = '';
522
        if ($referenceTable != '') {
523
            $referenceTable = '`' . $referenceTable . '`.';
524
        }
525
        foreach ($entryArray as $key => $value) {
526
            if (is_array($value)) {
527
                $filters2 = '';
528
                foreach ($value as $value2) {
529
                    if ($value2 != '') {
530
                        if ($filters2 != '') {
531
                            $filters2 .= ',';
532
                        }
533
                        $filters2 .= '"' . $value2 . '"';
534
                    }
535
                }
536
                if ($filters2 != '') {
537
                    if ($filters != '') {
538
                        $filters .= ' AND ';
539
                    }
540
                    $filters .= ' ' . $referenceTable . '`' . $key
541
                            . '` IN ("' . str_replace(',', '","', str_replace(["'", '"'], '', $filters2))
542
                            . '")';
543
                }
544
            } else {
545
                if (($filters != '') && (!in_array($value, ['', '%%']))) {
546
                    $filters .= ' AND ';
547
                }
548
                if (!in_array($value, ['', '%%'])) {
549
                    if ((substr($value, 0, 1) == '%') && (substr($value, -1) == '%')) {
550
                        $filters .= ' ' . $key . ' LIKE "' . $value . '"';
551
                    } else {
552
                        $filters .= ' ' . $key . ' = "' . $value . '"';
553
                    }
554
                }
555
            }
556
        }
557
        return $filters;
558
    }
559
560
    private function stFldLmts($colType, $loLmt, $upLmt, $szN, $szUS)
561
    {
562
        $aReturn = ['m' => $loLmt, 'M' => $upLmt, 'l' => $szN];
563
        if (strpos($colType, 'unsigned') !== false) {
564
            $aReturn = ['m' => 0, 'M' => ($upLmt - $loLmt), 'l' => $szUS];
565
        }
566
        return $aReturn;
567
    }
568
569
    /**
570
     * Returns maximum length for a given MySQL field
571
     *
572
     * @param string $field_full_type
0 ignored issues
show
Bug introduced by
There is no parameter named $field_full_type. 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...
573
     * @return array
574
     */
575
    protected function setFieldNumbers($fieldDetails, $outputFormated = false)
576
    {
577
        $sRtrn = null;
578
        if ($fieldDetails['DATA_TYPE'] == 'bigint') {
579
            $sRtrn = $this->stFldLmts($fieldDetails['COLUMN_TYPE'], -9223372036854775808, 9223372036854775807, 21, 20);
580
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['char', 'varchar', 'tinytext'])) {
581
            $lgth  = str_replace([$fieldDetails['DATA_TYPE'], '(', ')'], '', $fieldDetails['COLUMN_TYPE']);
582
            $sRtrn = ['l' => $lgth];
583
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['decimal', 'numeric'])) {
584
            $sRtrn = ['l' => $fieldDetails['NUMERIC_PRECISION'], 'd' => $fieldDetails['NUMERIC_SCALE']];
585 View Code Duplication
        } elseif ($fieldDetails['DATA_TYPE'] == 'int') {
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...
586
            $sRtrn = $this->stFldLmts($fieldDetails['COLUMN_TYPE'], -2147483648, 2147483647, 11, 10);
587
        } elseif ($fieldDetails['DATA_TYPE'] == 'mediumint') {
588
            $sRtrn = $this->stFldLmts($fieldDetails['COLUMN_TYPE'], -8388608, 8388607, 9, 8);
589 View Code Duplication
        } elseif ($fieldDetails['DATA_TYPE'] == 'smallint') {
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...
590
            $sRtrn = $this->stFldLmts($fieldDetails['COLUMN_TYPE'], -32768, 32767, 6, 5);
591
        } elseif ($fieldDetails['DATA_TYPE'] == 'tinyint') {
592
            $sRtrn = $this->stFldLmts($fieldDetails['COLUMN_TYPE'], -128, 127, 4, 3);
593
        }
594
        if ($outputFormated) {
595
            if (is_array($sRtrn)) {
596
                foreach ($sRtrn as $key => $value) {
597
                    $sRtrn[$key] = $this->setNumberFormat($value);
598
                }
599
            }
600
        }
601
        return $sRtrn;
602
    }
603
604
    /**
605
     * Transmit Query to MySQL server and get results back
606
     *
607
     * @param string $sQuery
608
     * @param string $sReturnType
609
     * @param array $ftrs
610
     * @return boolean|array|string
611
     */
612
    protected function setMySQLquery2Server($sQuery, $sReturnType = null, $ftrs = null)
613
    {
614
        $aReturn = [
615
            'customError' => '',
616
            'result'      => null
617
        ];
618
        if (is_null($sReturnType)) {
619
            return $this->mySQLconnection->query(html_entity_decode($sQuery));
620
        } elseif (is_null($this->mySQLconnection)) {
621
            $aReturn['customError'] = $this->lclMsgCmn('i18n_MySQL_ConnectionNotExisting');
622
        } else {
623
            $result = $this->mySQLconnection->query(html_entity_decode($sQuery));
624
            if ($result) {
625
                switch (strtolower($sReturnType)) {
626
                    case 'array_first_key_rest_values':
627
                    case 'array_key_value':
628
                    case 'array_key_value2':
629
                    case 'array_key2_value':
630
                    case 'array_numbered':
631
                    case 'array_pairs_key_value':
632 View Code Duplication
                    case 'full_array_key_numbered':
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...
633
                        $aReturn           = $this->setMySQLquery2ServerByPattern([
634
                            'NoOfColumns' => $result->field_count,
635
                            'NoOfRows'    => $result->num_rows,
636
                            'QueryResult' => $result,
637
                            'returnType'  => $sReturnType,
638
                            'return'      => $aReturn
639
                        ]);
640
                        break;
641
                    case 'full_array_key_numbered_with_record_number_prefix':
642 View Code Duplication
                    case 'full_array_key_numbered_with_prefix':
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...
643
                        $aReturn           = $this->setMySQLquery2ServerByPattern([
644
                            'NoOfColumns' => $result->field_count,
645
                            'NoOfRows'    => $result->num_rows,
646
                            'QueryResult' => $result,
647
                            'returnType'  => $sReturnType,
648
                            'prefix'      => $ftrs['prefix'],
649
                            'return'      => $aReturn
650
                        ]);
651
                        break;
652
                    case 'id':
653
                        $aReturn['result'] = $this->mySQLconnection->insert_id;
654
                        break;
655
                    case 'lines':
656
                        $aReturn['result'] = $result->num_rows;
657
                        break;
658
                    case 'value':
659
                        if (($result->num_rows == 1) && ($result->field_count == 1)) {
660
                            $aReturn['result'] = $result->fetch_row()[0];
661
                        } else {
662
                            $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected1ResultedOther');
663
                            $aReturn['customError'] = sprintf($msg, $result->num_rows);
664
                        }
665
                        break;
666
                    default:
667
                        $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryInvalidReturnTypeSpecified');
668
                        $aReturn['customError'] = sprintf($msg, $sReturnType, __FUNCTION__);
669
                        break;
670
                }
671
                if (is_object($result)) {
672
                    $result->close();
673
                }
674
            } else {
675
                $erNo                   = $this->mySQLconnection->errno;
676
                $erMsg                  = $this->mySQLconnection->error;
677
                $aReturn['customError'] = sprintf($this->lclMsgCmn('i18n_MySQL_QueryError'), $erNo, $erMsg);
678
            }
679
        }
680
        return $aReturn;
681
    }
682
683
    /**
684
     * Turns a raw query result into various structures
685
     * based on different predefined $parameters['returnType'] value
686
     *
687
     * @param array $parameters
688
     * @return array as ['customError' => '...', 'result' => '...']
689
     */
690
    protected function setMySQLquery2ServerByPattern($parameters)
691
    {
692
        $aReturn    = $parameters['return'];
693
        $buildArray = false;
694
        switch ($parameters['returnType']) {
695 View Code Duplication
            case 'array_first_key_rest_values':
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...
696
                if ($parameters['NoOfColumns'] >= 2) {
697
                    $buildArray = true;
698
                } else {
699
                    $msg                    = $this->lclMsgCmn('QueryResultExpectedAtLeast2ColsResultedOther');
700
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfColumns']);
701
                }
702
                break;
703
            case 'array_key_value':
704
            case 'array_key_value2':
705 View Code Duplication
            case 'array_key2_value':
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...
706
                if ($parameters['NoOfColumns'] == 2) {
707
                    $buildArray = true;
708
                } else {
709
                    $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected2ColumnsResultedOther');
710
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfColumns']);
711
                }
712
                break;
713 View Code Duplication
            case 'array_numbered':
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...
714
                if ($parameters['NoOfColumns'] == 1) {
715
                    $buildArray = true;
716
                } else {
717
                    $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected1ColumnResultedOther');
718
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfColumns']);
719
                }
720
                break;
721
            case 'array_pairs_key_value':
722
                if (($parameters['NoOfRows'] == 1) && ($parameters['NoOfColumns'] > 1)) {
723
                    $buildArray = true;
724
                } else {
725
                    $shorterLclString       = 'i18n_MySQL_QueryResultExpected1RowManyColumnsResultedOther';
726
                    $msg                    = $this->lclMsgCmn($shorterLclString);
727
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfRows'], $parameters['NoOfColumns']);
728
                }
729
                break;
730
            case 'full_array_key_numbered':
731
            case 'full_array_key_numbered_with_prefix':
732
            case 'full_array_key_numbered_with_record_number_prefix':
733
                if ($parameters['NoOfColumns'] == 0) {
734
                    $aReturn['customError'] = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected1OrMoreRows0Resulted');
735
                    if (in_array($parameters['returnType'], [
736
                                'full_array_key_numbered_with_prefix',
737
                                'full_array_key_numbered_with_record_number_prefix',
738
                            ])) {
739
                        $aReturn['result'][$parameters['prefix']] = null;
740
                    }
741
                } else {
742
                    $buildArray = true;
743
                }
744
                break;
745
            default:
746
                $aReturn['customError'] = $parameters['returnType'] . ' is not defined!';
747
                break;
748
        }
749
        if ($buildArray) {
750
            $counter2 = 0;
751
            for ($counter = 0; $counter < $parameters['NoOfRows']; $counter++) {
752
                $line = $parameters['QueryResult']->fetch_row();
753
                switch ($parameters['returnType']) {
754
                    case 'array_first_key_rest_values':
755
                        $finfo         = $parameters['QueryResult']->fetch_fields();
756
                        $columnCounter = 0;
757
                        foreach ($finfo as $value) {
758
                            if ($columnCounter != 0) {
759
                                $aReturn['result'][$line[0]][$value->name] = $line[$columnCounter];
760
                            }
761
                            $columnCounter++;
762
                        }
763
                        break;
764
                    case 'array_key_value':
765
                        $aReturn['result'][$line[0]]                  = $line[1];
766
                        break;
767
                    case 'array_key_value2':
768
                        $aReturn['result'][$line[0]][]                = $line[1];
769
                        break;
770
                    case 'array_key2_value':
771
                        $aReturn['result'][$line[0] . '@' . $line[1]] = $line[1];
772
                        break;
773
                    case 'array_numbered':
774
                        $aReturn['result'][]                          = $line[0];
775
                        break;
776
                    case 'array_pairs_key_value':
777
                        $finfo                                        = $parameters['QueryResult']->fetch_fields();
778
                        $columnCounter                                = 0;
779
                        foreach ($finfo as $value) {
780
                            $aReturn['result'][$value->name] = $line[$columnCounter];
781
                            $columnCounter++;
782
                        }
783
                        break;
784
                    case 'full_array_key_numbered':
785
                        $finfo         = $parameters['QueryResult']->fetch_fields();
786
                        $columnCounter = 0;
787
                        foreach ($finfo as $value) {
788
                            $aReturn['result'][$counter2][$value->name] = $line[$columnCounter];
789
                            $columnCounter++;
790
                        }
791
                        $counter2++;
792
                        break;
793
                    case 'full_array_key_numbered_with_record_number_prefix':
794
                        $parameters['prefix'] = 'RecordNo';
795
                    // intentionally left open
796
                    case 'full_array_key_numbered_with_prefix':
797
                        $finfo                = $parameters['QueryResult']->fetch_fields();
798
                        $columnCounter        = 0;
799
                        foreach ($finfo as $value) {
800
                            $aReturn['result'][$parameters['prefix']][$counter2][$value->name] = $line[$columnCounter];
801
                            $columnCounter++;
802
                        }
803
                        $counter2++;
804
                        break;
805
                }
806
            }
807
        }
808
        return $aReturn;
809
    }
810
}
811