FixtureTask.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  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('records', array(
  80. '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'),
  81. 'short' => 'r',
  82. 'boolean' => true
  83. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  84. }
  85. /**
  86. * Execution method always used for tasks
  87. * Handles dispatching to interactive, named, or all processes.
  88. *
  89. * @return void
  90. */
  91. public function execute() {
  92. parent::execute();
  93. if (empty($this->args)) {
  94. $this->_interactive();
  95. }
  96. if (isset($this->args[0])) {
  97. $this->interactive = false;
  98. if (!isset($this->connection)) {
  99. $this->connection = 'default';
  100. }
  101. if (strtolower($this->args[0]) === 'all') {
  102. return $this->all();
  103. }
  104. $model = $this->_modelName($this->args[0]);
  105. $this->bake($model);
  106. }
  107. }
  108. /**
  109. * Bake All the Fixtures at once. Will only bake fixtures for models that exist.
  110. *
  111. * @return void
  112. */
  113. public function all() {
  114. $this->interactive = false;
  115. $this->Model->interactive = false;
  116. $tables = $this->Model->listAll($this->connection, false);
  117. foreach ($tables as $table) {
  118. $model = $this->_modelName($table);
  119. $this->bake($model);
  120. }
  121. }
  122. /**
  123. * Interactive baking function
  124. *
  125. * @return void
  126. */
  127. protected function _interactive() {
  128. $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
  129. $this->hr();
  130. $this->out(__d('cake_console', "Bake Fixture\nPath: %s", $this->getPath()));
  131. $this->hr();
  132. if (!isset($this->connection)) {
  133. $this->connection = $this->DbConfig->getConfig();
  134. }
  135. $modelName = $this->Model->getName($this->connection);
  136. $useTable = $this->Model->getTable($modelName, $this->connection);
  137. $importOptions = $this->importOptions($modelName);
  138. $this->bake($modelName, $useTable, $importOptions);
  139. }
  140. /**
  141. * Interacts with the User to setup an array of import options. For a fixture.
  142. *
  143. * @param string $modelName Name of model you are dealing with.
  144. * @return array Array of import options.
  145. */
  146. public function importOptions($modelName) {
  147. $options = array();
  148. $doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
  149. if ($doSchema === 'y') {
  150. $options['schema'] = $modelName;
  151. }
  152. $doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
  153. if ($doRecords === 'y') {
  154. $options['records'] = true;
  155. }
  156. if ($doRecords === 'n') {
  157. $prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
  158. $fromTable = $this->in($prompt, array('y', 'n'), 'n');
  159. if (strtolower($fromTable) === 'y') {
  160. $options['fromTable'] = true;
  161. }
  162. }
  163. return $options;
  164. }
  165. /**
  166. * Assembles and writes a Fixture file
  167. *
  168. * @param string $model Name of model to bake.
  169. * @param string $useTable Name of table to use.
  170. * @param array $importOptions Options for public $import
  171. * @return string Baked fixture content
  172. */
  173. public function bake($model, $useTable = false, $importOptions = array()) {
  174. App::uses('CakeSchema', 'Model');
  175. $table = $schema = $records = $import = $modelImport = null;
  176. $importBits = array();
  177. if (!$useTable) {
  178. $useTable = Inflector::tableize($model);
  179. } elseif ($useTable != Inflector::tableize($model)) {
  180. $table = $useTable;
  181. }
  182. if (!empty($importOptions)) {
  183. if (isset($importOptions['schema'])) {
  184. $modelImport = true;
  185. $importBits[] = "'model' => '{$importOptions['schema']}'";
  186. }
  187. if (isset($importOptions['records'])) {
  188. $importBits[] = "'records' => true";
  189. }
  190. if ($this->connection !== 'default') {
  191. $importBits[] .= "'connection' => '{$this->connection}'";
  192. }
  193. if (!empty($importBits)) {
  194. $import = sprintf("array(%s)", implode(', ', $importBits));
  195. }
  196. }
  197. $this->_Schema = new CakeSchema();
  198. $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
  199. if (!isset($data['tables'][$useTable])) {
  200. $this->err('Could not find your selected table ' . $useTable);
  201. return false;
  202. }
  203. $tableInfo = $data['tables'][$useTable];
  204. if (is_null($modelImport)) {
  205. $schema = $this->_generateSchema($tableInfo);
  206. }
  207. if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) {
  208. $recordCount = 1;
  209. if (isset($this->params['count'])) {
  210. $recordCount = $this->params['count'];
  211. }
  212. $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
  213. }
  214. if (!empty($this->params['records']) || isset($importOptions['fromTable'])) {
  215. $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
  216. }
  217. $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import'));
  218. return $out;
  219. }
  220. /**
  221. * Generate the fixture file, and write to disk
  222. *
  223. * @param string $model name of the model being generated
  224. * @param string $otherVars Contents of the fixture file.
  225. * @return string Content saved into fixture file.
  226. */
  227. public function generateFixtureFile($model, $otherVars) {
  228. $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
  229. $vars = array_merge($defaults, $otherVars);
  230. $path = $this->getPath();
  231. $filename = Inflector::camelize($model) . 'Fixture.php';
  232. $this->Template->set('model', $model);
  233. $this->Template->set($vars);
  234. $content = $this->Template->generate('classes', 'fixture');
  235. $this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
  236. $this->createFile($path . $filename, $content);
  237. return $content;
  238. }
  239. /**
  240. * Get the path to the fixtures.
  241. *
  242. * @return string Path for the fixtures
  243. */
  244. public function getPath() {
  245. $path = $this->path;
  246. if (isset($this->plugin)) {
  247. $path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
  248. }
  249. return $path;
  250. }
  251. /**
  252. * Generates a string representation of a schema.
  253. *
  254. * @param array $tableInfo Table schema array
  255. * @return string fields definitions
  256. */
  257. protected function _generateSchema($tableInfo) {
  258. $schema = trim($this->_Schema->generateTable('f', $tableInfo), "\n");
  259. return substr($schema, 13, -1);
  260. }
  261. /**
  262. * Generate String representation of Records
  263. *
  264. * @param array $tableInfo Table schema array
  265. * @param integer $recordCount
  266. * @return array Array of records to use in the fixture.
  267. */
  268. protected function _generateRecords($tableInfo, $recordCount = 1) {
  269. $records = array();
  270. for ($i = 0; $i < $recordCount; $i++) {
  271. $record = array();
  272. foreach ($tableInfo as $field => $fieldInfo) {
  273. if (empty($fieldInfo['type'])) {
  274. continue;
  275. }
  276. $insert = '';
  277. switch ($fieldInfo['type']) {
  278. case 'integer':
  279. case 'float':
  280. $insert = $i + 1;
  281. break;
  282. case 'string':
  283. case 'binary':
  284. $isPrimaryUuid = (
  285. isset($fieldInfo['key']) && strtolower($fieldInfo['key']) === 'primary' &&
  286. isset($fieldInfo['length']) && $fieldInfo['length'] == 36
  287. );
  288. if ($isPrimaryUuid) {
  289. $insert = String::uuid();
  290. } else {
  291. $insert = "Lorem ipsum dolor sit amet";
  292. if (!empty($fieldInfo['length'])) {
  293. $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
  294. }
  295. }
  296. break;
  297. case 'timestamp':
  298. $insert = time();
  299. break;
  300. case 'datetime':
  301. $insert = date('Y-m-d H:i:s');
  302. break;
  303. case 'date':
  304. $insert = date('Y-m-d');
  305. break;
  306. case 'time':
  307. $insert = date('H:i:s');
  308. break;
  309. case 'boolean':
  310. $insert = 1;
  311. break;
  312. case 'text':
  313. $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
  314. $insert .= " Convallis morbi fringilla gravida,";
  315. $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
  316. $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
  317. $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
  318. $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
  319. $insert .= " duis vestibulum nunc mattis convallis.";
  320. break;
  321. }
  322. $record[$field] = $insert;
  323. }
  324. $records[] = $record;
  325. }
  326. return $records;
  327. }
  328. /**
  329. * Convert a $records array into a a string.
  330. *
  331. * @param array $records Array of records to be converted to string
  332. * @return string A string value of the $records array.
  333. */
  334. protected function _makeRecordString($records) {
  335. $out = "array(\n";
  336. foreach ($records as $record) {
  337. $values = array();
  338. foreach ($record as $field => $value) {
  339. $val = var_export($value, true);
  340. if ($val === 'NULL') {
  341. $val = 'null';
  342. }
  343. $values[] = "\t\t\t'$field' => $val";
  344. }
  345. $out .= "\t\tarray(\n";
  346. $out .= implode(",\n", $values);
  347. $out .= "\n\t\t),\n";
  348. }
  349. $out .= "\t)";
  350. return $out;
  351. }
  352. /**
  353. * Interact with the user to get a custom SQL condition and use that to extract data
  354. * to build a fixture.
  355. *
  356. * @param string $modelName name of the model to take records from.
  357. * @param string $useTable Name of table to use.
  358. * @return array Array of records.
  359. */
  360. protected function _getRecordsFromTable($modelName, $useTable = null) {
  361. if ($this->interactive) {
  362. $condition = null;
  363. $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
  364. while (!$condition) {
  365. $condition = $this->in($prompt, null, 'WHERE 1=1');
  366. }
  367. $prompt = __d('cake_console', "How many records do you want to import?");
  368. $recordCount = $this->in($prompt, null, 10);
  369. } else {
  370. $condition = 'WHERE 1=1';
  371. $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
  372. }
  373. $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
  374. $records = $modelObject->find('all', array(
  375. 'conditions' => $condition,
  376. 'recursive' => -1,
  377. 'limit' => $recordCount
  378. ));
  379. $schema = $modelObject->schema(true);
  380. $out = array();
  381. foreach ($records as $record) {
  382. $row = array();
  383. foreach ($record[$modelObject->alias] as $field => $value) {
  384. if ($schema[$field]['type'] === 'boolean') {
  385. $value = (int)(bool)$value;
  386. }
  387. $row[$field] = $value;
  388. }
  389. $out[] = $row;
  390. }
  391. return $out;
  392. }
  393. }