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

Mysql::normalizeColumnDefinition()   C

Complexity

Conditions 8
Paths 24

Size

Total Lines 25
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 25
rs 5.3846
c 0
b 0
f 0
cc 8
eloc 20
nc 24
nop 1
1
<?php
2
3
namespace ORM\Dbal;
4
5
use ORM\Exception;
6
7
/**
8
 * Database abstraction for MySQL databases
9
 *
10
 * @package ORM\Dbal
11
 * @author  Thomas Flori <[email protected]>
12
 */
13
class Mysql extends Dbal
14
{
15
    protected static $typeMapping = [
16
        'tinyint' => Type\Integer::class,
17
        'smallint' => Type\Integer::class,
18
        'mediumint' => Type\Integer::class,
19
        'int' => Type\Integer::class,
20
        'bigint' => Type\Integer::class,
21
22
        'decimal' => Type\Double::class,
23
        'float' => Type\Double::class,
24
        'double' => Type\Double::class,
25
26
        'varchar' => Type\VarChar::class,
27
        'char' => Type\VarChar::class,
28
29
        'text' => Type\Text::class,
30
        'tinytext' => Type\Text::class,
31
        'mediumtext' => Type\Text::class,
32
        'longtext' => Type\Text::class,
33
34
        'datetime' => Type\DateTime::class,
35
        'date' => Type\DateTime::class,
36
        'timestamp' => Type\DateTime::class,
37
38
        'time' => Type\Time::class,
39
        'enum' => Type\Enum::class,
40
        'set' => Type\Set::class,
41
        'json' => Type\Json::class,
42
    ];
43
44
    public function insert($entity, $useAutoIncrement = true)
45
    {
46
        $statement = $this->buildInsertStatement($entity);
47
        $pdo = $this->em->getConnection();
48
49
        if ($useAutoIncrement && $entity::isAutoIncremented()) {
50
            $pdo->query($statement);
51
            return $pdo->query("SELECT LAST_INSERT_ID()")->fetchColumn();
1 ignored issue
show
Bug Best Practice introduced by
The return type of return $pdo->query('SELE..._ID()')->fetchColumn(); (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...
52
        }
53
54
        $pdo->query($statement);
55
        $this->em->sync($entity, true);
56
        return true;
57
    }
58
59
    public function describe($table)
60
    {
61
        try {
62
            $result = $this->em->getConnection()->query('DESCRIBE ' . $this->escapeIdentifier($table));
63
        } catch (\PDOException $exception) {
64
            throw new Exception('Unknown table ' . $table, 0, $exception);
65
        }
66
67
        $cols = [];
68
        while ($rawColumn = $result->fetch(\PDO::FETCH_ASSOC)) {
69
            $columnDefinition = $this->normalizeColumnDefinition($rawColumn);
70
            $cols[] = Column::factory($columnDefinition, $this->getType($columnDefinition));
71
        }
72
73
        return $cols;
74
    }
75
76
    /**
77
     * Normalize a column definition
78
     *
79
     * The column definition from "DESCRIBE <table>" is to special as useful. Here we normalize it to a more
80
     * ANSI-SQL style.
81
     *
82
     * @param array $rawColumn
83
     * @return array
84
     */
85
    protected function normalizeColumnDefinition($rawColumn)
86
    {
87
        $definition = [];
88
        $definition['data_type'] = $this->normalizeType($rawColumn['Type']);
89
        $definition['column_name'] = $rawColumn['Field'];
90
        $definition['is_nullable'] = $rawColumn['Null'] === 'YES';
91
        $definition['column_default'] = $rawColumn['Default'] !== null ? $rawColumn['Default'] :
92
            ($rawColumn['Extra'] === 'auto_increment' ? 'sequence(AUTO_INCREMENT)' : null);
93
        $definition['character_maximum_length'] = null;
94
        $definition['datetime_precision'] = null;
95
96
        switch ($definition['data_type']) {
97
            case 'varchar':
98
            case 'char':
99
                $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['Type']);
100
                break;
101
            case 'datetime':
102
            case 'timestamp':
103
            case 'time':
104
                $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['Type']);
105
                break;
106
        }
107
108
        return $definition;
109
    }
110
111
    protected function getType($columnDefinition)
112
    {
113
        if (isset(static::$typeMapping[$columnDefinition['data_type']])) {
114
            return call_user_func([static::$typeMapping[$columnDefinition['data_type']], 'factory'], $columnDefinition);
115
        }
116
117
        return parent::getType($columnDefinition);
118
    }
119
}
120