forked from zarplata/mongodb-migrations
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMigration.php
92 lines (77 loc) · 2.87 KB
/
Migration.php
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
<?php
/*
* This file is part of the AntiMattr MongoDB Migrations Library, a library by Matthew Fitzgerald.
*
* (c) 2014 Matthew Fitzgerald
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace AntiMattr\MongoDB\Migrations;
use AntiMattr\MongoDB\Migrations\Configuration\Configuration;
use AntiMattr\MongoDB\Migrations\Exception\NoMigrationsToExecuteException;
use AntiMattr\MongoDB\Migrations\Exception\UnknownVersionException;
/**
* @author Matthew Fitzgerald <matthewfitz@gmail.com>
*/
class Migration
{
/**
* The OutputWriter object instance used for outputting information.
*
* @var OutputWriter
*/
private $outputWriter;
/**
* @var Configuration
*/
private $configuration;
/**
* Construct a Migration instance.
*
* @param Configuration $configuration A migration Configuration instance
*/
public function __construct(Configuration $configuration)
{
$this->configuration = $configuration;
$this->outputWriter = $configuration->getOutputWriter();
}
/**
* Run a migration to the current version or the given target version.
*
* @param string $to The version to migrate to
*
* @throws AntiMattr\MongoDB\Migrations\Exception\UnknownVersionException
* @throws AntiMattr\MongoDB\Migrations\Exception\NoMigrationsToExecuteException
*/
public function migrate($to = null)
{
if (null === $to) {
$to = $this->configuration->getLatestVersion();
}
$from = $this->configuration->getCurrentVersion();
$from = (string) $from;
$to = (string) $to;
$migrations = $this->configuration->getMigrations();
if (!isset($migrations[$to]) && $to > 0) {
throw new UnknownVersionException($to);
}
$direction = $from > $to ? 'down' : 'up';
$migrationsToExecute = $this->configuration->getMigrationsToExecute($direction, $to);
if ($from === $to && empty($migrationsToExecute) && $migrations) {
return;
}
$this->outputWriter->write(sprintf('Migrating <info>%s</info> to <comment>%s</comment> from <comment>%s</comment>', $direction, $to, $from));
if (empty($migrationsToExecute)) {
throw new NoMigrationsToExecuteException('Could not find any migrations to execute.');
}
$time = 0;
foreach ($migrationsToExecute as $version) {
$version->execute($direction);
$time += $version->getTime();
}
$this->outputWriter->write("\n <comment>------------------------</comment>\n");
$this->outputWriter->write(sprintf(' <info>++</info> finished in %s', $time));
$this->outputWriter->write(sprintf(' <info>++</info> %s migrations executed', count($migrationsToExecute)));
}
}