Passed
Pull Request — 2.x (#91)
by Aleksei
18:20
created

AbstractColumn::quoteEnum()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
cc 3
eloc 4
nc 4
nop 1
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 3.072
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\Schema;
13
14
use DateTimeImmutable;
15
use Cycle\Database\ColumnInterface;
16
use Cycle\Database\Driver\DriverInterface;
17
use Cycle\Database\Exception\DefaultValueException;
18
use Cycle\Database\Exception\SchemaException;
19
use Cycle\Database\Injection\Fragment;
20
use Cycle\Database\Injection\FragmentInterface;
21
use Cycle\Database\Query\QueryParameters;
22
use Cycle\Database\Schema\Traits\ElementTrait;
23
24
/**
25
 * Abstract column schema with read (see ColumnInterface) and write abilities. Must be implemented
26
 * by driver to support DBMS specific syntax and creation rules.
27
 *
28
 * Shortcuts for various column types:
29
 *
30
 * @method $this|AbstractColumn primary()
31
 * @method $this|AbstractColumn bigPrimary()
32
 * @method $this|AbstractColumn boolean()
33
 * @method $this|AbstractColumn integer()
34
 * @method $this|AbstractColumn tinyInteger()
35
 * @method $this|AbstractColumn smallInteger()
36
 * @method $this|AbstractColumn bigInteger()
37
 * @method $this|AbstractColumn text()
38
 * @method $this|AbstractColumn tinyText()
39
 * @method $this|AbstractColumn longText()
40
 * @method $this|AbstractColumn double()
41
 * @method $this|AbstractColumn float()
42
 * @method $this|AbstractColumn date()
43
 * @method $this|AbstractColumn time()
44
 * @method $this|AbstractColumn timestamp()
45
 * @method $this|AbstractColumn binary()
46
 * @method $this|AbstractColumn tinyBinary()
47
 * @method $this|AbstractColumn longBinary()
48
 * @method $this|AbstractColumn json()
49
 * @method $this|AbstractColumn uuid()
50
 */
51
abstract class AbstractColumn implements ColumnInterface, ElementInterface
52
{
53
    use ElementTrait;
54
55
    /**
56
     * Default timestamp expression (driver specific).
57
     */
58
    public const DATETIME_NOW = 'CURRENT_TIMESTAMP';
59
60
    /**
61
     * Value to be excluded from comparision.
62
     */
63
    public const EXCLUDE_FROM_COMPARE = ['timezone', 'userType'];
64
65
    /**
66
     * Normalization for time and dates.
67
     */
68
    public const DATE_FORMAT = 'Y-m-d';
69
    public const TIME_FORMAT = 'H:i:s';
70
71
    /**
72
     * Mapping between abstract type and internal database type with it's options. Multiple abstract
73
     * types can map into one database type, this implementation allows us to equalize two columns
74
     * if they have different abstract types but same database one. Must be declared by DBMS
75
     * specific implementation.
76
     *
77
     * Example:
78
     * integer => array('type' => 'int', 'size' => 1),
79
     * boolean => array('type' => 'tinyint', 'size' => 1)
80
     *
81
     * @internal
82
     */
83
    protected array $mapping = [
84
        //Primary sequences
85
        'primary'     => null,
86
        'bigPrimary'  => null,
87
88
        //Enum type (mapped via method)
89
        'enum'        => null,
90
91
        //Logical types
92
        'boolean'     => null,
93
94
        //Integer types (size can always be changed with size method), longInteger has method alias
95
        //bigInteger
96
        'integer'     => null,
97
        'tinyInteger' => null,
98
        'smallInteger'=> null,
99
        'bigInteger'  => null,
100
101
        //String with specified length (mapped via method)
102
        'string'      => null,
103
104
        //Generic types
105
        'text'        => null,
106
        'tinyText'    => null,
107
        'longText'    => null,
108
109
        //Real types
110
        'double'      => null,
111
        'float'       => null,
112
113
        //Decimal type (mapped via method)
114
        'decimal'     => null,
115
116
        //Date and Time types
117
        'datetime'    => null,
118
        'date'        => null,
119
        'time'        => null,
120
        'timestamp'   => null,
121
122
        //Binary types
123
        'binary'      => null,
124
        'tinyBinary'  => null,
125
        'longBinary'  => null,
126
127
        //Additional types
128
        'json'        => null,
129
    ];
130
131
    /**
132
     * Reverse mapping is responsible for generating abstact type based on database type and it's
133
     * options. Multiple database types can be mapped into one abstract type.
134
     *
135
     * @internal
136
     */
137
    protected array $reverseMapping = [
138
        'primary'     => [],
139
        'bigPrimary'  => [],
140
        'enum'        => [],
141
        'boolean'     => [],
142
        'integer'     => [],
143
        'tinyInteger' => [],
144
        'smallInteger'=> [],
145
        'bigInteger'  => [],
146
        'string'      => [],
147
        'text'        => [],
148
        'tinyText'    => [],
149
        'longText'    => [],
150
        'double'      => [],
151
        'float'       => [],
152
        'decimal'     => [],
153
        'datetime'    => [],
154
        'date'        => [],
155
        'time'        => [],
156
        'timestamp'   => [],
157
        'binary'      => [],
158
        'tinyBinary'  => [],
159
        'longBinary'  => [],
160
        'json'        => [],
161
    ];
162
163
    /**
164
     * User defined type. Only until actual mapping.
165
     */
166
    protected ?string $userType = null;
167
168
    /**
169
     * DBMS specific column type.
170
     */
171
    protected string $type = '';
172
173
    protected ?\DateTimeZone $timezone = null;
174
175
    /**
176
     * Indicates that column can contain null values.
177
     */
178
    protected bool $nullable = true;
179
180
    /**
181
     * Default column value, may not be applied to some datatypes (for example to primary keys),
182
     * should follow type size and other options.
183
     */
184
    protected mixed $defaultValue = null;
185
186
    /**
187
     * Column type size, can have different meanings for different datatypes.
188
     */
189
    protected int $size = 0;
190
191
    /**
192
     * Precision of column, applied only for "decimal" type.
193
     */
194
    protected int $precision = 0;
195
196
    /**
197
     * Scale of column, applied only for "decimal" type.
198
     */
199
    protected int $scale = 0;
200
201
    /**
202
     * List of allowed enum values.
203
     */
204
    protected array $enumValues = [];
205
206
    /**
207
     * Abstract type aliases (for consistency).
208
     */
209
    private array $aliases = [
210
        'int'            => 'integer',
211
        'smallint'       => 'smallInteger',
212
        'bigint'         => 'bigInteger',
213
        'incremental'    => 'primary',
214
        'bigIncremental' => 'bigPrimary',
215
        'bool'           => 'boolean',
216
        'blob'           => 'binary',
217
    ];
218
219
    /**
220
     * Association list between abstract types and native PHP types. Every non listed type will be
221
     * converted into string.
222
     *
223
     * @internal
224
     */
225
    private array $phpMapping = [
226
        self::INT   => ['primary', 'bigPrimary', 'integer', 'tinyInteger', 'smallInteger', 'bigInteger'],
227
        self::BOOL  => ['boolean'],
228
        self::FLOAT => ['double', 'float', 'decimal'],
229
    ];
230
231
    /**
232 1950
     * @psalm-param non-empty-string $table
233
     * @psalm-param non-empty-string $name
234
     */
235
    public function __construct(
236
        protected string $table,
237 1950
        protected string $name,
238 1950
        \DateTimeZone $timezone = null
239
    ) {
240
        $this->timezone = $timezone ?? new \DateTimeZone(date_default_timezone_get());
241
    }
242
243
    /**
244
     * Shortcut for AbstractColumn->type() method.
245 1750
     *
246
     * @psalm-param non-empty-string $type
247 1750
     */
248
    public function __call(string $type, array $arguments = []): self
249
    {
250 856
        return $this->type($type);
251
    }
252 856
253
    public function __toString(): string
254
    {
255
        return $this->table . '.' . $this->getName();
256
    }
257
258 24
    /**
259
     * Simplified way to dump information.
260 24
     */
261 24
    public function __debugInfo(): array
262
    {
263 24
        $column = [
264 24
            'name' => $this->name,
265 24
            'type' => [
266
                'database' => $this->type,
267
                'schema'   => $this->getAbstractType(),
268
                'php'      => $this->getType(),
269 24
            ],
270 8
        ];
271
272
        if (!empty($this->size)) {
273 24
            $column['size'] = $this->size;
274 24
        }
275
276
        if ($this->nullable) {
277 24
            $column['nullable'] = true;
278 8
        }
279
280
        if ($this->defaultValue !== null) {
281 24
            $column['defaultValue'] = $this->getDefaultValue();
282
        }
283
284
        if ($this->getAbstractType() === 'enum') {
285 24
            $column['enumValues'] = $this->enumValues;
286 16
        }
287 16
288
        if ($this->getAbstractType() === 'decimal') {
289
            $column['precision'] = $this->precision;
290 24
            $column['scale'] = $this->scale;
291
        }
292
293 8
        return $column;
294
    }
295 8
296
    public function getSize(): int
297
    {
298 852
        return $this->size;
299
    }
300 852
301
    public function getPrecision(): int
302
    {
303 852
        return $this->precision;
304
    }
305 852
306
    public function getScale(): int
307
    {
308 8
        return $this->scale;
309
    }
310 8
311
    public function isNullable(): bool
312
    {
313 1798
        return $this->nullable;
314
    }
315 1798
316
    public function hasDefaultValue(): bool
317
    {
318
        return $this->defaultValue !== null;
319
    }
320
321 1798
    /**
322
     * @throws DefaultValueException
323 1798
     */
324 1514
    public function getDefaultValue(): mixed
325
    {
326
        if (!$this->hasDefaultValue()) {
327 1074
            return null;
328
        }
329 368
330
        if ($this->defaultValue instanceof FragmentInterface) {
331
            //Defined as SQL piece
332 850
            return $this->defaultValue;
333 682
        }
334
335
        if (\in_array($this->getAbstractType(), ['time', 'date', 'datetime', 'timestamp'])) {
336 698
            return $this->formatDatetime($this->getAbstractType(), $this->defaultValue);
337 170
        }
338 293
339 205
        return match ($this->getType()) {
340 205
            'int' => (int) $this->defaultValue,
341 698
            'float' => (float) $this->defaultValue,
342
            'bool' => \is_string($this->defaultValue) && strtolower($this->defaultValue) === 'false'
343
                ? false : (bool) $this->defaultValue,
344
            default => (string)$this->defaultValue
345
        };
346
    }
347
348 60
    /**
349
     * Get every associated column constraint names.
350 60
     */
351
    public function getConstraints(): array
352
    {
353
        return [];
354
    }
355
356 852
    /**
357
     * Get allowed enum values.
358 852
     */
359
    public function getEnumValues(): array
360
    {
361 856
        return $this->enumValues;
362
    }
363 856
364
    public function getInternalType(): string
365
    {
366
        return $this->type;
367
    }
368
369 842
    /**
370
     * @psalm-return non-empty-string
371 842
     */
372 842
    public function getType(): string
373 842
    {
374 618
        $schemaType = $this->getAbstractType();
375
        foreach ($this->phpMapping as $phpType => $candidates) {
376
            if (in_array($schemaType, $candidates, true)) {
377
                return $phpType;
378 754
            }
379
        }
380
381
        return self::STRING;
382
    }
383
384
    /**
385
     * Returns type defined by the user, only until schema sync. Attention, this value is only preserved during the
386
     * declaration process. Value will become null after the schema fetched from database.
387
     *
388
     * @internal
389
     */
390
    public function getDeclaredType(): ?string
391
    {
392
        return $this->userType;
393
    }
394
395
    /**
396 1922
     * DBMS specific reverse mapping must map database specific type into limited set of abstract
397
     * types.
398 1922
     */
399 1922
    public function getAbstractType(): string
400 1922
    {
401 1890
        foreach ($this->reverseMapping as $type => $candidates) {
402 1862
            foreach ($candidates as $candidate) {
403
                if (\is_string($candidate)) {
404
                    if (strtolower($candidate) === strtolower($this->type)) {
405 1838
                        return $type;
406
                    }
407
408 1414
                    continue;
409 1360
                }
410
411
                if (strtolower($candidate['type']) !== strtolower($this->type)) {
412 1034
                    continue;
413 1034
                }
414 1034
415
                foreach ($candidate as $option => $required) {
416
                    if ($option === 'type') {
417 1034
                        continue;
418 876
                    }
419
420
                    if ($this->{$option} !== $required) {
421
                        continue 2;
422 688
                    }
423
                }
424
425
                return $type;
426 4
            }
427
        }
428
429
        return 'unknown';
430
    }
431
432
    /**
433
     * Give column new abstract type. DBMS specific implementation must map provided type into one
434
     * of internal database values.
435
     *
436
     * Attention, changing type of existed columns in some databases has a lot of restrictions like
437
     * cross type conversions and etc. Try do not change column type without a reason.
438
     *
439
     * @psalm-param non-empty-string $abstract Abstract or virtual type declared in mapping.
440
     *
441
     * @throws SchemaException
442 1932
     *
443
     * @todo Support native database types (simply bypass abstractType)!
444 1932
     */
445
    public function type(string $abstract): self
446
    {
447
        if (isset($this->aliases[$abstract])) {
448
            //Make recursive
449 1932
            $abstract = $this->aliases[$abstract];
450
        }
451
452 1932
        isset($this->mapping[$abstract]) or throw new SchemaException("Undefined abstract/virtual type '{$abstract}'");
453
454
        // Originally specified type.
455 1932
        $this->userType = $abstract;
456 1932
457
        // Resetting all values to default state.
458
        $this->size = $this->precision = $this->scale = 0;
459 1932
        $this->enumValues = [];
460 1656
461
        // Abstract type points to DBMS specific type
462 1656
        if (\is_string($this->mapping[$abstract])) {
463
            $this->type = $this->mapping[$abstract];
464
465
            return $this;
466 1442
        }
467 1442
468
        // Configuring column properties based on abstractType preferences
469
        foreach ($this->mapping[$abstract] as $property => $value) {
470 1442
            $this->{$property} = $value;
471
        }
472
473
        return $this;
474
    }
475
476 698
    /**
477
     * Set column nullable/not nullable.
478 698
     */
479
    public function nullable(bool $nullable = true): self
480 698
    {
481
        $this->nullable = $nullable;
482
483
        return $this;
484
    }
485
486
    /**
487 954
     * Change column default value (can be forbidden for some column types).
488
     * Use Database::TIMESTAMP_NOW to use driver specific NOW() function.
489
     */
490 954
    public function defaultValue(mixed $value): self
491 578
    {
492
        //Forcing driver specific values
493
        if ($value === self::DATETIME_NOW) {
494 954
            $value = static::DATETIME_NOW;
495
        }
496 954
497
        $this->defaultValue = $value;
498
499
        return $this;
500
    }
501
502
    /**
503
     * Set column as enum type and specify set of allowed values. Most of drivers will emulate enums
504
     * using column constraints.
505
     *
506
     * Examples:
507
     * $table->status->enum(['active', 'disabled']);
508
     * $table->status->enum('active', 'disabled');
509 304
     *
510
     * @param array|string $values Enum values (array or comma separated). String values only.
511 304
     */
512 304
    public function enum(string|array $values): self
513 304
    {
514 304
        $this->type('enum');
515
        $this->enumValues = array_map(
516
            'strval',
517 304
            is_array($values) ? $values : func_get_args()
0 ignored issues
show
introduced by
The condition is_array($values) is always true.
Loading history...
518
        );
519
520
        return $this;
521
    }
522
523
    /**
524
     * Set column type as string with limited size. Maximum allowed size is 255 bytes, use "text"
525
     * abstract types for longer strings.
526
     *
527
     * Strings are perfect type to store email addresses as it big enough to store valid address
528
     * and
529
     * can be covered with unique index.
530
     *
531
     * @link http://stackoverflow.com/questions/386294/what-is-the-maximum-length-of-a-valid-email-address
532
     *
533
     * @param int $size Max string length.
534 1008
     *
535
     * @throws SchemaException
536 1008
     */
537
    public function string(int $size = 255): self
538 1008
    {
539
        $this->type('string');
540 1008
541
        $size < 0 && throw new SchemaException('Invalid string length value');
542 1008
543
        $this->size = $size;
544
545
        return $this;
546
    }
547
548
    public function datetime(int $size = 0): self
549
    {
550 64
        $this->type('datetime');
551
552 64
        ($size < 0 || $size > 6) && throw new SchemaException('Invalid datetime length value');
553
554 64
        $this->size = $size;
555
556 56
        return $this;
557 56
    }
558
559 56
    /**
560
     * Set column type as decimal with specific precision and scale.
561
     *
562 1464
     * @throws SchemaException
563
     */
564 1464
    public function decimal(int $precision, int $scale = 0): self
565
    {
566 1464
        $this->type('decimal');
567
568 458
        empty($precision) && throw new SchemaException('Invalid precision value');
569 458
570
        $this->precision = $precision;
571 1440
        $this->scale = $scale;
572 42
573 1410
        return $this;
574 878
    }
575
576
    public function sqlStatement(DriverInterface $driver): string
577 1464
    {
578
        $statement = [$driver->identifier($this->name), $this->type];
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

578
        $statement = [$driver->/** @scrutinizer ignore-call */ identifier($this->name), $this->type];
Loading history...
579 1464
580 634
        if ($this->getAbstractType() === 'enum') {
581
            //Enum specific column options
582
            if (!empty($enumDefinition = $this->quoteEnum($driver))) {
583 1464
                $statement[] = $enumDefinition;
584
            }
585
        } elseif (!empty($this->precision)) {
586 1894
            $statement[] = "({$this->precision}, {$this->scale})";
587
        } elseif (!empty($this->size)) {
588 1894
            $statement[] = "({$this->size})";
589
        }
590
591 1894
        $statement[] = $this->nullable ? 'NULL' : 'NOT NULL';
592 1838
593
        if ($this->defaultValue !== null) {
594
            $statement[] = "DEFAULT {$this->quoteDefault($driver)}";
595 1598
        }
596 1598
597
        return implode(' ', $statement);
598 1598
    }
599 1598
600 1598
    public function compare(self $initial): bool
601 1598
    {
602
        $normalized = clone $initial;
603
604 1598
        // soft compare, todo: improve
605
        if ($this == $normalized) {
606 1598
            return true;
607 380
        }
608
609 1554
        $columnVars = get_object_vars($this);
610 1554
        $dbColumnVars = get_object_vars($normalized);
611
612 16
        $difference = [];
613
        foreach ($columnVars as $name => $value) {
614
            if (\in_array($name, static::EXCLUDE_FROM_COMPARE, true)) {
615 1598
                continue;
616
            }
617
618 1598
            if ($name === 'defaultValue') {
619 154
                //Default values has to compared using type-casted value
620
                if ($this->getDefaultValue() != $initial->getDefaultValue()) {
621
                    $difference[] = $name;
622
                } elseif (
623 1598
                    $this->getDefaultValue() !== $initial->getDefaultValue()
624
                    && (!\is_object($this->getDefaultValue()) && !\is_object($initial->getDefaultValue()))
625
                ) {
626
                    $difference[] = $name;
627
                }
628
629 152
                continue;
630
            }
631 152
632 152
            if ($value !== $dbColumnVars[$name]) {
633 152
                $difference[] = $name;
634
            }
635
        }
636 152
637
        return empty($difference);
638
    }
639
640
    /**
641
     * Get database specific enum type definition options.
642 846
     */
643
    protected function quoteEnum(DriverInterface $driver): string
644 846
    {
645 846
        $enumValues = [];
646
        foreach ($this->enumValues as $value) {
647
            $enumValues[] = $driver->quote($value);
648
        }
649 846
650 578
        return !empty($enumValues) ? '(' . implode(', ', $enumValues) . ')' : '';
651 578
    }
652 578
653
    /**
654
     * Must return driver specific default value.
655
     */
656
    protected function quoteDefault(DriverInterface $driver): string
657 798
    {
658 410
        $defaultValue = $this->getDefaultValue();
659 293
        if ($defaultValue === null) {
660 83
            return 'NULL';
661 798
        }
662
663
        if ($defaultValue instanceof FragmentInterface) {
664
            return $driver->getQueryCompiler()->compile(
665
                new QueryParameters(),
666
                '',
667
                $defaultValue
668
            );
669
        }
670
671
        return match ($this->getType()) {
672 682
            'bool' => $defaultValue ? 'TRUE' : 'FALSE',
673
            'float' => sprintf('%F', $defaultValue),
674
            'int' => (string) $defaultValue,
675
            default => $driver->quote($defaultValue)
676 682
        };
677
    }
678 578
679
    /**
680
     * Ensure that datetime fields are correctly formatted.
681 634
     *
682 8
     * @psalm-param non-empty-string $type
683
     *
684 634
     * @throws DefaultValueException
685
     */
686 32
    protected function formatDatetime(
687 32
        string $type,
688
        string|int|\DateTimeInterface $value
689 632
    ): \DateTimeInterface|FragmentInterface|string {
690
        if ($value === static::DATETIME_NOW) {
691
            //Dynamic default value
692
            return new Fragment($value);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type DateTimeInterface; however, parameter $fragment of Cycle\Database\Injection\Fragment::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

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

692
            return new Fragment(/** @scrutinizer ignore-type */ $value);
Loading history...
693 634
        }
694 32
695 301
        if ($value instanceof \DateTimeInterface) {
696
            $datetime = clone $value;
697 634
        } else {
698
            if (is_numeric($value)) {
699
                //Presumably timestamp
700
                $datetime = new DateTimeImmutable('now', $this->timezone);
701
                $datetime = $datetime->setTimestamp($value);
0 ignored issues
show
Bug introduced by
It seems like $value can also be of type string; however, parameter $timestamp of DateTimeImmutable::setTimestamp() does only seem to accept integer, maybe add an additional type check? ( Ignorable by Annotation )

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

701
                $datetime = $datetime->setTimestamp(/** @scrutinizer ignore-type */ $value);
Loading history...
702
            } else {
703
                $datetime = new DateTimeImmutable($value, $this->timezone);
704
            }
705
        }
706
707
        return match ($type) {
708
            'datetime', 'timestamp' => $datetime,
709
            'time' => $datetime->format(static::TIME_FORMAT),
710
            'date' => $datetime->format(static::DATE_FORMAT),
711
            default => $value
712
        };
713
    }
714
}
715