PageRenderTime 58ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

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

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