Completed
Push — master ( 7abd25...aaa9e1 )
by Daniel
03:00
created

MySQLiByDanielGP::getMySQLactiveEngines()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 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
 * 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
    private function stFldLmtsExact($colType)
570
    {
571
        $xct     = [
572
            'bigint'    => ['l' => -9223372036854775808, 'L' => 9223372036854775807, 's' => 21, 'sUS' => 20],
573
            'int'       => ['l' => -2147483648, 'L' => 2147483647, 's' => 11, 'sUS' => 10],
574
            'mediumint' => ['l' => -8388608, 'L' => 8388607, 's' => 9, 'sUS' => 8],
575
            'smallint'  => ['l' => -32768, 'L' => 32767, 's' => 6, 'sUS' => 5],
576
            'tinyint'   => ['l' => -128, 'L' => 127, 's' => 4, 'sUS' => 3],
577
        ];
578
        $sReturn = null;
579
        if (array_key_exists($colType, $xct)) {
580
            $sReturn = $this->stFldLmts($colType, $xct['l'], $xct['L'], $xct['s'], $xct['sUS']);
581
        }
582
        return $sReturn;
583
    }
584
585
    /**
586
     * Returns maximum length for a given MySQL field
587
     *
588
     * @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...
589
     * @return array
590
     */
591
    protected function setFieldNumbers($fieldDetails, $outputFormated = false)
592
    {
593
        $sRtrn = $this->stFldLmtsExact($fieldDetails['COLUMN_TYPE']);
594
        if (in_array($fieldDetails['DATA_TYPE'], ['char', 'varchar', 'tinytext'])) {
595
            $lgth  = str_replace([$fieldDetails['DATA_TYPE'], '(', ')'], '', $fieldDetails['COLUMN_TYPE']);
596
            $sRtrn = ['l' => $lgth];
597
        } elseif (in_array($fieldDetails['DATA_TYPE'], ['decimal', 'numeric'])) {
598
            $sRtrn = ['l' => $fieldDetails['NUMERIC_PRECISION'], 'd' => $fieldDetails['NUMERIC_SCALE']];
599
        }
600
        if ($outputFormated) {
601
            if (is_array($sRtrn)) {
602
                foreach ($sRtrn as $key => $value) {
603
                    $sRtrn[$key] = $this->setNumberFormat($value);
604
                }
605
            }
606
        }
607
        return $sRtrn;
608
    }
609
610
    /**
611
     * Transmit Query to MySQL server and get results back
612
     *
613
     * @param string $sQuery
614
     * @param string $sReturnType
615
     * @param array $ftrs
616
     * @return boolean|array|string
617
     */
618
    protected function setMySQLquery2Server($sQuery, $sReturnType = null, $ftrs = null)
619
    {
620
        $aReturn = [
621
            'customError' => '',
622
            'result'      => null
623
        ];
624
        if (is_null($sReturnType)) {
625
            return $this->mySQLconnection->query(html_entity_decode($sQuery));
626
        } elseif (is_null($this->mySQLconnection)) {
627
            $aReturn['customError'] = $this->lclMsgCmn('i18n_MySQL_ConnectionNotExisting');
628
        } else {
629
            $result = $this->mySQLconnection->query(html_entity_decode($sQuery));
630
            if ($result) {
631
                switch (strtolower($sReturnType)) {
632
                    case 'array_first_key_rest_values':
633
                    case 'array_key_value':
634
                    case 'array_key_value2':
635
                    case 'array_key2_value':
636
                    case 'array_numbered':
637
                    case 'array_pairs_key_value':
638 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...
639
                        $aReturn           = $this->setMySQLquery2ServerByPattern([
640
                            'NoOfColumns' => $result->field_count,
641
                            'NoOfRows'    => $result->num_rows,
642
                            'QueryResult' => $result,
643
                            'returnType'  => $sReturnType,
644
                            'return'      => $aReturn
645
                        ]);
646
                        break;
647
                    case 'full_array_key_numbered_with_record_number_prefix':
648 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...
649
                        $aReturn           = $this->setMySQLquery2ServerByPattern([
650
                            'NoOfColumns' => $result->field_count,
651
                            'NoOfRows'    => $result->num_rows,
652
                            'QueryResult' => $result,
653
                            'returnType'  => $sReturnType,
654
                            'prefix'      => $ftrs['prefix'],
655
                            'return'      => $aReturn
656
                        ]);
657
                        break;
658
                    case 'id':
659
                        $aReturn['result'] = $this->mySQLconnection->insert_id;
660
                        break;
661
                    case 'lines':
662
                        $aReturn['result'] = $result->num_rows;
663
                        break;
664
                    case 'value':
665
                        if (($result->num_rows == 1) && ($result->field_count == 1)) {
666
                            $aReturn['result'] = $result->fetch_row()[0];
667
                        } else {
668
                            $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected1ResultedOther');
669
                            $aReturn['customError'] = sprintf($msg, $result->num_rows);
670
                        }
671
                        break;
672
                    default:
673
                        $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryInvalidReturnTypeSpecified');
674
                        $aReturn['customError'] = sprintf($msg, $sReturnType, __FUNCTION__);
675
                        break;
676
                }
677
                if (is_object($result)) {
678
                    $result->close();
679
                }
680
            } else {
681
                $erNo                   = $this->mySQLconnection->errno;
682
                $erMsg                  = $this->mySQLconnection->error;
683
                $aReturn['customError'] = sprintf($this->lclMsgCmn('i18n_MySQL_QueryError'), $erNo, $erMsg);
684
            }
685
        }
686
        return $aReturn;
687
    }
688
689
    /**
690
     * Turns a raw query result into various structures
691
     * based on different predefined $parameters['returnType'] value
692
     *
693
     * @param array $parameters
694
     * @return array as ['customError' => '...', 'result' => '...']
695
     */
696
    protected function setMySQLquery2ServerByPattern($parameters)
697
    {
698
        $aReturn    = $parameters['return'];
699
        $buildArray = false;
700
        switch ($parameters['returnType']) {
701 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...
702
                if ($parameters['NoOfColumns'] >= 2) {
703
                    $buildArray = true;
704
                } else {
705
                    $msg                    = $this->lclMsgCmn('QueryResultExpectedAtLeast2ColsResultedOther');
706
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfColumns']);
707
                }
708
                break;
709
            case 'array_key_value':
710
            case 'array_key_value2':
711 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...
712
                if ($parameters['NoOfColumns'] == 2) {
713
                    $buildArray = true;
714
                } else {
715
                    $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected2ColumnsResultedOther');
716
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfColumns']);
717
                }
718
                break;
719 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...
720
                if ($parameters['NoOfColumns'] == 1) {
721
                    $buildArray = true;
722
                } else {
723
                    $msg                    = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected1ColumnResultedOther');
724
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfColumns']);
725
                }
726
                break;
727
            case 'array_pairs_key_value':
728
                if (($parameters['NoOfRows'] == 1) && ($parameters['NoOfColumns'] > 1)) {
729
                    $buildArray = true;
730
                } else {
731
                    $shorterLclString       = 'i18n_MySQL_QueryResultExpected1RowManyColumnsResultedOther';
732
                    $msg                    = $this->lclMsgCmn($shorterLclString);
733
                    $aReturn['customError'] = sprintf($msg, $parameters['NoOfRows'], $parameters['NoOfColumns']);
734
                }
735
                break;
736
            case 'full_array_key_numbered':
737
            case 'full_array_key_numbered_with_prefix':
738
            case 'full_array_key_numbered_with_record_number_prefix':
739
                if ($parameters['NoOfColumns'] == 0) {
740
                    $aReturn['customError'] = $this->lclMsgCmn('i18n_MySQL_QueryResultExpected1OrMoreRows0Resulted');
741
                    if (in_array($parameters['returnType'], [
742
                                'full_array_key_numbered_with_prefix',
743
                                'full_array_key_numbered_with_record_number_prefix',
744
                            ])) {
745
                        $aReturn['result'][$parameters['prefix']] = null;
746
                    }
747
                } else {
748
                    $buildArray = true;
749
                }
750
                break;
751
            default:
752
                $aReturn['customError'] = $parameters['returnType'] . ' is not defined!';
753
                break;
754
        }
755
        if ($buildArray) {
756
            $counter2 = 0;
757
            for ($counter = 0; $counter < $parameters['NoOfRows']; $counter++) {
758
                $line = $parameters['QueryResult']->fetch_row();
759
                switch ($parameters['returnType']) {
760
                    case 'array_first_key_rest_values':
761
                        $finfo         = $parameters['QueryResult']->fetch_fields();
762
                        $columnCounter = 0;
763
                        foreach ($finfo as $value) {
764
                            if ($columnCounter != 0) {
765
                                $aReturn['result'][$line[0]][$value->name] = $line[$columnCounter];
766
                            }
767
                            $columnCounter++;
768
                        }
769
                        break;
770
                    case 'array_key_value':
771
                        $aReturn['result'][$line[0]]                  = $line[1];
772
                        break;
773
                    case 'array_key_value2':
774
                        $aReturn['result'][$line[0]][]                = $line[1];
775
                        break;
776
                    case 'array_key2_value':
777
                        $aReturn['result'][$line[0] . '@' . $line[1]] = $line[1];
778
                        break;
779
                    case 'array_numbered':
780
                        $aReturn['result'][]                          = $line[0];
781
                        break;
782
                    case 'array_pairs_key_value':
783
                        $finfo                                        = $parameters['QueryResult']->fetch_fields();
784
                        $columnCounter                                = 0;
785
                        foreach ($finfo as $value) {
786
                            $aReturn['result'][$value->name] = $line[$columnCounter];
787
                            $columnCounter++;
788
                        }
789
                        break;
790
                    case 'full_array_key_numbered':
791
                        $finfo         = $parameters['QueryResult']->fetch_fields();
792
                        $columnCounter = 0;
793
                        foreach ($finfo as $value) {
794
                            $aReturn['result'][$counter2][$value->name] = $line[$columnCounter];
795
                            $columnCounter++;
796
                        }
797
                        $counter2++;
798
                        break;
799
                    case 'full_array_key_numbered_with_record_number_prefix':
800
                        $parameters['prefix'] = 'RecordNo';
801
                    // intentionally left open
802
                    case 'full_array_key_numbered_with_prefix':
803
                        $finfo                = $parameters['QueryResult']->fetch_fields();
804
                        $columnCounter        = 0;
805
                        foreach ($finfo as $value) {
806
                            $aReturn['result'][$parameters['prefix']][$counter2][$value->name] = $line[$columnCounter];
807
                            $columnCounter++;
808
                        }
809
                        $counter2++;
810
                        break;
811
                }
812
            }
813
        }
814
        return $aReturn;
815
    }
816
}
817