Passed
Push — master ( 7ffd5f...e12b56 )
by Anton
01:42
created

ComputeTypes::typecast()   A

Complexity

Conditions 5
Paths 5

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 16
rs 9.6111
c 0
b 0
f 0
1
<?php
2
declare(strict_types=1);
3
/**
4
 * Spiral Framework.
5
 *
6
 * @license   MIT
7
 * @author    Anton Titov (Wolfy-J)
8
 */
9
10
namespace Cycle\Schema\Compiler;
11
12
use Cycle\Schema\Registry;
13
use Cycle\Schema\Definition\Entity;
14
use Cycle\Schema\CompilerInterface;
15
use Spiral\Database\Schema\AbstractColumn;
16
17
class ComputeTypes implements CompilerInterface
18
{
19
    /**
20
     * Automatically clarify column types based on table column types.
21
     *
22
     * @param Registry $builder
23
     * @param Entity   $entity
24
     */
25
    public function compute(Registry $builder, Entity $entity)
26
    {
27
        $table = $builder->getTable($entity);
28
29
        foreach ($entity->getFields() as $field) {
30
            if ($field->hasTypecast() || !$table->hasColumn($field->getColumn())) {
31
                continue;
32
            }
33
34
            $column = $table->column($field->getColumn());
35
36
            $field->setTypecast($this->typecast($column));
37
        }
38
    }
39
40
    /**
41
     * @param AbstractColumn $column
42
     * @return string|callable
43
     */
44
    private function typecast(AbstractColumn $column)
45
    {
46
        switch ($column->getType()) {
47
            case AbstractColumn::BOOL:
48
                return 'bool';
49
            case AbstractColumn::INT:
50
                return 'int';
51
            case AbstractColumn::FLOAT:
52
                return 'float';
53
        }
54
55
        if (in_array($column->getAbstractType(), ['datetime', 'date', 'time'])) {
56
            return 'datetime';
57
        }
58
59
        return null;
60
    }
61
}