ModelTask.php 30 KB

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