FixtureTask.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.console.shells.tasks
  16. * @since CakePHP(tm) v 1.3
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('BakeTask', 'Console/Command/Task');
  20. App::uses('Model', 'Model');
  21. /**
  22. * Task class for creating and updating fixtures files.
  23. *
  24. * @package cake.console.shells.tasks
  25. */
  26. class FixtureTask extends BakeTask {
  27. /**
  28. * Tasks to be loaded by this Task
  29. *
  30. * @var array
  31. * @access public
  32. */
  33. public $tasks = array('DbConfig', 'Model', 'Template');
  34. /**
  35. * path to fixtures directory
  36. *
  37. * @var string
  38. * @access public
  39. */
  40. public $path = null;
  41. /**
  42. * Schema instance
  43. *
  44. * @var object
  45. * @access protected
  46. */
  47. protected $_Schema = null;
  48. /**
  49. * Override initialize
  50. *
  51. */
  52. public function __construct($stdout = null, $stderr = null, $stdin = null) {
  53. parent::__construct($stdout, $stderr, $stdin);
  54. $this->path = APP . 'tests' . DS . 'Fixture' . DS;
  55. }
  56. /**
  57. * get the option parser.
  58. *
  59. * @return void
  60. */
  61. public function getOptionParser() {
  62. $parser = parent::getOptionParser();
  63. return $parser->description(
  64. __d('cake_console', 'Generate fixtures for use with the test suite. You can use `bake fixture all` to bake all fixtures.')
  65. )->addArgument('name', array(
  66. 'help' => __d('cake_console', 'Name of the fixture to bake. Can use Plugin.name to bake plugin fixtures.')
  67. ))->addOption('count', array(
  68. 'help' => __d('cake_console', 'When using generated data, the number of records to include in the fixture(s).'),
  69. 'short' => 'n',
  70. 'default' => 10
  71. ))->addOption('connection', array(
  72. 'help' => __d('cake_console', 'Which database configuration to use for baking.'),
  73. 'short' => 'c',
  74. 'default' => 'default'
  75. ))->addOption('plugin', array(
  76. 'help' => __d('cake_console', 'CamelCased name of the plugin to bake fixtures for.'),
  77. 'short' => 'p',
  78. ))->addOption('records', array(
  79. 'help' => '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',
  80. 'short' => 'r',
  81. 'boolean' => true
  82. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));;
  83. }
  84. /**
  85. * Execution method always used for tasks
  86. * Handles dispatching to interactive, named, or all processess.
  87. *
  88. * @return void
  89. */
  90. public function execute() {
  91. parent::execute();
  92. if (empty($this->args)) {
  93. $this->_interactive();
  94. }
  95. if (isset($this->args[0])) {
  96. $this->interactive = false;
  97. if (!isset($this->connection)) {
  98. $this->connection = 'default';
  99. }
  100. if (strtolower($this->args[0]) == 'all') {
  101. return $this->all();
  102. }
  103. $model = $this->_modelName($this->args[0]);
  104. $this->bake($model);
  105. }
  106. }
  107. /**
  108. * Bake All the Fixtures at once. Will only bake fixtures for models that exist.
  109. *
  110. * @return void
  111. */
  112. public function all() {
  113. $this->interactive = false;
  114. $this->Model->interactive = false;
  115. $tables = $this->Model->listAll($this->connection, false);
  116. foreach ($tables as $table) {
  117. $model = $this->_modelName($table);
  118. $this->bake($model);
  119. }
  120. }
  121. /**
  122. * Interactive baking function
  123. *
  124. * @return void
  125. */
  126. protected function _interactive() {
  127. $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
  128. $this->hr();
  129. $this->out(sprintf("Bake Fixture\nPath: %s", $this->path));
  130. $this->hr();
  131. $useDbConfig = $this->connection;
  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 (!isset($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 (isset($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', 'fields'));
  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 $fixture 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("\nBaking test fixture for $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) . 'tests' . DS . 'Fixture' . DS;
  248. }
  249. return $path;
  250. }
  251. /**
  252. * Generates a string representation of a schema.
  253. *
  254. * @param array $table Table schema array
  255. * @return string fields definitions
  256. */
  257. protected function _generateSchema($tableInfo) {
  258. $schema = $this->_Schema->generateTable('f', $tableInfo);
  259. return substr($schema, 10, -2);
  260. }
  261. /**
  262. * Generate String representation of Records
  263. *
  264. * @param array $table Table schema array
  265. * @return array Array of records to use in the fixture.
  266. */
  267. protected function _generateRecords($tableInfo, $recordCount = 1) {
  268. $records = array();
  269. for ($i = 0; $i < $recordCount; $i++) {
  270. $record = array();
  271. foreach ($tableInfo as $field => $fieldInfo) {
  272. if (empty($fieldInfo['type'])) {
  273. continue;
  274. }
  275. switch ($fieldInfo['type']) {
  276. case 'integer':
  277. case 'float':
  278. $insert = $i + 1;
  279. break;
  280. case 'string':
  281. case 'binary':
  282. $isPrimaryUuid = (
  283. isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
  284. isset($fieldInfo['length']) && $fieldInfo['length'] == 36
  285. );
  286. if ($isPrimaryUuid) {
  287. $insert = String::uuid();
  288. } else {
  289. $insert = "Lorem ipsum dolor sit amet";
  290. if (!empty($fieldInfo['length'])) {
  291. $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
  292. }
  293. }
  294. $insert = "'$insert'";
  295. break;
  296. case 'timestamp':
  297. $ts = time();
  298. $insert = "'$ts'";
  299. break;
  300. case 'datetime':
  301. $ts = date('Y-m-d H:i:s');
  302. $insert = "'$ts'";
  303. break;
  304. case 'date':
  305. $ts = date('Y-m-d');
  306. $insert = "'$ts'";
  307. break;
  308. case 'time':
  309. $ts = date('H:i:s');
  310. $insert = "'$ts'";
  311. break;
  312. case 'boolean':
  313. $insert = 1;
  314. break;
  315. case 'text':
  316. $insert = "'Lorem ipsum dolor sit amet, aliquet feugiat.";
  317. $insert .= " Convallis morbi fringilla gravida,";
  318. $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
  319. $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
  320. $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
  321. $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
  322. $insert .= " duis vestibulum nunc mattis convallis.'";
  323. break;
  324. }
  325. $record[$field] = $insert;
  326. }
  327. $records[] = $record;
  328. }
  329. return $records;
  330. }
  331. /**
  332. * Convert a $records array into a a string.
  333. *
  334. * @param array $records Array of records to be converted to string
  335. * @return string A string value of the $records array.
  336. */
  337. protected function _makeRecordString($records) {
  338. $out = "array(\n";
  339. foreach ($records as $record) {
  340. $values = array();
  341. foreach ($record as $field => $value) {
  342. $values[] = "\t\t\t'$field' => $value";
  343. }
  344. $out .= "\t\tarray(\n";
  345. $out .= implode(",\n", $values);
  346. $out .= "\n\t\t),\n";
  347. }
  348. $out .= "\t)";
  349. return $out;
  350. }
  351. /**
  352. * Interact with the user to get a custom SQL condition and use that to extract data
  353. * to build a fixture.
  354. *
  355. * @param string $modelName name of the model to take records from.
  356. * @param string $useTable Name of table to use.
  357. * @return array Array of records.
  358. */
  359. protected function _getRecordsFromTable($modelName, $useTable = null) {
  360. if ($this->interactive) {
  361. $condition = null;
  362. $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1 LIMIT 10");
  363. while (!$condition) {
  364. $condition = $this->in($prompt, null, 'WHERE 1=1 LIMIT 10');
  365. }
  366. } else {
  367. $condition = 'WHERE 1=1 LIMIT ' . (isset($this->params['count']) ? $this->params['count'] : 10);
  368. }
  369. $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
  370. $records = $modelObject->find('all', array(
  371. 'conditions' => $condition,
  372. 'recursive' => -1
  373. ));
  374. $db = ConnectionManager::getDataSource($modelObject->useDbConfig);
  375. $schema = $modelObject->schema(true);
  376. $out = array();
  377. foreach ($records as $record) {
  378. $row = array();
  379. foreach ($record[$modelObject->alias] as $field => $value) {
  380. $row[$field] = $db->value($value, $schema[$field]['type']);
  381. }
  382. $out[] = $row;
  383. }
  384. return $out;
  385. }
  386. }