CakeManager.php
9.21 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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
<?php
/**
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
namespace Migrations;
use Phinx\Migration\Manager;
/**
* Overrides Phinx Manager class in order to provide an interface
* for running migrations within an app
*/
class CakeManager extends Manager
{
/**
* Reset the migrations stored in the object
*
* @return void
*/
public function resetMigrations()
{
$this->migrations = null;
}
/**
* Reset the seeds stored in the object
*
* @return void
*/
public function resetSeeds()
{
$this->seeds = null;
}
/**
* Prints the specified environment's migration status.
*
* @param string $environment
* @param null|string $format
* @return array Array of migrations
*/
public function printStatus($environment, $format = null)
{
$migrations = [];
if (count($this->getMigrations())) {
$env = $this->getEnvironment($environment);
$versions = $env->getVersions();
foreach ($this->getMigrations() as $migration) {
if (in_array($migration->getVersion(), $versions)) {
$status = 'up';
unset($versions[array_search($migration->getVersion(), $versions)]);
} else {
$status = 'down';
}
$migrations[] = [
'status' => $status,
'id' => $migration->getVersion(),
'name' => $migration->getName()
];
}
foreach ($versions as $missing) {
$migrations[] = ['status' => 'up', 'id' => $missing, 'name' => false];
}
}
if ($format === 'json') {
$migrations = json_encode($migrations);
}
return $migrations;
}
/**
* {@inheritdoc}
*/
public function migrateToDateTime($environment, \DateTime $dateTime)
{
$versions = array_keys($this->getMigrations());
$dateString = $dateTime->format('Ymdhis');
$versionToMigrate = null;
foreach ($versions as $version) {
if ($dateString > $version) {
$versionToMigrate = $version;
}
}
if ($versionToMigrate === null) {
$this->getOutput()->writeln(
'No migrations to run'
);
return;
}
$this->getOutput()->writeln(
'Migrating to version ' . $versionToMigrate
);
$this->migrate($environment, $versionToMigrate);
}
/**
* {@inheritdoc}
*/
public function rollbackToDateTime($environment, \DateTime $dateTime)
{
$env = $this->getEnvironment($environment);
$versions = $env->getVersions();
$dateString = $dateTime->format('Ymdhis');
sort($versions);
$versions = array_reverse($versions);
if ($dateString > $versions[0]) {
$this->getOutput()->writeln('No migrations to rollback');
return;
}
if ($dateString < end($versions)) {
$this->getOutput()->writeln('Rolling back all migrations');
$this->rollback($environment, 0);
return;
}
foreach ($versions as $index => $version) {
if ($dateString > $version) {
break;
}
}
$versionToRollback = $versions[$index];
$this->getOutput()->writeln('Rolling back to version ' . $versionToRollback);
$this->rollback($environment, $versionToRollback);
}
/**
* Checks if the migration with version number $version as already been mark migrated
*
* @param int|string $version Version number of the migration to check
* @return bool
*/
public function isMigrated($version)
{
$adapter = $this->getEnvironment('default')->getAdapter();
$versions = array_flip($adapter->getVersions());
return isset($versions[$version]);
}
/**
* Marks migration with version number $version migrated
*
* @param int|string $version Version number of the migration to check
* @param string $path Path where the migration file is located
* @return bool True if success
*/
public function markMigrated($version, $path)
{
$adapter = $this->getEnvironment('default')->getAdapter();
$migrationFile = glob($path . DS . $version . '*');
if (empty($migrationFile)) {
throw new \RuntimeException(
sprintf('A migration file matching version number `%s` could not be found', $version)
);
}
$migrationFile = $migrationFile[0];
$className = $this->getMigrationClassName($migrationFile);
require_once $migrationFile;
$Migration = new $className($version);
$time = date('Y-m-d H:i:s', time());
$adapter->migrated($Migration, 'up', $time, $time);
return true;
}
/**
* Decides which versions it should mark as migrated
*
* @param \Symfony\Component\Console\Input\InputInterface $input Input interface from which argument and options
* will be extracted to determine which versions to be marked as migrated
* @return array Array of versions that should be marked as migrated
* @throws \InvalidArgumentException If the `--exclude` or `--only` options are used without `--target`
* or version not found
*/
public function getVersionsToMark($input)
{
$migrations = $this->getMigrations();
$versions = array_keys($migrations);
$versionArg = $input->getArgument('version');
$targetArg = $input->getOption('target');
$hasAllVersion = in_array($versionArg, ['all', '*']);
if ((empty($versionArg) && empty($targetArg)) || $hasAllVersion) {
return $versions;
}
$version = $targetArg ?: $versionArg;
if ($input->getOption('only') || !empty($versionArg)) {
if (!in_array($version, $versions)) {
throw new \InvalidArgumentException("Migration `$version` was not found !");
}
return [$version];
}
$lengthIncrease = $input->getOption('exclude') ? 0 : 1;
$index = array_search($version, $versions);
if ($index === false) {
throw new \InvalidArgumentException("Migration `$version` was not found !");
}
return array_slice($versions, 0, $index + $lengthIncrease);
}
/**
* Mark all migrations in $versions array found in $path as migrated
*
* It will start a transaction and rollback in case one of the operation raises an exception
*
* @param string $path Path where to look for migrations
* @param array $versions Versions which should be marked
* @param \Symfony\Component\Console\Output\OutputInterface $output OutputInterface used to store
* the command output
* @return void
*/
public function markVersionsAsMigrated($path, $versions, $output)
{
$adapter = $this->getEnvironment('default')->getAdapter();
if (empty($versions)) {
$output->writeln('<info>No migrations were found. Nothing to mark as migrated.</info>');
return;
}
$adapter->beginTransaction();
foreach ($versions as $version) {
if ($this->isMigrated($version)) {
$output->writeln(sprintf('<info>Skipping migration `%s` (already migrated).</info>', $version));
continue;
}
try {
$this->markMigrated($version, $path);
$output->writeln(
sprintf('<info>Migration `%s` successfully marked migrated !</info>', $version)
);
} catch (\Exception $e) {
$adapter->rollbackTransaction();
$output->writeln(
sprintf(
'<error>An error occurred while marking migration `%s` as migrated : %s</error>',
$version,
$e->getMessage()
)
);
$output->writeln('<error>All marked migrations during this process were unmarked.</error>');
return;
}
}
$adapter->commitTransaction();
}
/**
* Resolves a migration class name based on $path
*
* @param string $path Path to the migration file of which we want the class name
* @return string Migration class name
*/
protected function getMigrationClassName($path)
{
$class = preg_replace('/^[0-9]+_/', '', basename($path));
$class = str_replace('_', ' ', $class);
$class = ucwords($class);
$class = str_replace(' ', '', $class);
if (strpos($class, '.') !== false) {
$class = substr($class, 0, strpos($class, '.'));
}
return $class;
}
}