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