PageRenderTime 40ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/app/vendors/shells/fixtures.php

https://github.com/rogerwu99/randomizr
PHP | 288 lines | 221 code | 33 blank | 34 comment | 37 complexity | 1ff887c192f04ab90e48a22ef4bb0cdf MD5 | raw file
Possible License(s): MIT, LGPL-3.0
  1. <?php
  2. /**
  3. * The FixtureTask runs a specified database fixture.
  4. *
  5. * PHP versions 4 and 5
  6. *
  7. * Licensed under The MIT License
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright 2006-2008, Joel Moss
  11. * @link http://joelmoss.info
  12. * @since CakePHP(tm) v 1.2
  13. * @license http://www.opensource.org/licenses/mit-license.php The MIT License
  14. *
  15. */
  16. vendor('Spyc');
  17. uses('file', 'folder');
  18. class FixturesShell extends Shell
  19. {
  20. var $dataSource = 'default';
  21. var $db;
  22. function startup()
  23. {
  24. if (isset($this->params['ds'])) $this->dataSource = $this->params['ds'];
  25. if (isset($this->params['datasource'])) $this->dataSource = $this->params['datasource'];
  26. uses('model'.DS.'connection_manager');
  27. define('FIXTURES_PATH', APP_PATH .'config' .DS. 'fixtures');
  28. if (!$this->_loadDbConfig()) exit;
  29. $this->db =& ConnectionManager::getDataSource($this->dataSource);
  30. App::import();
  31. $this->welcome();
  32. $this->out('App : '. APP_DIR);
  33. $this->out('Path: '. ROOT . DS . APP_DIR);
  34. $this->out('');
  35. $this->hr();
  36. }
  37. function main()
  38. {
  39. $this->out('');
  40. $this->fixture = isset($this->params['t']) ? $this->params['t'] : '*';
  41. $this->fixtures();
  42. $this->out('');
  43. $this->hr();
  44. }
  45. /**
  46. * Runs one or more specified fixture files if you append 'f' to your command along with the file name
  47. * Simply run 'cake fixtures f first_fixture_file [second_fixture_file] [...]
  48. */
  49. function f()
  50. {
  51. $this->out('');
  52. if (count($this->args))
  53. {
  54. foreach ($this->args as $file)
  55. {
  56. $this->fixture = $file;
  57. $this->fixtures();
  58. }
  59. }
  60. else
  61. {
  62. $this->fixture = '*';
  63. $this->fixtures();
  64. }
  65. $this->out('');
  66. $this->hr();
  67. }
  68. /**
  69. * Generates a fixture file for each database table.
  70. * This has been taken from the generator shell which is now deprecated
  71. */
  72. function generate()
  73. {
  74. $folder = new Folder(FIXTURES_PATH, true, 0777);
  75. $tables = $this->db->sources();
  76. if (!count($tables)) $this->error('Database contains no tables', "Please generate and run your migrations before your fixtures.\n");
  77. $this->out('');
  78. $data = "#\n# Fixture YAML file\n#\n#\n# Example:-\n# -\n# first_name: Bob\n# last_name: Bones\n# created: NOW\n#\n";
  79. foreach ($tables as $i=>$t)
  80. {
  81. if ($t == 'schema_info') continue;
  82. if (!file_exists(FIXTURES_PATH .DS. $t . '.yml'))
  83. {
  84. $file = new File(FIXTURES_PATH .DS. $t . '.yml', true);
  85. $file->write($data);
  86. $this->out(" Generating fixture file for '".$t."' table ... DONE!");
  87. }
  88. }
  89. if (!isset($file))
  90. {
  91. $this->out(" All fixtures generated.");
  92. $this->out('');
  93. $this->hr();
  94. }
  95. else
  96. {
  97. $this->out('');
  98. $this->hr();
  99. }
  100. }
  101. /**
  102. * Alias for generate method
  103. */
  104. function g()
  105. {
  106. $this->generate();
  107. }
  108. function fixtures()
  109. {
  110. if (!file_exists(FIXTURES_PATH)) $folder = new Folder(FIXTURES_PATH, true, 0777);
  111. $tables = $this->db->sources();
  112. if (!count($tables)) $this->err('Database contains no tables. Please run your migrations before your fixtures.');
  113. require 'fixture_helpers.php';
  114. $this->helpers = new FixtureHelpers();
  115. if ($this->fixture == '*')
  116. {
  117. foreach ($tables as $t)
  118. {
  119. if (!file_exists(FIXTURES_PATH .DS. $t .'.yml')) continue;
  120. $this->out(" Running fixtures for '".$t."' ...", false);
  121. $this->startFixture($t);
  122. }
  123. }
  124. else
  125. {
  126. if (!file_exists(FIXTURES_PATH .DS. $this->fixture .'.yml')) $this->err('Fixture file does not exist for table \''.$this->fixture.'\'.');
  127. $this->out(" Running fixtures for '".$this->fixture."' ...", false);
  128. $this->startFixture($this->fixture);
  129. }
  130. }
  131. function startFixture($name)
  132. {
  133. $file = FIXTURES_PATH .DS. $name .'.yml';
  134. $data = Spyc::YAMLLoad($this->_parsePhp($file));
  135. if (!is_array($data) || count($data) === 0)
  136. {
  137. $this->out('* Fixtures undefined *');
  138. return false;
  139. }
  140. if (!is_array($data) || !count($data)) $this->err("Unable to parse YAML Fixture file: '$file'");
  141. $model = new Model(false, $name);
  142. $this->db->truncate($model);
  143. $count = 0;
  144. $created = array();
  145. foreach($data as $ri=>$r)
  146. {
  147. $records = array();
  148. foreach($r as $fi => $f)
  149. {
  150. if (preg_match("/_id$/", $fi) && !is_id($f))
  151. {
  152. $records[$fi] = $created[$f]['id'];
  153. }
  154. elseif (preg_match("/^\.([A-Z_]+)$/", $f, $matches))
  155. {
  156. $helper = Inflector::variable(strtolower($matches[1]));
  157. if (!method_exists($this->helpers, $helper)) $this->err("Found Helper '$f' in fixture '$name.yml', but Helper method '$helper()' does not exist.");
  158. $records[$fi] = $this->helpers->$helper();
  159. }
  160. else
  161. {
  162. $records[$fi] = $f;
  163. }
  164. }
  165. if (isset($model->_schema['created']) && !array_key_exists('created', $records))
  166. {
  167. $records['created'] = date('Y-m-d H:i:s');
  168. }
  169. $use_uuid = false;
  170. if (!array_key_exists('id', $r) && isset($model->_schema['id']) && $model->_schema['id']['type'] == 'string' && $model->_schema['id']['length'] == 36)
  171. {
  172. $records['id'] = String::uuid();
  173. $use_uuid = true;
  174. }
  175. $res = $this->db->create($model, array_keys($records), array_values($records));
  176. if ($res)
  177. {
  178. $records['id'] = $use_uuid ? $records['id'] : $model->id;
  179. $created[$ri] = $records;
  180. }
  181. $count++;
  182. }
  183. $this->out("$count rows inserted.");
  184. }
  185. function _parsePhp($file)
  186. {
  187. ob_start();
  188. include ($file);
  189. $buf = ob_get_contents();
  190. ob_end_clean();
  191. return $buf;
  192. }
  193. /**
  194. * Help method
  195. */
  196. function help()
  197. {
  198. $this->out('Fixtures are an easy way to insert test data into your database.');
  199. $this->out('This shell Runs and generates fixtures for tables in your database.');
  200. $this->out('');
  201. $this->out('');
  202. $this->out('COMMAND LINE OPTIONS');
  203. $this->out('');
  204. $this->out(' cake fixtures');
  205. $this->out(' - Runs all fixtures files');
  206. $this->out(' cake fixtures f table_one [table_two] ...');
  207. $this->out(' - Runs one or more specified fixture files');
  208. $this->out(' cake fixtures help');
  209. $this->out(' - Displays this Help');
  210. $this->out('');
  211. $this->out(" append '-ds [data source]' to the command if you want to specify the");
  212. $this->out(' datasource to use from database.php');
  213. $this->out('');
  214. $this->out('');
  215. $this->out('For more information and for the latest release of this and others,');
  216. $this->out('go to http://joelmoss.info');
  217. $this->out('');
  218. $this->hr();
  219. $this->out('');
  220. }
  221. function err($str)
  222. {
  223. $this->out('');
  224. $this->out(' ** '.$str.' **');
  225. $this->out('');
  226. $this->hr();
  227. $this->out('');
  228. exit;
  229. }
  230. /**
  231. * Modifies the out method for prettier formatting
  232. *
  233. * @param string $string String to output.
  234. * @param boolean $newline If true, the outputs gets an added newline.
  235. */
  236. function out($string, $newline = true) {
  237. return parent::out(" ".$string, $newline);
  238. }
  239. function welcome()
  240. {
  241. $this->out('');
  242. $this->out(' __ __ _ _ __ __ _ _ __ __ ___ _ __ _ ');
  243. $this->out('| |__| |_/ |__ |__| |__| |__| |_ | \/ | | | |_| |__ |_ ');
  244. $this->out('|__ | | | \_ |__ | | | | | | /\ | |_| | \ |__ _|');
  245. $this->out('');
  246. }
  247. }
  248. if (!function_exists('is_id'))
  249. {
  250. function is_id($id)
  251. {
  252. return (preg_match("/^[a-zA-Z0-9]{8}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{4}-[a-zA-Z0-9]{12}$/", $id) || is_numeric($id));
  253. }
  254. }
  255. ?>