ModelTask.php 29 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-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. */
  62. public function initialize() {
  63. $this->path = current(App::path('Model'));
  64. }
  65. /**
  66. * Execution method always used for tasks
  67. *
  68. */
  69. public function execute() {
  70. parent::execute();
  71. if (empty($this->args)) {
  72. $this->_interactive();
  73. }
  74. if (!empty($this->args[0])) {
  75. $this->interactive = false;
  76. if (!isset($this->connection)) {
  77. $this->connection = 'default';
  78. }
  79. if (strtolower($this->args[0]) == 'all') {
  80. return $this->all();
  81. }
  82. $model = $this->_modelName($this->args[0]);
  83. $object = $this->_getModelObject($model);
  84. if ($this->bake($object, false)) {
  85. if ($this->_checkUnitTest()) {
  86. $this->bakeFixture($model);
  87. $this->bakeTest($model);
  88. }
  89. }
  90. }
  91. }
  92. /**
  93. * Bake all models at once.
  94. *
  95. * @return void
  96. */
  97. public function all() {
  98. $this->listAll($this->connection, false);
  99. $unitTestExists = $this->_checkUnitTest();
  100. foreach ($this->_tables as $table) {
  101. if (in_array($table, $this->skipTables)) {
  102. continue;
  103. }
  104. $modelClass = Inflector::classify($table);
  105. $this->out(__d('cake_console', 'Baking %s', $modelClass));
  106. $object = $this->_getModelObject($modelClass);
  107. if ($this->bake($object, false) && $unitTestExists) {
  108. $this->bakeFixture($modelClass);
  109. $this->bakeTest($modelClass);
  110. }
  111. }
  112. }
  113. /**
  114. * Get a model object for a class name.
  115. *
  116. * @param string $className Name of class you want model to be.
  117. * @return object Model instance
  118. */
  119. protected function &_getModelObject($className, $table = null) {
  120. if (!$table) {
  121. $table = Inflector::tableize($className);
  122. }
  123. $object = new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
  124. return $object;
  125. }
  126. /**
  127. * Generate a key value list of options and a prompt.
  128. *
  129. * @param array $options Array of options to use for the selections. indexes must start at 0
  130. * @param string $prompt Prompt to use for options list.
  131. * @param integer $default The default option for the given prompt.
  132. * @return result of user choice.
  133. */
  134. public function inOptions($options, $prompt = null, $default = null) {
  135. $valid = false;
  136. $max = count($options);
  137. while (!$valid) {
  138. foreach ($options as $i => $option) {
  139. $this->out($i + 1 .'. ' . $option);
  140. }
  141. if (empty($prompt)) {
  142. $prompt = __d('cake_console', 'Make a selection from the choices above');
  143. }
  144. $choice = $this->in($prompt, null, $default);
  145. if (intval($choice) > 0 && intval($choice) <= $max) {
  146. $valid = true;
  147. }
  148. }
  149. return $choice - 1;
  150. }
  151. /**
  152. * Handles interactive baking
  153. *
  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. $choices[$default] = 'none'; // Needed since index starts at 1
  323. $this->_validations = $choices;
  324. return $choices;
  325. }
  326. /**
  327. * Does individual field validation handling.
  328. *
  329. * @param string $fieldName Name of field to be validated.
  330. * @param array $metaData metadata for field
  331. * @return array Array of validation for the field.
  332. */
  333. public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
  334. $defaultChoice = count($this->_validations);
  335. $validate = $alreadyChosen = array();
  336. $anotherValidator = 'y';
  337. while ($anotherValidator == 'y') {
  338. if ($this->interactive) {
  339. $this->out();
  340. $this->out(__d('cake_console', 'Field: %s', $fieldName));
  341. $this->out(__d('cake_console', 'Type: %s', $metaData['type']));
  342. $this->hr();
  343. $this->out(__d('cake_console', 'Please select one of the following validation options:'));
  344. $this->hr();
  345. }
  346. $prompt = '';
  347. for ($i = 1; $i < $defaultChoice; $i++) {
  348. $prompt .= $i . ' - ' . $this->_validations[$i] . "\n";
  349. }
  350. $prompt .= __d('cake_console', "%s - Do not do any validation on this field.\n", $defaultChoice);
  351. $prompt .= __d('cake_console', "... or enter in a valid regex validation string.\n");
  352. $methods = array_flip($this->_validations);
  353. $guess = $defaultChoice;
  354. if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
  355. if ($fieldName == 'email') {
  356. $guess = $methods['email'];
  357. } elseif ($metaData['type'] == 'string' && $metaData['length'] == 36) {
  358. $guess = $methods['uuid'];
  359. } elseif ($metaData['type'] == 'string') {
  360. $guess = $methods['notempty'];
  361. } elseif ($metaData['type'] == 'integer') {
  362. $guess = $methods['numeric'];
  363. } elseif ($metaData['type'] == 'boolean') {
  364. $guess = $methods['boolean'];
  365. } elseif ($metaData['type'] == 'date') {
  366. $guess = $methods['date'];
  367. } elseif ($metaData['type'] == 'time') {
  368. $guess = $methods['time'];
  369. }
  370. }
  371. if ($this->interactive === true) {
  372. $choice = $this->in($prompt, null, $guess);
  373. if (in_array($choice, $alreadyChosen)) {
  374. $this->out(__d('cake_console', "You have already chosen that validation rule,\nplease choose again"));
  375. continue;
  376. }
  377. if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
  378. $this->out(__d('cake_console', 'Please make a valid selection.'));
  379. continue;
  380. }
  381. $alreadyChosen[] = $choice;
  382. } else {
  383. $choice = $guess;
  384. }
  385. if (isset($this->_validations[$choice])) {
  386. $validatorName = $this->_validations[$choice];
  387. } else {
  388. $validatorName = Inflector::slug($choice);
  389. }
  390. if ($choice != $defaultChoice) {
  391. if (is_numeric($choice) && isset($this->_validations[$choice])) {
  392. $validate[$validatorName] = $this->_validations[$choice];
  393. } else {
  394. $validate[$validatorName] = $choice;
  395. }
  396. }
  397. if ($this->interactive == true && $choice != $defaultChoice) {
  398. $anotherValidator = $this->in(__d('cake_console', 'Would you like to add another validation rule?'), array('y', 'n'), 'n');
  399. } else {
  400. $anotherValidator = 'n';
  401. }
  402. }
  403. return $validate;
  404. }
  405. /**
  406. * Handles associations
  407. *
  408. * @param object $model
  409. * @return array $assocaitons
  410. */
  411. public function doAssociations($model) {
  412. if (!is_object($model)) {
  413. return false;
  414. }
  415. if ($this->interactive === true) {
  416. $this->out(__d('cake_console', 'One moment while the associations are detected.'));
  417. }
  418. $fields = $model->schema(true);
  419. if (empty($fields)) {
  420. return false;
  421. }
  422. if (empty($this->_tables)) {
  423. $this->_tables = $this->getAllTables();
  424. }
  425. $associations = array(
  426. 'belongsTo' => array(), 'hasMany' => array(), 'hasOne'=> array(), 'hasAndBelongsToMany' => array()
  427. );
  428. $associations = $this->findBelongsTo($model, $associations);
  429. $associations = $this->findHasOneAndMany($model, $associations);
  430. $associations = $this->findHasAndBelongsToMany($model, $associations);
  431. if ($this->interactive !== true) {
  432. unset($associations['hasOne']);
  433. }
  434. if ($this->interactive === true) {
  435. $this->hr();
  436. if (empty($associations)) {
  437. $this->out(__d('cake_console', 'None found.'));
  438. } else {
  439. $this->out(__d('cake_console', 'Please confirm the following associations:'));
  440. $this->hr();
  441. $associations = $this->confirmAssociations($model, $associations);
  442. }
  443. $associations = $this->doMoreAssociations($model, $associations);
  444. }
  445. return $associations;
  446. }
  447. /**
  448. * Find belongsTo relations and add them to the associations list.
  449. *
  450. * @param object $model Model instance of model being generated.
  451. * @param array $associations Array of inprogress associations
  452. * @return array $associations with belongsTo added in.
  453. */
  454. public function findBelongsTo($model, $associations) {
  455. $fields = $model->schema(true);
  456. foreach ($fields as $fieldName => $field) {
  457. $offset = strpos($fieldName, '_id');
  458. if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
  459. $tmpModelName = $this->_modelNameFromKey($fieldName);
  460. $associations['belongsTo'][] = array(
  461. 'alias' => $tmpModelName,
  462. 'className' => $tmpModelName,
  463. 'foreignKey' => $fieldName,
  464. );
  465. } elseif ($fieldName == 'parent_id') {
  466. $associations['belongsTo'][] = array(
  467. 'alias' => 'Parent' . $model->name,
  468. 'className' => $model->name,
  469. 'foreignKey' => $fieldName,
  470. );
  471. }
  472. }
  473. return $associations;
  474. }
  475. /**
  476. * Find the hasOne and HasMany relations and add them to associations list
  477. *
  478. * @param object $model Model instance being generated
  479. * @param array $associations Array of inprogress associations
  480. * @return array $associations with hasOne and hasMany added in.
  481. */
  482. public function findHasOneAndMany($model, $associations) {
  483. $foreignKey = $this->_modelKey($model->name);
  484. foreach ($this->_tables as $otherTable) {
  485. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  486. $modelFieldsTemp = $tempOtherModel->schema(true);
  487. $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
  488. $possibleJoinTable = preg_match($pattern , $otherTable);
  489. if ($possibleJoinTable == true) {
  490. continue;
  491. }
  492. foreach ($modelFieldsTemp as $fieldName => $field) {
  493. $assoc = false;
  494. if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
  495. $assoc = array(
  496. 'alias' => $tempOtherModel->name,
  497. 'className' => $tempOtherModel->name,
  498. 'foreignKey' => $fieldName
  499. );
  500. } elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
  501. $assoc = array(
  502. 'alias' => 'Child' . $model->name,
  503. 'className' => $model->name,
  504. 'foreignKey' => $fieldName
  505. );
  506. }
  507. if ($assoc) {
  508. $associations['hasOne'][] = $assoc;
  509. $associations['hasMany'][] = $assoc;
  510. }
  511. }
  512. }
  513. return $associations;
  514. }
  515. /**
  516. * Find the hasAndBelongsToMany relations and add them to associations list
  517. *
  518. * @param object $model Model instance being generated
  519. * @param array $associations Array of in-progress associations
  520. * @return array $associations with hasAndBelongsToMany added in.
  521. */
  522. public function findHasAndBelongsToMany($model, $associations) {
  523. $foreignKey = $this->_modelKey($model->name);
  524. foreach ($this->_tables as $otherTable) {
  525. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  526. $modelFieldsTemp = $tempOtherModel->schema(true);
  527. $offset = strpos($otherTable, $model->table . '_');
  528. $otherOffset = strpos($otherTable, '_' . $model->table);
  529. if ($offset !== false) {
  530. $offset = strlen($model->table . '_');
  531. $habtmName = $this->_modelName(substr($otherTable, $offset));
  532. $associations['hasAndBelongsToMany'][] = array(
  533. 'alias' => $habtmName,
  534. 'className' => $habtmName,
  535. 'foreignKey' => $foreignKey,
  536. 'associationForeignKey' => $this->_modelKey($habtmName),
  537. 'joinTable' => $otherTable
  538. );
  539. } elseif ($otherOffset !== false) {
  540. $habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
  541. $associations['hasAndBelongsToMany'][] = array(
  542. 'alias' => $habtmName,
  543. 'className' => $habtmName,
  544. 'foreignKey' => $foreignKey,
  545. 'associationForeignKey' => $this->_modelKey($habtmName),
  546. 'joinTable' => $otherTable
  547. );
  548. }
  549. }
  550. return $associations;
  551. }
  552. /**
  553. * Interact with the user and confirm associations.
  554. *
  555. * @param array $model Temporary Model instance.
  556. * @param array $associations Array of associations to be confirmed.
  557. * @return array Array of confirmed associations
  558. */
  559. public function confirmAssociations($model, $associations) {
  560. foreach ($associations as $type => $settings) {
  561. if (!empty($associations[$type])) {
  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 = __d('cake_console', '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(__d('cake_console', 'What is the association type?'));
  590. $assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number')));
  591. $this->out(__d('cake_console', "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(__d('cake_console', 'What is the alias for this association?'));
  594. $className = $this->in(__d('cake_console', 'What className will %s use?', $alias), null, $alias );
  595. if ($assocType == 0) {
  596. $showKeys = $possibleKeys[$model->table];
  597. $suggestedForeignKey = $this->_modelKey($alias);
  598. } else {
  599. $otherTable = Inflector::tableize($className);
  600. if (in_array($otherTable, $this->_tables)) {
  601. if ($assocType < 3) {
  602. $showKeys = $possibleKeys[$otherTable];
  603. } else {
  604. $showKeys = null;
  605. }
  606. } else {
  607. $otherTable = $this->in(__d('cake_console', 'What is the table for this model?'));
  608. $showKeys = $possibleKeys[$otherTable];
  609. }
  610. $suggestedForeignKey = $this->_modelKey($model->name);
  611. }
  612. if (!empty($showKeys)) {
  613. $this->out(__d('cake_console', 'A helpful List of possible keys'));
  614. $foreignKey = $this->inOptions($showKeys, __d('cake_console', 'What is the foreignKey?'));
  615. $foreignKey = $showKeys[intval($foreignKey)];
  616. }
  617. if (!isset($foreignKey)) {
  618. $foreignKey = $this->in(__d('cake_console', 'What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
  619. }
  620. if ($assocType == 3) {
  621. $associationForeignKey = $this->in(__d('cake_console', 'What is the associationForeignKey?'), null, $this->_modelKey($model->name));
  622. $joinTable = $this->in(__d('cake_console', 'What is the joinTable?'));
  623. }
  624. $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
  625. $count = count($associations[$assocs[$assocType]]);
  626. $i = ($count > 0) ? $count : 0;
  627. $associations[$assocs[$assocType]][$i]['alias'] = $alias;
  628. $associations[$assocs[$assocType]][$i]['className'] = $className;
  629. $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
  630. if ($assocType == 3) {
  631. $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
  632. $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
  633. }
  634. $wannaDoMoreAssoc = $this->in(__d('cake_console', 'Define another association?'), array('y','n'), 'y');
  635. }
  636. return $associations;
  637. }
  638. /**
  639. * Finds all possible keys to use on custom associations.
  640. *
  641. * @return array array of tables and possible keys
  642. */
  643. protected function _generatePossibleKeys() {
  644. $possible = array();
  645. foreach ($this->_tables as $otherTable) {
  646. $tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
  647. $modelFieldsTemp = $tempOtherModel->schema(true);
  648. foreach ($modelFieldsTemp as $fieldName => $field) {
  649. if ($field['type'] == 'integer' || $field['type'] == 'string') {
  650. $possible[$otherTable][] = $fieldName;
  651. }
  652. }
  653. }
  654. return $possible;
  655. }
  656. /**
  657. * Assembles and writes a Model file.
  658. *
  659. * @param mixed $name Model name or object
  660. * @param mixed $data if array and $name is not an object assume bake data, otherwise boolean.
  661. */
  662. public function bake($name, $data = array()) {
  663. if (is_object($name)) {
  664. if ($data == false) {
  665. $data = $associations = array();
  666. $data['associations'] = $this->doAssociations($name, $associations);
  667. $data['validate'] = $this->doValidation($name);
  668. }
  669. $data['primaryKey'] = $name->primaryKey;
  670. $data['useTable'] = $name->table;
  671. $data['useDbConfig'] = $name->useDbConfig;
  672. $data['name'] = $name = $name->name;
  673. } else {
  674. $data['name'] = $name;
  675. }
  676. $defaults = array('associations' => array(), 'validate' => array(), 'primaryKey' => 'id',
  677. 'useTable' => null, 'useDbConfig' => 'default', 'displayField' => null);
  678. $data = array_merge($defaults, $data);
  679. $this->Template->set($data);
  680. $this->Template->set('plugin', $this->plugin);
  681. $out = $this->Template->generate('classes', 'model');
  682. $path = $this->getPath();
  683. $filename = $path . $name . '.php';
  684. $this->out("\n" . __d('cake_console', 'Baking model class for %s...', $name), 1, Shell::QUIET);
  685. $this->createFile($filename, $out);
  686. ClassRegistry::flush();
  687. return $out;
  688. }
  689. /**
  690. * Assembles and writes a unit test file
  691. *
  692. * @param string $className Model class name
  693. */
  694. public function bakeTest($className) {
  695. $this->Test->interactive = $this->interactive;
  696. $this->Test->plugin = $this->plugin;
  697. $this->Test->connection = $this->connection;
  698. return $this->Test->bake('Model', $className);
  699. }
  700. /**
  701. * outputs the a list of possible models or controllers from database
  702. *
  703. * @param string $useDbConfig Database configuration name
  704. */
  705. public function listAll($useDbConfig = null) {
  706. $this->_tables = $this->getAllTables($useDbConfig);
  707. if ($this->interactive === true) {
  708. $this->out(__d('cake_console', 'Possible Models based on your current database:'));
  709. $this->_modelNames = array();
  710. $count = count($this->_tables);
  711. for ($i = 0; $i < $count; $i++) {
  712. $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
  713. $this->out($i + 1 . ". " . $this->_modelNames[$i]);
  714. }
  715. }
  716. return $this->_tables;
  717. }
  718. /**
  719. * Interact with the user to determine the table name of a particular model
  720. *
  721. * @param string $modelName Name of the model you want a table for.
  722. * @param string $useDbConfig Name of the database config you want to get tables from.
  723. * @return string Table name
  724. */
  725. public function getTable($modelName, $useDbConfig = null) {
  726. if (!isset($useDbConfig)) {
  727. $useDbConfig = $this->connection;
  728. }
  729. $db = ConnectionManager::getDataSource($useDbConfig);
  730. $useTable = Inflector::tableize($modelName);
  731. $fullTableName = $db->fullTableName($useTable, false);
  732. $tableIsGood = false;
  733. if (array_search($useTable, $this->_tables) === false) {
  734. $this->out();
  735. $this->out(__d('cake_console', "Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
  736. $tableIsGood = $this->in(__d('cake_console', 'Do you want to use this table?'), array('y','n'), 'y');
  737. }
  738. if (strtolower($tableIsGood) == 'n') {
  739. $useTable = $this->in(__d('cake_console', 'What is the name of the table?'));
  740. }
  741. return $useTable;
  742. }
  743. /**
  744. * Get an Array of all the tables in the supplied connection
  745. * will halt the script if no tables are found.
  746. *
  747. * @param string $useDbConfig Connection name to scan.
  748. * @return array Array of tables in the database.
  749. */
  750. public function getAllTables($useDbConfig = null) {
  751. if (!isset($useDbConfig)) {
  752. $useDbConfig = $this->connection;
  753. }
  754. $tables = array();
  755. $db = ConnectionManager::getDataSource($useDbConfig);
  756. $db->cacheSources = false;
  757. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  758. if ($usePrefix) {
  759. foreach ($db->listSources() as $table) {
  760. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  761. $tables[] = substr($table, strlen($usePrefix));
  762. }
  763. }
  764. } else {
  765. $tables = $db->listSources();
  766. }
  767. if (empty($tables)) {
  768. $this->err(__d('cake_console', 'Your database does not have any tables.'));
  769. $this->_stop();
  770. }
  771. return $tables;
  772. }
  773. /**
  774. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  775. *
  776. * @return string the model name
  777. */
  778. public function getName($useDbConfig = null) {
  779. $this->listAll($useDbConfig);
  780. $enteredModel = '';
  781. while ($enteredModel == '') {
  782. $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');
  783. if ($enteredModel === 'q') {
  784. $this->out(__d('cake_console', 'Exit'));
  785. $this->_stop();
  786. }
  787. if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
  788. $this->err(__d('cake_console', "The model name you supplied was empty,\nor the number you selected was not an option. Please try again."));
  789. $enteredModel = '';
  790. }
  791. }
  792. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  793. $currentModelName = $this->_modelNames[intval($enteredModel) - 1];
  794. } else {
  795. $currentModelName = $enteredModel;
  796. }
  797. return $currentModelName;
  798. }
  799. /**
  800. * get the option parser.
  801. *
  802. * @return void
  803. */
  804. public function getOptionParser() {
  805. $parser = parent::getOptionParser();
  806. return $parser->description(
  807. __d('cake_console', 'Bake models.')
  808. )->addArgument('name', array(
  809. 'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
  810. ))->addSubcommand('all', array(
  811. 'help' => __d('cake_console', 'Bake all model files with associations and validation.')
  812. ))->addOption('plugin', array(
  813. 'short' => 'p',
  814. 'help' => __d('cake_console', 'Plugin to bake the model into.')
  815. ))->addOption('connection', array(
  816. 'short' => 'c',
  817. 'help' => __d('cake_console', 'The connection the model table is on.')
  818. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  819. }
  820. /**
  821. * Interact with FixtureTask to automatically bake fixtures when baking models.
  822. *
  823. * @param string $className Name of class to bake fixture for
  824. * @param string $useTable Optional table name for fixture to use.
  825. * @return void
  826. * @see FixtureTask::bake
  827. */
  828. public function bakeFixture($className, $useTable = null) {
  829. $this->Fixture->interactive = $this->interactive;
  830. $this->Fixture->connection = $this->connection;
  831. $this->Fixture->plugin = $this->plugin;
  832. $this->Fixture->bake($className, $useTable);
  833. }
  834. }