Passed
Push — master ( 050c29...4fa43a )
by Thomas
58s
created

Sqlite::normalizeColumnDefinition()   C

Complexity

Conditions 11
Paths 16

Size

Total Lines 34
Code Lines 25

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 25
CRAP Score 11

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 25
cts 25
cp 1
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 25
nc 16
nop 2
crap 11

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
3
namespace ORM\Dbal;
4
5
use ORM\Entity;
6
use ORM\Exception;
7
8
/**
9
 * Database abstraction for SQLite databases
10
 *
11
 * @package ORM\Dbal
12
 * @author  Thomas Flori <[email protected]>
13
 */
14
class Sqlite extends Dbal
15
{
16
    protected static $typeMapping = [
17
        'integer' => Type\Number::class,
18
        'int'     => Type\Number::class,
19
        'double'  => Type\Number::class,
20
        'real'    => Type\Number::class,
21
        'float'   => Type\Number::class,
22
        'numeric' => Type\Number::class,
23
        'decimal' => Type\Number::class,
24
25
        'varchar'   => Type\VarChar::class,
26
        'character' => Type\VarChar::class,
27
28
        'text' => Type\Text::class,
29
30
        'boolean' => Type\Boolean::class,
31
        'json'    => Type\Json::class,
32
33
        'datetime' => Type\DateTime::class,
34
        'date'     => Type\DateTime::class,
35
        'time'     => Type\Time::class,
36
    ];
37
38 2
    public function insert(Entity $entity, $useAutoIncrement = true)
39
    {
40 2
        $statement = $this->buildInsertStatement($entity);
41 2
        $pdo       = $this->entityManager->getConnection();
42
43 2
        if ($useAutoIncrement && $entity::isAutoIncremented()) {
44 1
            $pdo->query($statement);
45 1
            $this->updateAutoincrement($entity, $pdo->lastInsertId());
46
        } else {
47 1
            $pdo->query($statement);
48
        }
49
50 2
        return $this->entityManager->sync($entity, true);
51
    }
52
53 32
    public function describe($schemaTable)
54
    {
55 32
        $table = explode($this->identifierDivider, $schemaTable);
56 32
        list($schema, $table) = count($table) === 2 ? $table : [ null, $table[ 0 ] ];
57 32
        $schema = $schema !== null ? $this->escapeIdentifier($schema) . '.' : '';
58
59 32
        $result     = $this->entityManager->getConnection()->query(
60 32
            'PRAGMA ' . $schema . 'table_info(' . $this->escapeIdentifier($table) . ')'
61
        );
62 32
        $rawColumns = $result->fetchAll(\PDO::FETCH_ASSOC);
63
64 32
        if (count($rawColumns) === 0) {
65 2
            throw new Exception('Unknown table ' . $table);
66
        }
67
68 30
        $hasMultiplePrimaryKey = $this->hasMultiplePrimaryKey($rawColumns);
69
70
        $cols = array_map(function ($rawColumn) use ($hasMultiplePrimaryKey) {
71 30
            $columnDefinition = $this->normalizeColumnDefinition($rawColumn, $hasMultiplePrimaryKey);
72 30
            return new Column($this, $columnDefinition);
73 30
        }, $rawColumns);
74
75 30
        return new Table($cols);
76
    }
77
78
    /**
79
     * Checks $rawColumns for a multiple primary key
80
     *
81
     * @param array $rawColumns
82
     * @return bool
83
     */
84 30
    protected function hasMultiplePrimaryKey($rawColumns)
85
    {
86 30
        return count(array_filter(array_map(
87 30
            function ($rawColumn) {
88 30
                return $rawColumn[ 'pk' ];
89 30
            },
90
            $rawColumns
91 30
        ))) > 1;
92
    }
93
94
    /**
95
     * Normalize a column definition
96
     *
97
     * The column definition from "PRAGMA table_info(<table>)" is to special as useful. Here we normalize it to a more
98
     * ANSI-SQL style.
99
     *
100
     * @param array $rawColumn
101
     * @param bool  $hasMultiplePrimaryKey
102
     * @return array
103
     */
104 30
    protected function normalizeColumnDefinition($rawColumn, $hasMultiplePrimaryKey = false)
105
    {
106 30
        $definition = [];
107
108 30
        $definition['data_type'] = $this->normalizeType($rawColumn['type']);
109 30
        if (isset(static::$typeMapping[$definition['data_type']])) {
110 29
            $definition['type'] = static::$typeMapping[$definition['data_type']];
111
        }
112
113 30
        $definition['column_name']              = $rawColumn['name'];
114 30
        $definition['is_nullable']              = $rawColumn['notnull'] === '0';
115 30
        $definition['column_default']           = $rawColumn['dflt_value'];
116 30
        $definition['character_maximum_length'] = null;
117 30
        $definition['datetime_precision']       = null;
118
119 30
        switch ($definition['data_type']) {
120 30
            case 'varchar':
121 28
            case 'char':
122 2
                $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['type']);
123 2
                break;
124 28
            case 'datetime':
125 27
            case 'timestamp':
126 27
            case 'time':
127 2
                $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['type']);
128 2
                break;
129 26
            case 'integer':
130 9
                if (!$definition['column_default'] && $rawColumn['pk'] === '1' && !$hasMultiplePrimaryKey) {
131 1
                    $definition['column_default'] = 'sequence(rowid)';
132
                }
133 9
                break;
134
        }
135
136 30
        return $definition;
137
    }
138
}
139