Passed
Pull Request — 2.x (#146)
by Maxim
17:15
created

MySQLColumn::binary()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

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

372
            $driver->/** @scrutinizer ignore-call */ 
373
                     identifier($this->name),
Loading history...
373
            $this->type,
374
            $this->size,
375
            $this->unsigned ? ' UNSIGNED' : '',
376
            $this->zerofill ? ' ZEROFILL' : '',
377
            $this->nullable ? ' NULL' : ' NOT NULL',
378
            $this->defaultValue !== null ? " DEFAULT {$this->quoteDefault($driver)}" : '',
379
            $this->autoIncrement ? ' AUTO_INCREMENT' : ''
380
        );
381
    }
382
}
383