PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 1ms app.codeStats 0ms

/myth/CIModules/database/controllers/Database.php

https://gitlab.com/digitalpoetry/catt-old
PHP | 297 lines | 181 code | 38 blank | 78 comment | 25 complexity | 945c11b459e3ac2f855f40ae843dc923 MD5 | raw file
  1. <?php
  2. /**
  3. * Sprint
  4. *
  5. * A set of power tools to enhance the CodeIgniter framework and provide consistent workflow.
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in
  15. * all copies or substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. * THE SOFTWARE.
  24. *
  25. * @package Sprint
  26. * @author Lonnie Ezell
  27. * @copyright Copyright 2014-2015, New Myth Media, LLC (http://newmythmedia.com)
  28. * @license http://opensource.org/licenses/MIT (MIT)
  29. * @link http://sprintphp.com
  30. * @since Version 1.0
  31. */
  32. use \Myth\CLI as CLI;
  33. class Database extends \Myth\Controllers\CLIController
  34. {
  35. protected $descriptions = [
  36. 'migrate' => ['migrate [$to]', 'Runs the migrations up or down until schema at version \$to'],
  37. 'quietMigrate' => ['quiteMigrate [$to]', 'Same as migrate but without any feedback.'],
  38. 'refresh' => ['refresh', 'Runs migrations back to version 0 (uninstall) and then back to the most recent migration.'],
  39. 'newMigration' => ['newMigration [$name]', 'Creates a new migration file.'],
  40. 'seed' => ['seed [$name]', 'Runs the named database seeder.']
  41. ];
  42. protected $long_descriptions = [
  43. 'migrate' => '',
  44. 'quietMigrate' => '',
  45. 'refresh' => '',
  46. 'newMigration' => '',
  47. 'seed' => ''
  48. ];
  49. //-------------------------------------------------------------------
  50. //--------------------------------------------------------------------
  51. // Migration Methods
  52. //--------------------------------------------------------------------
  53. /**
  54. * Provides a command-line interface to the migration scripts.
  55. * If no $to is provided, will migrate to the latest version.
  56. *
  57. * Example:
  58. * > php index.php database migrate
  59. *
  60. * @param string $type 'app', 'myth', 'all' or {module_name}
  61. * @param null $to
  62. * @param bool $silent If TRUE, will NOT display any prompts for verification.
  63. * @return bool|void
  64. */
  65. public function migrate($type=null, $to = null, $silent = false)
  66. {
  67. $this->load->library('migration');
  68. if (empty($type))
  69. {
  70. $type = CLI::prompt("Migration group to refresh?", $this->migration->default_migration_path());
  71. if (empty($type))
  72. {
  73. return $silent ? false : CLI::error("\tYou must supply a group to refresh.");
  74. }
  75. }
  76. // We need to append 'mod:' to properly handle modules, if
  77. // the $type is not one of the recognized migration groups.
  78. $this->config->load('migration');
  79. $groups = config_item('migration_paths');
  80. $groups = array_keys($groups);
  81. // If it's not in the groups list, then assume it's a module.
  82. if (! in_array($type, $groups))
  83. {
  84. if (strpos($type, 'mod:') !== 0)
  85. {
  86. $type = 'mod:'. $type;
  87. }
  88. }
  89. unset($groups);
  90. // Get our stats on the migrations
  91. $latest = $this->migration->get_latest($type);
  92. $latest = empty($latest) ? 0 : substr($latest, 0, strpos($latest, '_'));
  93. if (empty($latest)) {
  94. return CLI::write("\tNo migrations found.", 'yellow');
  95. }
  96. $current = $this->migration->get_version($type);
  97. // Already at the desired version?
  98. if ((! is_null($to) && $current == $to) OR (is_null($to) && $current == $latest))
  99. {
  100. return $silent ? true : CLI::write("\tDatabase is already at the desired version ({$current})", 'yellow');
  101. }
  102. $target = is_null($to) ? $latest : $to;
  103. // Just to be safe, verify with the user they want to migrate
  104. // to the latest version.
  105. if (is_null($to)) {
  106. // If we're in silent mode, don't prompt, just go to the latest...
  107. if (! $silent) {
  108. $go_ahead = CLI::prompt('Migrate to the latest available version?', array('y', 'n'));
  109. if ($go_ahead == 'n') {
  110. return CLI::write('Bailing...', 'yellow');
  111. }
  112. }
  113. if (! $this->migration->latest($type)) {
  114. return CLI::error("\n\tERROR: " . $this->migration->error_string() . "\n");
  115. }
  116. } else {
  117. if ($this->migration->version($type, $to) === false) {
  118. return CLI::error("\n\tERROR: " . $this->migration->error_string() . "\n");
  119. }
  120. }
  121. return $silent ? true :
  122. CLI::write("\n\tSuccessfully migrated database from version {$current} to {$target}.\n", 'green');
  123. }
  124. //--------------------------------------------------------------------
  125. /**
  126. * Performs a migration that does not prompt for any information.
  127. * Suitable for use within automated scripts that can't be
  128. * bothered with answering questions.
  129. *
  130. * @param string $type 'app', 'myth', 'all' or {module_name}
  131. * @param null $to
  132. * @return bool|void
  133. */
  134. public function quietMigrate($type='app', $to = null)
  135. {
  136. return $this->migrate($type, $to, true);
  137. }
  138. //--------------------------------------------------------------------
  139. /**
  140. * Migrates the database back to 0, then back up to the latest version.
  141. *
  142. * @param string $type The group or module to refresh.
  143. * @return mixed
  144. */
  145. public function refresh($type=null)
  146. {
  147. $this->load->library('migration');
  148. if (empty($type))
  149. {
  150. $type = CLI::prompt("Migration group to refresh?", $this->migration->default_migration_path());
  151. if (empty($type))
  152. {
  153. return CLI::error("\tYou must supply a group to refresh.");
  154. }
  155. }
  156. if ($this->migration->version($type, 0) === false) {
  157. return CLI::error("\tERROR: " . $this->migration->error_string());
  158. }
  159. CLI::write(CLI::color("\tCleared the database.", 'green'));
  160. if ($this->migration->latest($type) === false) {
  161. return CLI::error("\tERROR: " . $this->migration->error_string());
  162. }
  163. CLI::write("\tRe-installed the database to the latest migration.", 'green');
  164. }
  165. //--------------------------------------------------------------------
  166. /**
  167. * Creates a new migration file ready to be used.
  168. *
  169. * @param $name
  170. */
  171. public function newMigration($name = null, $type = 'app')
  172. {
  173. if (empty($name)) {
  174. $name = CLI::prompt('Migration name? ');
  175. if (empty($name)) {
  176. return CLI::error("\tYou must provide a migration name.", 'red');
  177. }
  178. }
  179. $this->load->library('migration');
  180. $path = $this->migration->determine_migration_path($type);
  181. // Does the alias path exist in our config?
  182. if (! $path) {
  183. return CLI::error("\tThe migration path for '{$type}' does not exist.'");
  184. }
  185. // Does the path really exist?
  186. if (! is_dir($path)) {
  187. return CLI::error("\tThe path for '{$type}' is not a directory.");
  188. }
  189. // Is the folder writeable?
  190. if (! is_writeable($path)) {
  191. return CLI::error("\tThe folder for '{$type}' migrations is not writeable.");
  192. }
  193. $file = $this->migration->make_name($name);
  194. $path = rtrim($path, '/') .'/'. $file;
  195. $contents = <<<EOT
  196. <?php
  197. /**
  198. * Migration: {clean_name}
  199. *
  200. * Created by: SprintPHP
  201. * Created on: {date}
  202. */
  203. class Migration_{name} extends CI_Migration {
  204. public function up ()
  205. {
  206. }
  207. //--------------------------------------------------------------------
  208. public function down ()
  209. {
  210. }
  211. //--------------------------------------------------------------------
  212. }
  213. EOT;
  214. $contents = str_replace('{name}', $name, $contents);
  215. $contents = str_replace('{date}', date('Y-m-d H:i:s a'), $contents);
  216. $contents = str_replace('{clean_name}', ucwords(str_replace('_', ' ', $name)), $contents);
  217. $this->load->helper('file');
  218. if (write_file($path, $contents)) {
  219. return CLI::write("\tNew migration created: " . CLI::color($file, 'yellow'), 'green');
  220. }
  221. return CLI::error("\tUnkown error trying to create migration: {$file}", 'red');
  222. }
  223. //--------------------------------------------------------------------
  224. //--------------------------------------------------------------------
  225. // Seeding Methods
  226. //--------------------------------------------------------------------
  227. /**
  228. * Installs any database seeds stored in database/seeds. Seeds just need to
  229. * extend the Seeder class and have a method named run.
  230. */
  231. public function seed($name = null)
  232. {
  233. $this->load->library('seeder');
  234. $this->seeder->call($name);
  235. }
  236. //--------------------------------------------------------------------
  237. }