|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Created by PhpStorm. |
|
4
|
|
|
* User: liow.kitloong |
|
5
|
|
|
* Date: 2020/03/29 |
|
6
|
|
|
* Time: 14:54 |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace KitLoong\MigrationsGenerator\Generators; |
|
10
|
|
|
|
|
11
|
|
|
use Doctrine\DBAL\Schema\Column; |
|
12
|
|
|
use KitLoong\MigrationsGenerator\MigrationMethod\ColumnModifier; |
|
13
|
|
|
use KitLoong\MigrationsGenerator\Types\DBALTypes; |
|
14
|
|
|
|
|
15
|
|
|
class DecimalField |
|
16
|
|
|
{ |
|
17
|
|
|
// (8, 2) are default value of decimal, float |
|
18
|
|
|
private const DEFAULT_DECIMAL_PRECISION = 8; |
|
19
|
|
|
private const DEFAULT_DECIMAL_SCALE = 2; |
|
20
|
|
|
|
|
21
|
|
|
// DBAL return (10, 0) if double length is empty |
|
22
|
|
|
private const EMPTY_DOUBLE_PRECISION = 10; |
|
23
|
|
|
private const EMPTY_DOUBLE_SCALE = 0; |
|
24
|
|
|
|
|
25
|
|
|
private $decorator; |
|
26
|
|
|
|
|
27
|
|
|
public function __construct(Decorator $decorator) |
|
28
|
|
|
{ |
|
29
|
|
|
$this->decorator = $decorator; |
|
30
|
|
|
} |
|
31
|
|
|
|
|
32
|
|
|
public function makeField(array $field, Column $column): array |
|
33
|
|
|
{ |
|
34
|
|
|
if (in_array($field['type'], [DBALTypes::DECIMAL, DBALTypes::FLOAT])) { |
|
35
|
|
|
$args = $this->getDecimalPrecision($column->getPrecision(), $column->getScale()); |
|
36
|
|
|
} else { |
|
37
|
|
|
// double |
|
38
|
|
|
$args = $this->getDoublePrecision($column->getPrecision(), $column->getScale()); |
|
39
|
|
|
} |
|
40
|
|
|
if (!empty($args)) { |
|
41
|
|
|
$field['args'] = $args; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
if ($column->getUnsigned()) { |
|
45
|
|
|
$field['decorators'][] = ColumnModifier::UNSIGNED; |
|
46
|
|
|
} |
|
47
|
|
|
return $field; |
|
48
|
|
|
} |
|
49
|
|
|
|
|
50
|
|
|
private function getDecimalPrecision(int $precision, int $scale): array |
|
51
|
|
|
{ |
|
52
|
|
|
$return = []; |
|
53
|
|
|
if ($precision != self::DEFAULT_DECIMAL_PRECISION || $scale != self::DEFAULT_DECIMAL_SCALE) { |
|
54
|
|
|
$return[] = $precision; |
|
55
|
|
|
if ($scale != self::DEFAULT_DECIMAL_SCALE) { |
|
56
|
|
|
$return[] = $scale; |
|
57
|
|
|
} |
|
58
|
|
|
} |
|
59
|
|
|
return $return; |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
private function getDoublePrecision(int $precision, int $scale) |
|
63
|
|
|
{ |
|
64
|
|
|
if ($precision === self::EMPTY_DOUBLE_PRECISION && $scale === self::EMPTY_DOUBLE_SCALE) { |
|
65
|
|
|
return []; |
|
66
|
|
|
} else { |
|
67
|
|
|
return [$precision, $scale]; |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
} |
|
71
|
|
|
|