-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathBakeSimpleMigrationCommand.php
More file actions
281 lines (245 loc) · 9.07 KB
/
BakeSimpleMigrationCommand.php
File metadata and controls
281 lines (245 loc) · 9.07 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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
<?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 Bake\Command\SimpleBakeCommand;
use Bake\Utility\TemplateRenderer;
use Cake\Console\Arguments;
use Cake\Console\ConsoleIo;
use Cake\Console\ConsoleOptionParser;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Utility\Inflector;
use DateTime;
use DateTimeZone;
use Migrations\Util\Util;
/**
* Task class for generating migration snapshot files.
*/
abstract class BakeSimpleMigrationCommand extends SimpleBakeCommand
{
public const DEFAULT_MIGRATION_FOLDER = 'Migrations';
protected const RESERVED_KEYWORDS = [
'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const',
'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor',
'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'finally', 'for', 'foreach',
'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface',
'isset', 'list', 'namespace', 'new', 'or', 'parent', 'private', 'protected', 'public', 'return','static',
];
/**
* path to Migration directory
*
* @var string
*/
public string $pathFragment = 'config';
/**
* Console IO
*
* @var \Cake\Console\ConsoleIo
*/
protected ConsoleIo $io;
/**
* Arguments
*
* @var \Cake\Console\Arguments
*/
protected Arguments $args;
/**
* @inheritDoc
*/
public function name(): string
{
return 'migration';
}
/**
* @inheritDoc
*/
public function fileName($name): string
{
$name = $this->getMigrationName($name);
$style = $this->args->getOption('style') ?? Configure::read('Migrations.style', 'traditional');
if ($style === 'anonymous') {
// Use readable format: 2024_12_08_120000_CamelCaseName.php
$timestamp = Util::getCurrentTimestamp();
$dt = new DateTime();
$dt->setTimestamp((int)substr($timestamp, 0, 10));
$dt->setTimezone(new DateTimeZone('UTC'));
$readableDate = $dt->format('Y_m_d');
$time = substr($timestamp, 8);
$camelName = Inflector::camelize($name);
$path = $this->getPath($this->args);
$offset = 0;
while (glob($path . $readableDate . '_' . $time . '_*.php')) {
$timestamp = Util::getCurrentTimestamp(++$offset);
$dt->setTimestamp((int)substr($timestamp, 0, 10));
$readableDate = $dt->format('Y_m_d');
$time = substr($timestamp, 8);
}
return $readableDate . '_' . $time . '_' . $camelName . '.php';
}
// Traditional format
$timestamp = Util::getCurrentTimestamp();
$suffix = '_' . Inflector::camelize($name) . '.php';
$path = $this->getPath($this->args);
$offset = 0;
while (glob($path . $timestamp . '_*.php')) {
$timestamp = Util::getCurrentTimestamp(++$offset);
}
return $timestamp . $suffix;
}
/**
* @inheritDoc
*/
public function getPath(Arguments $args): string
{
$migrationFolder = $this->pathFragment . DS . $args->getOption('source') . DS;
$path = ROOT . DS . $migrationFolder;
if ($this->plugin) {
$path = $this->_pluginPath($this->plugin) . $migrationFolder;
}
return str_replace('/', DS, $path);
}
/**
* @inheritDoc
*/
public function execute(Arguments $args, ConsoleIo $io): ?int
{
if (!Plugin::isLoaded('Bake')) {
$io->err('Bake plugin is not loaded. Please load it first to generate a migration.');
$this->abort();
}
$this->extractCommonProperties($args);
$name = $args->getArgumentAt(0);
if (!$name) {
$io->err('You must provide a name to bake a ' . $this->name());
$this->abort();
}
$name = $this->_getName($name);
$name = Inflector::camelize($name);
$this->bake($name, $args, $io);
return static::CODE_SUCCESS;
}
/**
* @inheritDoc
*/
public function bake(string $name, Arguments $args, ConsoleIo $io): void
{
$this->io = $io;
$this->args = $args;
if ($this->isReservedKeyword($name)) {
$prefix = $io->ask('Reserved keywords cannot be used for class names. What prefix would you like to use? Defaults to `Migration`.', 'Migration');
$name = $prefix . ucfirst($name);
}
$migrationWithSameName = glob($this->getPath($args) . '*_' . $name . '.php');
if ($migrationWithSameName) {
$force = $args->getOption('force');
if (!$force) {
$io->abort(
sprintf(
'A migration with the name `%s` already exists. Please use a different name.',
$name,
),
);
}
$io->info(sprintf('A migration with the name `%s` already exists, it will be deleted.', $name));
foreach ($migrationWithSameName as $migration) {
$io->info(sprintf('Deleting migration file `%s`...', $migration));
if (unlink($migration)) {
$io->success(sprintf('Deleted `%s`', $migration));
} else {
$io->err(sprintf('An error occurred while deleting `%s`', $migration));
}
}
}
$renderer = new TemplateRenderer($this->theme);
$renderer->set('name', $name);
$renderer->set($this->templateData($args));
$contents = $renderer->generate($this->template());
$path = $this->getPath($args);
$filename = $path . $this->fileName($name);
$this->createFile($filename, $contents, $args, $io);
$emptyFile = $path . '.gitkeep';
$this->deleteEmptyFile($emptyFile, $io);
}
/**
* @param string $path Where to put the file.
* @param string $contents Content to put in the file.
* @param \Cake\Console\Arguments $args The command arguments.
* @param \Cake\Console\ConsoleIo $io The console io
* @return bool Success
*/
protected function createFile(string $path, string $contents, Arguments $args, ConsoleIo $io): bool
{
return $io->createFile($path, $contents);
}
/**
* Returns a class name for the migration class
*
* If the name is invalid, the task will exit
*
* @param string|null $name Name for the generated migration
* @return string Name of the migration file
*/
protected function getMigrationName(?string $name = null): string
{
if (!$name) {
$this->io->abort('Choose a migration name to bake in CamelCase format');
}
$name = $this->_getName($name);
$name = Inflector::camelize($name);
if (!preg_match('/^[A-Z]{1}[a-zA-Z0-9]+$/', $name)) {
$this->io->abort('The className is not correct. The className can only contain "A-Z" and "0-9" and has to start with a letter.');
}
return $name;
}
/**
* Gets the option parser instance and configures it.
*
* @param \Cake\Console\ConsoleOptionParser $parser Option parser to update.
* @return \Cake\Console\ConsoleOptionParser
*/
public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionParser
{
$parser = $this->_setCommonOptions($parser);
$parser->setDescription(
'Bake migration class.',
)->addOption('no-test', [
'boolean' => true,
'help' => 'Do not generate a test skeleton.',
])->addOption('source', [
'short' => 's',
'default' => self::DEFAULT_MIGRATION_FOLDER,
'help' => 'Name of the folder in which the migration should be saved.',
]);
$options = $parser->options();
if (!isset($options['force'])) {
$parser->addOption('force', [
'short' => 'f',
'boolean' => true,
'help' => 'Force overwriting existing file if a migration already exists with the same name.',
]);
}
return $parser;
}
/**
* If reserved PHP keyword.
*
* @param string $name
* @return bool
*/
protected function isReservedKeyword(string $name): bool
{
return in_array(strtolower($name), static::RESERVED_KEYWORDS);
}
}