-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathAddForeignKey.php
More file actions
91 lines (79 loc) · 2.63 KB
/
Copy pathAddForeignKey.php
File metadata and controls
91 lines (79 loc) · 2.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
<?php
declare(strict_types=1);
/**
* MIT License
* For full license information, please view the LICENSE file that was distributed with this source code.
*/
namespace Migrations\Db\Action;
use Migrations\Db\Table\ForeignKey;
use Migrations\Db\Table\TableMetadata;
class AddForeignKey extends Action
{
/**
* The foreign key to add
*
* @var \Migrations\Db\Table\ForeignKey
*/
protected ForeignKey $foreignKey;
/**
* Constructor
*
* @param \Migrations\Db\Table\TableMetadata $table The table to add the foreign key to
* @param \Migrations\Db\Table\ForeignKey $fk The foreign key to add
*/
public function __construct(TableMetadata $table, ForeignKey $fk)
{
parent::__construct($table);
$this->foreignKey = $fk;
}
/**
* Creates a new AddForeignKey object after building the foreign key with
* the passed attributes
*
* @param \Migrations\Db\Table\TableMetadata $table The table object to add the foreign key to
* @param string|string[] $columns The columns for the foreign key
* @param \Migrations\Db\Table\TableMetadata|string $referencedTable The table the foreign key references
* @param string|string[] $referencedColumns The columns in the referenced table
* @param array<string, mixed> $options Extra options for the foreign key
* @param string|null $name The name of the foreign key
* @return self
*/
public static function build(
TableMetadata $table,
string|array $columns,
TableMetadata|string $referencedTable,
string|array $referencedColumns = ['id'],
array $options = [],
?string $name = null,
): self {
if (is_string($referencedColumns)) {
$referencedColumns = [$referencedColumns]; // str to array
}
if (is_string($referencedTable)) {
$referencedTable = new TableMetadata($referencedTable);
}
// Shimming old 4.x
if (isset($options['constraint'])) {
$options['name'] = $options['constraint'];
unset($options['constraint']);
}
$fk = new ForeignKey();
$fk->setReferencedTable($referencedTable)
->setColumns($columns)
->setReferencedColumns($referencedColumns)
->setOptions($options);
if ($name !== null) {
$fk->setName($name);
}
return new AddForeignKey($table, $fk);
}
/**
* Returns the foreign key to be added
*
* @return \Migrations\Db\Table\ForeignKey
*/
public function getForeignKey(): ForeignKey
{
return $this->foreignKey;
}
}