ModelTask.php 29 KB

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