PageRenderTime 44ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/modules/migrations/classes/migrations.php

https://bitbucket.org/sklyarov_ivan/trap
PHP | 226 lines | 162 code | 36 blank | 28 comment | 14 complexity | 09e8206f611ebeaf7dc87bead0422522 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php defined('SYSPATH') OR die('No direct script access.');
  2. /**
  3. * Migrations class.
  4. *
  5. * @package Despark/timestamped-migrations
  6. * @author Ivan Kerin
  7. * @copyright (c) 2011-2012 Despark Ltd.
  8. * @license http://creativecommons.org/licenses/by-sa/3.0/legalcode
  9. */
  10. class Migrations
  11. {
  12. protected $config;
  13. protected $driver;
  14. protected $migrations;
  15. public $output = NULL;
  16. /**
  17. * Intialize migration library
  18. *
  19. * @param bool Do we want output of migration steps?
  20. * @param string Database group
  21. */
  22. public function __construct($config = NULL)
  23. {
  24. $this->config = arr::merge(Kohana::$config->load('migrations')->as_array(), (array) $config);
  25. $database = Kohana::$config->load('database.'.Arr::get(Kohana::$config->load('migrations'), 'database', 'default'));
  26. // Set the driver class name
  27. $driver = 'Migration_Driver_'.ucfirst($database['type']);
  28. // Create the database connection instance
  29. $this->driver = new $driver(Arr::get(Kohana::$config->load('migrations'), 'database', 'default'));
  30. $this->driver->versions()->init();
  31. if( ! is_dir($this->config['path']))
  32. {
  33. mkdir($this->config['path'], 0777, TRUE);
  34. }
  35. }
  36. public function set_executed($version)
  37. {
  38. $this->driver->versions()->set($version);
  39. }
  40. public function set_unexecuted($version)
  41. {
  42. $this->driver->versions()->clear($version);
  43. }
  44. public function generate_new_migration_file($name, $actions_template = NULL)
  45. {
  46. $actions = new Migration_Actions($this->driver);
  47. if ($actions_template)
  48. {
  49. $actions->template(getcwd().DIRECTORY_SEPARATOR.$actions_template);
  50. }
  51. else
  52. {
  53. $actions->parse($name);
  54. }
  55. $template = file_get_contents(Kohana::find_file('templates', 'migration', 'tpl'));
  56. $class_name = str_replace(' ', '_', ucwords(str_replace('_',' ',$name)));
  57. $filename = sprintf("%d_$name.php", time());
  58. file_put_contents(
  59. $this->config['path'].DIRECTORY_SEPARATOR.$filename,
  60. strtr($template, array(
  61. '{up}' => join("\n", array_map('Migrations::indent', $actions->up)),
  62. '{down}' => join("\n", array_map('Migrations::indent', $actions->down)),
  63. '{class_name}' => $class_name
  64. ))
  65. );
  66. return $filename;
  67. }
  68. static function indent($action)
  69. {
  70. return "\t\t$action";
  71. }
  72. /**
  73. * Loads a migration
  74. *
  75. * @param integer Migration version number
  76. * @return Migration_Core Class object
  77. */
  78. public function load_migration($version)
  79. {
  80. $f = glob(sprintf($this->config['path'] . DIRECTORY_SEPARATOR . '%d_*.php', $version));
  81. if (count($f) > 1)
  82. throw new Migration_Exception('Only one migration per step is permitted, there are :count of version :version', array(':count' => count($f), ':version' => $version));
  83. if (count($f) == 0)
  84. throw new Migration_Exception('Migration step not found with version :version', array(":version" => $version));
  85. $file = basename($f[0]);
  86. $name = basename($f[0], EXT);
  87. // Filename validations
  88. if ( ! preg_match('/^\d+_(\w+)$/', $name, $match))
  89. throw new Migration_Exception('Invalid filename :file', array(':file' => $file));
  90. $match[1] = strtolower($match[1]);
  91. include_once $f[0];
  92. $class = ucfirst($match[1]);
  93. if ( ! class_exists($class))
  94. throw new Migration_Exception('Migration class :class does not exist', array( ':class' => $class));
  95. return new $class($this->config);
  96. }
  97. /**
  98. * Retrieves all the timestamps of the migration files
  99. *
  100. * @return array
  101. */
  102. public function get_migrations()
  103. {
  104. if ( ! $this->migrations)
  105. {
  106. $migrations = glob($this->config['path'] . DIRECTORY_SEPARATOR . '*' . EXT);
  107. $ids = array();
  108. foreach ((array) $migrations as $file)
  109. {
  110. $name = basename($file, EXT);
  111. $matches = array();
  112. if ( preg_match('/^(\d+)_(\w+)$/', $name, $matches))
  113. {
  114. $ids[] = intval($matches[1]);
  115. }
  116. }
  117. $this->migrations = $ids;
  118. }
  119. return $this->migrations;
  120. }
  121. public function clear_all()
  122. {
  123. $this->driver->clear_all();
  124. $this->driver->versions()->clear_all();
  125. return $this;
  126. }
  127. public function get_executed_migrations()
  128. {
  129. return $this->driver->versions()->get();
  130. }
  131. public function get_unexecuted_migrations()
  132. {
  133. return array_diff($this->get_migrations(), $this->get_executed_migrations());
  134. }
  135. protected function execute($version, $direction, $dry_run)
  136. {
  137. $migration = $this->load_migration($version)->dry_run($dry_run);
  138. $this->log($version.' '.get_class($migration).' : migrating '.$direction.($dry_run ? " -- Dry Run" : ''));
  139. $start = microtime(TRUE);
  140. switch ($direction)
  141. {
  142. case 'down':
  143. $migration->down();
  144. if ( ! $dry_run)
  145. {
  146. $this->set_unexecuted($version);
  147. }
  148. break;
  149. case 'up':
  150. $migration->up();
  151. if ( ! $dry_run)
  152. {
  153. $this->set_executed($version);
  154. }
  155. break;
  156. }
  157. $end = microtime(TRUE);
  158. $this->log($version.' '.get_class($migration).' : migrated ('.number_format($end - $start, 4).'s)');
  159. }
  160. public function execute_all($up = array(), $down = array(), $dry_run = FALSE)
  161. {
  162. if ( ! count($down) AND ! count($up))
  163. {
  164. $this->log("Nothing to do");
  165. }
  166. else
  167. {
  168. foreach ($down as $version)
  169. {
  170. $this->execute($version, 'down', $dry_run);
  171. }
  172. foreach ($up as $version)
  173. {
  174. $this->execute($version, 'up', $dry_run);
  175. }
  176. }
  177. }
  178. public function log($message)
  179. {
  180. if ($this->config['log'])
  181. {
  182. call_user_func($this->config['log'], $message);
  183. }
  184. else
  185. {
  186. echo $message."\n";
  187. ob_flush();
  188. }
  189. }
  190. }