Passed
Pull Request — master (#171)
by ARP
03:29
created

ImmutableCaster::castSchemaToImmutable()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
eloc 3
c 1
b 0
f 1
dl 0
loc 5
rs 10
cc 3
nc 3
nop 1
1
<?php
2
3
namespace TheCodingMachine\TDBM\Utils;
4
5
use Doctrine\DBAL\Schema\Column;
6
use Doctrine\DBAL\Schema\Schema;
7
use Doctrine\DBAL\Types\Type;
8
9
class ImmutableCaster
10
{
11
    public static function castSchemaToImmutable(Schema $schema): void
12
    {
13
        foreach ($schema->getTables() as $table) {
14
            foreach ($table->getColumns() as $column) {
15
                self::toImmutableType($column);
16
            }
17
        }
18
    }
19
20
    /**
21
     * Changes the type of a column to an immutable date type if the type is a date.
22
     * This is needed because by default, when reading a Schema, Doctrine assumes a mutable datetime.
23
     */
24
    private static function toImmutableType(Column $column): void
25
    {
26
        $mapping = [
27
            Type::DATE => Type::DATE_IMMUTABLE,
28
            Type::DATETIME => Type::DATETIME_IMMUTABLE,
29
            Type::DATETIMETZ => Type::DATETIMETZ_IMMUTABLE,
30
            Type::TIME => Type::TIME_IMMUTABLE
31
        ];
32
33
        $typeName = $column->getType()->getName();
34
        if (isset($mapping[$typeName])) {
35
            $column->setType(Type::getType($mapping[$typeName]));
36
        }
37
    }
38
}
39