Completed
Push — master ( 0c0c29...3b7e97 )
by Davey
02:25
created

MySQL::getFieldType()   D

Complexity

Conditions 33
Paths 33

Size

Total Lines 44
Code Lines 41

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 762.5449
Metric Value
dl 0
loc 44
ccs 5
cts 40
cp 0.125
rs 4.5202
cc 33
eloc 41
nc 33
nop 1
crap 762.5449

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
namespace {
3
4
    if (!function_exists('\mysql_connect')) {
5
        define('MYSQL_CLIENT_COMPRESS', MYSQLI_CLIENT_COMPRESS);
6
        define('MYSQL_CLIENT_IGNORE_SPACE', MYSQLI_CLIENT_IGNORE_SPACE);
7
        define('MYSQL_CLIENT_INTERACTIVE', MYSQLI_CLIENT_INTERACTIVE);
8
        define('MYSQL_CLIENT_SSL', MYSQLI_CLIENT_SSL);
9
10
        function mysql_connect(
11
            $hostname = null,
12
            $username = null,
13
            $password = null,
14
            $new = false,
15
            $flags = 0
16
        ) {
17 32
            if ($new !== false) {
18 1
                trigger_error('Argument $new is no longer supported in PHP > 7', E_USER_WARNING);
19
            }
20
21 31
            $hash = sha1($hostname . $username . $flags);
22 31
            if ($hostname{1} != ':' && isset(\Dshafik\MySQL::$connections[$hash])) {
23 10
                \Dshafik\MySQL::$last_connection = \Dshafik\MySQL::$connections[$hash]['conn'];
24 10
                \Dshafik\MySQL::$connections[$hash]['refcount'] += 1;
25 10
                return \Dshafik\MySQL::$connections[$hash]['conn'];
26
            }
27
28 22
            if ($flags === 0) {
29 20
                \Dshafik\MySQL::$last_connection = $conn = mysqli_connect($hostname, $username, $password);
30 19
                $conn->hash = $hash;
31 19
                \Dshafik\MySQL::$connections[$hash] = ['refcount' => 1, 'conn' => $conn];
32
33 19
                return $conn;
34
            }
35
36
            try {
37 2
                \Dshafik\MySQL::$last_connection = $conn = mysqli_init();
38
39 2
                mysqli_real_connect(
40
                    $conn,
41
                    $hostname,
42
                    $username,
43
                    $password,
44 2
                    '',
45 2
                    null,
46 2
                    '',
47
                    $flags
48
                );
49
50
                // @codeCoverageIgnoreStart
51
                // PHPUnit turns the warning from mysqli_real_connect into an exception, so this never runs
52
                if ($conn === false) {
53
                    return false;
54
                }
55
                // @codeCoverageIgnoreEnd
56
57 1
                $conn->hash = $hash;
58 1
                \Dshafik\MySQL::$connections[$hash] = ['refcount' => 1, 'conn' => $conn];
59
60 1
                return $conn;
61 1
            } catch (\Throwable $e) {
62 1
                trigger_error($e->getMessage(), E_USER_WARNING);
63
                // @codeCoverageIgnoreStart
64
                // PHPUnit turns the warning into an exception, so this never runs
65
                return false;
66
                // @codeCoverageIgnoreEnd
67
            }
68
        }
69
70
        function mysql_pconnect(
71
            $hostname = null,
72
            $username = null,
73
            $password = null,
74
            $flags = 0
75
        ) {
76 1
            $hostname = 'p:' . $hostname;
77 1
            return mysql_connect($hostname, $username, $password, false, $flags);
78
        }
79
80
        function mysql_close(\mysqli $link = null)
81
        {
82 33
            $isDefault = ($link === null);
83
84 33
            $link = \Dshafik\MySQL::getConnection($link, __FUNCTION__);
85 33
            if ($link === null) {
86
                // @codeCoverageIgnoreStart
87
                // PHPUnit Warning -> Exception
88
                return false;
89
                // @codeCoverageIgnoreEnd
90
            }
91
92 33
            if (isset(\Dshafik\MySQL::$connections[$link->hash])) {
93 29
                \Dshafik\MySQL::$connections[$link->hash]['refcount'] -= 1;
94
            }
95
96 33
            $return = true;
97 33
            if (\Dshafik\MySQL::$connections[$link->hash]['refcount'] == 0) {
98 24
                $return = mysqli_close($link);
99 24
                unset(\Dshafik\MySQL::$connections[$link->hash]);
100
            }
101
102 33
            if ($isDefault) {
103 33
                Dshafik\MySQL::$last_connection = null;
104
            }
105
106 33
            return $return;
107
        }
108
109
        function mysql_select_db($databaseName, \mysqli $link = null)
110
        {
111 18
            $link = \Dshafik\MySQL::getConnection($link);
112
113 18
            return mysqli_query(
114
                $link,
115 18
                "USE " . mysqli_real_escape_string($link, $databaseName)
116 18
            ) !== false;
117
        }
118
119
        function mysql_query($query, \mysqli $link = null)
120
        {
121 26
            return mysqli_query(\Dshafik\MySQL::getConnection($link), $query);
122
        }
123
124
        function mysql_unbuffered_query($query, \mysqli $link = null)
125
        {
126 4
            $link = \Dshafik\MySQL::getConnection($link);
127 4
            if (mysqli_real_query($link, $query)) {
128 3
                return mysqli_use_result($link);
129
            }
130
131 1
            return false;
132
        }
133
134
        function mysql_db_query($databaseName, $query, \mysqli $link = null)
135
        {
136 2
            if (mysql_select_db($databaseName, $link)) {
137 1
                return mysql_query($query, $link);
138
            }
139 1
            return false;
140
        }
141
142
        function mysql_list_dbs(\mysqli $link = null)
143
        {
144 1
            return mysql_query("SHOW DATABASES", $link);
145
        }
146
147
        function mysql_list_tables($databaseName, \mysqli $link = null)
148
        {
149 2
            $link = \Dshafik\MySQL::getConnection($link);
150 2
            return mysql_query("SHOW TABLES FROM " . mysql_real_escape_string($databaseName, $link), $link);
151
        }
152
153
        function mysql_list_fields($databaseName, $tableName, \mysqli $link = null)
154
        {
155 2
            $link = \Dshafik\MySQL::getConnection($link);
156 2
            $result = mysql_query(
157
                "SHOW FULL COLUMNS FROM " .
158 2
                mysqli_real_escape_string($link, $databaseName) . "." .
159 2
                mysqli_real_escape_string($link, $tableName),
160
                $link
161
            );
162 2
            if ($result instanceof \mysqli_result) {
163 2
                $result->table = $tableName;
164
            }
165 2
            return $result;
166
        }
167
168
        function mysql_list_processes(\mysqli $link = null)
169
        {
170
            return mysql_query("SHOW PROCESSLIST", $link);
171
        }
172
173
        function mysql_error(\mysqli $link = null)
174
        {
175 18
            return mysqli_error(\Dshafik\MySQL::getConnection($link));
176
        }
177
178
        function mysql_errno(\mysqli $link = null)
179
        {
180
            return mysqli_errno(\Dshafik\MySQL::getConnection($link));
181
        }
182
183
        function mysql_affected_rows(\mysqli $link = null)
184
        {
185 1
            return mysqli_affected_rows(\Dshafik\MySQL::getConnection($link));
186
        }
187
188
        function mysql_insert_id($link = null) /*|*/
189
        {
190
            return mysqli_insert_id(\Dshafik\MySQL::getConnection($link));
191
        }
192
193
        function mysql_result(\mysqli_result $result, $row, $field = 0)
194
        {
195
            if (!mysqli_data_seek($result, $row)) {
196
                return false;
197
            }
198
199
            if ($row = mysqli_fetch_array($result) === false) {
200
                return false;
201
            }
202
203
            if (isset($row[$field])) {
204
                return $row[$field];
205
            }
206
207
            return false;
208
        }
209
210
        function mysql_num_rows(\mysqli_result $result)
211
        {
212 6
            $previous = error_reporting(0);
213 6
            $rows = mysqli_num_rows($result);
214 6
            error_reporting($previous);
215
216 6
            return $rows;
217
        }
218
219
        function mysql_num_fields($result)
220
        {
221 2
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
222
                return false;
223
            }
224 1
            return mysqli_num_fields($result);
225
        }
226
227
        function mysql_fetch_row($result) /* : array|null */
228
        {
229 4
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
230
                return false;
231
            }
232 4
            return mysqli_fetch_row($result);
233
        }
234
235
        function mysql_fetch_array($result) /* : array|null */
236
        {
237 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
238
                return false;
239
            }
240 1
            return mysqli_fetch_array($result);
241
        }
242
243
        function mysql_fetch_assoc($result) /* : array|null */
244
        {
245 5
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
246
                return false;
247
            }
248 5
            return mysqli_fetch_assoc($result);
249
        }
250
251
        function mysql_fetch_object($result, $class = null, array $params = []) /* : object|null */
252
        {
253 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
254
                return false;
255
            }
256
257 1
            if ($class == null) {
258 1
                return mysqli_fetch_object($result);
259
            }
260
261
            return mysqli_fetch_object($result, $class, $params);
262
        }
263
264
        function mysql_data_seek($result, $offset)
265
        {
266
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
267
                return false;
268
            }
269
            return mysqli_data_seek($result, $offset);
270
        }
271
272
        function mysql_fetch_lengths($result) /* : array|*/
273
        {
274
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
275
                return false;
276
            }
277
            return mysqli_fetch_lengths($result);
278
        }
279
280
        function mysql_fetch_field($result) /* : object|*/
281
        {
282
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
283
                return false;
284
            }
285
            return mysqli_fetch_field($result);
286
        }
287
288
        function mysql_field_seek($result, $field)
289
        {
290
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
291
                return false;
292
            }
293
            return mysqli_field_seek($result, $field);
294
        }
295
296
        function mysql_free_result($result)
297
        {
298 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
299
                return false;
300
            }
301 1
            return mysqli_free_result($result);
302
        }
303
304
        function mysql_field_name($result, $field)
305
        {
306 2
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
307
                return false;
308
            }
309 2
            return \Dshafik\MySQL::mysqlFieldInfo($result, $field, 'name');
310
        }
311
312
        function mysql_field_table($result, $field)
313
        {
314 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
315
                return false;
316
            }
317 1
            return \Dshafik\MySQL::mysqlFieldInfo($result, $field, 'table');
318
        }
319
320
        function mysql_field_len($result, $field)
321
        {
322 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
323
                return false;
324
            }
325 1
            return \Dshafik\MySQL::mysqlFieldInfo($result, $field, 'length');
326
        }
327
328
        function mysql_field_type($result, $field)
329
        {
330 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
331
                return false;
332
            }
333 1
            return \Dshafik\MySQL::mysqlFieldInfo($result, $field, 'type');
334
        }
335
336
        function mysql_field_flags($result, $field)
337
        {
338 1
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
339
                return false;
340
            }
341 1
            return \Dshafik\MySQL::mysqlFieldInfo($result, $field, 'flags');
342
        }
343
344
        function mysql_escape_string($unescapedString)
345
        {
346
            return mysql_real_escape_string($unescapedString, null);
347
        }
348
349
        function mysql_real_escape_string($unescapedString, \mysqli $link = null)
350
        {
351 2
            return mysqli_escape_string(\Dshafik\MySQL::getConnection($link), $unescapedString);
352
        }
353
354
        function mysql_stat(\mysqli $link = null)
355
        {
356
            return mysqli_stat(\Dshafik\MySQL::getConnection($link));
357
        }
358
359
        function mysql_thread_id(\mysqli $link = null)
360
        {
361
            return mysqli_thread_id(\Dshafik\MySQL::getConnection($link));
362
        }
363
364
        function mysql_client_encoding(\mysqli $link = null)
365
        {
366
            return mysqli_character_set_name(\Dshafik\MySQL::getConnection($link));
367
        }
368
369
        function mysql_ping(\mysqli $link = null)
370
        {
371
            return mysqli_ping($link);
372
        }
373
374
        function mysql_get_client_info(\mysqli $link = null)
375
        {
376
            return mysqli_get_client_info(\Dshafik\MySQL::getConnection($link));
377
        }
378
379
        function mysql_get_host_info(\mysqli $link = null)
380
        {
381
            return mysqli_get_host_info(\Dshafik\MySQL::getConnection($link));
382
        }
383
384
        function mysql_get_proto_info(\mysqli $link = null)
385
        {
386
            return mysqli_get_proto_info(\Dshafik\MySQL::getConnection($link));
387
        }
388
389
        function mysql_get_server_info(\mysqli $link = null)
390
        {
391
            return mysqli_get_server_info(\Dshafik\MySQL::getConnection($link));
392
        }
393
394
        function mysql_info(\mysqli $link = null)
395
        {
396
            return mysqli_info(\Dshafik\MySQL::getConnection($link));
397
        }
398
399
        function mysql_set_charset($charset, \mysqli $link = null)
400
        {
401
            return mysqli_set_charset(\Dshafik\MySQL::getConnection($link), $charset);
402
        }
403
404
        function mysql_db_name($result)
405
        {
406
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
407
                return false;
408
            }
409
            return mysqli_fetch_row($result)['Database'];
410
        }
411
412
        function mysql_table_name($result)
413
        {
414
            if (\Dshafik\MySQL::checkValidResult($result, __FUNCTION__)) {
415
                return false;
416
            }
417
            return mysqli_fetch_row($result)['Table'];
418
        }
419
420
        /* Aliases */
421
422
        function mysql_fieldname(... $args)
423
        {
424
            return mysql_field_name(... $args);
1 ignored issue
show
Bug introduced by
The call to mysql_field_name() misses a required argument $field.

This check looks for function calls that miss required arguments.

Loading history...
425
        }
426
427
        function mysql_fieldtable(... $args)
428
        {
429
            return mysql_field_table(... $args);
1 ignored issue
show
Bug introduced by
The call to mysql_field_table() misses a required argument $field.

This check looks for function calls that miss required arguments.

Loading history...
430
        }
431
432
        function mysql_fieldlen(... $args)
433
        {
434
            return mysql_field_len(... $args);
1 ignored issue
show
Bug introduced by
The call to mysql_field_len() misses a required argument $field.

This check looks for function calls that miss required arguments.

Loading history...
435
        }
436
437
        function mysql_fieldtype(... $args)
438
        {
439
            return mysql_field_type(... $args);
1 ignored issue
show
Bug introduced by
The call to mysql_field_type() misses a required argument $field.

This check looks for function calls that miss required arguments.

Loading history...
440
        }
441
442
        function mysql_fieldflags(... $args)
443
        {
444
            return mysql_field_flags(... $args);
445
        }
446
447
        function mysql_selectdb(... $args)
448
        {
449
            return mysql_select_db(... $args);
450
        }
451
452
        function mysql_freeresult(... $args)
453
        {
454
            return mysql_free_result(... $args);
455
        }
456
457
        function mysql_numfields(... $args)
458
        {
459
            return mysql_num_fields(... $args);
460
        }
461
462
        function mysql_numrows(... $args)
463
        {
464
            return mysql_num_rows(... $args);
465
        }
466
467
        function mysql_listdbs(... $args)
468
        {
469
            return mysql_list_dbs(... $args);
470
        }
471
472
        function mysql_listtables(... $args)
473
        {
474
            return mysql_list_tables(... $args);
475
        }
476
477
        function mysql_listfields(... $args)
478
        {
479
            return mysql_list_fields(... $args);
480
        }
481
482
        function mysql_dbname(... $args)
483
        {
484
            return mysql_db_name(... $args);
485
        }
486
487
        function mysql_tablename(... $args)
488
        {
489
            return mysql_table_name(... $args);
490
        }
491
    }
492
}
493
494
namespace Dshafik {
495
496
    class MySQL
497
    {
498
        public static $last_connection = null;
499
        public static $connections = [];
500
501 33
        public static function getConnection($link = null, $func = null)
502
        {
503 33
            if ($link !== null) {
504 7
                return $link;
505
            }
506
507 33
            if (static::$last_connection === null) {
508 4
                $err = "A link to the server could not be established";
509 4
                if ($func !== null) {
510 4
                    $err = $func . "(): no MySQL-Link resource supplied";
511
                }
512 4
                trigger_error($err, E_USER_WARNING);
513 4
                return false;
514
            }
515
516 30
            return static::$last_connection;
517
        }
518
519 2
        public static function mysqlFieldInfo(\mysqli_result $result, $field, $what)
520
        {
521 2
            if (!\mysqli_data_seek($result, $field)) {
522 1
                trigger_error(
523
                    sprintf(
524 1
                        "mysql_field_name(): Field %d is invalid for MySQL result index %s",
525
                        $field,
526
                        spl_object_hash($result)
527
                    ),
528 1
                    E_USER_WARNING
529
                );
530
                // @codeCoverageIgnoreStart
531
                // PHPUnit turns the warning into an exception, so this never runs
532
                return false;
533
                // @codeCoverageIgnoreEnd
534
            }
535
536 1
            $field = \mysql_fetch_assoc($result);
537
538
            switch ($what) {
539 1
                case "name":
540 1
                    return $field['Field'];
541
                case "table":
542 1
                    return $result->table;
543
                case "length":
544
                case "type":
545 1
                    $matches = [];
546 1
                    preg_match("/(?<type>[a-z]+)(?:\((?<length>.+)\))?/", $field['Type'], $matches);
547 1
                    if (!isset($matches[$what])) {
548 1
                        $matches[$what] = null;
549
                    }
550 1
                    if ($what == 'length') {
551 1
                        return static::getFieldLength($matches[$what], $field['Type']);
552
                    }
553 1
                    return static::getFieldType($matches[$what]);
554
                case "flags":
555 1
                    $flags = [];
556 1
                    if ($field['Null'] == "NO") {
557 1
                        $flags[] = "not_null";
558
                    }
559
560 1
                    if ($field['Key'] == 'PRI') {
561 1
                        $flags[] = "primary_key";
562
                    }
563
564 1
                    if (strpos($field['Extra'], "auto_increment") !== false) {
565 1
                        $flags[] = "auto_increment";
566
                    }
567
568 1
                    if ($field['Key'] == 'UNI') {
569 1
                        $flags[] = "unique_key";
570
                    }
571
572 1
                    if ($field['Key'] == 'MUL') {
573 1
                        $flags[] = "multiple_key";
574
                    }
575
576 1
                    $type = strtolower($field['Type']);
577 1
                    if (in_array(substr($type, -4), ["text", "blob"])) {
578 1
                        $flags[] = "blob";
579
                    }
580
581 1
                    if (substr($type, 0, 4) == "enum") {
582 1
                        $flags[] = "enum";
583
                    }
584
585 1
                    if (substr($type, 0, 3) == "set") {
586 1
                        $flags[] = "set";
587
                    }
588
589 1
                    return implode(" ", $flags);
590
            }
591
592
            return false;
593
        }
594
595 15
        public static function checkValidResult($result, $function)
596
        {
597 15
            if (!($result instanceof \mysqli_result)) {
598 1
                trigger_error(
599 1
                    $function . "() expects parameter 1 to be resource, " . gettype($result) . " given",
600 1
                    E_USER_WARNING
601
                );
602
                return false;
603
            }
604 14
        }
605
606 1
        protected static function getFieldLength($what, $type)
607
        {
608 1
            if (is_numeric($what)) {
609 1
                return (int) $what;
610
            }
611
612
            switch ($type) {
613 1
                case "text":
614
                case "blob":
615
                    return 65535;
616
                case "longtext":
617
                case "longblob":
618
                    return 4294967295;
619
                case "tinytext":
620
                case "tinyblob":
621
                    return 255;
622
                case "mediumtext":
623 1
                case "mediumblob":
624 1
                    return 16777215;
625
            }
626
627 1
            if (strtolower(substr($type, 0, 3)) == "set") {
628 1
                return (int)strlen($what)
629 1
                - 2                                         // Remove open and closing quotes
630 1
                - substr_count($what, "'")              // Remove quotes
631 1
                + substr_count($what, "'''")            // Re-add escaped quotes
632
                + (
633 1
                    substr_count(
634 1
                        str_replace("''", "", $what), // Remove escaped quotes
635 1
                        "'"
636
                    )
637 1
                    / 2                                 // We have two quotes per value
638
                )
639 1
                - 1;                                    // But we have one less comma than values
640
            }
641
642 1
            if (strtolower(substr($type, 0, 4) == "enum")) {
643 1
                $values = str_getcsv($what, ",", "'", "'");
644 1
                return (int) max(array_map('strlen', $values));
645
            }
646
        }
647
648 1
        protected static function getFieldType($what)
649
        {
650 1
            switch (strtolower($what)) {
651
                case "char":
652
                case "varchar":
653
                case "binary":
654
                case "varbinary":
655
                case "enum":
656
                case "set":
657 1
                    return "string";
658
                case "text":
659
                case "tinytext":
660
                case "mediumtext":
661
                case "longtext":
662
                case "blob":
663
                case "tinyblob":
664
                case "mediumblob":
665
                case "longblob":
666 1
                    return "blob";
667
                case "integer":
668
                case "bit":
669
                case "int":
670
                case "smallint":
671
                case "tinyint":
672
                case "mediumint":
673
                case "bigint":
674 1
                    return "int";
675
                case "decimal":
676
                case "numeric":
677
                case "float":
678
                case "double":
679
                    return "real";
680
                case "date":
681
                case "time":
682
                case "timestamp":
683
                case "year":
684
                case "datetime":
685
                case "null":
686
                case "geometry":
687
                    return $what;
688
                default:
689
                    return "unknown";
690
            }
691
        }
692
    }
693
}
694