Completed
Push — master ( 0eeb04...4002ae )
by Oscar
02:31
created

Mysql::getTableFields()   B

Complexity

Conditions 6
Paths 6

Size

Total Lines 40
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 40
rs 8.439
cc 6
eloc 27
nc 6
nop 1
1
<?php
2
3
namespace SimpleCrud\Scheme;
4
5
use PDO;
6
7
/**
8
 * Class to retrieve info from a mysql database.
9
 */
10
class Mysql extends Scheme
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15
    protected function getTables()
16
    {
17
        return $this->db->execute('SHOW TABLES')->fetchAll(PDO::FETCH_COLUMN, 0);
18
    }
19
20
    /**
21
     * {@inheritdoc}
22
     */
23
    protected function getTableFields($table)
24
    {
25
        $result = $this->db->execute("DESCRIBE `{$table}`")->fetchAll(PDO::FETCH_ASSOC);
26
        $fields = [];
27
28
        foreach ($result as $field) {
29
            $name = $field['Field'];
30
31
            preg_match('#^(\w+)(\((.+)\))?( unsigned)?$#', $field['Type'], $matches);
32
33
            $config = [
34
                'type' => $matches[1],
35
                'null' => ($field['Null'] === 'YES'),
36
                'default' => $field['Default'],
37
                'unsigned' => !empty($matches[4]),
38
                'length' => null,
39
                'values' => null,
40
            ];
41
42
            switch ($config['type']) {
43
                case 'enum':
44
                case 'set':
45
                    $config['values'] = explode(',', $matches[3]);
46
                    break;
47
48
                default:
49
                    if (!isset($matches[3])) {
50
                        $config['length'] = null;
51
                    } elseif (strpos($matches[3], ',')) {
52
                        $config['length'] = floatval(str_replace(',', '.', $matches[3]));
53
                    } else {
54
                        $config['length'] = intval($matches[3]);
55
                    }
56
            }
57
58
            $fields[$name] = $config;
59
        }
60
61
        return $fields;
62
    }
63
}
64