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

Mysql::normalizeColumnDefinition()   C

Complexity

Conditions 8
Paths 24

Size

Total Lines 25
Code Lines 20

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 20
CRAP Score 8

Importance

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