123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978 |
- <?php
- namespace yii\console\controllers;
- use Yii;
- use yii\base\BaseObject;
- use yii\base\InvalidConfigException;
- use yii\base\NotSupportedException;
- use yii\console\Controller;
- use yii\console\Exception;
- use yii\console\ExitCode;
- use yii\db\MigrationInterface;
- use yii\helpers\Console;
- use yii\helpers\FileHelper;
- use yii\helpers\Inflector;
- abstract class BaseMigrateController extends Controller
- {
-
- const BASE_MIGRATION = 'm000000_000000_base';
-
- public $defaultAction = 'up';
-
- public $migrationPath = ['@app/migrations'];
-
- public $migrationNamespaces = [];
-
- public $templateFile;
-
- public $compact = false;
-
- public function options($actionID)
- {
- return array_merge(
- parent::options($actionID),
- ['migrationPath', 'migrationNamespaces', 'compact'],
- $actionID === 'create' ? ['templateFile'] : []
- );
- }
-
- public function beforeAction($action)
- {
- if (parent::beforeAction($action)) {
- if (empty($this->migrationNamespaces) && empty($this->migrationPath)) {
- throw new InvalidConfigException('At least one of `migrationPath` or `migrationNamespaces` should be specified.');
- }
- foreach ($this->migrationNamespaces as $key => $value) {
- $this->migrationNamespaces[$key] = trim($value, '\\');
- }
- if (is_array($this->migrationPath)) {
- foreach ($this->migrationPath as $i => $path) {
- $this->migrationPath[$i] = Yii::getAlias($path);
- }
- } elseif ($this->migrationPath !== null) {
- $path = Yii::getAlias($this->migrationPath);
- if (!is_dir($path)) {
- if ($action->id !== 'create') {
- throw new InvalidConfigException("Migration failed. Directory specified in migrationPath doesn't exist: {$this->migrationPath}");
- }
- FileHelper::createDirectory($path);
- }
- $this->migrationPath = $path;
- }
- $version = Yii::getVersion();
- $this->stdout("Yii Migration Tool (based on Yii v{$version})\n\n");
- return true;
- }
- return false;
- }
-
- public function actionUp($limit = 0)
- {
- $migrations = $this->getNewMigrations();
- if (empty($migrations)) {
- $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
- return ExitCode::OK;
- }
- $total = count($migrations);
- $limit = (int) $limit;
- if ($limit > 0) {
- $migrations = array_slice($migrations, 0, $limit);
- }
- $n = count($migrations);
- if ($n === $total) {
- $this->stdout("Total $n new " . ($n === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
- } else {
- $this->stdout("Total $n out of $total new " . ($total === 1 ? 'migration' : 'migrations') . " to be applied:\n", Console::FG_YELLOW);
- }
- foreach ($migrations as $migration) {
- $nameLimit = $this->getMigrationNameLimit();
- if ($nameLimit !== null && strlen($migration) > $nameLimit) {
- $this->stdout("\nThe migration name '$migration' is too long. Its not possible to apply this migration.\n", Console::FG_RED);
- return ExitCode::UNSPECIFIED_ERROR;
- }
- $this->stdout("\t$migration\n");
- }
- $this->stdout("\n");
- $applied = 0;
- if ($this->confirm('Apply the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
- foreach ($migrations as $migration) {
- if (!$this->migrateUp($migration)) {
- $this->stdout("\n$applied from $n " . ($applied === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_RED);
- $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
- return ExitCode::UNSPECIFIED_ERROR;
- }
- $applied++;
- }
- $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " applied.\n", Console::FG_GREEN);
- $this->stdout("\nMigrated up successfully.\n", Console::FG_GREEN);
- }
- }
-
- public function actionDown($limit = 1)
- {
- if ($limit === 'all') {
- $limit = null;
- } else {
- $limit = (int) $limit;
- if ($limit < 1) {
- throw new Exception('The step argument must be greater than 0.');
- }
- }
- $migrations = $this->getMigrationHistory($limit);
- if (empty($migrations)) {
- $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
- return ExitCode::OK;
- }
- $migrations = array_keys($migrations);
- $n = count($migrations);
- $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
- foreach ($migrations as $migration) {
- $this->stdout("\t$migration\n");
- }
- $this->stdout("\n");
- $reverted = 0;
- if ($this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
- foreach ($migrations as $migration) {
- if (!$this->migrateDown($migration)) {
- $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED);
- $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
- return ExitCode::UNSPECIFIED_ERROR;
- }
- $reverted++;
- }
- $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN);
- $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
- }
- }
-
- public function actionRedo($limit = 1)
- {
- if ($limit === 'all') {
- $limit = null;
- } else {
- $limit = (int) $limit;
- if ($limit < 1) {
- throw new Exception('The step argument must be greater than 0.');
- }
- }
- $migrations = $this->getMigrationHistory($limit);
- if (empty($migrations)) {
- $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
- return ExitCode::OK;
- }
- $migrations = array_keys($migrations);
- $n = count($migrations);
- $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be redone:\n", Console::FG_YELLOW);
- foreach ($migrations as $migration) {
- $this->stdout("\t$migration\n");
- }
- $this->stdout("\n");
- if ($this->confirm('Redo the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')) {
- foreach ($migrations as $migration) {
- if (!$this->migrateDown($migration)) {
- $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
- return ExitCode::UNSPECIFIED_ERROR;
- }
- }
- foreach (array_reverse($migrations) as $migration) {
- if (!$this->migrateUp($migration)) {
- $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
- return ExitCode::UNSPECIFIED_ERROR;
- }
- }
- $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " redone.\n", Console::FG_GREEN);
- $this->stdout("\nMigration redone successfully.\n", Console::FG_GREEN);
- }
- }
-
- public function actionTo($version)
- {
- if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
- $this->migrateToVersion($namespaceVersion);
- } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
- $this->migrateToVersion($migrationName);
- } elseif ((string) (int) $version == $version) {
- $this->migrateToTime($version);
- } elseif (($time = strtotime($version)) !== false) {
- $this->migrateToTime($time);
- } else {
- throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401),\n the full name of a migration (e.g. m101129_185401_create_user_table),\n the full namespaced name of a migration (e.g. app\\migrations\\M101129185401CreateUserTable),\n a UNIX timestamp (e.g. 1392853000), or a datetime string parseable\nby the strtotime() function (e.g. 2014-02-15 13:00:50).");
- }
- }
-
- public function actionMark($version)
- {
- $originalVersion = $version;
- if (($namespaceVersion = $this->extractNamespaceMigrationVersion($version)) !== false) {
- $version = $namespaceVersion;
- } elseif (($migrationName = $this->extractMigrationVersion($version)) !== false) {
- $version = $migrationName;
- } elseif ($version !== static::BASE_MIGRATION) {
- throw new Exception("The version argument must be either a timestamp (e.g. 101129_185401)\nor the full name of a migration (e.g. m101129_185401_create_user_table)\nor the full name of a namespaced migration (e.g. app\\migrations\\M101129185401CreateUserTable).");
- }
-
- $migrations = $this->getNewMigrations();
- foreach ($migrations as $i => $migration) {
- if (strpos($migration, $version) === 0) {
- if ($this->confirm("Set migration history at $originalVersion?")) {
- for ($j = 0; $j <= $i; ++$j) {
- $this->addMigrationHistory($migrations[$j]);
- }
- $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
- }
- return ExitCode::OK;
- }
- }
-
- $migrations = array_keys($this->getMigrationHistory(null));
- $migrations[] = static::BASE_MIGRATION;
- foreach ($migrations as $i => $migration) {
- if (strpos($migration, $version) === 0) {
- if ($i === 0) {
- $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
- } else {
- if ($this->confirm("Set migration history at $originalVersion?")) {
- for ($j = 0; $j < $i; ++$j) {
- $this->removeMigrationHistory($migrations[$j]);
- }
- $this->stdout("The migration history is set at $originalVersion.\nNo actual migration was performed.\n", Console::FG_GREEN);
- }
- }
- return ExitCode::OK;
- }
- }
- throw new Exception("Unable to find the version '$originalVersion'.");
- }
-
- public function actionFresh()
- {
- if (YII_ENV_PROD) {
- $this->stdout("YII_ENV is set to 'prod'.\nRefreshing migrations is not possible on production systems.\n");
- return ExitCode::OK;
- }
- if ($this->confirm(
- "Are you sure you want to reset the database and start the migration from the beginning?\nAll data will be lost irreversibly!")) {
- $this->truncateDatabase();
- $this->actionUp();
- } else {
- $this->stdout('Action was cancelled by user. Nothing has been performed.');
- }
- }
-
- private function extractNamespaceMigrationVersion($rawVersion)
- {
- if (preg_match('/^\\\\?([\w_]+\\\\)+m(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
- return trim($rawVersion, '\\');
- }
- return false;
- }
-
- private function extractMigrationVersion($rawVersion)
- {
- if (preg_match('/^m?(\d{6}_?\d{6})(\D.*)?$/is', $rawVersion, $matches)) {
- return 'm' . $matches[1];
- }
- return false;
- }
-
- public function actionHistory($limit = 10)
- {
- if ($limit === 'all') {
- $limit = null;
- } else {
- $limit = (int) $limit;
- if ($limit < 1) {
- throw new Exception('The limit must be greater than 0.');
- }
- }
- $migrations = $this->getMigrationHistory($limit);
- if (empty($migrations)) {
- $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
- } else {
- $n = count($migrations);
- if ($limit > 0) {
- $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
- } else {
- $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
- }
- foreach ($migrations as $version => $time) {
- $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
- }
- }
- }
-
- public function actionNew($limit = 10)
- {
- if ($limit === 'all') {
- $limit = null;
- } else {
- $limit = (int) $limit;
- if ($limit < 1) {
- throw new Exception('The limit must be greater than 0.');
- }
- }
- $migrations = $this->getNewMigrations();
- if (empty($migrations)) {
- $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
- } else {
- $n = count($migrations);
- if ($limit && $n > $limit) {
- $migrations = array_slice($migrations, 0, $limit);
- $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
- } else {
- $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
- }
- foreach ($migrations as $migration) {
- $this->stdout("\t" . $migration . "\n");
- }
- }
- }
-
- public function actionCreate($name)
- {
- if (!preg_match('/^[\w\\\\]+$/', $name)) {
- throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
- }
- list($namespace, $className) = $this->generateClassName($name);
-
- $nameLimit = $this->getMigrationNameLimit();
- if ($nameLimit !== null && strlen($className) > $nameLimit) {
- throw new Exception('The migration name is too long.');
- }
- $migrationPath = $this->findMigrationPath($namespace);
- $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
- if ($this->confirm("Create new migration '$file'?")) {
- $content = $this->generateMigrationSourceCode([
- 'name' => $name,
- 'className' => $className,
- 'namespace' => $namespace,
- ]);
- FileHelper::createDirectory($migrationPath);
- file_put_contents($file, $content, LOCK_EX);
- $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
- }
- }
-
- private function generateClassName($name)
- {
- $namespace = null;
- $name = trim($name, '\\');
- if (strpos($name, '\\') !== false) {
- $namespace = substr($name, 0, strrpos($name, '\\'));
- $name = substr($name, strrpos($name, '\\') + 1);
- } elseif ($this->migrationPath === null) {
- $migrationNamespaces = $this->migrationNamespaces;
- $namespace = array_shift($migrationNamespaces);
- }
- if ($namespace === null) {
- $class = 'm' . gmdate('ymd_His') . '_' . $name;
- } else {
- $class = 'M' . gmdate('ymdHis') . Inflector::camelize($name);
- }
- return [$namespace, $class];
- }
-
- private function findMigrationPath($namespace)
- {
- if (empty($namespace)) {
- return is_array($this->migrationPath) ? reset($this->migrationPath) : $this->migrationPath;
- }
- if (!in_array($namespace, $this->migrationNamespaces, true)) {
- throw new Exception("Namespace '{$namespace}' not found in `migrationNamespaces`");
- }
- return $this->getNamespacePath($namespace);
- }
-
- private function getNamespacePath($namespace)
- {
- return str_replace('/', DIRECTORY_SEPARATOR, Yii::getAlias('@' . str_replace('\\', '/', $namespace)));
- }
-
- protected function migrateUp($class)
- {
- if ($class === self::BASE_MIGRATION) {
- return true;
- }
- $this->stdout("*** applying $class\n", Console::FG_YELLOW);
- $start = microtime(true);
- $migration = $this->createMigration($class);
- if ($migration->up() !== false) {
- $this->addMigrationHistory($class);
- $time = microtime(true) - $start;
- $this->stdout("*** applied $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
- return true;
- }
- $time = microtime(true) - $start;
- $this->stdout("*** failed to apply $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
- return false;
- }
-
- protected function migrateDown($class)
- {
- if ($class === self::BASE_MIGRATION) {
- return true;
- }
- $this->stdout("*** reverting $class\n", Console::FG_YELLOW);
- $start = microtime(true);
- $migration = $this->createMigration($class);
- if ($migration->down() !== false) {
- $this->removeMigrationHistory($class);
- $time = microtime(true) - $start;
- $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
- return true;
- }
- $time = microtime(true) - $start;
- $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
- return false;
- }
-
- protected function createMigration($class)
- {
- $this->includeMigrationFile($class);
-
- $migration = Yii::createObject($class);
- if ($migration instanceof BaseObject && $migration->canSetProperty('compact')) {
- $migration->compact = $this->compact;
- }
- return $migration;
- }
-
- protected function includeMigrationFile($class)
- {
- $class = trim($class, '\\');
- if (strpos($class, '\\') === false) {
- if (is_array($this->migrationPath)) {
- foreach ($this->migrationPath as $path) {
- $file = $path . DIRECTORY_SEPARATOR . $class . '.php';
- if (is_file($file)) {
- require_once $file;
- break;
- }
- }
- } else {
- $file = $this->migrationPath . DIRECTORY_SEPARATOR . $class . '.php';
- require_once $file;
- }
- }
- }
-
- protected function migrateToTime($time)
- {
- $count = 0;
- $migrations = array_values($this->getMigrationHistory(null));
- while ($count < count($migrations) && $migrations[$count] > $time) {
- ++$count;
- }
- if ($count === 0) {
- $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
- } else {
- $this->actionDown($count);
- }
- }
-
- protected function migrateToVersion($version)
- {
- $originalVersion = $version;
-
- $migrations = $this->getNewMigrations();
- foreach ($migrations as $i => $migration) {
- if (strpos($migration, $version) === 0) {
- $this->actionUp($i + 1);
- return ExitCode::OK;
- }
- }
-
- $migrations = array_keys($this->getMigrationHistory(null));
- foreach ($migrations as $i => $migration) {
- if (strpos($migration, $version) === 0) {
- if ($i === 0) {
- $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
- } else {
- $this->actionDown($i);
- }
- return ExitCode::OK;
- }
- }
- throw new Exception("Unable to find the version '$originalVersion'.");
- }
-
- protected function getNewMigrations()
- {
- $applied = [];
- foreach ($this->getMigrationHistory(null) as $class => $time) {
- $applied[trim($class, '\\')] = true;
- }
- $migrationPaths = [];
- if (is_array($this->migrationPath)) {
- foreach ($this->migrationPath as $path) {
- $migrationPaths[] = [$path, ''];
- }
- } elseif (!empty($this->migrationPath)) {
- $migrationPaths[] = [$this->migrationPath, ''];
- }
- foreach ($this->migrationNamespaces as $namespace) {
- $migrationPaths[] = [$this->getNamespacePath($namespace), $namespace];
- }
- $migrations = [];
- foreach ($migrationPaths as $item) {
- list($migrationPath, $namespace) = $item;
- if (!file_exists($migrationPath)) {
- continue;
- }
- $handle = opendir($migrationPath);
- while (($file = readdir($handle)) !== false) {
- if ($file === '.' || $file === '..') {
- continue;
- }
- $path = $migrationPath . DIRECTORY_SEPARATOR . $file;
- if (preg_match('/^(m(\d{6}_?\d{6})\D.*?)\.php$/is', $file, $matches) && is_file($path)) {
- $class = $matches[1];
- if (!empty($namespace)) {
- $class = $namespace . '\\' . $class;
- }
- $time = str_replace('_', '', $matches[2]);
- if (!isset($applied[$class])) {
- $migrations[$time . '\\' . $class] = $class;
- }
- }
- }
- closedir($handle);
- }
- ksort($migrations);
- return array_values($migrations);
- }
-
- protected function generateMigrationSourceCode($params)
- {
- return $this->renderFile(Yii::getAlias($this->templateFile), $params);
- }
-
- protected function truncateDatabase()
- {
- throw new NotSupportedException('This command is not implemented in ' . get_class($this));
- }
-
- protected function getMigrationNameLimit()
- {
- return null;
- }
-
- abstract protected function getMigrationHistory($limit);
-
- abstract protected function addMigrationHistory($version);
-
- abstract protected function removeMigrationHistory($version);
- }
|