FixtureTask.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php
  2. /**
  3. * The FixtureTask handles creating and updating fixture files.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc.
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.3
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. App::uses('BakeTask', 'Console/Command/Task');
  19. App::uses('Model', 'Model');
  20. /**
  21. * Task class for creating and updating fixtures files.
  22. *
  23. * @package Cake.Console.Command.Task
  24. */
  25. class FixtureTask extends BakeTask {
  26. /**
  27. * Tasks to be loaded by this Task
  28. *
  29. * @var array
  30. */
  31. public $tasks = array('DbConfig', 'Model', 'Template');
  32. /**
  33. * path to fixtures directory
  34. *
  35. * @var string
  36. */
  37. public $path = null;
  38. /**
  39. * Schema instance
  40. *
  41. * @var object
  42. */
  43. protected $_Schema = null;
  44. /**
  45. * Override initialize
  46. *
  47. */
  48. public function __construct($stdout = null, $stderr = null, $stdin = null) {
  49. parent::__construct($stdout, $stderr, $stdin);
  50. $this->path = APP . 'Test' . DS . 'Fixture' . DS;
  51. }
  52. /**
  53. * get the option parser.
  54. *
  55. * @return void
  56. */
  57. public function getOptionParser() {
  58. $parser = parent::getOptionParser();
  59. return $parser->description(
  60. __d('cake_console', 'Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures.')
  61. )->addArgument('name', array(
  62. 'help' => __d('cake_console', 'Name of the fixture to bake. Can use Plugin.name to bake plugin fixtures.')
  63. ))->addOption('count', array(
  64. 'help' => __d('cake_console', 'When using generated data, the number of records to include in the fixture(s).'),
  65. 'short' => 'n',
  66. 'default' => 10
  67. ))->addOption('connection', array(
  68. 'help' => __d('cake_console', 'Which database configuration to use for baking.'),
  69. 'short' => 'c',
  70. 'default' => 'default'
  71. ))->addOption('plugin', array(
  72. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake fixtures for.'),
  73. 'short' => 'p',
  74. ))->addOption('records', array(
  75. 'help' => __d('cake_console', 'Used with --count and <name>/all commands to pull [n] records from the live tables, where [n] is either --count or the default of 10'),
  76. 'short' => 'r',
  77. 'boolean' => true
  78. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));;
  79. }
  80. /**
  81. * Execution method always used for tasks
  82. * Handles dispatching to interactive, named, or all processeses.
  83. *
  84. * @return void
  85. */
  86. public function execute() {
  87. parent::execute();
  88. if (empty($this->args)) {
  89. $this->_interactive();
  90. }
  91. if (isset($this->args[0])) {
  92. $this->interactive = false;
  93. if (!isset($this->connection)) {
  94. $this->connection = 'default';
  95. }
  96. if (strtolower($this->args[0]) == 'all') {
  97. return $this->all();
  98. }
  99. $model = $this->_modelName($this->args[0]);
  100. $this->bake($model);
  101. }
  102. }
  103. /**
  104. * Bake All the Fixtures at once. Will only bake fixtures for models that exist.
  105. *
  106. * @return void
  107. */
  108. public function all() {
  109. $this->interactive = false;
  110. $this->Model->interactive = false;
  111. $tables = $this->Model->listAll($this->connection, false);
  112. foreach ($tables as $table) {
  113. $model = $this->_modelName($table);
  114. $this->bake($model);
  115. }
  116. }
  117. /**
  118. * Interactive baking function
  119. *
  120. * @return void
  121. */
  122. protected function _interactive() {
  123. $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
  124. $this->hr();
  125. $this->out(__d('cake_console', "Bake Fixture\nPath: %s", $this->path));
  126. $this->hr();
  127. if (!isset($this->connection)) {
  128. $this->connection = $this->DbConfig->getConfig();
  129. }
  130. $modelName = $this->Model->getName($this->connection);
  131. $useTable = $this->Model->getTable($modelName, $this->connection);
  132. $importOptions = $this->importOptions($modelName);
  133. $this->bake($modelName, $useTable, $importOptions);
  134. }
  135. /**
  136. * Interacts with the User to setup an array of import options. For a fixture.
  137. *
  138. * @param string $modelName Name of model you are dealing with.
  139. * @return array Array of import options.
  140. */
  141. public function importOptions($modelName) {
  142. $options = array();
  143. $doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
  144. if ($doSchema == 'y') {
  145. $options['schema'] = $modelName;
  146. }
  147. $doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
  148. if ($doRecords == 'y') {
  149. $options['records'] = true;
  150. }
  151. if ($doRecords == 'n') {
  152. $prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
  153. $fromTable = $this->in($prompt, array('y', 'n'), 'n');
  154. if (strtolower($fromTable) == 'y') {
  155. $options['fromTable'] = true;
  156. }
  157. }
  158. return $options;
  159. }
  160. /**
  161. * Assembles and writes a Fixture file
  162. *
  163. * @param string $model Name of model to bake.
  164. * @param string $useTable Name of table to use.
  165. * @param array $importOptions Options for public $import
  166. * @return string Baked fixture content
  167. */
  168. public function bake($model, $useTable = false, $importOptions = array()) {
  169. App::uses('CakeSchema', 'Model');
  170. $table = $schema = $records = $import = $modelImport = null;
  171. $importBits = array();
  172. if (!$useTable) {
  173. $useTable = Inflector::tableize($model);
  174. } elseif ($useTable != Inflector::tableize($model)) {
  175. $table = $useTable;
  176. }
  177. if (!empty($importOptions)) {
  178. if (isset($importOptions['schema'])) {
  179. $modelImport = true;
  180. $importBits[] = "'model' => '{$importOptions['schema']}'";
  181. }
  182. if (isset($importOptions['records'])) {
  183. $importBits[] = "'records' => true";
  184. }
  185. if ($this->connection != 'default') {
  186. $importBits[] .= "'connection' => '{$this->connection}'";
  187. }
  188. if (!empty($importBits)) {
  189. $import = sprintf("array(%s)", implode(', ', $importBits));
  190. }
  191. }
  192. $this->_Schema = new CakeSchema();
  193. $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
  194. if (!isset($data['tables'][$useTable])) {
  195. $this->err('Could not find your selected table ' . $useTable);
  196. return false;
  197. }
  198. $tableInfo = $data['tables'][$useTable];
  199. if (is_null($modelImport)) {
  200. $schema = $this->_generateSchema($tableInfo);
  201. }
  202. if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
  203. $recordCount = 1;
  204. if (isset($this->params['count'])) {
  205. $recordCount = $this->params['count'];
  206. }
  207. $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
  208. }
  209. if (isset($this->params['records']) || isset($importOptions['fromTable'])) {
  210. $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
  211. }
  212. $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
  213. return $out;
  214. }
  215. /**
  216. * Generate the fixture file, and write to disk
  217. *
  218. * @param string $model name of the model being generated
  219. * @param string $fixture Contents of the fixture file.
  220. * @return string Content saved into fixture file.
  221. */
  222. public function generateFixtureFile($model, $otherVars) {
  223. $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
  224. $vars = array_merge($defaults, $otherVars);
  225. $path = $this->getPath();
  226. $filename = Inflector::camelize($model) . 'Fixture.php';
  227. $this->Template->set('model', $model);
  228. $this->Template->set($vars);
  229. $content = $this->Template->generate('classes', 'fixture');
  230. $this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
  231. $this->createFile($path . $filename, $content);
  232. return $content;
  233. }
  234. /**
  235. * Get the path to the fixtures.
  236. *
  237. * @return string Path for the fixtures
  238. */
  239. public function getPath() {
  240. $path = $this->path;
  241. if (isset($this->plugin)) {
  242. $path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
  243. }
  244. return $path;
  245. }
  246. /**
  247. * Generates a string representation of a schema.
  248. *
  249. * @param array $table Table schema array
  250. * @return string fields definitions
  251. */
  252. protected function _generateSchema($tableInfo) {
  253. $schema = $this->_Schema->generateTable('f', $tableInfo);
  254. return substr($schema, 10, -2);
  255. }
  256. /**
  257. * Generate String representation of Records
  258. *
  259. * @param array $table Table schema array
  260. * @return array Array of records to use in the fixture.
  261. */
  262. protected function _generateRecords($tableInfo, $recordCount = 1) {
  263. $records = array();
  264. for ($i = 0; $i < $recordCount; $i++) {
  265. $record = array();
  266. foreach ($tableInfo as $field => $fieldInfo) {
  267. if (empty($fieldInfo['type'])) {
  268. continue;
  269. }
  270. switch ($fieldInfo['type']) {
  271. case 'integer':
  272. case 'float':
  273. $insert = $i + 1;
  274. break;
  275. case 'string':
  276. case 'binary':
  277. $isPrimaryUuid = (
  278. isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
  279. isset($fieldInfo['length']) && $fieldInfo['length'] == 36
  280. );
  281. if ($isPrimaryUuid) {
  282. $insert = String::uuid();
  283. } else {
  284. $insert = "Lorem ipsum dolor sit amet";
  285. if (!empty($fieldInfo['length'])) {
  286. $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
  287. }
  288. }
  289. $insert = "'$insert'";
  290. break;
  291. case 'timestamp':
  292. $ts = time();
  293. $insert = "'$ts'";
  294. break;
  295. case 'datetime':
  296. $ts = date('Y-m-d H:i:s');
  297. $insert = "'$ts'";
  298. break;
  299. case 'date':
  300. $ts = date('Y-m-d');
  301. $insert = "'$ts'";
  302. break;
  303. case 'time':
  304. $ts = date('H:i:s');
  305. $insert = "'$ts'";
  306. break;
  307. case 'boolean':
  308. $insert = 1;
  309. break;
  310. case 'text':
  311. $insert = "'Lorem ipsum dolor sit amet, aliquet feugiat.";
  312. $insert .= " Convallis morbi fringilla gravida,";
  313. $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
  314. $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
  315. $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
  316. $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
  317. $insert .= " duis vestibulum nunc mattis convallis.'";
  318. break;
  319. }
  320. $record[$field] = $insert;
  321. }
  322. $records[] = $record;
  323. }
  324. return $records;
  325. }
  326. /**
  327. * Convert a $records array into a a string.
  328. *
  329. * @param array $records Array of records to be converted to string
  330. * @return string A string value of the $records array.
  331. */
  332. protected function _makeRecordString($records) {
  333. $out = "array(\n";
  334. foreach ($records as $record) {
  335. $values = array();
  336. foreach ($record as $field => $value) {
  337. $values[] = "\t\t\t'$field' => $value";
  338. }
  339. $out .= "\t\tarray(\n";
  340. $out .= implode(",\n", $values);
  341. $out .= "\n\t\t),\n";
  342. }
  343. $out .= "\t)";
  344. return $out;
  345. }
  346. /**
  347. * Interact with the user to get a custom SQL condition and use that to extract data
  348. * to build a fixture.
  349. *
  350. * @param string $modelName name of the model to take records from.
  351. * @param string $useTable Name of table to use.
  352. * @return array Array of records.
  353. */
  354. protected function _getRecordsFromTable($modelName, $useTable = null) {
  355. if ($this->interactive) {
  356. $condition = null;
  357. $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
  358. while (!$condition) {
  359. $condition = $this->in($prompt, null, 'WHERE 1=1');
  360. }
  361. $prompt = __d('cake_console', "How many records do you want to import?");
  362. $recordCount = $this->in($prompt, null, 10);
  363. } else {
  364. $condition = 'WHERE 1=1';
  365. $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
  366. }
  367. $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
  368. $records = $modelObject->find('all', array(
  369. 'conditions' => $condition,
  370. 'recursive' => -1,
  371. 'limit' => $recordCount
  372. ));
  373. $db = $modelObject->getDatasource();
  374. $schema = $modelObject->schema(true);
  375. $out = array();
  376. foreach ($records as $record) {
  377. $row = array();
  378. foreach ($record[$modelObject->alias] as $field => $value) {
  379. $row[$field] = $db->value($value, $schema[$field]['type']);
  380. }
  381. $out[] = $row;
  382. }
  383. return $out;
  384. }
  385. }