Passed
Pull Request — 2.x (#219)
by
unknown
17:24
created

AbstractColumn::getInternalType()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

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

556
        $statement = [$driver->/** @scrutinizer ignore-call */ identifier($this->name), $this->type];
Loading history...
557 56
558
        if (static::isEnum($this)) {
559 56
            //Enum specific column options
560
            if (!empty($enumDefinition = $this->quoteEnum($driver))) {
561
                $statement[] = $enumDefinition;
562 1464
            }
563
        } elseif (!empty($this->precision)) {
564 1464
            $statement[] = "({$this->precision}, {$this->scale})";
565
        } elseif (!empty($this->size)) {
566 1464
            $statement[] = "({$this->size})";
567
        }
568 458
569 458
        $statement[] = $this->nullable ? 'NULL' : 'NOT NULL';
570
571 1440
        if ($this->defaultValue !== null) {
572 42
            $statement[] = "DEFAULT {$this->quoteDefault($driver)}";
573 1410
        }
574 878
575
        return \implode(' ', $statement);
576
    }
577 1464
578
    public function compare(self $initial): bool
579 1464
    {
580 634
        $normalized = clone $initial;
581
582
        // soft compare, todo: improve
583 1464
        if ($this == $normalized) {
584
            return true;
585
        }
586 1894
587
        $columnVars = \get_object_vars($this);
588 1894
        $dbColumnVars = \get_object_vars($normalized);
589
590
        $difference = [];
591 1894
        foreach ($columnVars as $name => $value) {
592 1838
            if (\in_array($name, static::EXCLUDE_FROM_COMPARE, true)) {
593
                continue;
594
            }
595 1598
596 1598
            if ($name === 'type') {
597
                // user defined type
598 1598
                if (!isset($this->mapping[$this->type]) && $this->type === $this->userType) {
599 1598
                    continue;
600 1598
                }
601 1598
            }
602
603
            if ($name === 'defaultValue') {
604 1598
                $defaultValue = $this->getDefaultValue() instanceof FragmentInterface
605
                    ? $this->getDefaultValue()->__toString()
0 ignored issues
show
Bug introduced by
The method __toString() does not exist on Cycle\Database\Injection\FragmentInterface. It seems like you code against a sub-type of said class. However, the method does not exist in Cycle\Database\Query\QueryInterface or Spiral\Database\Injection\FragmentInterface or Spiral\Database\Query\QueryInterface or Cycle\Database\Query\ReturningInterface. Are you sure you never get one of those? ( Ignorable by Annotation )

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

605
                    ? $this->getDefaultValue()->/** @scrutinizer ignore-call */ __toString()
Loading history...
606 1598
                    : $this->getDefaultValue();
607 380
                $initialDefaultValue = $initial->getDefaultValue() instanceof FragmentInterface
608
                    ? $initial->getDefaultValue()->__toString()
609 1554
                    : $initial->getDefaultValue();
610 1554
611
                //Default values has to compared using type-casted value
612 16
                if ($defaultValue != $initialDefaultValue) {
613
                    $difference[] = $name;
614
                } elseif (
615 1598
                    $defaultValue !== $initialDefaultValue
616
                    && (!\is_object($this->getDefaultValue()) && !\is_object($initial->getDefaultValue()))
617
                ) {
618 1598
                    $difference[] = $name;
619 154
                }
620
621
                continue;
622
            }
623 1598
624
            if ($value !== $dbColumnVars[$name]) {
625
                $difference[] = $name;
626
            }
627
        }
628
629 152
        return empty($difference);
630
    }
631 152
632 152
    public function isReadonlySchema(): bool
633 152
    {
634
        return $this->getAttributes()['readonlySchema'] ?? false;
635
    }
636 152
637
    /**
638
     * Shortcut for AbstractColumn->type() method.
639
     *
640
     * @psalm-param non-empty-string $name
641
     */
642 846
    public function __call(string $name, array $arguments = []): self
643
    {
644 846
        if (isset($this->aliases[$name]) || isset($this->mapping[$name])) {
645 846
            $this->type($name);
646
        }
647
648
        // The type must be set before the attributes are filled.
649 846
        !empty($this->type) or throw new SchemaException('Undefined abstract/virtual type');
650 578
651 578
        if (\count($arguments) === 1 && \key($arguments) === 0) {
652 578
            if (\array_key_exists($name, $this->getAttributesMap())) {
653
                $this->fillAttributes([$name => $arguments[0]]);
654
                return $this;
655
            }
656
        }
657 798
658 410
        $this->fillAttributes($arguments);
659 293
660 83
        return $this;
661 798
    }
662
663
    public function __toString(): string
664
    {
665
        return $this->table . '.' . $this->getName();
666
    }
667
668
    /**
669
     * Simplified way to dump information.
670
     */
671
    public function __debugInfo(): array
672 682
    {
673
        $column = [
674
            'name' => $this->name,
675
            'type' => [
676 682
                'database' => $this->type,
677
                'schema'   => $this->getAbstractType(),
678 578
                'php'      => $this->getType(),
679
            ],
680
        ];
681 634
682 8
        if (!empty($this->size)) {
683
            $column['size'] = $this->size;
684 634
        }
685
686 32
        if ($this->nullable) {
687 32
            $column['nullable'] = true;
688
        }
689 632
690
        if ($this->defaultValue !== null) {
691
            $column['defaultValue'] = $this->getDefaultValue();
692
        }
693 634
694 32
        if (static::isEnum($this)) {
695 301
            $column['enumValues'] = $this->enumValues;
696
        }
697 634
698
        if ($this->getAbstractType() === 'decimal') {
699
            $column['precision'] = $this->precision;
700
            $column['scale'] = $this->scale;
701
        }
702
703
        if ($this->attributes !== []) {
704
            $column['attributes'] = $this->attributes;
705
        }
706
707
        return $column;
708
    }
709
710
    protected static function isEnum(self $column): bool
711
    {
712
        return $column->getAbstractType() === 'enum';
713
    }
714
715
    /**
716
     * Checks if the column is JSON or no.
717
     *
718
     * Returns null if it's impossible to explicitly define the JSON type.
719
     */
720
    protected static function isJson(self $column): ?bool
721
    {
722
        return $column->getAbstractType() === 'json';
723
    }
724
725
    /**
726
     * Get database specific enum type definition options.
727
     */
728
    protected function quoteEnum(DriverInterface $driver): string
729
    {
730
        $enumValues = [];
731
        foreach ($this->enumValues as $value) {
732
            $enumValues[] = $driver->quote($value);
733
        }
734
735
        return !empty($enumValues) ? '(' . \implode(', ', $enumValues) . ')' : '';
736
    }
737
738
    /**
739
     * Must return driver specific default value.
740
     */
741
    protected function quoteDefault(DriverInterface $driver): string
742
    {
743
        $defaultValue = $this->getDefaultValue();
744
        if ($defaultValue === null) {
745
            return 'NULL';
746
        }
747
748
        if ($defaultValue instanceof FragmentInterface) {
749
            return $driver->getQueryCompiler()->compile(
750
                new QueryParameters(),
751
                '',
752
                $defaultValue,
753
            );
754
        }
755
756
        return match ($this->getType()) {
757
            'bool' => $defaultValue ? 'TRUE' : 'FALSE',
758
            'float' => \sprintf('%F', $defaultValue),
759
            'int' => (string) $defaultValue,
760
            default => $driver->quote($defaultValue),
761
        };
762
    }
763
764
    /**
765
     * Ensure that datetime fields are correctly formatted.
766
     *
767
     * @psalm-param non-empty-string $type
768
     *
769
     * @throws DefaultValueException
770
     */
771
    protected function formatDatetime(
772
        string $type,
773
        string|int|\DateTimeInterface $value,
774
    ): \DateTimeInterface|FragmentInterface|string {
775
        if ($value === static::DATETIME_NOW) {
776
            //Dynamic default value
777
            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

777
            return new Fragment(/** @scrutinizer ignore-type */ $value);
Loading history...
778
        }
779
780
        if ($value instanceof \DateTimeInterface) {
781
            $datetime = clone $value;
782
        } else {
783
            if (\is_numeric($value)) {
784
                //Presumably timestamp
785
                $datetime = new \DateTimeImmutable('now', $this->timezone);
786
                $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

786
                $datetime = $datetime->setTimestamp(/** @scrutinizer ignore-type */ $value);
Loading history...
787
            } else {
788
                $datetime = new \DateTimeImmutable($value, $this->timezone);
789
            }
790
        }
791
792
        return match ($type) {
793
            'datetime', 'timestamp' => $datetime,
794
            'time' => $datetime->format(static::TIME_FORMAT),
795
            'date' => $datetime->format(static::DATE_FORMAT),
796
            default => $value,
797
        };
798
    }
799
}
800