Passed
Pull Request — 2.x (#88)
by Aleksei
19:47
created

MySQLColumn::compare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 1
dl 0
loc 4
ccs 0
cts 0
cp 0
crap 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * This file is part of Cycle ORM package.
5
 *
6
 * For the full copyright and license information, please view the LICENSE
7
 * file that was distributed with this source code.
8
 */
9
10
declare(strict_types=1);
11
12
namespace Cycle\Database\Driver\MySQL\Schema;
13
14
use Cycle\Database\Driver\DriverInterface;
15
use Cycle\Database\Exception\DefaultValueException;
16
use Cycle\Database\Injection\Fragment;
17
use Cycle\Database\Injection\FragmentInterface;
18
use Cycle\Database\Schema\AbstractColumn;
0 ignored issues
show
Bug introduced by
The type Cycle\Database\Schema\AbstractColumn was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
use Cycle\Database\Schema\Attribute\ColumnAttribute;
20
21
/**
22
 * Attention! You can use only one timestamp or datetime with DATETIME_NOW setting! Thought, it will
23
 * work on multiple fields with MySQL 5.6.6+ version.
24
 *
25
 * @method $this|AbstractColumn primary(int $size, bool $unsigned = false, $zerofill = false)
26
 * @method $this|AbstractColumn bigPrimary(int $size, bool $unsigned = false, $zerofill = false)
27
 * @method $this|AbstractColumn integer(int $size, bool $unsigned = false, $zerofill = false)
28
 * @method $this|AbstractColumn tinyInteger(int $size, bool $unsigned = false, $zerofill = false)
29
 * @method $this|AbstractColumn smallInteger(int $size, bool $unsigned = false, $zerofill = false)
30
 * @method $this|AbstractColumn bigInteger(int $size, bool $unsigned = false, $zerofill = false)
31
 * @method $this|AbstractColumn unsigned(bool $value)
32
 * @method $this|AbstractColumn zerofill(bool $value)
33
 */
34
class MySQLColumn extends AbstractColumn
35
{
36
    /**
37
     * Default timestamp expression (driver specific).
38
     */
39
    public const DATETIME_NOW = 'CURRENT_TIMESTAMP';
40
41
    protected const INTEGER_TYPES = ['tinyint', 'smallint', 'mediumint', 'int', 'bigint'];
42
43
    protected array $mapping = [
44
        //Primary sequences
45
        'primary'     => [
46
            'type'          => 'int',
47
            'size'          => 11,
48
            'autoIncrement' => true,
49
            'nullable'      => false,
50
        ],
51
        'bigPrimary'  => [
52
            'type'          => 'bigint',
53
            'size'          => 20,
54
            'autoIncrement' => true,
55
            'nullable'      => false,
56
        ],
57
58
        //Enum type (mapped via method)
59
        'enum'        => 'enum',
60
61
        //Logical types
62
        'boolean'     => ['type' => 'tinyint', 'size' => 1],
63
64
        //Integer types (size can always be changed with size method), longInteger has method alias
65
        //bigInteger
66
        'integer'     => ['type' => 'int', 'size' => 11, 'unsigned' => false, 'zerofill' => false],
67
        'tinyInteger' => ['type' => 'tinyint', 'size' => 4, 'unsigned' => false, 'zerofill' => false],
68
        'smallInteger'=> ['type' => 'smallint', 'size' => 6, 'unsigned' => false, 'zerofill' => false],
69
        'bigInteger'  => ['type' => 'bigint', 'size' => 20, 'unsigned' => false, 'zerofill' => false],
70
71
        //String with specified length (mapped via method)
72
        'string'      => ['type' => 'varchar', 'size' => 255],
73
74
        //Generic types
75
        'text'        => 'text',
76
        'tinyText'    => 'tinytext',
77
        'longText'    => 'longtext',
78
79
        //Real types
80
        'double'      => 'double',
81
        'float'       => 'float',
82
83
        //Decimal type (mapped via method)
84
        'decimal'     => 'decimal',
85
86
        //Date and Time types
87
        'datetime'    => 'datetime',
88
        'date'        => 'date',
89
        'time'        => 'time',
90
        'timestamp'   => ['type' => 'timestamp', 'defaultValue' => null],
91
92
        //Binary types
93
        'binary'      => 'blob',
94
        'tinyBinary'  => 'tinyblob',
95
        'longBinary'  => 'longblob',
96
97
        //Additional types
98
        'json'        => 'text',
99
        'uuid'        => ['type' => 'varchar', 'size' => 36],
100
    ];
101
102
    protected array $reverseMapping = [
103
        'primary'     => [['type' => 'int', 'autoIncrement' => true]],
104
        'bigPrimary'  => ['serial', ['type' => 'bigint', 'size' => 20, 'autoIncrement' => true]],
105
        'enum'        => ['enum'],
106
        'boolean'     => ['bool', 'boolean', ['type' => 'tinyint', 'size' => 1]],
107
        'integer'     => ['int', 'integer', 'mediumint'],
108
        'tinyInteger' => ['tinyint'],
109
        'smallInteger'=> ['smallint'],
110
        'bigInteger'  => ['bigint'],
111
        'string'      => ['varchar', 'char'],
112
        'text'        => ['text', 'mediumtext'],
113
        'tinyText'    => ['tinytext'],
114
        'longText'    => ['longtext'],
115
        'double'      => ['double'],
116
        'float'       => ['float', 'real'],
117
        'decimal'     => ['decimal'],
118
        'datetime'    => ['datetime'],
119
        'date'        => ['date'],
120
        'time'        => ['time'],
121
        'timestamp'   => ['timestamp'],
122
        'binary'      => ['blob', 'binary', 'varbinary'],
123
        'tinyBinary'  => ['tinyblob'],
124
        'longBinary'  => ['longblob'],
125
    ];
126
127
    /**
128
     * List of types forbids default value set.
129
     */
130
    protected array $forbiddenDefaults = [
131
        'text',
132
        'mediumtext',
133
        'tinytext',
134 474
        'longtext',
135
        'blob',
136 474
        'tinyblob',
137
        'longblob',
138 474
    ];
139
140 214
    /**
141
     * Column is auto incremental.
142
     */
143 474
    #[ColumnAttribute(self::INTEGER_TYPES)]
144
    protected bool $autoIncrement = false;
145 474
146 474
    /**
147 332
     * Unsigned integer type. Related to {@see INTEGER_TYPES} only.
148
     */
149
    #[ColumnAttribute(self::INTEGER_TYPES)]
150 456
    protected bool $unsigned = false;
151
152
    /**
153
     * Zerofill option. Related to {@see INTEGER_TYPES} only.
154
     */
155
    #[ColumnAttribute(self::INTEGER_TYPES)]
156 470
    protected bool $zerofill = false;
157
158 470
    /**
159
     * @psalm-return non-empty-string
160 470
     */
161 470
    public function sqlStatement(DriverInterface $driver): string
162 470
    {
163 470
        if (\in_array($this->type, self::INTEGER_TYPES, true)) {
164
            return $this->sqlStatementInteger($driver);
165
        }
166 470
167 470
        $defaultValue = $this->defaultValue;
168 470
169
        if (\in_array($this->type, $this->forbiddenDefaults, true)) {
170
            //Flushing default value for forbidden types
171
            $this->defaultValue = null;
0 ignored issues
show
Bug Best Practice introduced by
The property defaultValue does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
172
        }
173
174
        $statement = parent::sqlStatement($driver);
175
176 470
        $this->defaultValue = $defaultValue;
177
        if ($this->autoIncrement) {
178 470
            return "{$statement} AUTO_INCREMENT";
179 470
        }
180 280
181
        return $statement;
182 280
    }
183 162
184 162
    /**
185
     * @psalm-param non-empty-string $table
186 262
     */
187
    public static function createInstance(string $table, array $schema, \DateTimeZone $timezone = null): self
188
    {
189
        $column = new self($table, $schema['Field'], $timezone);
190
191 470
        $column->type = $schema['Type'];
0 ignored issues
show
Bug Best Practice introduced by
The property type does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
192 446
        $column->nullable = strtolower($schema['Null']) === 'yes';
0 ignored issues
show
Bug Best Practice introduced by
The property nullable does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
193 446
        $column->defaultValue = $schema['Default'];
0 ignored issues
show
Bug Best Practice introduced by
The property defaultValue does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
194 338
        $column->autoIncrement = stripos($schema['Extra'], 'auto_increment') !== false;
195 338
196 320
        if (
197 6
            !preg_match(
198 6
                '/^(?P<type>[a-z]+)(?:\((?P<options>[^)]+)\))?(?: (?P<attr>[a-z ]+))?/',
199 316
                $column->type,
200 2
                $matches
201 2
            )
202
        ) {
203
            //No extra definitions
204
            return $column;
205
        }
206
207 470
        $column->type = $matches['type'];
208 152
209
        $options = [];
210 152
        if (!empty($matches['options'])) {
211
            $options = \explode(',', $matches['options']);
212
213
            if (count($options) > 1) {
214 462
                $column->precision = (int)$options[0];
0 ignored issues
show
Bug Best Practice introduced by
The property precision does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
215
                $column->scale = (int)$options[1];
0 ignored issues
show
Bug Best Practice introduced by
The property scale does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
216
            } else {
217
                $column->size = (int)$options[0];
0 ignored issues
show
Bug Best Practice introduced by
The property size does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
218
            }
219
        }
220 462
221 462
        if (!empty($matches['attr'])) {
222
            if (\in_array($column->type, self::INTEGER_TYPES, true)) {
223
                $intAttr = array_map('trim', explode(' ', $matches['attr']));
224
                if (\in_array('unsigned', $intAttr, true)) {
225
                    $column->unsigned = true;
226
                }
227 462
                if (\in_array('zerofill', $intAttr, true)) {
228
                    $column->zerofill = true;
229
                }
230
                unset($intAttr);
231
            }
232
        }
233
234
        // since 8.0 database does not provide size for some columns
235
        if ($column->size === 0) {
236
            switch ($column->type) {
237 170
                case 'int':
238
                    $column->size = 11;
239
                    break;
240
                case 'bigint':
241 170
                    $column->size = 20;
242
                    break;
243
                case 'tinyint':
244
                    $column->size = 4;
245 170
                    break;
246
                case 'smallint':
247
                    $column->size = 6;
248
                    break;
249
            }
250
        }
251
252
        //Fetching enum values
253
        if ($options !== [] && $column->getAbstractType() === 'enum') {
254
            $column->enumValues = \array_map(static fn ($value) => trim($value, $value[0]), $options);
0 ignored issues
show
Bug Best Practice introduced by
The property enumValues does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
255
256
            return $column;
257
        }
258
259
        //Default value conversions
260
        if ($column->type === 'bit' && $column->hasDefaultValue()) {
261
            //Cutting b\ and '
262
            $column->defaultValue = new Fragment($column->defaultValue);
263
        }
264
265
        if (
266
            $column->defaultValue === '0000-00-00 00:00:00'
267
            && $column->getAbstractType() === 'timestamp'
268
        ) {
269
            //Normalizing default value for timestamps
270
            $column->defaultValue = 0;
271
        }
272
273
        return $column;
274
    }
275
276
    public function compare(AbstractColumn $initial): bool
277
    {
278
        assert($initial instanceof self);
279
        return ! (!parent::compare($initial));
280
    }
281
282
    public function isUnsigned(): bool
283
    {
284
        return $this->unsigned;
285
    }
286
287
    public function isZerofill(): bool
288
    {
289
        return $this->zerofill;
290
    }
291
292
    /**
293
     * Ensure that datetime fields are correctly formatted.
294
     *
295
     * @psalm-param non-empty-string $type
296
     *
297
     * @throws DefaultValueException
298
     */
299
    protected function formatDatetime(
300
        string $type,
301
        string|int|\DateTimeInterface $value
302
    ): \DateTimeInterface|FragmentInterface|string {
303
        if ($value === 'current_timestamp()') {
304
            $value = self::DATETIME_NOW;
305
        }
306
307
        return parent::formatDatetime($type, $value);
308
    }
309
310
    private function sqlStatementInteger(DriverInterface $driver): string
311
    {
312
        return \sprintf(
313
            '%s %s(%s)%s%s%s%s%s',
314
            $driver->identifier($this->name),
0 ignored issues
show
Bug introduced by
The method identifier() does not exist on Cycle\Database\Driver\DriverInterface. It seems like you code against a sub-type of Cycle\Database\Driver\DriverInterface such as Cycle\Database\Driver\Driver. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

314
            $driver->/** @scrutinizer ignore-call */ 
315
                     identifier($this->name),
Loading history...
315
            $this->type,
316
            $this->size,
317
            $this->unsigned ? ' UNSIGNED' : '',
318
            $this->zerofill ? ' ZEROFILL' : '',
319
            $this->nullable ? ' NULL' : ' NOT NULL',
320
            $this->defaultValue !== null ? " DEFAULT {$this->quoteDefault($driver)}" : '',
321
            $this->autoIncrement ? ' AUTO_INCREMENT' : ''
322
        );
323
    }
324
}
325