PageRenderTime 34ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://bitbucket.org/udeshika/fake_twitter
PHP | 418 lines | 335 code | 13 blank | 70 comment | 13 complexity | b271191396b433d1c4360487a029fa16 MD5 | raw file
  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-2011, 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-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.3
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. App::uses('AppShell', 'Console/Command');
  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.Command.Task
  25. */
  26. class FixtureTask extends BakeTask {
  27. /**
  28. * Tasks to be loaded by this Task
  29. *
  30. * @var array
  31. */
  32. public $tasks = array('DbConfig', 'Model', 'Template');
  33. /**
  34. * path to fixtures directory
  35. *
  36. * @var string
  37. */
  38. public $path = null;
  39. /**
  40. * Schema instance
  41. *
  42. * @var CakeSchema
  43. */
  44. protected $_Schema = null;
  45. /**
  46. * Override initialize
  47. *
  48. * @param ConsoleOutput $stdout A ConsoleOutput object for stdout.
  49. * @param ConsoleOutput $stderr A ConsoleOutput object for stderr.
  50. * @param ConsoleInput $stdin A ConsoleInput object for stdin.
  51. */
  52. public function __construct($stdout = null, $stderr = null, $stdin = null) {
  53. parent::__construct($stdout, $stderr, $stdin);
  54. $this->path = APP . 'Test' . 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' => __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'),
  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 processes.
  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(__d('cake_console', "Bake Fixture\nPath: %s", $this->path));
  130. $this->hr();
  131. if (!isset($this->connection)) {
  132. $this->connection = $this->DbConfig->getConfig();
  133. }
  134. $modelName = $this->Model->getName($this->connection);
  135. $useTable = $this->Model->getTable($modelName, $this->connection);
  136. $importOptions = $this->importOptions($modelName);
  137. $this->bake($modelName, $useTable, $importOptions);
  138. }
  139. /**
  140. * Interacts with the User to setup an array of import options. For a fixture.
  141. *
  142. * @param string $modelName Name of model you are dealing with.
  143. * @return array Array of import options.
  144. */
  145. public function importOptions($modelName) {
  146. $options = array();
  147. $doSchema = $this->in(__d('cake_console', 'Would you like to import schema for this fixture?'), array('y', 'n'), 'n');
  148. if ($doSchema == 'y') {
  149. $options['schema'] = $modelName;
  150. }
  151. $doRecords = $this->in(__d('cake_console', 'Would you like to use record importing for this fixture?'), array('y', 'n'), 'n');
  152. if ($doRecords == 'y') {
  153. $options['records'] = true;
  154. }
  155. if ($doRecords == 'n') {
  156. $prompt = __d('cake_console', "Would you like to build this fixture with data from %s's table?", $modelName);
  157. $fromTable = $this->in($prompt, array('y', 'n'), 'n');
  158. if (strtolower($fromTable) == 'y') {
  159. $options['fromTable'] = true;
  160. }
  161. }
  162. return $options;
  163. }
  164. /**
  165. * Assembles and writes a Fixture file
  166. *
  167. * @param string $model Name of model to bake.
  168. * @param string $useTable Name of table to use.
  169. * @param array $importOptions Options for public $import
  170. * @return string Baked fixture content
  171. */
  172. public function bake($model, $useTable = false, $importOptions = array()) {
  173. App::uses('CakeSchema', 'Model');
  174. $table = $schema = $records = $import = $modelImport = null;
  175. $importBits = array();
  176. if (!$useTable) {
  177. $useTable = Inflector::tableize($model);
  178. } elseif ($useTable != Inflector::tableize($model)) {
  179. $table = $useTable;
  180. }
  181. if (!empty($importOptions)) {
  182. if (isset($importOptions['schema'])) {
  183. $modelImport = true;
  184. $importBits[] = "'model' => '{$importOptions['schema']}'";
  185. }
  186. if (isset($importOptions['records'])) {
  187. $importBits[] = "'records' => true";
  188. }
  189. if ($this->connection != 'default') {
  190. $importBits[] .= "'connection' => '{$this->connection}'";
  191. }
  192. if (!empty($importBits)) {
  193. $import = sprintf("array(%s)", implode(', ', $importBits));
  194. }
  195. }
  196. $this->_Schema = new CakeSchema();
  197. $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
  198. if (!isset($data['tables'][$useTable])) {
  199. $this->err('Could not find your selected table ' . $useTable);
  200. return false;
  201. }
  202. $tableInfo = $data['tables'][$useTable];
  203. if (is_null($modelImport)) {
  204. $schema = $this->_generateSchema($tableInfo);
  205. }
  206. if (empty($importOptions['records']) && !isset($importOptions['fromTable'])) {
  207. $recordCount = 1;
  208. if (isset($this->params['count'])) {
  209. $recordCount = $this->params['count'];
  210. }
  211. $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
  212. }
  213. if (!empty($this->params['records']) || isset($importOptions['fromTable'])) {
  214. $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
  215. }
  216. $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
  217. return $out;
  218. }
  219. /**
  220. * Generate the fixture file, and write to disk
  221. *
  222. * @param string $model name of the model being generated
  223. * @param string $otherVars Contents of the fixture file.
  224. * @return string Content saved into fixture file.
  225. */
  226. public function generateFixtureFile($model, $otherVars) {
  227. $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
  228. $vars = array_merge($defaults, $otherVars);
  229. $path = $this->getPath();
  230. $filename = Inflector::camelize($model) . 'Fixture.php';
  231. $this->Template->set('model', $model);
  232. $this->Template->set($vars);
  233. $content = $this->Template->generate('classes', 'fixture');
  234. $this->out("\n" . __d('cake_console', 'Baking test fixture for %s...', $model), 1, Shell::QUIET);
  235. $this->createFile($path . $filename, $content);
  236. return $content;
  237. }
  238. /**
  239. * Get the path to the fixtures.
  240. *
  241. * @return string Path for the fixtures
  242. */
  243. public function getPath() {
  244. $path = $this->path;
  245. if (isset($this->plugin)) {
  246. $path = $this->_pluginPath($this->plugin) . 'Test' . DS . 'Fixture' . DS;
  247. }
  248. return $path;
  249. }
  250. /**
  251. * Generates a string representation of a schema.
  252. *
  253. * @param array $tableInfo Table schema array
  254. * @return string fields definitions
  255. */
  256. protected function _generateSchema($tableInfo) {
  257. $schema = $this->_Schema->generateTable('f', $tableInfo);
  258. return substr($schema, 13, -2);
  259. }
  260. /**
  261. * Generate String representation of Records
  262. *
  263. * @param array $tableInfo Table schema array
  264. * @param integer $recordCount
  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. break;
  295. case 'timestamp':
  296. $insert = time();
  297. break;
  298. case 'datetime':
  299. $insert = date('Y-m-d H:i:s');
  300. break;
  301. case 'date':
  302. $insert = date('Y-m-d');
  303. break;
  304. case 'time':
  305. $insert = date('H:i:s');
  306. break;
  307. case 'boolean':
  308. $insert = 1;
  309. break;
  310. case 'text':
  311. $insert = "Lorem ipsum dolor sit amet, aliquet feugiat.";
  312. $insert .= " Convallis morbi fringilla gravida,";
  313. $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
  314. $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
  315. $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
  316. $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
  317. $insert .= " duis vestibulum nunc mattis convallis.";
  318. break;
  319. }
  320. $record[$field] = $insert;
  321. }
  322. $records[] = $record;
  323. }
  324. return $records;
  325. }
  326. /**
  327. * Convert a $records array into a a string.
  328. *
  329. * @param array $records Array of records to be converted to string
  330. * @return string A string value of the $records array.
  331. */
  332. protected function _makeRecordString($records) {
  333. $out = "array(\n";
  334. foreach ($records as $record) {
  335. $values = array();
  336. foreach ($record as $field => $value) {
  337. $val = var_export($value, true);
  338. $values[] = "\t\t\t'$field' => $val";
  339. }
  340. $out .= "\t\tarray(\n";
  341. $out .= implode(",\n", $values);
  342. $out .= "\n\t\t),\n";
  343. }
  344. $out .= "\t)";
  345. return $out;
  346. }
  347. /**
  348. * Interact with the user to get a custom SQL condition and use that to extract data
  349. * to build a fixture.
  350. *
  351. * @param string $modelName name of the model to take records from.
  352. * @param string $useTable Name of table to use.
  353. * @return array Array of records.
  354. */
  355. protected function _getRecordsFromTable($modelName, $useTable = null) {
  356. if ($this->interactive) {
  357. $condition = null;
  358. $prompt = __d('cake_console', "Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1");
  359. while (!$condition) {
  360. $condition = $this->in($prompt, null, 'WHERE 1=1');
  361. }
  362. $prompt = __d('cake_console', "How many records do you want to import?");
  363. $recordCount = $this->in($prompt, null, 10);
  364. } else {
  365. $condition = 'WHERE 1=1';
  366. $recordCount = (isset($this->params['count']) ? $this->params['count'] : 10);
  367. }
  368. $modelObject = new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
  369. $records = $modelObject->find('all', array(
  370. 'conditions' => $condition,
  371. 'recursive' => -1,
  372. 'limit' => $recordCount
  373. ));
  374. $db = $modelObject->getDatasource();
  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. if ($schema[$field]['type'] === 'boolean') {
  381. $value = (int)(bool)$value;
  382. }
  383. $row[$field] = $value;
  384. }
  385. $out[] = $row;
  386. }
  387. return $out;
  388. }
  389. }