PageRenderTime 39ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/code/ryzom/tools/server/www/webtt/cake/console/libs/tasks/fixture.php

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 425 lines | 344 code | 10 blank | 71 comment | 12 complexity | d165306844363ac91b95b0f159382686 MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * The FixtureTask handles creating and updating fixture files.
  4. *
  5. * PHP versions 4 and 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
  16. * @subpackage cake.cake.console.libs.tasks
  17. * @since CakePHP(tm) v 1.3
  18. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  19. */
  20. include_once dirname(__FILE__) . DS . 'bake.php';
  21. /**
  22. * Task class for creating and updating fixtures files.
  23. *
  24. * @package cake
  25. * @subpackage cake.cake.console.libs.tasks
  26. */
  27. class FixtureTask extends BakeTask {
  28. /**
  29. * Tasks to be loaded by this Task
  30. *
  31. * @var array
  32. * @access public
  33. */
  34. var $tasks = array('DbConfig', 'Model', 'Template');
  35. /**
  36. * path to fixtures directory
  37. *
  38. * @var string
  39. * @access public
  40. */
  41. var $path = null;
  42. /**
  43. * Schema instance
  44. *
  45. * @var object
  46. * @access protected
  47. */
  48. var $_Schema = null;
  49. /**
  50. * Override initialize
  51. *
  52. * @access public
  53. */
  54. function __construct(&$dispatch) {
  55. parent::__construct($dispatch);
  56. $this->path = $this->params['working'] . DS . 'tests' . DS . 'fixtures' . DS;
  57. }
  58. /**
  59. * Execution method always used for tasks
  60. * Handles dispatching to interactive, named, or all processess.
  61. *
  62. * @access public
  63. */
  64. function execute() {
  65. if (empty($this->args)) {
  66. $this->__interactive();
  67. }
  68. if (isset($this->args[0])) {
  69. $this->interactive = false;
  70. if (!isset($this->connection)) {
  71. $this->connection = 'default';
  72. }
  73. if (strtolower($this->args[0]) == 'all') {
  74. return $this->all();
  75. }
  76. $model = $this->_modelName($this->args[0]);
  77. $this->bake($model);
  78. }
  79. }
  80. /**
  81. * Bake All the Fixtures at once. Will only bake fixtures for models that exist.
  82. *
  83. * @access public
  84. * @return void
  85. */
  86. function all() {
  87. $this->interactive = false;
  88. $this->Model->interactive = false;
  89. $tables = $this->Model->listAll($this->connection, false);
  90. foreach ($tables as $table) {
  91. $model = $this->_modelName($table);
  92. $this->bake($model);
  93. }
  94. }
  95. /**
  96. * Interactive baking function
  97. *
  98. * @access private
  99. */
  100. function __interactive() {
  101. $this->DbConfig->interactive = $this->Model->interactive = $this->interactive = true;
  102. $this->hr();
  103. $this->out(sprintf("Bake Fixture\nPath: %s", $this->path));
  104. $this->hr();
  105. $useDbConfig = $this->connection;
  106. if (!isset($this->connection)) {
  107. $this->connection = $this->DbConfig->getConfig();
  108. }
  109. $modelName = $this->Model->getName($this->connection);
  110. $useTable = $this->Model->getTable($modelName, $this->connection);
  111. $importOptions = $this->importOptions($modelName);
  112. $this->bake($modelName, $useTable, $importOptions);
  113. }
  114. /**
  115. * Interacts with the User to setup an array of import options. For a fixture.
  116. *
  117. * @param string $modelName Name of model you are dealing with.
  118. * @return array Array of import options.
  119. * @access public
  120. */
  121. function importOptions($modelName) {
  122. $options = array();
  123. $doSchema = $this->in(__('Would you like to import schema for this fixture?', true), array('y', 'n'), 'n');
  124. if ($doSchema == 'y') {
  125. $options['schema'] = $modelName;
  126. }
  127. $doRecords = $this->in(__('Would you like to use record importing for this fixture?', true), array('y', 'n'), 'n');
  128. if ($doRecords == 'y') {
  129. $options['records'] = true;
  130. }
  131. if ($doRecords == 'n') {
  132. $prompt = sprintf(__("Would you like to build this fixture with data from %s's table?", true), $modelName);
  133. $fromTable = $this->in($prompt, array('y', 'n'), 'n');
  134. if (strtolower($fromTable) == 'y') {
  135. $options['fromTable'] = true;
  136. }
  137. }
  138. return $options;
  139. }
  140. /**
  141. * Assembles and writes a Fixture file
  142. *
  143. * @param string $model Name of model to bake.
  144. * @param string $useTable Name of table to use.
  145. * @param array $importOptions Options for var $import
  146. * @return string Baked fixture content
  147. * @access public
  148. */
  149. function bake($model, $useTable = false, $importOptions = array()) {
  150. if (!class_exists('CakeSchema')) {
  151. App::import('Model', 'CakeSchema', false);
  152. }
  153. $table = $schema = $records = $import = $modelImport = null;
  154. $importBits = array();
  155. if (!$useTable) {
  156. $useTable = Inflector::tableize($model);
  157. } elseif ($useTable != Inflector::tableize($model)) {
  158. $table = $useTable;
  159. }
  160. if (!empty($importOptions)) {
  161. if (isset($importOptions['schema'])) {
  162. $modelImport = true;
  163. $importBits[] = "'model' => '{$importOptions['schema']}'";
  164. }
  165. if (isset($importOptions['records'])) {
  166. $importBits[] = "'records' => true";
  167. }
  168. if ($this->connection != 'default') {
  169. $importBits[] .= "'connection' => '{$this->connection}'";
  170. }
  171. if (!empty($importBits)) {
  172. $import = sprintf("array(%s)", implode(', ', $importBits));
  173. }
  174. }
  175. $this->_Schema = new CakeSchema();
  176. $data = $this->_Schema->read(array('models' => false, 'connection' => $this->connection));
  177. if (!isset($data['tables'][$useTable])) {
  178. $this->err('Could not find your selected table ' . $useTable);
  179. return false;
  180. }
  181. $tableInfo = $data['tables'][$useTable];
  182. if (is_null($modelImport)) {
  183. $schema = $this->_generateSchema($tableInfo);
  184. }
  185. if (!isset($importOptions['records']) && !isset($importOptions['fromTable'])) {
  186. $recordCount = 1;
  187. if (isset($this->params['count'])) {
  188. $recordCount = $this->params['count'];
  189. }
  190. $records = $this->_makeRecordString($this->_generateRecords($tableInfo, $recordCount));
  191. }
  192. if (isset($this->params['records']) || isset($importOptions['fromTable'])) {
  193. $records = $this->_makeRecordString($this->_getRecordsFromTable($model, $useTable));
  194. }
  195. $out = $this->generateFixtureFile($model, compact('records', 'table', 'schema', 'import', 'fields'));
  196. return $out;
  197. }
  198. /**
  199. * Generate the fixture file, and write to disk
  200. *
  201. * @param string $model name of the model being generated
  202. * @param string $fixture Contents of the fixture file.
  203. * @return string Content saved into fixture file.
  204. * @access public
  205. */
  206. function generateFixtureFile($model, $otherVars) {
  207. $defaults = array('table' => null, 'schema' => null, 'records' => null, 'import' => null, 'fields' => null);
  208. $vars = array_merge($defaults, $otherVars);
  209. $path = $this->getPath();
  210. $filename = Inflector::underscore($model) . '_fixture.php';
  211. $this->Template->set('model', $model);
  212. $this->Template->set($vars);
  213. $content = $this->Template->generate('classes', 'fixture');
  214. $this->out("\nBaking test fixture for $model...");
  215. $this->createFile($path . $filename, $content);
  216. return $content;
  217. }
  218. /**
  219. * Get the path to the fixtures.
  220. *
  221. * @return void
  222. */
  223. function getPath() {
  224. $path = $this->path;
  225. if (isset($this->plugin)) {
  226. $path = $this->_pluginPath($this->plugin) . 'tests' . DS . 'fixtures' . DS;
  227. }
  228. return $path;
  229. }
  230. /**
  231. * Generates a string representation of a schema.
  232. *
  233. * @param array $table Table schema array
  234. * @return string fields definitions
  235. * @access protected
  236. */
  237. function _generateSchema($tableInfo) {
  238. $schema = $this->_Schema->generateTable('f', $tableInfo);
  239. return substr($schema, 10, -2);
  240. }
  241. /**
  242. * Generate String representation of Records
  243. *
  244. * @param array $table Table schema array
  245. * @return array Array of records to use in the fixture.
  246. * @access protected
  247. */
  248. function _generateRecords($tableInfo, $recordCount = 1) {
  249. $records = array();
  250. for ($i = 0; $i < $recordCount; $i++) {
  251. $record = array();
  252. foreach ($tableInfo as $field => $fieldInfo) {
  253. if (empty($fieldInfo['type'])) {
  254. continue;
  255. }
  256. switch ($fieldInfo['type']) {
  257. case 'integer':
  258. case 'float':
  259. $insert = $i + 1;
  260. break;
  261. case 'string':
  262. case 'binary':
  263. $isPrimaryUuid = (
  264. isset($fieldInfo['key']) && strtolower($fieldInfo['key']) == 'primary' &&
  265. isset($fieldInfo['length']) && $fieldInfo['length'] == 36
  266. );
  267. if ($isPrimaryUuid) {
  268. $insert = String::uuid();
  269. } else {
  270. $insert = "Lorem ipsum dolor sit amet";
  271. if (!empty($fieldInfo['length'])) {
  272. $insert = substr($insert, 0, (int)$fieldInfo['length'] - 2);
  273. }
  274. }
  275. $insert = "'$insert'";
  276. break;
  277. case 'timestamp':
  278. $ts = time();
  279. $insert = "'$ts'";
  280. break;
  281. case 'datetime':
  282. $ts = date('Y-m-d H:i:s');
  283. $insert = "'$ts'";
  284. break;
  285. case 'date':
  286. $ts = date('Y-m-d');
  287. $insert = "'$ts'";
  288. break;
  289. case 'time':
  290. $ts = date('H:i:s');
  291. $insert = "'$ts'";
  292. break;
  293. case 'boolean':
  294. $insert = 1;
  295. break;
  296. case 'text':
  297. $insert = "'Lorem ipsum dolor sit amet, aliquet feugiat.";
  298. $insert .= " Convallis morbi fringilla gravida,";
  299. $insert .= " phasellus feugiat dapibus velit nunc, pulvinar eget sollicitudin";
  300. $insert .= " venenatis cum nullam, vivamus ut a sed, mollitia lectus. Nulla";
  301. $insert .= " vestibulum massa neque ut et, id hendrerit sit,";
  302. $insert .= " feugiat in taciti enim proin nibh, tempor dignissim, rhoncus";
  303. $insert .= " duis vestibulum nunc mattis convallis.'";
  304. break;
  305. }
  306. $record[$field] = $insert;
  307. }
  308. $records[] = $record;
  309. }
  310. return $records;
  311. }
  312. /**
  313. * Convert a $records array into a a string.
  314. *
  315. * @param array $records Array of records to be converted to string
  316. * @return string A string value of the $records array.
  317. * @access protected
  318. */
  319. function _makeRecordString($records) {
  320. $out = "array(\n";
  321. foreach ($records as $record) {
  322. $values = array();
  323. foreach ($record as $field => $value) {
  324. $values[] = "\t\t\t'$field' => $value";
  325. }
  326. $out .= "\t\tarray(\n";
  327. $out .= implode(",\n", $values);
  328. $out .= "\n\t\t),\n";
  329. }
  330. $out .= "\t)";
  331. return $out;
  332. }
  333. /**
  334. * Interact with the user to get a custom SQL condition and use that to extract data
  335. * to build a fixture.
  336. *
  337. * @param string $modelName name of the model to take records from.
  338. * @param string $useTable Name of table to use.
  339. * @return array Array of records.
  340. * @access protected
  341. */
  342. function _getRecordsFromTable($modelName, $useTable = null) {
  343. if ($this->interactive) {
  344. $condition = null;
  345. $prompt = __("Please provide a SQL fragment to use as conditions\nExample: WHERE 1=1 LIMIT 10", true);
  346. while (!$condition) {
  347. $condition = $this->in($prompt, null, 'WHERE 1=1 LIMIT 10');
  348. }
  349. } else {
  350. $condition = 'WHERE 1=1 LIMIT ' . (isset($this->params['count']) ? $this->params['count'] : 10);
  351. }
  352. App::import('Model', 'Model', false);
  353. $modelObject =& new Model(array('name' => $modelName, 'table' => $useTable, 'ds' => $this->connection));
  354. $records = $modelObject->find('all', array(
  355. 'conditions' => $condition,
  356. 'recursive' => -1
  357. ));
  358. $db =& ConnectionManager::getDataSource($modelObject->useDbConfig);
  359. $schema = $modelObject->schema(true);
  360. $out = array();
  361. foreach ($records as $record) {
  362. $row = array();
  363. foreach ($record[$modelObject->alias] as $field => $value) {
  364. $row[$field] = $db->value($value, $schema[$field]['type']);
  365. }
  366. $out[] = $row;
  367. }
  368. return $out;
  369. }
  370. /**
  371. * Displays help contents
  372. *
  373. * @access public
  374. */
  375. function help() {
  376. $this->hr();
  377. $this->out("Usage: cake bake fixture <arg1> <params>");
  378. $this->hr();
  379. $this->out('Arguments:');
  380. $this->out();
  381. $this->out("<name>");
  382. $this->out("\tName of the fixture to bake. Can use Plugin.name");
  383. $this->out("\tas a shortcut for plugin baking.");
  384. $this->out();
  385. $this->out('Commands:');
  386. $this->out("\nfixture <name>\n\tbakes fixture with specified name.");
  387. $this->out("\nfixture all\n\tbakes all fixtures.");
  388. $this->out();
  389. $this->out('Parameters:');
  390. $this->out("\t-count When using generated data, the number of records to include in the fixture(s).");
  391. $this->out("\t-connection Which database configuration to use for baking.");
  392. $this->out("\t-plugin CamelCased name of plugin to bake fixtures for.");
  393. $this->out("\t-records Used with -count and <name>/all commands to pull [n] records from the live tables");
  394. $this->out("\t Where [n] is either -count or the default of 10.");
  395. $this->out();
  396. $this->_stop();
  397. }
  398. }