Passed
Pull Request — 2.x (#146)
by
unknown
18:06
created

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

382
            $driver->/** @scrutinizer ignore-call */ 
383
                     identifier($this->name),
Loading history...
383
            $this->type,
384
            $this->size,
385
            $this->unsigned ? ' UNSIGNED' : '',
386
            $this->zerofill ? ' ZEROFILL' : '',
387
            $this->nullable ? ' NULL' : ' NOT NULL',
388
            $this->defaultValue !== null ? " DEFAULT {$this->quoteDefault($driver)}" : '',
389
            $this->autoIncrement ? ' AUTO_INCREMENT' : ''
390
        );
391
    }
392
}
393