FixtureTask.php 13 KB

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