ModelTask.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  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(__('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 = __('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(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(__('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 = __("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 = __("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(__('The following Model will be created:'));
  197. $this->hr();
  198. $this->out("Name: " . $currentModelName);
  199. if ($this->connection !== 'default') {
  200. $this->out(__("DB Config: %s", $this->connection));
  201. }
  202. if ($fullTableName !== Inflector::tableize($currentModelName)) {
  203. $this->out(__('DB Table: %s', $fullTableName));
  204. }
  205. if ($primaryKey != 'id') {
  206. $this->out(__('Primary Key: %s', $primaryKey));
  207. }
  208. if (!empty($validate)) {
  209. $this->out(__('Validation: %s', print_r($validate, true)));
  210. }
  211. if (!empty($associations)) {
  212. $this->out(__('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(__('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(__('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 = __("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 = __('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(__('Field: %s', $fieldName));
  340. $this->out(__('Type: %s', $metaData['type']));
  341. $this->hr();
  342. $this->out(__('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 .= __("%s - Do not do any validation on this field.\n", $defaultChoice);
  350. $prompt .= __("... 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(__("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(__('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(__('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(__('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. $possibleKeys = array();
  426. $associations = $this->findBelongsTo($model, $associations);
  427. $associations = $this->findHasOneAndMany($model, $associations);
  428. $associations = $this->findHasAndBelongsToMany($model, $associations);
  429. if ($this->interactive !== true) {
  430. unset($associations['hasOne']);
  431. }
  432. if ($this->interactive === true) {
  433. $this->hr();
  434. if (empty($associations)) {
  435. $this->out(__('None found.'));
  436. } else {
  437. $this->out(__('Please confirm the following associations:'));
  438. $this->hr();
  439. $associations = $this->confirmAssociations($model, $associations);
  440. }
  441. $associations = $this->doMoreAssociations($model, $associations);
  442. }
  443. return $associations;
  444. }
  445. /**
  446. * Find belongsTo relations and add them to the associations list.
  447. *
  448. * @param object $model Model instance of model being generated.
  449. * @param array $associations Array of inprogress associations
  450. * @return array $associations with belongsTo added in.
  451. */
  452. public function findBelongsTo(&$model, $associations) {
  453. $fields = $model->schema(true);
  454. foreach ($fields as $fieldName => $field) {
  455. $offset = strpos($fieldName, '_id');
  456. if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
  457. $tmpModelName = $this->_modelNameFromKey($fieldName);
  458. $associations['belongsTo'][] = array(
  459. 'alias' => $tmpModelName,
  460. 'className' => $tmpModelName,
  461. 'foreignKey' => $fieldName,
  462. );
  463. } elseif ($fieldName == 'parent_id') {
  464. $associations['belongsTo'][] = array(
  465. 'alias' => 'Parent' . $model->name,
  466. 'className' => $model->name,
  467. 'foreignKey' => $fieldName,
  468. );
  469. }
  470. }
  471. return $associations;
  472. }
  473. /**
  474. * Find the hasOne and HasMany relations and add them to associations list
  475. *
  476. * @param object $model Model instance being generated
  477. * @param array $associations Array of inprogress associations
  478. * @return array $associations with hasOne and hasMany added in.
  479. */
  480. public function findHasOneAndMany(&$model, $associations) {
  481. $foreignKey = $this->_modelKey($model->name);
  482. foreach ($this->_tables as $otherTable) {
  483. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  484. $modelFieldsTemp = $tempOtherModel->schema(true);
  485. $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
  486. $possibleJoinTable = preg_match($pattern , $otherTable);
  487. if ($possibleJoinTable == true) {
  488. continue;
  489. }
  490. foreach ($modelFieldsTemp as $fieldName => $field) {
  491. $assoc = false;
  492. if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
  493. $assoc = array(
  494. 'alias' => $tempOtherModel->name,
  495. 'className' => $tempOtherModel->name,
  496. 'foreignKey' => $fieldName
  497. );
  498. } elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
  499. $assoc = array(
  500. 'alias' => 'Child' . $model->name,
  501. 'className' => $model->name,
  502. 'foreignKey' => $fieldName
  503. );
  504. }
  505. if ($assoc) {
  506. $associations['hasOne'][] = $assoc;
  507. $associations['hasMany'][] = $assoc;
  508. }
  509. }
  510. }
  511. return $associations;
  512. }
  513. /**
  514. * Find the hasAndBelongsToMany relations and add them to associations list
  515. *
  516. * @param object $model Model instance being generated
  517. * @param array $associations Array of inprogress associations
  518. * @return array $associations with hasAndBelongsToMany added in.
  519. */
  520. public function findHasAndBelongsToMany(&$model, $associations) {
  521. $foreignKey = $this->_modelKey($model->name);
  522. foreach ($this->_tables as $otherTable) {
  523. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  524. $modelFieldsTemp = $tempOtherModel->schema(true);
  525. $offset = strpos($otherTable, $model->table . '_');
  526. $otherOffset = strpos($otherTable, '_' . $model->table);
  527. if ($offset !== false) {
  528. $offset = strlen($model->table . '_');
  529. $habtmName = $this->_modelName(substr($otherTable, $offset));
  530. $associations['hasAndBelongsToMany'][] = array(
  531. 'alias' => $habtmName,
  532. 'className' => $habtmName,
  533. 'foreignKey' => $foreignKey,
  534. 'associationForeignKey' => $this->_modelKey($habtmName),
  535. 'joinTable' => $otherTable
  536. );
  537. } elseif ($otherOffset !== false) {
  538. $habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
  539. $associations['hasAndBelongsToMany'][] = array(
  540. 'alias' => $habtmName,
  541. 'className' => $habtmName,
  542. 'foreignKey' => $foreignKey,
  543. 'associationForeignKey' => $this->_modelKey($habtmName),
  544. 'joinTable' => $otherTable
  545. );
  546. }
  547. }
  548. return $associations;
  549. }
  550. /**
  551. * Interact with the user and confirm associations.
  552. *
  553. * @param array $model Temporary Model instance.
  554. * @param array $associations Array of associations to be confirmed.
  555. * @return array Array of confirmed associations
  556. */
  557. public function confirmAssociations(&$model, $associations) {
  558. foreach ($associations as $type => $settings) {
  559. if (!empty($associations[$type])) {
  560. $count = count($associations[$type]);
  561. $response = 'y';
  562. foreach ($associations[$type] as $i => $assoc) {
  563. $prompt = "{$model->name} {$type} {$assoc['alias']}?";
  564. $response = $this->in($prompt, array('y','n'), 'y');
  565. if ('n' == strtolower($response)) {
  566. unset($associations[$type][$i]);
  567. } elseif ($type == 'hasMany') {
  568. unset($associations['hasOne'][$i]);
  569. }
  570. }
  571. $associations[$type] = array_merge($associations[$type]);
  572. }
  573. }
  574. return $associations;
  575. }
  576. /**
  577. * Interact with the user and generate additional non-conventional associations
  578. *
  579. * @param object $model Temporary model instance
  580. * @param array $associations Array of associations.
  581. * @return array Array of associations.
  582. */
  583. public function doMoreAssociations($model, $associations) {
  584. $prompt = __('Would you like to define some additional model associations?');
  585. $wannaDoMoreAssoc = $this->in($prompt, array('y','n'), 'n');
  586. $possibleKeys = $this->_generatePossibleKeys();
  587. while (strtolower($wannaDoMoreAssoc) == 'y') {
  588. $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  589. $this->out(__('What is the association type?'));
  590. $assocType = intval($this->inOptions($assocs, __('Enter a number')));
  591. $this->out(__("For the following options be very careful to match your setup exactly.\nAny spelling mistakes will cause errors."));
  592. $this->hr();
  593. $alias = $this->in(__('What is the alias for this association?'));
  594. $className = $this->in(__('What className will %s use?', $alias), null, $alias );
  595. $suggestedForeignKey = null;
  596. if ($assocType == 0) {
  597. $showKeys = $possibleKeys[$model->table];
  598. $suggestedForeignKey = $this->_modelKey($alias);
  599. } else {
  600. $otherTable = Inflector::tableize($className);
  601. if (in_array($otherTable, $this->_tables)) {
  602. if ($assocType < 3) {
  603. $showKeys = $possibleKeys[$otherTable];
  604. } else {
  605. $showKeys = null;
  606. }
  607. } else {
  608. $otherTable = $this->in(__('What is the table for this model?'));
  609. $showKeys = $possibleKeys[$otherTable];
  610. }
  611. $suggestedForeignKey = $this->_modelKey($model->name);
  612. }
  613. if (!empty($showKeys)) {
  614. $this->out(__('A helpful List of possible keys'));
  615. $foreignKey = $this->inOptions($showKeys, __('What is the foreignKey?'));
  616. $foreignKey = $showKeys[intval($foreignKey)];
  617. }
  618. if (!isset($foreignKey)) {
  619. $foreignKey = $this->in(__('What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
  620. }
  621. if ($assocType == 3) {
  622. $associationForeignKey = $this->in(__('What is the associationForeignKey?'), null, $this->_modelKey($model->name));
  623. $joinTable = $this->in(__('What is the joinTable?'));
  624. }
  625. $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
  626. $count = count($associations[$assocs[$assocType]]);
  627. $i = ($count > 0) ? $count : 0;
  628. $associations[$assocs[$assocType]][$i]['alias'] = $alias;
  629. $associations[$assocs[$assocType]][$i]['className'] = $className;
  630. $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
  631. if ($assocType == 3) {
  632. $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
  633. $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
  634. }
  635. $wannaDoMoreAssoc = $this->in(__('Define another association?'), array('y','n'), 'y');
  636. }
  637. return $associations;
  638. }
  639. /**
  640. * Finds all possible keys to use on custom associations.
  641. *
  642. * @return array array of tables and possible keys
  643. */
  644. protected function _generatePossibleKeys() {
  645. $possible = array();
  646. foreach ($this->_tables as $otherTable) {
  647. $tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
  648. $modelFieldsTemp = $tempOtherModel->schema(true);
  649. foreach ($modelFieldsTemp as $fieldName => $field) {
  650. if ($field['type'] == 'integer' || $field['type'] == 'string') {
  651. $possible[$otherTable][] = $fieldName;
  652. }
  653. }
  654. }
  655. return $possible;
  656. }
  657. /**
  658. * Assembles and writes a Model file.
  659. *
  660. * @param mixed $name Model name or object
  661. * @param mixed $data if array and $name is not an object assume bake data, otherwise boolean.
  662. */
  663. public function bake($name, $data = array()) {
  664. if (is_object($name)) {
  665. if ($data == false) {
  666. $data = $associations = array();
  667. $data['associations'] = $this->doAssociations($name, $associations);
  668. $data['validate'] = $this->doValidation($name);
  669. }
  670. $data['primaryKey'] = $name->primaryKey;
  671. $data['useTable'] = $name->table;
  672. $data['useDbConfig'] = $name->useDbConfig;
  673. $data['name'] = $name = $name->name;
  674. } else {
  675. $data['name'] = $name;
  676. }
  677. $defaults = array('associations' => array(), 'validate' => array(), 'primaryKey' => 'id',
  678. 'useTable' => null, 'useDbConfig' => 'default', 'displayField' => null);
  679. $data = array_merge($defaults, $data);
  680. $this->Template->set($data);
  681. $this->Template->set('plugin', Inflector::camelize($this->plugin));
  682. $out = $this->Template->generate('classes', 'model');
  683. $path = $this->getPath();
  684. $filename = $path . Inflector::underscore($name) . '.php';
  685. $this->out("\nBaking model class for $name...", 1, Shell::QUIET);
  686. $this->createFile($filename, $out);
  687. ClassRegistry::flush();
  688. return $out;
  689. }
  690. /**
  691. * Assembles and writes a unit test file
  692. *
  693. * @param string $className Model class name
  694. */
  695. public function bakeTest($className) {
  696. $this->Test->interactive = $this->interactive;
  697. $this->Test->plugin = $this->plugin;
  698. $this->Test->connection = $this->connection;
  699. return $this->Test->bake('Model', $className);
  700. }
  701. /**
  702. * outputs the a list of possible models or controllers from database
  703. *
  704. * @param string $useDbConfig Database configuration name
  705. */
  706. public function listAll($useDbConfig = null) {
  707. $this->_tables = $this->getAllTables($useDbConfig);
  708. if ($this->interactive === true) {
  709. $this->out(__('Possible Models based on your current database:'));
  710. $this->_modelNames = array();
  711. $count = count($this->_tables);
  712. for ($i = 0; $i < $count; $i++) {
  713. $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
  714. $this->out($i + 1 . ". " . $this->_modelNames[$i]);
  715. }
  716. }
  717. return $this->_tables;
  718. }
  719. /**
  720. * Interact with the user to determine the table name of a particular model
  721. *
  722. * @param string $modelName Name of the model you want a table for.
  723. * @param string $useDbConfig Name of the database config you want to get tables from.
  724. * @return string Table name
  725. */
  726. public function getTable($modelName, $useDbConfig = null) {
  727. if (!isset($useDbConfig)) {
  728. $useDbConfig = $this->connection;
  729. }
  730. $db = ConnectionManager::getDataSource($useDbConfig);
  731. $useTable = Inflector::tableize($modelName);
  732. $fullTableName = $db->fullTableName($useTable, false);
  733. $tableIsGood = false;
  734. if (array_search($useTable, $this->_tables) === false) {
  735. $this->out();
  736. $this->out(__("Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
  737. $tableIsGood = $this->in(__('Do you want to use this table?'), array('y','n'), 'y');
  738. }
  739. if (strtolower($tableIsGood) == 'n') {
  740. $useTable = $this->in(__('What is the name of the table?'));
  741. }
  742. return $useTable;
  743. }
  744. /**
  745. * Get an Array of all the tables in the supplied connection
  746. * will halt the script if no tables are found.
  747. *
  748. * @param string $useDbConfig Connection name to scan.
  749. * @return array Array of tables in the database.
  750. */
  751. public function getAllTables($useDbConfig = null) {
  752. if (!isset($useDbConfig)) {
  753. $useDbConfig = $this->connection;
  754. }
  755. $tables = array();
  756. $db = ConnectionManager::getDataSource($useDbConfig);
  757. $db->cacheSources = false;
  758. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  759. if ($usePrefix) {
  760. foreach ($db->listSources() as $table) {
  761. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  762. $tables[] = substr($table, strlen($usePrefix));
  763. }
  764. }
  765. } else {
  766. $tables = $db->listSources();
  767. }
  768. if (empty($tables)) {
  769. $this->err(__('Your database does not have any tables.'));
  770. $this->_stop();
  771. }
  772. return $tables;
  773. }
  774. /**
  775. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  776. *
  777. * @return string the model name
  778. */
  779. public function getName($useDbConfig = null) {
  780. $this->listAll($useDbConfig);
  781. $enteredModel = '';
  782. while ($enteredModel == '') {
  783. $enteredModel = $this->in(__("Enter a number from the list above,\ntype in the name of another model, or 'q' to exit"), null, 'q');
  784. if ($enteredModel === 'q') {
  785. $this->out(__('Exit'));
  786. $this->_stop();
  787. }
  788. if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
  789. $this->err(__("The model name you supplied was empty,\nor the number you selected was not an option. Please try again."));
  790. $enteredModel = '';
  791. }
  792. }
  793. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  794. $currentModelName = $this->_modelNames[intval($enteredModel) - 1];
  795. } else {
  796. $currentModelName = $enteredModel;
  797. }
  798. return $currentModelName;
  799. }
  800. /**
  801. * get the option parser.
  802. *
  803. * @return void
  804. */
  805. public function getOptionParser() {
  806. $parser = parent::getOptionParser();
  807. return $parser->description(
  808. __('Bake models.')
  809. )->addArgument('name', array(
  810. 'help' => __('Name of the model to bake. Can use Plugin.name to bake plugin models.')
  811. ))->addSubcommand('all', array(
  812. 'help' => __('Bake all model files with associations and validation.')
  813. ))->addOption('plugin', array(
  814. 'short' => 'p',
  815. 'help' => __('Plugin to bake the model into.')
  816. ))->addOption('connection', array(
  817. 'short' => 'c',
  818. 'help' => __('The connection the model table is on.')
  819. ))->epilog(__('Omitting all arguments and options will enter into an interactive mode.'));
  820. }
  821. /**
  822. * Interact with FixtureTask to automatically bake fixtures when baking models.
  823. *
  824. * @param string $className Name of class to bake fixture for
  825. * @param string $useTable Optional table name for fixture to use.
  826. * @return void
  827. * @see FixtureTask::bake
  828. */
  829. public function bakeFixture($className, $useTable = null) {
  830. $this->Fixture->interactive = $this->interactive;
  831. $this->Fixture->connection = $this->connection;
  832. $this->Fixture->plugin = $this->plugin;
  833. $this->Fixture->bake($className, $useTable);
  834. }
  835. }