-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathBakeMigrationCommand.php
More file actions
250 lines (209 loc) · 8.74 KB
/
BakeMigrationCommand.php
File metadata and controls
250 lines (209 loc) · 8.74 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Migrations\Command;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Core\Configure;
use Cake\Event\Event;
use Cake\Event\EventManager;
use Cake\Utility\Inflector;
use Migrations\Util\ColumnParser;
/**
* Command class for generating migration snapshot files.
*/
class BakeMigrationCommand extends BakeSimpleMigrationCommand
{
/**
* @var string
*/
protected string $_name;
/**
* @inheritDoc
*/
public static function defaultName(): string
{
return 'bake migration';
}
/**
* @inheritDoc
*/
public function bake(string $name, Arguments $args, ConsoleIo $io): void
{
EventManager::instance()->on('Bake.initialize', function (Event $event): void {
$event->getSubject()->loadHelper('Migrations.Migration');
});
$this->_name = $name;
parent::bake($name, $args, $io);
}
/**
* @inheritDoc
*/
public function template(): string
{
return 'Migrations.config/skeleton';
}
/**
* @inheritDoc
*/
public function templateData(Arguments $arguments): array
{
$className = $this->_name;
$namespace = Configure::read('App.namespace');
$pluginPath = '';
if ($this->plugin) {
$namespace = $this->_pluginNamespace($this->plugin);
$pluginPath = $this->plugin . '.';
}
/** @var array<int, string> $args */
$args = $arguments->getArguments();
unset($args[0]);
$columnParser = new ColumnParser();
$fields = $columnParser->parseFields($args);
$indexes = $columnParser->parseIndexes($args);
$primaryKey = $columnParser->parsePrimaryKey($args);
$foreignKeys = $columnParser->parseForeignKeys($args);
$action = $this->detectAction($className);
if (!$action && count($fields)) {
$this->io->abort('When applying fields the migration name should start with one of the following prefixes: `Create`, `Drop`, `Add`, `Remove`, `Alter`. See: https://book.cakephp.org/migrations/4/en/index.html#migrations-file-name');
}
if (!$action) {
return [
'plugin' => $this->plugin,
'pluginPath' => $pluginPath,
'namespace' => $namespace,
'tables' => [],
'action' => null,
'name' => $className,
'backend' => Configure::read('Migrations.backend', 'builtin'),
];
}
if (in_array($action[0], ['alter_table', 'add_field'], true) && $primaryKey) {
$this->io->abort('Adding a primary key to an already existing table is not supported.');
}
[$action, $table] = $action;
return [
'plugin' => $this->plugin,
'pluginPath' => $pluginPath,
'namespace' => $namespace,
'tables' => [$table],
'action' => $action,
'columns' => [
'fields' => $fields,
'indexes' => $indexes,
'primaryKey' => $primaryKey,
],
'constraints' => $foreignKeys,
'name' => $className,
'backend' => Configure::read('Migrations.backend', 'builtin'),
];
}
/**
* Gets the option parser instance and configures it.
*
* @return \Cake\Console\ConsoleOptionParser
*/
public function getOptionParser(): ConsoleOptionParser
{
$parser = parent::getOptionParser();
$text = <<<'TEXT'
Create a blank or generated migration. Using the name of the migration
Operations and table names will be inferred.
<info>Examples</info>
<warning>bin/cake bake migration CreateUsers</warning>
This command will generate a migration that creates
a table named users.
<warning>bin/cake bake migration DropGroups</warning>
This command will generate a migration that drops
the groups table.
<warning>bin/cake bake migration AlterUsers</warning>
This command will generate a migration that alters the users table.
<warning>bin/cake bake migration AddFieldToUsers role:string</warning>
This command will generate a migration that adds a 'role' field
with a 'string' type to the users table. Migrations that operate
on columns can use the <info>Column Grammar</info> to describe
the column in detail.
<warning>bin/cake bake migration AlterFieldOnUsers role</warning>
These commands will generate a migration that will alter the 'role'
field on the users table.
<warning>bin/cake bake migration RemoveFieldsFromUsers role</warning>
<warning>bin/cake bake migration RemoveRoleFromUsers</warning>
These commands will generate a migration that will remove the 'role'
field on the users table.
<info>Column Grammar</info>
When describing columns you can use the following syntax:
<warning>{name}:{primary}{type}{nullable}[{length}]:{index}:{indexName}</warning>
All sections other than name are optional.
* The types are the abstract database column types in CakePHP.
* The <warning>?</warning> value indicates if a column is nullable.
e.g. <warning>role:string?</warning>.
* Length option must be enclosed in <warning>[]</warning>, for example: <warning>name:string?[100]</warning>.
* The <warning>index</warning> attribute can define the column as having a unique
key with <warning>unique</warning> or a primary key with <warning>primary</warning>.
* Use <warning>references</warning> type to create a foreign key constraint.
e.g. <warning>category_id:references</warning> (auto-infers table as 'categories')
or <warning>category_id:references:custom_table</warning> to specify the referenced table.
<info>Examples</info>
<warning>bin/cake bake migration AddOrgIdToProjects org_id:int</warning>
Create a migration that adds a column (<warning>org_id INT</warning>) to the <warning>projects</warning>
table.
<warning>bin/cake bake migration AddOrgIdToProjects org_id:int?</warning>
Create a migration that adds a nullable column (<warning>org_id INT NULL</warning>) to the <warning>projects</warning>
table.
<warning>bin/cake bake migration AddNameToProjects name:string[128]</warning>
Create a migration that adds (<warning>name VARCHAR(128)</warning>) to the <warning>projects</warning>
table.
<warning>bin/cake bake migration AddSlugToProjects name:string[128]:unique</warning>
Create a migration that adds (<warning>name VARCHAR(128)</warning> and a <warning>UNIQUE</warning> index)
to the <warning>projects</warning> table.
<warning>bin/cake bake migration CreatePosts title:string user_id:references</warning>
Create a migration that creates the <warning>posts</warning> table with a foreign key
constraint on <warning>user_id</warning> referencing the <warning>users</warning> table.
<warning>bin/cake bake migration AddCategoryIdToArticles category_id:references:categories</warning>
Create a migration that adds a foreign key column (<warning>category_id</warning>) to the <warning>articles</warning>
table referencing the <warning>categories</warning> table.
TEXT;
$parser->setDescription($text);
return $parser;
}
/**
* Detects the action and table from the name of a migration
*
* @param string $name Name of migration
* @return array<string>
*/
public function detectAction(string $name): array
{
if (preg_match('/^(Create|Drop)(.*)/', $name, $matches)) {
$action = strtolower($matches[1]) . '_table';
$table = Inflector::underscore($matches[2]);
} elseif (preg_match('/^(Add).+?(?:To)(.*)/', $name, $matches)) {
$action = 'add_field';
$table = Inflector::underscore($matches[2]);
} elseif (preg_match('/^(Remove).+?(?:From)(.*)/', $name, $matches)) {
$action = 'drop_field';
$table = Inflector::underscore($matches[2]);
} elseif (preg_match('/^(Alter).+?(?:On)(.*)/', $name, $matches)) {
$action = 'alter_field';
$table = Inflector::underscore($matches[2]);
} elseif (preg_match('/^(Alter)(.*)/', $name, $matches)) {
$action = 'alter_table';
$table = Inflector::underscore($matches[2]);
} else {
return [];
}
return [$action, $table];
}
}