FixtureTask.php 13 KB

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