PageRenderTime 53ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

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

https://bitbucket.org/mattraykowski/ryzomcore_demoshard
PHP | 938 lines | 639 code | 75 blank | 224 comment | 160 complexity | 8ac58beed99fb9de642a64fc726e44ae MD5 | raw file
Possible License(s): AGPL-3.0, GPL-3.0, LGPL-2.1
  1. <?php
  2. /**
  3. * The ModelTask handles creating and updating models 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. (http://cakefoundation.org)
  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.2
  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 model files.
  23. *
  24. * @package cake
  25. * @subpackage cake.cake.console.libs.tasks
  26. */
  27. class ModelTask extends BakeTask {
  28. /**
  29. * path to MODELS directory
  30. *
  31. * @var string
  32. * @access public
  33. */
  34. var $path = MODELS;
  35. /**
  36. * tasks
  37. *
  38. * @var array
  39. * @access public
  40. */
  41. var $tasks = array('DbConfig', 'Fixture', 'Test', 'Template');
  42. /**
  43. * Tables to skip when running all()
  44. *
  45. * @var array
  46. * @access protected
  47. */
  48. var $skipTables = array('i18n');
  49. /**
  50. * Holds tables found on connection.
  51. *
  52. * @var array
  53. * @access protected
  54. */
  55. var $_tables = array();
  56. /**
  57. * Holds validation method map.
  58. *
  59. * @var array
  60. * @access protected
  61. */
  62. var $_validations = array();
  63. /**
  64. * Execution method always used for tasks
  65. *
  66. * @access public
  67. */
  68. function execute() {
  69. App::import('Model', 'Model', false);
  70. if (empty($this->args)) {
  71. $this->__interactive();
  72. }
  73. if (!empty($this->args[0])) {
  74. $this->interactive = false;
  75. if (!isset($this->connection)) {
  76. $this->connection = 'default';
  77. }
  78. if (strtolower($this->args[0]) == 'all') {
  79. return $this->all();
  80. }
  81. $model = $this->_modelName($this->args[0]);
  82. $object = $this->_getModelObject($model);
  83. if ($this->bake($object, false)) {
  84. if ($this->_checkUnitTest()) {
  85. $this->bakeFixture($model);
  86. $this->bakeTest($model);
  87. }
  88. }
  89. }
  90. }
  91. /**
  92. * Bake all models at once.
  93. *
  94. * @return void
  95. */
  96. function all() {
  97. $this->listAll($this->connection, false);
  98. $unitTestExists = $this->_checkUnitTest();
  99. foreach ($this->_tables as $table) {
  100. if (in_array($table, $this->skipTables)) {
  101. continue;
  102. }
  103. $modelClass = Inflector::classify($table);
  104. $this->out(sprintf(__('Baking %s', true), $modelClass));
  105. $object = $this->_getModelObject($modelClass);
  106. if ($this->bake($object, false) && $unitTestExists) {
  107. $this->bakeFixture($modelClass);
  108. $this->bakeTest($modelClass);
  109. }
  110. }
  111. }
  112. /**
  113. * Get a model object for a class name.
  114. *
  115. * @param string $className Name of class you want model to be.
  116. * @return object Model instance
  117. */
  118. function &_getModelObject($className, $table = null) {
  119. if (!$table) {
  120. $table = Inflector::tableize($className);
  121. }
  122. $object =& new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
  123. return $object;
  124. }
  125. /**
  126. * Generate a key value list of options and a prompt.
  127. *
  128. * @param array $options Array of options to use for the selections. indexes must start at 0
  129. * @param string $prompt Prompt to use for options list.
  130. * @param integer $default The default option for the given prompt.
  131. * @return result of user choice.
  132. */
  133. function inOptions($options, $prompt = null, $default = null) {
  134. $valid = false;
  135. $max = count($options);
  136. while (!$valid) {
  137. foreach ($options as $i => $option) {
  138. $this->out($i + 1 .'. ' . $option);
  139. }
  140. if (empty($prompt)) {
  141. $prompt = __('Make a selection from the choices above', true);
  142. }
  143. $choice = $this->in($prompt, null, $default);
  144. if (intval($choice) > 0 && intval($choice) <= $max) {
  145. $valid = true;
  146. }
  147. }
  148. return $choice - 1;
  149. }
  150. /**
  151. * Handles interactive baking
  152. *
  153. * @access private
  154. */
  155. function __interactive() {
  156. $this->hr();
  157. $this->out(sprintf("Bake Model\nPath: %s", $this->path));
  158. $this->hr();
  159. $this->interactive = true;
  160. $primaryKey = 'id';
  161. $validate = $associations = array();
  162. if (empty($this->connection)) {
  163. $this->connection = $this->DbConfig->getConfig();
  164. }
  165. $currentModelName = $this->getName();
  166. $useTable = $this->getTable($currentModelName);
  167. $db =& ConnectionManager::getDataSource($this->connection);
  168. $fullTableName = $db->fullTableName($useTable);
  169. if (in_array($useTable, $this->_tables)) {
  170. $tempModel = new Model(array('name' => $currentModelName, 'table' => $useTable, 'ds' => $this->connection));
  171. $fields = $tempModel->schema(true);
  172. if (!array_key_exists('id', $fields)) {
  173. $primaryKey = $this->findPrimaryKey($fields);
  174. }
  175. } else {
  176. $this->err(sprintf(__('Table %s does not exist, cannot bake a model without a table.', true), $useTable));
  177. $this->_stop();
  178. return false;
  179. }
  180. $displayField = $tempModel->hasField(array('name', 'title'));
  181. if (!$displayField) {
  182. $displayField = $this->findDisplayField($tempModel->schema());
  183. }
  184. $prompt = __("Would you like to supply validation criteria \nfor the fields in your model?", true);
  185. $wannaDoValidation = $this->in($prompt, array('y','n'), 'y');
  186. if (array_search($useTable, $this->_tables) !== false && strtolower($wannaDoValidation) == 'y') {
  187. $validate = $this->doValidation($tempModel);
  188. }
  189. $prompt = __("Would you like to define model associations\n(hasMany, hasOne, belongsTo, etc.)?", true);
  190. $wannaDoAssoc = $this->in($prompt, array('y','n'), 'y');
  191. if (strtolower($wannaDoAssoc) == 'y') {
  192. $associations = $this->doAssociations($tempModel);
  193. }
  194. $this->out();
  195. $this->hr();
  196. $this->out(__('The following Model will be created:', true));
  197. $this->hr();
  198. $this->out("Name: " . $currentModelName);
  199. if ($this->connection !== 'default') {
  200. $this->out(sprintf(__("DB Config: %s", true), $this->connection));
  201. }
  202. if ($fullTableName !== Inflector::tableize($currentModelName)) {
  203. $this->out(sprintf(__("DB Table: %s", true), $fullTableName));
  204. }
  205. if ($primaryKey != 'id') {
  206. $this->out(sprintf(__("Primary Key: %s", true), $primaryKey));
  207. }
  208. if (!empty($validate)) {
  209. $this->out(sprintf(__("Validation: %s", true), print_r($validate, true)));
  210. }
  211. if (!empty($associations)) {
  212. $this->out(__("Associations:", true));
  213. $assocKeys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  214. foreach ($assocKeys as $assocKey) {
  215. $this->_printAssociation($currentModelName, $assocKey, $associations);
  216. }
  217. }
  218. $this->hr();
  219. $looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y');
  220. if (strtolower($looksGood) == 'y') {
  221. $vars = compact('associations', 'validate', 'primaryKey', 'useTable', 'displayField');
  222. $vars['useDbConfig'] = $this->connection;
  223. if ($this->bake($currentModelName, $vars)) {
  224. if ($this->_checkUnitTest()) {
  225. $this->bakeFixture($currentModelName, $useTable);
  226. $this->bakeTest($currentModelName, $useTable, $associations);
  227. }
  228. }
  229. } else {
  230. return false;
  231. }
  232. }
  233. /**
  234. * Print out all the associations of a particular type
  235. *
  236. * @param string $modelName Name of the model relations belong to.
  237. * @param string $type Name of association you want to see. i.e. 'belongsTo'
  238. * @param string $associations Collection of associations.
  239. * @access protected
  240. * @return void
  241. */
  242. function _printAssociation($modelName, $type, $associations) {
  243. if (!empty($associations[$type])) {
  244. for ($i = 0; $i < count($associations[$type]); $i++) {
  245. $out = "\t" . $modelName . ' ' . $type . ' ' . $associations[$type][$i]['alias'];
  246. $this->out($out);
  247. }
  248. }
  249. }
  250. /**
  251. * Finds a primary Key in a list of fields.
  252. *
  253. * @param array $fields Array of fields that might have a primary key.
  254. * @return string Name of field that is a primary key.
  255. * @access public
  256. */
  257. function findPrimaryKey($fields) {
  258. foreach ($fields as $name => $field) {
  259. if (isset($field['key']) && $field['key'] == 'primary') {
  260. break;
  261. }
  262. }
  263. return $this->in(__('What is the primaryKey?', true), null, $name);
  264. }
  265. /**
  266. * interact with the user to find the displayField value for a model.
  267. *
  268. * @param array $fields Array of fields to look for and choose as a displayField
  269. * @return mixed Name of field to use for displayField or false if the user declines to choose
  270. */
  271. function findDisplayField($fields) {
  272. $fieldNames = array_keys($fields);
  273. $prompt = __("A displayField could not be automatically detected\nwould you like to choose one?", true);
  274. $continue = $this->in($prompt, array('y', 'n'));
  275. if (strtolower($continue) == 'n') {
  276. return false;
  277. }
  278. $prompt = __('Choose a field from the options above:', true);
  279. $choice = $this->inOptions($fieldNames, $prompt);
  280. return $fieldNames[$choice];
  281. }
  282. /**
  283. * Handles Generation and user interaction for creating validation.
  284. *
  285. * @param object $model Model to have validations generated for.
  286. * @return array $validate Array of user selected validations.
  287. * @access public
  288. */
  289. function doValidation(&$model) {
  290. if (!is_object($model)) {
  291. return false;
  292. }
  293. $fields = $model->schema();
  294. if (empty($fields)) {
  295. return false;
  296. }
  297. $validate = array();
  298. $this->initValidations();
  299. foreach ($fields as $fieldName => $field) {
  300. $validation = $this->fieldValidation($fieldName, $field, $model->primaryKey);
  301. if (!empty($validation)) {
  302. $validate[$fieldName] = $validation;
  303. }
  304. }
  305. return $validate;
  306. }
  307. /**
  308. * Populate the _validations array
  309. *
  310. * @return void
  311. */
  312. function initValidations() {
  313. $options = $choices = array();
  314. if (class_exists('Validation')) {
  315. $parent = get_class_methods(get_parent_class('Validation'));
  316. $options = get_class_methods('Validation');
  317. $options = array_diff($options, $parent);
  318. }
  319. sort($options);
  320. $default = 1;
  321. foreach ($options as $key => $option) {
  322. if ($option{0} != '_' && strtolower($option) != 'getinstance') {
  323. $choices[$default] = strtolower($option);
  324. $default++;
  325. }
  326. }
  327. $choices[$default] = 'none'; // Needed since index starts at 1
  328. $this->_validations = $choices;
  329. return $choices;
  330. }
  331. /**
  332. * Does individual field validation handling.
  333. *
  334. * @param string $fieldName Name of field to be validated.
  335. * @param array $metaData metadata for field
  336. * @return array Array of validation for the field.
  337. */
  338. function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
  339. $defaultChoice = count($this->_validations);
  340. $validate = $alreadyChosen = array();
  341. $anotherValidator = 'y';
  342. while ($anotherValidator == 'y') {
  343. if ($this->interactive) {
  344. $this->out();
  345. $this->out(sprintf(__('Field: %s', true), $fieldName));
  346. $this->out(sprintf(__('Type: %s', true), $metaData['type']));
  347. $this->hr();
  348. $this->out(__('Please select one of the following validation options:', true));
  349. $this->hr();
  350. }
  351. $prompt = '';
  352. for ($i = 1; $i < $defaultChoice; $i++) {
  353. $prompt .= $i . ' - ' . $this->_validations[$i] . "\n";
  354. }
  355. $prompt .= sprintf(__("%s - Do not do any validation on this field.\n", true), $defaultChoice);
  356. $prompt .= __("... or enter in a valid regex validation string.\n", true);
  357. $methods = array_flip($this->_validations);
  358. $guess = $defaultChoice;
  359. if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
  360. if ($fieldName == 'email') {
  361. $guess = $methods['email'];
  362. } elseif ($metaData['type'] == 'string' && $metaData['length'] == 36) {
  363. $guess = $methods['uuid'];
  364. } elseif ($metaData['type'] == 'string') {
  365. $guess = $methods['notempty'];
  366. } elseif ($metaData['type'] == 'integer') {
  367. $guess = $methods['numeric'];
  368. } elseif ($metaData['type'] == 'boolean') {
  369. $guess = $methods['boolean'];
  370. } elseif ($metaData['type'] == 'date') {
  371. $guess = $methods['date'];
  372. } elseif ($metaData['type'] == 'time') {
  373. $guess = $methods['time'];
  374. }
  375. }
  376. if ($this->interactive === true) {
  377. $choice = $this->in($prompt, null, $guess);
  378. if (in_array($choice, $alreadyChosen)) {
  379. $this->out(__("You have already chosen that validation rule,\nplease choose again", true));
  380. continue;
  381. }
  382. if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
  383. $this->out(__('Please make a valid selection.', true));
  384. continue;
  385. }
  386. $alreadyChosen[] = $choice;
  387. } else {
  388. $choice = $guess;
  389. }
  390. if (isset($this->_validations[$choice])) {
  391. $validatorName = $this->_validations[$choice];
  392. } else {
  393. $validatorName = Inflector::slug($choice);
  394. }
  395. if ($choice != $defaultChoice) {
  396. if (is_numeric($choice) && isset($this->_validations[$choice])) {
  397. $validate[$validatorName] = $this->_validations[$choice];
  398. } else {
  399. $validate[$validatorName] = $choice;
  400. }
  401. }
  402. if ($this->interactive == true && $choice != $defaultChoice) {
  403. $anotherValidator = $this->in(__('Would you like to add another validation rule?', true), array('y', 'n'), 'n');
  404. } else {
  405. $anotherValidator = 'n';
  406. }
  407. }
  408. return $validate;
  409. }
  410. /**
  411. * Handles associations
  412. *
  413. * @param object $model
  414. * @return array $assocaitons
  415. * @access public
  416. */
  417. function doAssociations(&$model) {
  418. if (!is_object($model)) {
  419. return false;
  420. }
  421. if ($this->interactive === true) {
  422. $this->out(__('One moment while the associations are detected.', true));
  423. }
  424. $fields = $model->schema(true);
  425. if (empty($fields)) {
  426. return false;
  427. }
  428. if (empty($this->_tables)) {
  429. $this->_tables = $this->getAllTables();
  430. }
  431. $associations = array(
  432. 'belongsTo' => array(), 'hasMany' => array(), 'hasOne'=> array(), 'hasAndBelongsToMany' => array()
  433. );
  434. $possibleKeys = array();
  435. $associations = $this->findBelongsTo($model, $associations);
  436. $associations = $this->findHasOneAndMany($model, $associations);
  437. $associations = $this->findHasAndBelongsToMany($model, $associations);
  438. if ($this->interactive !== true) {
  439. unset($associations['hasOne']);
  440. }
  441. if ($this->interactive === true) {
  442. $this->hr();
  443. if (empty($associations)) {
  444. $this->out(__('None found.', true));
  445. } else {
  446. $this->out(__('Please confirm the following associations:', true));
  447. $this->hr();
  448. $associations = $this->confirmAssociations($model, $associations);
  449. }
  450. $associations = $this->doMoreAssociations($model, $associations);
  451. }
  452. return $associations;
  453. }
  454. /**
  455. * Find belongsTo relations and add them to the associations list.
  456. *
  457. * @param object $model Model instance of model being generated.
  458. * @param array $associations Array of inprogress associations
  459. * @return array $associations with belongsTo added in.
  460. */
  461. function findBelongsTo(&$model, $associations) {
  462. $fields = $model->schema(true);
  463. foreach ($fields as $fieldName => $field) {
  464. $offset = strpos($fieldName, '_id');
  465. if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
  466. $tmpModelName = $this->_modelNameFromKey($fieldName);
  467. $associations['belongsTo'][] = array(
  468. 'alias' => $tmpModelName,
  469. 'className' => $tmpModelName,
  470. 'foreignKey' => $fieldName,
  471. );
  472. } elseif ($fieldName == 'parent_id') {
  473. $associations['belongsTo'][] = array(
  474. 'alias' => 'Parent' . $model->name,
  475. 'className' => $model->name,
  476. 'foreignKey' => $fieldName,
  477. );
  478. }
  479. }
  480. return $associations;
  481. }
  482. /**
  483. * Find the hasOne and HasMany relations and add them to associations list
  484. *
  485. * @param object $model Model instance being generated
  486. * @param array $associations Array of inprogress associations
  487. * @return array $associations with hasOne and hasMany added in.
  488. */
  489. function findHasOneAndMany(&$model, $associations) {
  490. $foreignKey = $this->_modelKey($model->name);
  491. foreach ($this->_tables as $otherTable) {
  492. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  493. $modelFieldsTemp = $tempOtherModel->schema(true);
  494. $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
  495. $possibleJoinTable = preg_match($pattern , $otherTable);
  496. if ($possibleJoinTable == true) {
  497. continue;
  498. }
  499. foreach ($modelFieldsTemp as $fieldName => $field) {
  500. $assoc = false;
  501. if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
  502. $assoc = array(
  503. 'alias' => $tempOtherModel->name,
  504. 'className' => $tempOtherModel->name,
  505. 'foreignKey' => $fieldName
  506. );
  507. } elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
  508. $assoc = array(
  509. 'alias' => 'Child' . $model->name,
  510. 'className' => $model->name,
  511. 'foreignKey' => $fieldName
  512. );
  513. }
  514. if ($assoc) {
  515. $associations['hasOne'][] = $assoc;
  516. $associations['hasMany'][] = $assoc;
  517. }
  518. }
  519. }
  520. return $associations;
  521. }
  522. /**
  523. * Find the hasAndBelongsToMany relations and add them to associations list
  524. *
  525. * @param object $model Model instance being generated
  526. * @param array $associations Array of inprogress associations
  527. * @return array $associations with hasAndBelongsToMany added in.
  528. */
  529. function findHasAndBelongsToMany(&$model, $associations) {
  530. $foreignKey = $this->_modelKey($model->name);
  531. foreach ($this->_tables as $otherTable) {
  532. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  533. $modelFieldsTemp = $tempOtherModel->schema(true);
  534. $offset = strpos($otherTable, $model->table . '_');
  535. $otherOffset = strpos($otherTable, '_' . $model->table);
  536. if ($offset !== false) {
  537. $offset = strlen($model->table . '_');
  538. $habtmName = $this->_modelName(substr($otherTable, $offset));
  539. $associations['hasAndBelongsToMany'][] = array(
  540. 'alias' => $habtmName,
  541. 'className' => $habtmName,
  542. 'foreignKey' => $foreignKey,
  543. 'associationForeignKey' => $this->_modelKey($habtmName),
  544. 'joinTable' => $otherTable
  545. );
  546. } elseif ($otherOffset !== false) {
  547. $habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
  548. $associations['hasAndBelongsToMany'][] = array(
  549. 'alias' => $habtmName,
  550. 'className' => $habtmName,
  551. 'foreignKey' => $foreignKey,
  552. 'associationForeignKey' => $this->_modelKey($habtmName),
  553. 'joinTable' => $otherTable
  554. );
  555. }
  556. }
  557. return $associations;
  558. }
  559. /**
  560. * Interact with the user and confirm associations.
  561. *
  562. * @param array $model Temporary Model instance.
  563. * @param array $associations Array of associations to be confirmed.
  564. * @return array Array of confirmed associations
  565. */
  566. function confirmAssociations(&$model, $associations) {
  567. foreach ($associations as $type => $settings) {
  568. if (!empty($associations[$type])) {
  569. $count = count($associations[$type]);
  570. $response = 'y';
  571. foreach ($associations[$type] as $i => $assoc) {
  572. $prompt = "{$model->name} {$type} {$assoc['alias']}?";
  573. $response = $this->in($prompt, array('y','n'), 'y');
  574. if ('n' == strtolower($response)) {
  575. unset($associations[$type][$i]);
  576. } elseif ($type == 'hasMany') {
  577. unset($associations['hasOne'][$i]);
  578. }
  579. }
  580. $associations[$type] = array_merge($associations[$type]);
  581. }
  582. }
  583. return $associations;
  584. }
  585. /**
  586. * Interact with the user and generate additional non-conventional associations
  587. *
  588. * @param object $model Temporary model instance
  589. * @param array $associations Array of associations.
  590. * @return array Array of associations.
  591. */
  592. function doMoreAssociations($model, $associations) {
  593. $prompt = __('Would you like to define some additional model associations?', true);
  594. $wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n');
  595. $possibleKeys = $this->_generatePossibleKeys();
  596. while (strtolower($wannaDoMoreAssoc) == 'y') {
  597. $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  598. $this->out(__('What is the association type?', true));
  599. $assocType = intval($this->inOptions($assocs, __('Enter a number',true)));
  600. $this->out(__("For the following options be very careful to match your setup exactly.\nAny spelling mistakes will cause errors.", true));
  601. $this->hr();
  602. $alias = $this->in(__('What is the alias for this association?', true));
  603. $className = $this->in(sprintf(__('What className will %s use?', true), $alias), null, $alias );
  604. $suggestedForeignKey = null;
  605. if ($assocType == 0) {
  606. $showKeys = $possibleKeys[$model->table];
  607. $suggestedForeignKey = $this->_modelKey($alias);
  608. } else {
  609. $otherTable = Inflector::tableize($className);
  610. if (in_array($otherTable, $this->_tables)) {
  611. if ($assocType < 3) {
  612. $showKeys = $possibleKeys[$otherTable];
  613. } else {
  614. $showKeys = null;
  615. }
  616. } else {
  617. $otherTable = $this->in(__('What is the table for this model?', true));
  618. $showKeys = $possibleKeys[$otherTable];
  619. }
  620. $suggestedForeignKey = $this->_modelKey($model->name);
  621. }
  622. if (!empty($showKeys)) {
  623. $this->out(__('A helpful List of possible keys', true));
  624. $foreignKey = $this->inOptions($showKeys, __('What is the foreignKey?', true));
  625. $foreignKey = $showKeys[intval($foreignKey)];
  626. }
  627. if (!isset($foreignKey)) {
  628. $foreignKey = $this->in(__('What is the foreignKey? Specify your own.', true), null, $suggestedForeignKey);
  629. }
  630. if ($assocType == 3) {
  631. $associationForeignKey = $this->in(__('What is the associationForeignKey?', true), null, $this->_modelKey($model->name));
  632. $joinTable = $this->in(__('What is the joinTable?', true));
  633. }
  634. $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
  635. $count = count($associations[$assocs[$assocType]]);
  636. $i = ($count > 0) ? $count : 0;
  637. $associations[$assocs[$assocType]][$i]['alias'] = $alias;
  638. $associations[$assocs[$assocType]][$i]['className'] = $className;
  639. $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
  640. if ($assocType == 3) {
  641. $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
  642. $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
  643. }
  644. $wannaDoMoreAssoc = $this->in(__('Define another association?', true), array('y','n'), 'y');
  645. }
  646. return $associations;
  647. }
  648. /**
  649. * Finds all possible keys to use on custom associations.
  650. *
  651. * @return array array of tables and possible keys
  652. */
  653. function _generatePossibleKeys() {
  654. $possible = array();
  655. foreach ($this->_tables as $otherTable) {
  656. $tempOtherModel = & new Model(array('table' => $otherTable, 'ds' => $this->connection));
  657. $modelFieldsTemp = $tempOtherModel->schema(true);
  658. foreach ($modelFieldsTemp as $fieldName => $field) {
  659. if ($field['type'] == 'integer' || $field['type'] == 'string') {
  660. $possible[$otherTable][] = $fieldName;
  661. }
  662. }
  663. }
  664. return $possible;
  665. }
  666. /**
  667. * Assembles and writes a Model file.
  668. *
  669. * @param mixed $name Model name or object
  670. * @param mixed $data if array and $name is not an object assume bake data, otherwise boolean.
  671. * @access private
  672. */
  673. function bake($name, $data = array()) {
  674. if (is_object($name)) {
  675. if ($data == false) {
  676. $data = $associations = array();
  677. $data['associations'] = $this->doAssociations($name, $associations);
  678. $data['validate'] = $this->doValidation($name);
  679. }
  680. $data['primaryKey'] = $name->primaryKey;
  681. $data['useTable'] = $name->table;
  682. $data['useDbConfig'] = $name->useDbConfig;
  683. $data['name'] = $name = $name->name;
  684. } else {
  685. $data['name'] = $name;
  686. }
  687. $defaults = array('associations' => array(), 'validate' => array(), 'primaryKey' => 'id',
  688. 'useTable' => null, 'useDbConfig' => 'default', 'displayField' => null);
  689. $data = array_merge($defaults, $data);
  690. $this->Template->set($data);
  691. $this->Template->set('plugin', Inflector::camelize($this->plugin));
  692. $out = $this->Template->generate('classes', 'model');
  693. $path = $this->getPath();
  694. $filename = $path . Inflector::underscore($name) . '.php';
  695. $this->out("\nBaking model class for $name...");
  696. $this->createFile($filename, $out);
  697. ClassRegistry::flush();
  698. return $out;
  699. }
  700. /**
  701. * Assembles and writes a unit test file
  702. *
  703. * @param string $className Model class name
  704. * @access private
  705. */
  706. function bakeTest($className) {
  707. $this->Test->interactive = $this->interactive;
  708. $this->Test->plugin = $this->plugin;
  709. $this->Test->connection = $this->connection;
  710. return $this->Test->bake('Model', $className);
  711. }
  712. /**
  713. * outputs the a list of possible models or controllers from database
  714. *
  715. * @param string $useDbConfig Database configuration name
  716. * @access public
  717. */
  718. function listAll($useDbConfig = null) {
  719. $this->_tables = $this->getAllTables($useDbConfig);
  720. if ($this->interactive === true) {
  721. $this->out(__('Possible Models based on your current database:', true));
  722. $this->_modelNames = array();
  723. $count = count($this->_tables);
  724. for ($i = 0; $i < $count; $i++) {
  725. $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
  726. $this->out($i + 1 . ". " . $this->_modelNames[$i]);
  727. }
  728. }
  729. return $this->_tables;
  730. }
  731. /**
  732. * Interact with the user to determine the table name of a particular model
  733. *
  734. * @param string $modelName Name of the model you want a table for.
  735. * @param string $useDbConfig Name of the database config you want to get tables from.
  736. * @return void
  737. */
  738. function getTable($modelName, $useDbConfig = null) {
  739. if (!isset($useDbConfig)) {
  740. $useDbConfig = $this->connection;
  741. }
  742. App::import('Model', 'ConnectionManager', false);
  743. $db =& ConnectionManager::getDataSource($useDbConfig);
  744. $useTable = Inflector::tableize($modelName);
  745. $fullTableName = $db->fullTableName($useTable, false);
  746. $tableIsGood = false;
  747. if (array_search($useTable, $this->_tables) === false) {
  748. $this->out();
  749. $this->out(sprintf(__("Given your model named '%s',\nCake would expect a database table named '%s'", true), $modelName, $fullTableName));
  750. $tableIsGood = $this->in(__('Do you want to use this table?', true), array('y','n'), 'y');
  751. }
  752. if (strtolower($tableIsGood) == 'n') {
  753. $useTable = $this->in(__('What is the name of the table?', true));
  754. }
  755. return $useTable;
  756. }
  757. /**
  758. * Get an Array of all the tables in the supplied connection
  759. * will halt the script if no tables are found.
  760. *
  761. * @param string $useDbConfig Connection name to scan.
  762. * @return array Array of tables in the database.
  763. */
  764. function getAllTables($useDbConfig = null) {
  765. if (!isset($useDbConfig)) {
  766. $useDbConfig = $this->connection;
  767. }
  768. App::import('Model', 'ConnectionManager', false);
  769. $tables = array();
  770. $db =& ConnectionManager::getDataSource($useDbConfig);
  771. $db->cacheSources = false;
  772. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  773. if ($usePrefix) {
  774. foreach ($db->listSources() as $table) {
  775. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  776. $tables[] = substr($table, strlen($usePrefix));
  777. }
  778. }
  779. } else {
  780. $tables = $db->listSources();
  781. }
  782. if (empty($tables)) {
  783. $this->err(__('Your database does not have any tables.', true));
  784. $this->_stop();
  785. }
  786. return $tables;
  787. }
  788. /**
  789. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  790. *
  791. * @return string the model name
  792. * @access public
  793. */
  794. function getName($useDbConfig = null) {
  795. $this->listAll($useDbConfig);
  796. $enteredModel = '';
  797. while ($enteredModel == '') {
  798. $enteredModel = $this->in(__("Enter a number from the list above,\ntype in the name of another model, or 'q' to exit", true), null, 'q');
  799. if ($enteredModel === 'q') {
  800. $this->out(__("Exit", true));
  801. $this->_stop();
  802. }
  803. if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
  804. $this->err(__("The model name you supplied was empty,\nor the number you selected was not an option. Please try again.", true));
  805. $enteredModel = '';
  806. }
  807. }
  808. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  809. $currentModelName = $this->_modelNames[intval($enteredModel) - 1];
  810. } else {
  811. $currentModelName = $enteredModel;
  812. }
  813. return $currentModelName;
  814. }
  815. /**
  816. * Displays help contents
  817. *
  818. * @access public
  819. */
  820. function help() {
  821. $this->hr();
  822. $this->out("Usage: cake bake model <arg1>");
  823. $this->hr();
  824. $this->out('Arguments:');
  825. $this->out();
  826. $this->out("<name>");
  827. $this->out("\tName of the model to bake. Can use Plugin.name");
  828. $this->out("\tas a shortcut for plugin baking.");
  829. $this->out();
  830. $this->out('Params:');
  831. $this->out();
  832. $this->out('-connection <config>');
  833. $this->out("\tset db config <config>. uses 'default' if none is specified");
  834. $this->out();
  835. $this->out('Commands:');
  836. $this->out();
  837. $this->out("model");
  838. $this->out("\tbakes model in interactive mode.");
  839. $this->out();
  840. $this->out("model <name>");
  841. $this->out("\tbakes model file with no associations or validation");
  842. $this->out();
  843. $this->out("model all");
  844. $this->out("\tbakes all model files with associations and validation");
  845. $this->out();
  846. $this->_stop();
  847. }
  848. /**
  849. * Interact with FixtureTask to automatically bake fixtures when baking models.
  850. *
  851. * @param string $className Name of class to bake fixture for
  852. * @param string $useTable Optional table name for fixture to use.
  853. * @access public
  854. * @return void
  855. * @see FixtureTask::bake
  856. */
  857. function bakeFixture($className, $useTable = null) {
  858. $this->Fixture->interactive = $this->interactive;
  859. $this->Fixture->connection = $this->connection;
  860. $this->Fixture->plugin = $this->plugin;
  861. $this->Fixture->bake($className, $useTable);
  862. }
  863. }