1
|
|
|
<?php namespace KitLoong\MigrationsGenerator\Generators; |
2
|
|
|
|
3
|
|
|
class ForeignKeyGenerator |
4
|
|
|
{ |
5
|
|
|
/** |
6
|
|
|
* @var string |
7
|
|
|
*/ |
8
|
|
|
protected $table; |
9
|
|
|
|
10
|
|
|
private $decorator; |
11
|
|
|
|
12
|
18 |
|
public function __construct(Decorator $decorator) |
13
|
|
|
{ |
14
|
18 |
|
$this->decorator = $decorator; |
15
|
18 |
|
} |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* Get array of foreign keys |
19
|
|
|
* |
20
|
|
|
* @param string $table Table name |
21
|
|
|
* @param \Doctrine\DBAL\Schema\ForeignKeyConstraint[] $foreignKeys |
22
|
|
|
* @param bool $ignoreForeignKeyNames |
23
|
|
|
* |
24
|
|
|
* @return array |
25
|
|
|
*/ |
26
|
|
|
public function generate(string $table, $foreignKeys, bool $ignoreForeignKeyNames): array |
27
|
|
|
{ |
28
|
|
|
$this->table = $table; |
29
|
|
|
$fields = []; |
30
|
|
|
|
31
|
|
|
if (empty($foreignKeys)) { |
32
|
|
|
return []; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
foreach ($foreignKeys as $foreignKey) { |
36
|
|
|
$fields[] = [ |
37
|
|
|
'name' => $this->getName($foreignKey, $ignoreForeignKeyNames), |
38
|
|
|
'field' => $foreignKey->getLocalColumns()[0], |
39
|
|
|
'references' => $foreignKey->getForeignColumns()[0], |
40
|
|
|
'on' => $this->decorator->tableWithoutPrefix($foreignKey->getForeignTableName()), |
41
|
|
|
'onUpdate' => $foreignKey->hasOption('onUpdate') ? $foreignKey->getOption('onUpdate') : 'RESTRICT', |
42
|
|
|
'onDelete' => $foreignKey->hasOption('onDelete') ? $foreignKey->getOption('onDelete') : 'RESTRICT', |
43
|
|
|
]; |
44
|
|
|
} |
45
|
|
|
return $fields; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey |
50
|
|
|
* @param bool $ignoreForeignKeyNames |
51
|
|
|
* |
52
|
|
|
* @return null|string |
53
|
|
|
*/ |
54
|
|
|
protected function getName($foreignKey, bool $ignoreForeignKeyNames): ?string |
55
|
|
|
{ |
56
|
|
|
if ($ignoreForeignKeyNames or $this->isDefaultName($foreignKey)) { |
57
|
|
|
return null; |
58
|
|
|
} |
59
|
|
|
return $foreignKey->getName(); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* @param \Doctrine\DBAL\Schema\ForeignKeyConstraint $foreignKey |
64
|
|
|
* |
65
|
|
|
* @return bool |
66
|
|
|
*/ |
67
|
|
|
protected function isDefaultName($foreignKey): bool |
68
|
|
|
{ |
69
|
|
|
return $foreignKey->getName() === $this->createIndexName($foreignKey->getLocalColumns()[0]); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Create a default index name for the table. |
74
|
|
|
* |
75
|
|
|
* @param string $column |
76
|
|
|
* @return string |
77
|
|
|
*/ |
78
|
|
|
protected function createIndexName(string $column): string |
79
|
|
|
{ |
80
|
|
|
$index = strtolower($this->table.'_'.$column.'_foreign'); |
81
|
|
|
|
82
|
|
|
return str_replace(['-', '.'], '_', $index); |
83
|
|
|
} |
84
|
|
|
} |
85
|
|
|
|