Completed
Branch feature/pre-split (1b5228)
by Anton
03:14
created

MySQLColumn::createInstance()   C

Complexity

Conditions 10
Paths 16

Size

Total Lines 57
Code Lines 31

Duplication

Lines 10
Ratio 17.54 %

Importance

Changes 0
Metric Value
cc 10
eloc 31
nc 16
nop 2
dl 10
loc 57
rs 6.7123
c 0
b 0
f 0

How to fix   Long Method    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
 * components
4
 *
5
 * @author    Wolfy-J
6
 */
7
namespace Spiral\Database\Drivers\MySQL\Schemas;
8
9
use Spiral\Database\Entities\Driver;
10
use Spiral\Database\Injections\Fragment;
11
use Spiral\Database\Schemas\Prototypes\AbstractColumn;
12
13
class MySQLColumn extends AbstractColumn
14
{
15
    /**
16
     * Default timestamp expression (driver specific).
17
     */
18
    const DATETIME_CURRENT = 'CURRENT_TIMESTAMP';
19
20
    /**
21
     * {@inheritdoc}
22
     */
23
    protected $mapping = [
24
        //Primary sequences
25
        'primary'     => [
26
            'type'          => 'int',
27
            'size'          => 11,
28
            'autoIncrement' => true,
29
            'nullable'      => false,
30
        ],
31
        'bigPrimary'  => [
32
            'type'          => 'bigint',
33
            'size'          => 20,
34
            'autoIncrement' => true,
35
            'nullable'      => false,
36
        ],
37
38
        //Enum type (mapped via method)
39
        'enum'        => 'enum',
40
41
        //Logical types
42
        'boolean'     => ['type' => 'tinyint', 'size' => 1],
43
44
        //Integer types (size can always be changed with size method), longInteger has method alias
45
        //bigInteger
46
        'integer'     => ['type' => 'int', 'size' => 11],
47
        'tinyInteger' => ['type' => 'tinyint', 'size' => 4],
48
        'bigInteger'  => ['type' => 'bigint', 'size' => 20],
49
50
        //String with specified length (mapped via method)
51
        'string'      => 'varchar',
52
53
        //Generic types
54
        'text'        => 'text',
55
        'tinyText'    => 'tinytext',
56
        'longText'    => 'longtext',
57
58
        //Real types
59
        'double'      => 'double',
60
        'float'       => 'float',
61
62
        //Decimal type (mapped via method)
63
        'decimal'     => 'decimal',
64
65
        //Date and Time types
66
        'datetime'    => 'datetime',
67
        'date'        => 'date',
68
        'time'        => 'time',
69
        'timestamp'   => ['type' => 'timestamp', 'defaultValue' => null],
70
71
        //Binary types
72
        'binary'      => 'blob',
73
        'tinyBinary'  => 'tinyblob',
74
        'longBinary'  => 'longblob',
75
76
        //Additional types
77
        'json'        => 'text',
78
    ];
79
80
    /**
81
     * {@inheritdoc}
82
     */
83
    protected $reverseMapping = [
84
        'primary'     => [['type' => 'int', 'autoIncrement' => true]],
85
        'bigPrimary'  => ['serial', ['type' => 'bigint', 'autoIncrement' => true]],
86
        'enum'        => ['enum'],
87
        'boolean'     => ['bool', 'boolean', ['type' => 'tinyint', 'size' => 1]],
88
        'integer'     => ['int', 'integer', 'smallint', 'mediumint'],
89
        'tinyInteger' => ['tinyint'],
90
        'bigInteger'  => ['bigint'],
91
        'string'      => ['varchar', 'char'],
92
        'text'        => ['text', 'mediumtext'],
93
        'tinyText'    => ['tinytext'],
94
        'longText'    => ['longtext'],
95
        'double'      => ['double'],
96
        'float'       => ['float', 'real'],
97
        'decimal'     => ['decimal'],
98
        'datetime'    => ['datetime'],
99
        'date'        => ['date'],
100
        'time'        => ['time'],
101
        'timestamp'   => ['timestamp'],
102
        'binary'      => ['blob', 'binary', 'varbinary'],
103
        'tinyBinary'  => ['tinyblob'],
104
        'longBinary'  => ['longblob'],
105
    ];
106
107
    /**
108
     * List of types forbids default value set.
109
     *
110
     * @var array
111
     */
112
    protected $forbiddenDefaults = [
113
        'text',
114
        'mediumtext',
115
        'tinytext',
116
        'longtext',
117
        'blog',
118
        'tinyblob',
119
        'longblob',
120
    ];
121
122
    /**
123
     * Column is auto incremental.
124
     *
125
     * @var bool
126
     */
127
    protected $autoIncrement = false;
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function sqlStatement(Driver $driver): string
133
    {
134
        $defaultValue = $this->defaultValue;
135
136
        if (in_array($this->type, $this->forbiddenDefaults)) {
137
            //Flushing default value for forbidden types
138
            $this->defaultValue = null;
139
        }
140
141
        $statement = parent::sqlStatement($driver);
142
143
        $this->defaultValue = $defaultValue;
144
        if ($this->autoIncrement) {
145
            return "{$statement} AUTO_INCREMENT";
146
        }
147
148
        return $statement;
149
    }
150
151
    /**
152
     * @param string $table Table name.
153
     * @param array  $schema
154
     *
155
     * @return MySQLColumn
156
     */
157
    public static function createInstance(string $table, array $schema): self
158
    {
159
        $column = new self($table, $schema['Field']);
160
161
        $column->type = $schema['Type'];
162
        $column->nullable = strtolower($schema['Null']) == 'yes';
163
        $column->defaultValue = $schema['Default'];
164
        $column->autoIncrement = stripos($schema['Extra'], 'auto_increment') !== false;
165
166
        if (!preg_match(
167
            '/^(?P<type>[a-z]+)(?:\((?P<options>[^\)]+)\))?/',
168
            $column->type,
169
            $matches
170
        )
171
        ) {
172
            //No extra definitions
173
            return $column;
174
        }
175
176
        $column->type = $matches['type'];
177
178 View Code Duplication
        if (!empty($matches['options'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
179
            $options = explode(',', $matches['options']);
180
181
            if (count($options) > 1) {
182
                $column->precision = (int)$options[0];
183
                $column->scale = (int)$options[1];
184
            } else {
185
                $column->size = (int)$options[0];
186
            }
187
        }
188
189
        //Fetching enum values
190
        if ($column->abstractType() == 'enum' && !empty($options)) {
191
            $column->enumValues = array_map(function ($value) {
192
                return trim($value, $value[0]);
193
            }, $options);
194
195
            return $column;
196
        }
197
198
        //Default value conversions
199
        if ($column->type == 'bit' && $column->hasDefaultValue()) {
200
            //Cutting b\ and '
201
            $column->defaultValue = new Fragment($column->defaultValue);
202
        }
203
204
        if (
205
            $column->abstractType() == 'timestamp'
206
            && $column->defaultValue == '0000-00-00 00:00:00'
207
        ) {
208
            //Normalizing default value
209
            $column->defaultValue = self::DATETIME_DEFAULT;
210
        }
211
212
        return $column;
213
    }
214
}