Manager.php
16.5 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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
<?php
/**
* Phinx
*
* (The MIT license)
* Copyright (c) 2015 Rob Morgan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated * documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* @package Phinx
* @subpackage Phinx\Migration
*/
namespace Phinx\Migration;
use Symfony\Component\Console\Output\OutputInterface;
use Phinx\Config\ConfigInterface;
use Phinx\Migration\Manager\Environment;
class Manager
{
/**
* @var ConfigInterface
*/
protected $config;
/**
* @var OutputInterface
*/
protected $output;
/**
* @var array
*/
protected $environments;
/**
* @var array
*/
protected $migrations;
/**
* Class Constructor.
*
* @param ConfigInterface $config Configuration Object
* @param OutputInterface $output Console Output
*/
public function __construct(ConfigInterface $config, OutputInterface $output)
{
$this->setConfig($config);
$this->setOutput($output);
}
/**
* Prints the specified environment's migration status.
*
* @param string $environment
* @param null $format
* @return void
*/
public function printStatus($environment, $format = null)
{
$output = $this->getOutput();
$migrations = array();
if (count($this->getMigrations())) {
$output->writeln('');
$output->writeln(' Status Migration ID Migration Name ');
$output->writeln('-----------------------------------------');
$env = $this->getEnvironment($environment);
$versions = $env->getVersions();
foreach ($this->getMigrations() as $migration) {
if (in_array($migration->getVersion(), $versions)) {
$status = ' <info>up</info> ';
unset($versions[array_search($migration->getVersion(), $versions)]);
} else {
$status = ' <error>down</error> ';
}
$output->writeln(
$status
. sprintf(' %14.0f ', $migration->getVersion())
. ' <comment>' . $migration->getName() . '</comment>'
);
$migrations[] = array('migration_status' => trim(strip_tags($status)), 'migration_id' => sprintf('%14.0f', $migration->getVersion()), 'migration_name' => $migration->getName());
}
foreach ($versions as $missing) {
$output->writeln(
' <error>up</error> '
. sprintf(' %14.0f ', $missing)
. ' <error>** MISSING **</error>'
);
}
} else {
// there are no migrations
$output->writeln('');
$output->writeln('There are no available migrations. Try creating one using the <info>create</info> command.');
}
// write an empty line
$output->writeln('');
if ($format != null) {
switch ($format) {
case 'json':
$output->writeln(json_encode($migrations));
break;
default:
$output->writeln('<info>Unsupported format: '.$format.'</info>');
break;
}
}
}
/**
* Migrate to the version of the database on a given date.
*
* @param string $environment Environment
* @param \DateTime $dateTime Date to migrate to
*
* @return void
*/
public function migrateToDateTime($environment, \DateTime $dateTime)
{
$env = $this->getEnvironment($environment);
$versions = array_keys($this->getMigrations());
$dateString = $dateTime->format('Ymdhis');
$earlierVersion = null;
foreach ($versions as $version) {
if ($version > $dateString) {
if (!is_null($earlierVersion)) {
$this->getOutput()->writeln(
'Migrating to version ' . $earlierVersion
);
}
return $this->migrate($environment, $earlierVersion);
}
$earlierVersion = $version;
}
//If the date is greater than the latest version, migrate
//to the latest version.
$this->getOutput()->writeln(
'Migrating to version ' . $earlierVersion
);
return $this->migrate($environment, $earlierVersion);
}
/**
* Roll back to the version of the database on a given date.
*
* @param string $environment Environment
* @param \DateTime $dateTime Date to roll back to
*
* @return void
*/
public function rollbackToDateTime($environment, \DateTime $dateTime)
{
$env = $this->getEnvironment($environment);
$versions = $env->getVersions();
$dateString = $dateTime->format('Ymdhis');
sort($versions);
$laterVersion = null;
foreach (array_reverse($versions) as $version) {
if ($version < $dateString) {
if (!is_null($laterVersion)) {
$this->getOutput()->writeln('Rolling back to version '.$version);
}
return $this->rollback($environment, $version);
}
$laterVersion = $version;
}
$this->getOutput()->writeln('Rolling back to version ' . $laterVersion);
return $this->rollback($environment, $laterVersion);
}
/**
* Migrate an environment to the specified version.
*
* @param string $environment Environment
* @param int $version
* @return void
*/
public function migrate($environment, $version = null)
{
$migrations = $this->getMigrations();
$env = $this->getEnvironment($environment);
$versions = $env->getVersions();
$current = $env->getCurrentVersion();
if (empty($versions) && empty($migrations)) {
return;
}
if (null === $version) {
$version = max(array_merge($versions, array_keys($migrations)));
} else {
if (0 != $version && !isset($migrations[$version])) {
$this->output->writeln(sprintf(
'<comment>warning</comment> %s is not a valid version',
$version
));
return;
}
}
// are we migrating up or down?
$direction = $version > $current ? MigrationInterface::UP : MigrationInterface::DOWN;
if ($direction == MigrationInterface::DOWN) {
// run downs first
krsort($migrations);
foreach ($migrations as $migration) {
if ($migration->getVersion() <= $version) {
break;
}
if (in_array($migration->getVersion(), $versions)) {
$this->executeMigration($environment, $migration, MigrationInterface::DOWN);
}
}
}
ksort($migrations);
foreach ($migrations as $migration) {
if ($migration->getVersion() > $version) {
break;
}
if (!in_array($migration->getVersion(), $versions)) {
$this->executeMigration($environment, $migration, MigrationInterface::UP);
}
}
}
/**
* Execute a migration against the specified Environment.
*
* @param string $name Environment Name
* @param MigrationInterface $migration Migration
* @param string $direction Direction
* @return void
*/
public function executeMigration($name, MigrationInterface $migration, $direction = MigrationInterface::UP)
{
$this->getOutput()->writeln('');
$this->getOutput()->writeln(
' =='
. ' <info>' . $migration->getVersion() . ' ' . $migration->getName() . ':</info>'
. ' <comment>' . ($direction == 'up' ? 'migrating' : 'reverting') . '</comment>'
);
// Execute the migration and log the time elapsed.
$start = microtime(true);
$this->getEnvironment($name)->executeMigration($migration, $direction);
$end = microtime(true);
$this->getOutput()->writeln(
' =='
. ' <info>' . $migration->getVersion() . ' ' . $migration->getName() . ':</info>'
. ' <comment>' . ($direction == 'up' ? 'migrated' : 'reverted')
. ' ' . sprintf('%.4fs', $end - $start) . '</comment>'
);
}
/**
* Rollback an environment to the specified version.
*
* @param string $environment Environment
* @param int $version
* @return void
*/
public function rollback($environment, $version = null)
{
$migrations = $this->getMigrations();
$env = $this->getEnvironment($environment);
$versions = $env->getVersions();
ksort($migrations);
sort($versions);
// Check we have at least 1 migration to revert
if (empty($versions) || $version == end($versions)) {
$this->getOutput()->writeln('<error>No migrations to rollback</error>');
return;
}
// If no target version was supplied, revert the last migration
if (null === $version) {
// Get the migration before the last run migration
$prev = count($versions) - 2;
$version = $prev >= 0 ? $versions[$prev] : 0;
} else {
// Get the first migration number
$first = reset($versions);
// If the target version is before the first migration, revert all migrations
if ($version < $first) {
$version = 0;
}
}
// Check the target version exists
if (0 !== $version && !isset($migrations[$version])) {
$this->getOutput()->writeln("<error>Target version ($version) not found</error>");
return;
}
// Revert the migration(s)
krsort($migrations);
foreach ($migrations as $migration) {
if ($migration->getVersion() <= $version) {
break;
}
if (in_array($migration->getVersion(), $versions)) {
$this->executeMigration($environment, $migration, MigrationInterface::DOWN);
}
}
}
/**
* Sets the environments.
*
* @param array $environments Environments
* @return Manager
*/
public function setEnvironments($environments = array())
{
$this->environments = $environments;
return $this;
}
/**
* Gets the manager class for the given environment.
*
* @param string $name Environment Name
* @throws \InvalidArgumentException
* @return Environment
*/
public function getEnvironment($name)
{
if (isset($this->environments[$name])) {
return $this->environments[$name];
}
// check the environment exists
if (!$this->getConfig()->hasEnvironment($name)) {
throw new \InvalidArgumentException(sprintf(
'The environment "%s" does not exist',
$name
));
}
// create an environment instance and cache it
$environment = new Environment($name, $this->getConfig()->getEnvironment($name));
$this->environments[$name] = $environment;
$environment->setOutput($this->getOutput());
return $environment;
}
/**
* Sets the console output.
*
* @param OutputInterface $output Output
* @return Manager
*/
public function setOutput(OutputInterface $output)
{
$this->output = $output;
return $this;
}
/**
* Gets the console output.
*
* @return OutputInterface
*/
public function getOutput()
{
return $this->output;
}
/**
* Sets the database migrations.
*
* @param array $migrations Migrations
* @return Manager
*/
public function setMigrations(array $migrations)
{
$this->migrations = $migrations;
return $this;
}
/**
* Gets an array of the database migrations.
*
* @throws \InvalidArgumentException
* @return AbstractMigration[]
*/
public function getMigrations()
{
if (null === $this->migrations) {
$config = $this->getConfig();
$phpFiles = glob($config->getMigrationPath() . DIRECTORY_SEPARATOR . '*.php');
// filter the files to only get the ones that match our naming scheme
$fileNames = array();
/** @var AbstractMigration[] $versions */
$versions = array();
foreach ($phpFiles as $filePath) {
if (preg_match('/([0-9]+)_([_a-z0-9]*).php/', basename($filePath))) {
$matches = array();
preg_match('/^[0-9]+/', basename($filePath), $matches); // get the version from the start of the filename
$version = $matches[0];
if (isset($versions[$version])) {
throw new \InvalidArgumentException(sprintf('Duplicate migration - "%s" has the same version as "%s"', $filePath, $versions[$version]->getVersion()));
}
// convert the filename to a class name
$class = preg_replace('/^[0-9]+_/', '', basename($filePath));
$class = str_replace('_', ' ', $class);
$class = ucwords($class);
$class = str_replace(' ', '', $class);
if (false !== strpos($class, '.')) {
$class = substr($class, 0, strpos($class, '.'));
}
if (isset($fileNames[$class])) {
throw new \InvalidArgumentException(sprintf(
'Migration "%s" has the same name as "%s"',
basename($filePath),
$fileNames[$class]
));
}
$fileNames[$class] = basename($filePath);
// load the migration file
/** @noinspection PhpIncludeInspection */
require_once $filePath;
if (!class_exists($class)) {
throw new \InvalidArgumentException(sprintf(
'Could not find class "%s" in file "%s"',
$class,
$filePath
));
}
// instantiate it
$migration = new $class($version);
if (!($migration instanceof AbstractMigration)) {
throw new \InvalidArgumentException(sprintf(
'The class "%s" in file "%s" must extend \Phinx\Migration\AbstractMigration',
$class,
$filePath
));
}
$migration->setOutput($this->getOutput());
$versions[$version] = $migration;
}
}
ksort($versions);
$this->setMigrations($versions);
}
return $this->migrations;
}
/**
* Sets the config.
*
* @param ConfigInterface $config Configuration Object
* @return Manager
*/
public function setConfig(ConfigInterface $config)
{
$this->config = $config;
return $this;
}
/**
* Gets the config.
*
* @return ConfigInterface
*/
public function getConfig()
{
return $this->config;
}
}