Completed
Pull Request — master (#36)
by Thomas
02:38
created

Sqlite   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 126
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 100%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 20
lcom 1
cbo 4
dl 0
loc 126
ccs 53
cts 53
cp 1
rs 10
c 2
b 0
f 0

5 Methods

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