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

Mysql::normalizeColumnDefinition()   C

Complexity

Conditions 11
Paths 64

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 26
CRAP Score 11

Importance

Changes 0
Metric Value
dl 0
loc 34
ccs 26
cts 26
cp 1
rs 5.2653
c 0
b 0
f 0
cc 11
eloc 26
nc 64
nop 1
crap 11

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 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\Number::class,
17
        'smallint' => Type\Number::class,
18
        'mediumint' => Type\Number::class,
19
        'int' => Type\Number::class,
20
        'bigint' => Type\Number::class,
21
        'decimal' => Type\Number::class,
22
        'float' => Type\Number::class,
23
        'double' => Type\Number::class,
24
25
        'varchar' => Type\VarChar::class,
26
        'char' => Type\VarChar::class,
27
28
        'text' => Type\Text::class,
29
        'tinytext' => Type\Text::class,
30
        'mediumtext' => Type\Text::class,
31
        'longtext' => Type\Text::class,
32
33
        'datetime' => Type\DateTime::class,
34
        'date' => Type\DateTime::class,
35
        'timestamp' => Type\DateTime::class,
36
37
        'time' => Type\Time::class,
38
        'enum' => Type\Enum::class,
39
        'set' => Type\Set::class,
40
        'json' => Type\Json::class,
41
    ];
42
43 5
    public function insert($entity, $useAutoIncrement = true)
44
    {
45 5
        $statement = $this->buildInsertStatement($entity);
46 5
        $pdo = $this->entityManager->getConnection();
47
48 5
        if ($useAutoIncrement && $entity::isAutoIncremented()) {
49 3
            $pdo->query($statement);
50 1
            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...
51
        }
52
53 2
        $pdo->query($statement);
54 2
        $this->entityManager->sync($entity, true);
55 2
        return true;
56
    }
57
58 50
    public function describe($table)
59
    {
60
        try {
61 50
            $result = $this->entityManager->getConnection()->query('DESCRIBE ' . $this->escapeIdentifier($table));
62 1
        } catch (\PDOException $exception) {
63 1
            throw new Exception('Unknown table ' . $table, 0, $exception);
64
        }
65
66 49
        $cols = [];
67 49
        while ($rawColumn = $result->fetch(\PDO::FETCH_ASSOC)) {
68 49
            $cols[] = new Column($this, $this->normalizeColumnDefinition($rawColumn));
69
        }
70
71 49
        return new Table($cols);
72
    }
73
74
    /**
75
     * Normalize a column definition
76
     *
77
     * The column definition from "DESCRIBE <table>" is to special as useful. Here we normalize it to a more
78
     * ANSI-SQL style.
79
     *
80
     * @param array $rawColumn
81
     * @return array
82
     */
83 49
    protected function normalizeColumnDefinition($rawColumn)
84
    {
85 49
        $definition = [];
86
87 49
        $definition['data_type'] = $this->normalizeType($rawColumn['Type']);
88 49
        if (isset(static::$typeMapping[$definition['data_type']])) {
89 44
            $definition['type'] = static::$typeMapping[$definition['data_type']];
90
        }
91
92 49
        $definition['column_name'] = $rawColumn['Field'];
93 49
        $definition['is_nullable'] = $rawColumn['Null'] === 'YES';
94 49
        $definition['column_default'] = $rawColumn['Default'] !== null ? $rawColumn['Default'] :
95 46
            ($rawColumn['Extra'] === 'auto_increment' ? 'sequence(AUTO_INCREMENT)' : null);
96 49
        $definition['character_maximum_length'] = null;
97 49
        $definition['datetime_precision'] = null;
98
99 49
        switch ($definition['data_type']) {
100 49
            case 'varchar':
101 47
            case 'char':
102 4
                $definition['character_maximum_length'] = $this->extractParenthesis($rawColumn['Type']);
103 4
                break;
104 45
            case 'datetime':
105 41
            case 'timestamp':
106 37
            case 'time':
107 12
                $definition['datetime_precision'] = $this->extractParenthesis($rawColumn['Type']);
108 12
                break;
109 33
            case 'set':
110 31
            case 'enum':
111 4
                $definition['enumeration_values'] = $this->extractParenthesis($rawColumn['Type']);
112 4
                break;
113
        }
114
115 49
        return $definition;
116
    }
117
}
118