Test Failed
Pull Request — master (#36)
by Thomas
02:48
created

Sqlite::normalizeColumnDefinition()   D

Complexity

Conditions 10
Paths 8

Size

Total Lines 29
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 29
rs 4.8196
c 0
b 0
f 0
cc 10
eloc 23
nc 8
nop 2

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\Exception;
6
7
/**
8
 * Database abstraction for SQLite databases
9
 *
10
 * @package ORM\Dbal
11
 * @author  Thomas Flori <[email protected]>
12
 */
13
class Sqlite extends Dbal
14
{
15
    protected static $typeMapping = [
16
        'integer' => Type\Integer::class,
17
        'int' => Type\Integer::class,
18
19
        'double' => Type\Double::class,
20
        'real' => Type\Double::class,
21
        'float' => Type\Double::class,
22
        'numeric' => Type\Double::class,
23
        'decimal' => Type\Double::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
    public function insert($entity, $useAutoIncrement = true)
39
    {
40
        $statement = $this->buildInsertStatement($entity);
41
        $pdo = $this->em->getConnection();
42
43
        if ($useAutoIncrement && $entity::isAutoIncremented()) {
44
            $pdo->query($statement);
45
            return $pdo->lastInsertId();
1 ignored issue
show
Bug Best Practice introduced by
The return type of return $pdo->lastInsertId(); (string) is incompatible with the return type of the parent method ORM\Dbal\Dbal::insert of type boolean.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
46
        }
47
48
        $pdo->query($statement);
49
        $this->em->sync($entity, true);
50
        return true;
51
    }
52
53
    public function describe($schemaTable)
54
    {
55
        $table = explode(static::$identifierDivider, $schemaTable);
56
        list($schema, $table) = count($table) === 2 ? $table : [null, $table[0]];
57
        $schema = $schema !== null ? $this->escapeIdentifier($schema) . '.' : '';
58
59
        $result = $this->em->getConnection()->query(
60
            'PRAGMA ' . $schema . 'table_info(' . $this->escapeIdentifier($table) . ')'
61
        );
62
        $rawColumns = $result->fetchAll(\PDO::FETCH_ASSOC);
63
64
        if (count($rawColumns) === 0) {
65
            throw new Exception('Unknown table '  . $table);
66
        }
67
68
        $hasMultiplePrimaryKey = $this->hasMultiplePrimaryKey($rawColumns);
69
70
        $cols = array_map(function ($rawColumn) use ($hasMultiplePrimaryKey) {
71
            $columnDefinition = $this->normalizeColumnDefinition($rawColumn, $hasMultiplePrimaryKey);
72
            return Column::factory($columnDefinition, $this->getType($columnDefinition));
73
        }, $rawColumns);
74
75
        return $cols;
76
    }
77
78
    /**
79
     * Checks $rawColumns for a multiple primary key
80
     *
81
     * @param array $rawColumns
82
     * @return bool
83
     */
84
    protected function hasMultiplePrimaryKey($rawColumns)
85
    {
86
        return count(array_filter(array_map(function ($rawColumn) {
87
            return $rawColumn['pk'];
88
        }, $rawColumns))) > 1;
89
    }
90
91
    /**
92
     * Normalize a column definition
93
     *
94
     * The column definition from "PRAGMA table_info(<table>)" is to special as useful. Here we normalize it to a more
95
     * ANSI-SQL style.
96
     *
97
     * @param array $rawColumn
98
     * @return array
99
     */
100
    protected function normalizeColumnDefinition($rawColumn, $hasMultiplePrimaryKey = false)
101
    {
102
        $definition = [];
103
        $definition['data_type'] = $this->normalizeType($rawColumn['type']);
104
        $definition['column_name'] = $rawColumn['name'];
105
        $definition['is_nullable'] = $rawColumn['notnull'] === '0';
106
        $definition['column_default'] = $rawColumn['dflt_value'];
107
        $definition['character_maximum_length'] = null;
108
        $definition['datetime_precision'] = null;
109
110
        switch ($definition['data_type']) {
111
            case 'varchar':
112
            case 'char':
113
                $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['type']);
114
                break;
115
            case 'datetime':
116
            case 'timestamp':
117
            case 'time':
118
                $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['type']);
119
                break;
120
            case 'integer':
121
                if (!$definition['column_default'] && $rawColumn['pk'] === '1' && !$hasMultiplePrimaryKey) {
122
                    $definition['column_default'] = 'sequence(rowid)';
123
                }
124
                break;
125
        }
126
127
        return $definition;
128
    }
129
130
    protected function getType($columnDefinition)
131
    {
132
        if (isset(static::$typeMapping[$columnDefinition['data_type']])) {
133
            return call_user_func([static::$typeMapping[$columnDefinition['data_type']], 'factory'], $columnDefinition);
134
        }
135
136
        return parent::getType($columnDefinition);
137
    }
138
}
139