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