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

Sqlite::describe()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 24
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 4

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 24
ccs 14
cts 14
cp 1
rs 8.6845
c 1
b 0
f 0
cc 4
eloc 15
nc 8
nop 1
crap 4
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 2
    public function insert($entity, $useAutoIncrement = true)
39
    {
40 2
        $statement = $this->buildInsertStatement($entity);
41 2
        $pdo = $this->em->getConnection();
42
43 2
        if ($useAutoIncrement && $entity::isAutoIncremented()) {
44 1
            $pdo->query($statement);
45 1
            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 1
        $pdo->query($statement);
49 1
        $this->em->sync($entity, true);
50 1
        return true;
51
    }
52
53 32
    public function describe($schemaTable)
54
    {
55 32
        $table = explode(static::$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->em->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 Column::factory($columnDefinition, $this->getType($columnDefinition));
73 30
        }, $rawColumns);
74
75 30
        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 30
        return count(array_filter(array_map(function ($rawColumn) {
87 30
            return $rawColumn['pk'];
88 30
        }, $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 30
    protected function normalizeColumnDefinition($rawColumn, $hasMultiplePrimaryKey = false)
101
    {
102 30
        $definition = [];
103 30
        $definition['data_type'] = $this->normalizeType($rawColumn['type']);
104 30
        $definition['column_name'] = $rawColumn['name'];
105 30
        $definition['is_nullable'] = $rawColumn['notnull'] === '0';
106 30
        $definition['column_default'] = $rawColumn['dflt_value'];
107 30
        $definition['character_maximum_length'] = null;
108 30
        $definition['datetime_precision'] = null;
109
110 30
        switch ($definition['data_type']) {
111 30
            case 'varchar':
112 28
            case 'char':
113 2
                $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['type']);
114 2
                break;
115 28
            case 'datetime':
116 27
            case 'timestamp':
117 27
            case 'time':
118 2
                $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['type']);
119 2
                break;
120 26
            case 'integer':
121 9
                if (!$definition['column_default'] && $rawColumn['pk'] === '1' && !$hasMultiplePrimaryKey) {
122 1
                    $definition['column_default'] = 'sequence(rowid)';
123
                }
124 9
                break;
125
        }
126
127 30
        return $definition;
128
    }
129
130 30
    protected function getType($columnDefinition)
131
    {
132 30
        if (isset(static::$typeMapping[$columnDefinition['data_type']])) {
133 29
            return call_user_func([static::$typeMapping[$columnDefinition['data_type']], 'factory'], $columnDefinition);
134
        }
135
136 1
        return parent::getType($columnDefinition);
137
    }
138
}
139