ModelTask.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906
  1. <?php
  2. /**
  3. * The ModelTask handles creating and updating models files.
  4. *
  5. * PHP 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.console.shells.tasks
  16. * @since CakePHP(tm) v 1.2
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('BakeTask', 'Console/Command/Task');
  20. App::uses('ConnectionManager', 'Model');
  21. App::uses('Model', 'Model');
  22. App::uses('Validation', 'Utility');
  23. /**
  24. * Task class for creating and updating model files.
  25. *
  26. * @package cake.console.shells.tasks
  27. */
  28. class ModelTask extends BakeTask {
  29. /**
  30. * path to MODELS directory
  31. *
  32. * @var string
  33. * @access public
  34. */
  35. public $path = MODELS;
  36. /**
  37. * tasks
  38. *
  39. * @var array
  40. * @access public
  41. */
  42. public $tasks = array('DbConfig', 'Fixture', 'Test', 'Template');
  43. /**
  44. * Tables to skip when running all()
  45. *
  46. * @var array
  47. * @access protected
  48. */
  49. public $skipTables = array('i18n');
  50. /**
  51. * Holds tables found on connection.
  52. *
  53. * @var array
  54. * @access protected
  55. */
  56. protected $_tables = array();
  57. /**
  58. * Holds validation method map.
  59. *
  60. * @var array
  61. * @access protected
  62. */
  63. protected $_validations = array();
  64. /**
  65. * Execution method always used for tasks
  66. *
  67. */
  68. public function execute() {
  69. parent::execute();
  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. public 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(__d('cake_console', 'Baking %s', $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. protected 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. public 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 = __d('cake_console', 'Make a selection from the choices above');
  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. protected function _interactive() {
  156. $this->hr();
  157. $this->out(__d('cake_console', "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(__d('cake_console', 'Table %s does not exist, cannot bake a model without a table.', $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 = __d('cake_console', "Would you like to supply validation criteria \nfor the fields in your model?");
  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 = __d('cake_console', "Would you like to define model associations\n(hasMany, hasOne, belongsTo, etc.)?");
  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(__d('cake_console', 'The following Model will be created:'));
  197. $this->hr();
  198. $this->out(__d('cake_console', "Name: %s", $currentModelName));
  199. if ($this->connection !== 'default') {
  200. $this->out(__d('cake_console', "DB Config: %s", $this->connection));
  201. }
  202. if ($fullTableName !== Inflector::tableize($currentModelName)) {
  203. $this->out(__d('cake_console', 'DB Table: %s', $fullTableName));
  204. }
  205. if ($primaryKey != 'id') {
  206. $this->out(__d('cake_console', 'Primary Key: %s', $primaryKey));
  207. }
  208. if (!empty($validate)) {
  209. $this->out(__d('cake_console', 'Validation: %s', print_r($validate, true)));
  210. }
  211. if (!empty($associations)) {
  212. $this->out(__d('cake_console', 'Associations:'));
  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(__d('cake_console', 'Look okay?'), 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. * @return void
  240. */
  241. protected function _printAssociation($modelName, $type, $associations) {
  242. if (!empty($associations[$type])) {
  243. for ($i = 0; $i < count($associations[$type]); $i++) {
  244. $out = "\t" . $modelName . ' ' . $type . ' ' . $associations[$type][$i]['alias'];
  245. $this->out($out);
  246. }
  247. }
  248. }
  249. /**
  250. * Finds a primary Key in a list of fields.
  251. *
  252. * @param array $fields Array of fields that might have a primary key.
  253. * @return string Name of field that is a primary key.
  254. */
  255. public function findPrimaryKey($fields) {
  256. foreach ($fields as $name => $field) {
  257. if (isset($field['key']) && $field['key'] == 'primary') {
  258. break;
  259. }
  260. }
  261. return $this->in(__d('cake_console', 'What is the primaryKey?'), null, $name);
  262. }
  263. /**
  264. * interact with the user to find the displayField value for a model.
  265. *
  266. * @param array $fields Array of fields to look for and choose as a displayField
  267. * @return mixed Name of field to use for displayField or false if the user declines to choose
  268. */
  269. public function findDisplayField($fields) {
  270. $fieldNames = array_keys($fields);
  271. $prompt = __d('cake_console', "A displayField could not be automatically detected\nwould you like to choose one?");
  272. $continue = $this->in($prompt, array('y', 'n'));
  273. if (strtolower($continue) == 'n') {
  274. return false;
  275. }
  276. $prompt = __d('cake_console', 'Choose a field from the options above:');
  277. $choice = $this->inOptions($fieldNames, $prompt);
  278. return $fieldNames[$choice];
  279. }
  280. /**
  281. * Handles Generation and user interaction for creating validation.
  282. *
  283. * @param object $model Model to have validations generated for.
  284. * @return array $validate Array of user selected validations.
  285. */
  286. public function doValidation($model) {
  287. if (!is_object($model)) {
  288. return false;
  289. }
  290. $fields = $model->schema();
  291. if (empty($fields)) {
  292. return false;
  293. }
  294. $validate = array();
  295. $this->initValidations();
  296. foreach ($fields as $fieldName => $field) {
  297. $validation = $this->fieldValidation($fieldName, $field, $model->primaryKey);
  298. if (!empty($validation)) {
  299. $validate[$fieldName] = $validation;
  300. }
  301. }
  302. return $validate;
  303. }
  304. /**
  305. * Populate the _validations array
  306. *
  307. * @return void
  308. */
  309. public function initValidations() {
  310. $options = $choices = array();
  311. if (class_exists('Validation')) {
  312. $options = get_class_methods('Validation');
  313. }
  314. sort($options);
  315. $default = 1;
  316. foreach ($options as $key => $option) {
  317. if ($option{0} != '_') {
  318. $choices[$default] = strtolower($option);
  319. $default++;
  320. }
  321. }
  322. $this->_validations = $choices;
  323. return $choices;
  324. }
  325. /**
  326. * Does individual field validation handling.
  327. *
  328. * @param string $fieldName Name of field to be validated.
  329. * @param array $metaData metadata for field
  330. * @return array Array of validation for the field.
  331. */
  332. public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
  333. $defaultChoice = count($this->_validations);
  334. $validate = $alreadyChosen = array();
  335. $anotherValidator = 'y';
  336. while ($anotherValidator == 'y') {
  337. if ($this->interactive) {
  338. $this->out();
  339. $this->out(__d('cake_console', 'Field: %s', $fieldName));
  340. $this->out(__d('cake_console', 'Type: %s', $metaData['type']));
  341. $this->hr();
  342. $this->out(__d('cake_console', 'Please select one of the following validation options:'));
  343. $this->hr();
  344. }
  345. $prompt = '';
  346. for ($i = 1; $i < $defaultChoice; $i++) {
  347. $prompt .= $i . ' - ' . $this->_validations[$i] . "\n";
  348. }
  349. $prompt .= __d('cake_console', "%s - Do not do any validation on this field.\n", $defaultChoice);
  350. $prompt .= __d('cake_console', "... or enter in a valid regex validation string.\n");
  351. $methods = array_flip($this->_validations);
  352. $guess = $defaultChoice;
  353. if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
  354. if ($fieldName == 'email') {
  355. $guess = $methods['email'];
  356. } elseif ($metaData['type'] == 'string') {
  357. $guess = $methods['notempty'];
  358. } elseif ($metaData['type'] == 'integer') {
  359. $guess = $methods['numeric'];
  360. } elseif ($metaData['type'] == 'boolean') {
  361. $guess = $methods['boolean'];
  362. } elseif ($metaData['type'] == 'date') {
  363. $guess = $methods['date'];
  364. } elseif ($metaData['type'] == 'time') {
  365. $guess = $methods['time'];
  366. }
  367. }
  368. if ($this->interactive === true) {
  369. $choice = $this->in($prompt, null, $guess);
  370. if (in_array($choice, $alreadyChosen)) {
  371. $this->out(__d('cake_console', "You have already chosen that validation rule,\nplease choose again"));
  372. continue;
  373. }
  374. if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
  375. $this->out(__d('cake_console', 'Please make a valid selection.'));
  376. continue;
  377. }
  378. $alreadyChosen[] = $choice;
  379. } else {
  380. $choice = $guess;
  381. }
  382. if (isset($this->_validations[$choice])) {
  383. $validatorName = $this->_validations[$choice];
  384. } else {
  385. $validatorName = Inflector::slug($choice);
  386. }
  387. if ($choice != $defaultChoice) {
  388. if (is_numeric($choice) && isset($this->_validations[$choice])) {
  389. $validate[$validatorName] = $this->_validations[$choice];
  390. } else {
  391. $validate[$validatorName] = $choice;
  392. }
  393. }
  394. if ($this->interactive == true && $choice != $defaultChoice) {
  395. $anotherValidator = $this->in(__d('cake_console', 'Would you like to add another validation rule?'), array('y', 'n'), 'n');
  396. } else {
  397. $anotherValidator = 'n';
  398. }
  399. }
  400. return $validate;
  401. }
  402. /**
  403. * Handles associations
  404. *
  405. * @param object $model
  406. * @return array $assocaitons
  407. */
  408. public function doAssociations($model) {
  409. if (!is_object($model)) {
  410. return false;
  411. }
  412. if ($this->interactive === true) {
  413. $this->out(__d('cake_console', 'One moment while the associations are detected.'));
  414. }
  415. $fields = $model->schema(true);
  416. if (empty($fields)) {
  417. return false;
  418. }
  419. if (empty($this->_tables)) {
  420. $this->_tables = $this->getAllTables();
  421. }
  422. $associations = array(
  423. 'belongsTo' => array(), 'hasMany' => array(), 'hasOne'=> array(), 'hasAndBelongsToMany' => array()
  424. );
  425. $associations = $this->findBelongsTo($model, $associations);
  426. $associations = $this->findHasOneAndMany($model, $associations);
  427. $associations = $this->findHasAndBelongsToMany($model, $associations);
  428. if ($this->interactive !== true) {
  429. unset($associations['hasOne']);
  430. }
  431. if ($this->interactive === true) {
  432. $this->hr();
  433. if (empty($associations)) {
  434. $this->out(__d('cake_console', 'None found.'));
  435. } else {
  436. $this->out(__d('cake_console', 'Please confirm the following associations:'));
  437. $this->hr();
  438. $associations = $this->confirmAssociations($model, $associations);
  439. }
  440. $associations = $this->doMoreAssociations($model, $associations);
  441. }
  442. return $associations;
  443. }
  444. /**
  445. * Find belongsTo relations and add them to the associations list.
  446. *
  447. * @param object $model Model instance of model being generated.
  448. * @param array $associations Array of inprogress associations
  449. * @return array $associations with belongsTo added in.
  450. */
  451. public function findBelongsTo($model, $associations) {
  452. $fields = $model->schema(true);
  453. foreach ($fields as $fieldName => $field) {
  454. $offset = strpos($fieldName, '_id');
  455. if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
  456. $tmpModelName = $this->_modelNameFromKey($fieldName);
  457. $associations['belongsTo'][] = array(
  458. 'alias' => $tmpModelName,
  459. 'className' => $tmpModelName,
  460. 'foreignKey' => $fieldName,
  461. );
  462. } elseif ($fieldName == 'parent_id') {
  463. $associations['belongsTo'][] = array(
  464. 'alias' => 'Parent' . $model->name,
  465. 'className' => $model->name,
  466. 'foreignKey' => $fieldName,
  467. );
  468. }
  469. }
  470. return $associations;
  471. }
  472. /**
  473. * Find the hasOne and HasMany relations and add them to associations list
  474. *
  475. * @param object $model Model instance being generated
  476. * @param array $associations Array of inprogress associations
  477. * @return array $associations with hasOne and hasMany added in.
  478. */
  479. public function findHasOneAndMany($model, $associations) {
  480. $foreignKey = $this->_modelKey($model->name);
  481. foreach ($this->_tables as $otherTable) {
  482. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  483. $modelFieldsTemp = $tempOtherModel->schema(true);
  484. $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
  485. $possibleJoinTable = preg_match($pattern , $otherTable);
  486. if ($possibleJoinTable == true) {
  487. continue;
  488. }
  489. foreach ($modelFieldsTemp as $fieldName => $field) {
  490. $assoc = false;
  491. if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
  492. $assoc = array(
  493. 'alias' => $tempOtherModel->name,
  494. 'className' => $tempOtherModel->name,
  495. 'foreignKey' => $fieldName
  496. );
  497. } elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
  498. $assoc = array(
  499. 'alias' => 'Child' . $model->name,
  500. 'className' => $model->name,
  501. 'foreignKey' => $fieldName
  502. );
  503. }
  504. if ($assoc) {
  505. $associations['hasOne'][] = $assoc;
  506. $associations['hasMany'][] = $assoc;
  507. }
  508. }
  509. }
  510. return $associations;
  511. }
  512. /**
  513. * Find the hasAndBelongsToMany relations and add them to associations list
  514. *
  515. * @param object $model Model instance being generated
  516. * @param array $associations Array of in-progress associations
  517. * @return array $associations with hasAndBelongsToMany added in.
  518. */
  519. public function findHasAndBelongsToMany($model, $associations) {
  520. $foreignKey = $this->_modelKey($model->name);
  521. foreach ($this->_tables as $otherTable) {
  522. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  523. $modelFieldsTemp = $tempOtherModel->schema(true);
  524. $offset = strpos($otherTable, $model->table . '_');
  525. $otherOffset = strpos($otherTable, '_' . $model->table);
  526. if ($offset !== false) {
  527. $offset = strlen($model->table . '_');
  528. $habtmName = $this->_modelName(substr($otherTable, $offset));
  529. $associations['hasAndBelongsToMany'][] = array(
  530. 'alias' => $habtmName,
  531. 'className' => $habtmName,
  532. 'foreignKey' => $foreignKey,
  533. 'associationForeignKey' => $this->_modelKey($habtmName),
  534. 'joinTable' => $otherTable
  535. );
  536. } elseif ($otherOffset !== false) {
  537. $habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
  538. $associations['hasAndBelongsToMany'][] = array(
  539. 'alias' => $habtmName,
  540. 'className' => $habtmName,
  541. 'foreignKey' => $foreignKey,
  542. 'associationForeignKey' => $this->_modelKey($habtmName),
  543. 'joinTable' => $otherTable
  544. );
  545. }
  546. }
  547. return $associations;
  548. }
  549. /**
  550. * Interact with the user and confirm associations.
  551. *
  552. * @param array $model Temporary Model instance.
  553. * @param array $associations Array of associations to be confirmed.
  554. * @return array Array of confirmed associations
  555. */
  556. public function confirmAssociations($model, $associations) {
  557. foreach ($associations as $type => $settings) {
  558. if (!empty($associations[$type])) {
  559. foreach ($associations[$type] as $i => $assoc) {
  560. $prompt = "{$model->name} {$type} {$assoc['alias']}?";
  561. $response = $this->in($prompt, array('y','n'), 'y');
  562. if ('n' == strtolower($response)) {
  563. unset($associations[$type][$i]);
  564. } elseif ($type == 'hasMany') {
  565. unset($associations['hasOne'][$i]);
  566. }
  567. }
  568. $associations[$type] = array_merge($associations[$type]);
  569. }
  570. }
  571. return $associations;
  572. }
  573. /**
  574. * Interact with the user and generate additional non-conventional associations
  575. *
  576. * @param object $model Temporary model instance
  577. * @param array $associations Array of associations.
  578. * @return array Array of associations.
  579. */
  580. public function doMoreAssociations($model, $associations) {
  581. $prompt = __d('cake_console', 'Would you like to define some additional model associations?');
  582. $wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n');
  583. $possibleKeys = $this->_generatePossibleKeys();
  584. while (strtolower($wannaDoMoreAssoc) == 'y') {
  585. $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  586. $this->out(__d('cake_console', 'What is the association type?'));
  587. $assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number')));
  588. $this->out(__d('cake_console', "For the following options be very careful to match your setup exactly.\nAny spelling mistakes will cause errors."));
  589. $this->hr();
  590. $alias = $this->in(__d('cake_console', 'What is the alias for this association?'));
  591. $className = $this->in(__d('cake_console', 'What className will %s use?', $alias), null, $alias );
  592. if ($assocType == 0) {
  593. $showKeys = $possibleKeys[$model->table];
  594. $suggestedForeignKey = $this->_modelKey($alias);
  595. } else {
  596. $otherTable = Inflector::tableize($className);
  597. if (in_array($otherTable, $this->_tables)) {
  598. if ($assocType < 3) {
  599. $showKeys = $possibleKeys[$otherTable];
  600. } else {
  601. $showKeys = null;
  602. }
  603. } else {
  604. $otherTable = $this->in(__d('cake_console', 'What is the table for this model?'));
  605. $showKeys = $possibleKeys[$otherTable];
  606. }
  607. $suggestedForeignKey = $this->_modelKey($model->name);
  608. }
  609. if (!empty($showKeys)) {
  610. $this->out(__d('cake_console', 'A helpful List of possible keys'));
  611. $foreignKey = $this->inOptions($showKeys, __d('cake_console', 'What is the foreignKey?'));
  612. $foreignKey = $showKeys[intval($foreignKey)];
  613. }
  614. if (!isset($foreignKey)) {
  615. $foreignKey = $this->in(__d('cake_console', 'What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
  616. }
  617. if ($assocType == 3) {
  618. $associationForeignKey = $this->in(__d('cake_console', 'What is the associationForeignKey?'), null, $this->_modelKey($model->name));
  619. $joinTable = $this->in(__d('cake_console', 'What is the joinTable?'));
  620. }
  621. $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
  622. $count = count($associations[$assocs[$assocType]]);
  623. $i = ($count > 0) ? $count : 0;
  624. $associations[$assocs[$assocType]][$i]['alias'] = $alias;
  625. $associations[$assocs[$assocType]][$i]['className'] = $className;
  626. $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
  627. if ($assocType == 3) {
  628. $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
  629. $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
  630. }
  631. $wannaDoMoreAssoc = $this->in(__d('cake_console', 'Define another association?'), array('y','n'), 'y');
  632. }
  633. return $associations;
  634. }
  635. /**
  636. * Finds all possible keys to use on custom associations.
  637. *
  638. * @return array array of tables and possible keys
  639. */
  640. protected function _generatePossibleKeys() {
  641. $possible = array();
  642. foreach ($this->_tables as $otherTable) {
  643. $tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
  644. $modelFieldsTemp = $tempOtherModel->schema(true);
  645. foreach ($modelFieldsTemp as $fieldName => $field) {
  646. if ($field['type'] == 'integer' || $field['type'] == 'string') {
  647. $possible[$otherTable][] = $fieldName;
  648. }
  649. }
  650. }
  651. return $possible;
  652. }
  653. /**
  654. * Assembles and writes a Model file.
  655. *
  656. * @param mixed $name Model name or object
  657. * @param mixed $data if array and $name is not an object assume bake data, otherwise boolean.
  658. */
  659. public function bake($name, $data = array()) {
  660. if (is_object($name)) {
  661. if ($data == false) {
  662. $data = $associations = array();
  663. $data['associations'] = $this->doAssociations($name, $associations);
  664. $data['validate'] = $this->doValidation($name);
  665. }
  666. $data['primaryKey'] = $name->primaryKey;
  667. $data['useTable'] = $name->table;
  668. $data['useDbConfig'] = $name->useDbConfig;
  669. $data['name'] = $name = $name->name;
  670. } else {
  671. $data['name'] = $name;
  672. }
  673. $defaults = array('associations' => array(), 'validate' => array(), 'primaryKey' => 'id',
  674. 'useTable' => null, 'useDbConfig' => 'default', 'displayField' => null);
  675. $data = array_merge($defaults, $data);
  676. $this->Template->set($data);
  677. $this->Template->set('plugin', Inflector::camelize($this->plugin));
  678. $out = $this->Template->generate('classes', 'model');
  679. $path = $this->getPath();
  680. $filename = $path . $name . '.php';
  681. $this->out("\n" . __d('cake_console', 'Baking model class for %s...', $name), 1, Shell::QUIET);
  682. $this->createFile($filename, $out);
  683. ClassRegistry::flush();
  684. return $out;
  685. }
  686. /**
  687. * Assembles and writes a unit test file
  688. *
  689. * @param string $className Model class name
  690. */
  691. public function bakeTest($className) {
  692. $this->Test->interactive = $this->interactive;
  693. $this->Test->plugin = $this->plugin;
  694. $this->Test->connection = $this->connection;
  695. return $this->Test->bake('Model', $className);
  696. }
  697. /**
  698. * outputs the a list of possible models or controllers from database
  699. *
  700. * @param string $useDbConfig Database configuration name
  701. */
  702. public function listAll($useDbConfig = null) {
  703. $this->_tables = $this->getAllTables($useDbConfig);
  704. if ($this->interactive === true) {
  705. $this->out(__d('cake_console', 'Possible Models based on your current database:'));
  706. $this->_modelNames = array();
  707. $count = count($this->_tables);
  708. for ($i = 0; $i < $count; $i++) {
  709. $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
  710. $this->out($i + 1 . ". " . $this->_modelNames[$i]);
  711. }
  712. }
  713. return $this->_tables;
  714. }
  715. /**
  716. * Interact with the user to determine the table name of a particular model
  717. *
  718. * @param string $modelName Name of the model you want a table for.
  719. * @param string $useDbConfig Name of the database config you want to get tables from.
  720. * @return string Table name
  721. */
  722. public function getTable($modelName, $useDbConfig = null) {
  723. if (!isset($useDbConfig)) {
  724. $useDbConfig = $this->connection;
  725. }
  726. $db = ConnectionManager::getDataSource($useDbConfig);
  727. $useTable = Inflector::tableize($modelName);
  728. $fullTableName = $db->fullTableName($useTable, false);
  729. $tableIsGood = false;
  730. if (array_search($useTable, $this->_tables) === false) {
  731. $this->out();
  732. $this->out(__d('cake_console', "Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
  733. $tableIsGood = $this->in(__d('cake_console', 'Do you want to use this table?'), array('y','n'), 'y');
  734. }
  735. if (strtolower($tableIsGood) == 'n') {
  736. $useTable = $this->in(__d('cake_console', 'What is the name of the table?'));
  737. }
  738. return $useTable;
  739. }
  740. /**
  741. * Get an Array of all the tables in the supplied connection
  742. * will halt the script if no tables are found.
  743. *
  744. * @param string $useDbConfig Connection name to scan.
  745. * @return array Array of tables in the database.
  746. */
  747. public function getAllTables($useDbConfig = null) {
  748. if (!isset($useDbConfig)) {
  749. $useDbConfig = $this->connection;
  750. }
  751. $tables = array();
  752. $db = ConnectionManager::getDataSource($useDbConfig);
  753. $db->cacheSources = false;
  754. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  755. if ($usePrefix) {
  756. foreach ($db->listSources() as $table) {
  757. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  758. $tables[] = substr($table, strlen($usePrefix));
  759. }
  760. }
  761. } else {
  762. $tables = $db->listSources();
  763. }
  764. if (empty($tables)) {
  765. $this->err(__d('cake_console', 'Your database does not have any tables.'));
  766. $this->_stop();
  767. }
  768. return $tables;
  769. }
  770. /**
  771. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  772. *
  773. * @return string the model name
  774. */
  775. public function getName($useDbConfig = null) {
  776. $this->listAll($useDbConfig);
  777. $enteredModel = '';
  778. while ($enteredModel == '') {
  779. $enteredModel = $this->in(__d('cake_console', "Enter a number from the list above,\ntype in the name of another model, or 'q' to exit"), null, 'q');
  780. if ($enteredModel === 'q') {
  781. $this->out(__d('cake_console', 'Exit'));
  782. $this->_stop();
  783. }
  784. if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
  785. $this->err(__d('cake_console', "The model name you supplied was empty,\nor the number you selected was not an option. Please try again."));
  786. $enteredModel = '';
  787. }
  788. }
  789. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  790. $currentModelName = $this->_modelNames[intval($enteredModel) - 1];
  791. } else {
  792. $currentModelName = $enteredModel;
  793. }
  794. return $currentModelName;
  795. }
  796. /**
  797. * get the option parser.
  798. *
  799. * @return void
  800. */
  801. public function getOptionParser() {
  802. $parser = parent::getOptionParser();
  803. return $parser->description(
  804. __d('cake_console', 'Bake models.')
  805. )->addArgument('name', array(
  806. 'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
  807. ))->addSubcommand('all', array(
  808. 'help' => __d('cake_console', 'Bake all model files with associations and validation.')
  809. ))->addOption('plugin', array(
  810. 'short' => 'p',
  811. 'help' => __d('cake_console', 'Plugin to bake the model into.')
  812. ))->addOption('connection', array(
  813. 'short' => 'c',
  814. 'help' => __d('cake_console', 'The connection the model table is on.')
  815. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  816. }
  817. /**
  818. * Interact with FixtureTask to automatically bake fixtures when baking models.
  819. *
  820. * @param string $className Name of class to bake fixture for
  821. * @param string $useTable Optional table name for fixture to use.
  822. * @return void
  823. * @see FixtureTask::bake
  824. */
  825. public function bakeFixture($className, $useTable = null) {
  826. $this->Fixture->interactive = $this->interactive;
  827. $this->Fixture->connection = $this->connection;
  828. $this->Fixture->plugin = $this->plugin;
  829. $this->Fixture->bake($className, $useTable);
  830. }
  831. }