1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Cycle\Migrations\Operation\ForeignKey; |
6
|
|
|
|
7
|
|
|
use Cycle\Database\ForeignKeyInterface; |
8
|
|
|
use Cycle\Migrations\CapsuleInterface; |
9
|
|
|
use Cycle\Migrations\Exception\Operation\ForeignKeyException; |
10
|
|
|
use Cycle\Migrations\Operation\Traits\OptionsTrait; |
11
|
|
|
|
12
|
|
|
final class Alter extends ForeignKey |
13
|
|
|
{ |
14
|
|
|
use OptionsTrait; |
15
|
|
|
|
16
|
32 |
|
public function __construct( |
17
|
|
|
string $table, |
18
|
|
|
array $columns, |
19
|
|
|
private string $foreignTable, |
20
|
|
|
private array $foreignKeys, |
21
|
|
|
array $options |
22
|
|
|
) { |
23
|
32 |
|
$this->options = $options; |
24
|
32 |
|
parent::__construct($table, $columns); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* {@inheritdoc} |
29
|
|
|
*/ |
30
|
32 |
|
public function execute(CapsuleInterface $capsule): void |
31
|
|
|
{ |
32
|
32 |
|
$schema = $capsule->getSchema($this->getTable()); |
33
|
|
|
|
34
|
32 |
|
if (!$schema->hasForeignKey($this->columns)) { |
35
|
8 |
|
throw new ForeignKeyException( |
36
|
8 |
|
"Unable to alter foreign key '{$schema->getName()}'.({$this->columnNames()}), " |
37
|
|
|
. 'key does not exists' |
38
|
|
|
); |
39
|
|
|
} |
40
|
|
|
|
41
|
24 |
|
$outerSchema = $capsule->getSchema($this->foreignTable); |
42
|
|
|
|
43
|
24 |
|
if ($this->foreignTable != $this->table && !$outerSchema->exists()) { |
44
|
8 |
|
throw new ForeignKeyException( |
45
|
8 |
|
"Unable to alter foreign key '{$schema->getName()}'.'{$this->columnNames()}', " |
46
|
8 |
|
. "foreign table '{$this->foreignTable}' does not exists" |
47
|
|
|
); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
|
51
|
16 |
|
foreach ($this->foreignKeys as $fk) { |
52
|
16 |
|
if ($this->foreignTable != $this->table && !$outerSchema->hasColumn($fk)) { |
53
|
8 |
|
throw new ForeignKeyException( |
54
|
8 |
|
"Unable to alter foreign key '{$schema->getName()}'.'{$this->columnNames()}'," |
55
|
8 |
|
. " foreign column '{$this->foreignTable}'.'{$fk}' does not exists" |
56
|
|
|
); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
8 |
|
$foreignKey = $schema->foreignKey($this->columns)->references( |
61
|
8 |
|
$this->foreignTable, |
62
|
8 |
|
$this->foreignKeys |
63
|
|
|
); |
64
|
|
|
|
65
|
|
|
/* |
66
|
|
|
* We are allowing both formats "NO_ACTION" and "NO ACTION". |
67
|
|
|
*/ |
68
|
|
|
|
69
|
8 |
|
$foreignKey->onDelete( |
70
|
8 |
|
str_replace( |
71
|
|
|
'_', |
72
|
|
|
' ', |
73
|
8 |
|
$this->getOption('delete', ForeignKeyInterface::NO_ACTION) |
74
|
|
|
) |
75
|
|
|
); |
76
|
|
|
|
77
|
8 |
|
$foreignKey->onUpdate( |
78
|
8 |
|
str_replace( |
79
|
|
|
'_', |
80
|
|
|
' ', |
81
|
8 |
|
$this->getOption('update', ForeignKeyInterface::NO_ACTION) |
82
|
|
|
) |
83
|
|
|
); |
84
|
|
|
} |
85
|
|
|
} |
86
|
|
|
|