PageRenderTime 34ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/Console/Command/Task/FixtureTask.php

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