ModelTask.php 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993
  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 $key => $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. for ($i = 1, $m=$defaultChoice/2; $i < $m; $i++) {
  378. $str_aux = sprintf("%2d. %s", $i, $this->_validations[$i]);
  379. $str_aux = $str_aux.str_repeat(" ", 31 - strlen($str_aux));
  380. $str_aux .= sprintf("%2d. %s", $m+$i, $this->_validations[$m+$i]);
  381. $this->out($str_aux);
  382. }
  383. $this->out(__d('cake_console', "%s - Do not do any validation on this field.", $defaultChoice));
  384. $this->hr();
  385. }
  386. $prompt = __d('cake_console', "... or enter in a valid regex validation string.\n");
  387. $methods = array_flip($this->_validations);
  388. $guess = $defaultChoice;
  389. if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
  390. if ($fieldName == 'email') {
  391. $guess = $methods['email'];
  392. } elseif ($metaData['type'] == 'string' && $metaData['length'] == 36) {
  393. $guess = $methods['uuid'];
  394. } elseif ($metaData['type'] == 'string') {
  395. $guess = $methods['notempty'];
  396. } elseif ($metaData['type'] == 'text') {
  397. $guess = $methods['notempty'];
  398. } elseif ($metaData['type'] == 'integer') {
  399. $guess = $methods['numeric'];
  400. } elseif ($metaData['type'] == 'boolean') {
  401. $guess = $methods['boolean'];
  402. } elseif ($metaData['type'] == 'date') {
  403. $guess = $methods['date'];
  404. } elseif ($metaData['type'] == 'time') {
  405. $guess = $methods['time'];
  406. } elseif ($metaData['type'] == 'inet') {
  407. $guess = $methods['ip'];
  408. }
  409. }
  410. if ($this->interactive === true) {
  411. $choice = $this->in($prompt, null, $guess);
  412. if (in_array($choice, $alreadyChosen)) {
  413. $this->out(__d('cake_console', "You have already chosen that validation rule,\nplease choose again"));
  414. continue;
  415. }
  416. if (!isset($this->_validations[$choice]) && is_numeric($choice)) {
  417. $this->out(__d('cake_console', 'Please make a valid selection.'));
  418. continue;
  419. }
  420. $alreadyChosen[] = $choice;
  421. } else {
  422. $choice = $guess;
  423. }
  424. if (isset($this->_validations[$choice])) {
  425. $validatorName = $this->_validations[$choice];
  426. } else {
  427. $validatorName = Inflector::slug($choice);
  428. }
  429. if ($choice != $defaultChoice) {
  430. if (is_numeric($choice) && isset($this->_validations[$choice])) {
  431. $validate[$validatorName] = $this->_validations[$choice];
  432. } else {
  433. $validate[$validatorName] = $choice;
  434. }
  435. }
  436. if ($this->interactive == true && $choice != $defaultChoice) {
  437. $anotherValidator = $this->in(__d('cake_console', 'Would you like to add another validation rule?'), array('y', 'n'), 'n');
  438. } else {
  439. $anotherValidator = 'n';
  440. }
  441. }
  442. return $validate;
  443. }
  444. /**
  445. * Handles associations
  446. *
  447. * @param Model $model
  448. * @return array $associations
  449. */
  450. public function doAssociations($model) {
  451. if (!is_object($model)) {
  452. return false;
  453. }
  454. if ($this->interactive === true) {
  455. $this->out(__d('cake_console', 'One moment while the associations are detected.'));
  456. }
  457. $fields = $model->schema(true);
  458. if (empty($fields)) {
  459. return array();
  460. }
  461. if (empty($this->_tables)) {
  462. $this->_tables = (array)$this->getAllTables();
  463. }
  464. $associations = array(
  465. 'belongsTo' => array(),
  466. 'hasMany' => array(),
  467. 'hasOne' => array(),
  468. 'hasAndBelongsToMany' => array()
  469. );
  470. $associations = $this->findBelongsTo($model, $associations);
  471. $associations = $this->findHasOneAndMany($model, $associations);
  472. $associations = $this->findHasAndBelongsToMany($model, $associations);
  473. if ($this->interactive !== true) {
  474. unset($associations['hasOne']);
  475. }
  476. if ($this->interactive === true) {
  477. $this->hr();
  478. if (empty($associations)) {
  479. $this->out(__d('cake_console', 'None found.'));
  480. } else {
  481. $this->out(__d('cake_console', 'Please confirm the following associations:'));
  482. $this->hr();
  483. $associations = $this->confirmAssociations($model, $associations);
  484. }
  485. $associations = $this->doMoreAssociations($model, $associations);
  486. }
  487. return $associations;
  488. }
  489. /**
  490. * Find belongsTo relations and add them to the associations list.
  491. *
  492. * @param Model $model Model instance of model being generated.
  493. * @param array $associations Array of in progress associations
  494. * @return array $associations with belongsTo added in.
  495. */
  496. public function findBelongsTo(Model $model, $associations) {
  497. $fields = $model->schema(true);
  498. foreach ($fields as $fieldName => $field) {
  499. $offset = strpos($fieldName, '_id');
  500. if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
  501. $tmpModelName = $this->_modelNameFromKey($fieldName);
  502. $associations['belongsTo'][] = array(
  503. 'alias' => $tmpModelName,
  504. 'className' => $tmpModelName,
  505. 'foreignKey' => $fieldName,
  506. );
  507. } elseif ($fieldName == 'parent_id') {
  508. $associations['belongsTo'][] = array(
  509. 'alias' => 'Parent' . $model->name,
  510. 'className' => $model->name,
  511. 'foreignKey' => $fieldName,
  512. );
  513. }
  514. }
  515. return $associations;
  516. }
  517. /**
  518. * Find the hasOne and HasMany relations and add them to associations list
  519. *
  520. * @param Model $model Model instance being generated
  521. * @param array $associations Array of in progress associations
  522. * @return array $associations with hasOne and hasMany added in.
  523. */
  524. public function findHasOneAndMany(Model $model, $associations) {
  525. $foreignKey = $this->_modelKey($model->name);
  526. foreach ($this->_tables as $otherTable) {
  527. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  528. $modelFieldsTemp = $tempOtherModel->schema(true);
  529. $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
  530. $possibleJoinTable = preg_match($pattern, $otherTable);
  531. if ($possibleJoinTable == true) {
  532. continue;
  533. }
  534. foreach ($modelFieldsTemp as $fieldName => $field) {
  535. $assoc = false;
  536. if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
  537. $assoc = array(
  538. 'alias' => $tempOtherModel->name,
  539. 'className' => $tempOtherModel->name,
  540. 'foreignKey' => $fieldName
  541. );
  542. } elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
  543. $assoc = array(
  544. 'alias' => 'Child' . $model->name,
  545. 'className' => $model->name,
  546. 'foreignKey' => $fieldName
  547. );
  548. }
  549. if ($assoc) {
  550. $associations['hasOne'][] = $assoc;
  551. $associations['hasMany'][] = $assoc;
  552. }
  553. }
  554. }
  555. return $associations;
  556. }
  557. /**
  558. * Find the hasAndBelongsToMany relations and add them to associations list
  559. *
  560. * @param Model $model Model instance being generated
  561. * @param array $associations Array of in-progress associations
  562. * @return array $associations with hasAndBelongsToMany added in.
  563. */
  564. public function findHasAndBelongsToMany(Model $model, $associations) {
  565. $foreignKey = $this->_modelKey($model->name);
  566. foreach ($this->_tables as $otherTable) {
  567. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  568. $modelFieldsTemp = $tempOtherModel->schema(true);
  569. $offset = strpos($otherTable, $model->table . '_');
  570. $otherOffset = strpos($otherTable, '_' . $model->table);
  571. if ($offset !== false) {
  572. $offset = strlen($model->table . '_');
  573. $habtmName = $this->_modelName(substr($otherTable, $offset));
  574. $associations['hasAndBelongsToMany'][] = array(
  575. 'alias' => $habtmName,
  576. 'className' => $habtmName,
  577. 'foreignKey' => $foreignKey,
  578. 'associationForeignKey' => $this->_modelKey($habtmName),
  579. 'joinTable' => $otherTable
  580. );
  581. } elseif ($otherOffset !== false) {
  582. $habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
  583. $associations['hasAndBelongsToMany'][] = array(
  584. 'alias' => $habtmName,
  585. 'className' => $habtmName,
  586. 'foreignKey' => $foreignKey,
  587. 'associationForeignKey' => $this->_modelKey($habtmName),
  588. 'joinTable' => $otherTable
  589. );
  590. }
  591. }
  592. return $associations;
  593. }
  594. /**
  595. * Interact with the user and confirm associations.
  596. *
  597. * @param array $model Temporary Model instance.
  598. * @param array $associations Array of associations to be confirmed.
  599. * @return array Array of confirmed associations
  600. */
  601. public function confirmAssociations(Model $model, $associations) {
  602. foreach ($associations as $type => $settings) {
  603. if (!empty($associations[$type])) {
  604. foreach ($associations[$type] as $i => $assoc) {
  605. $prompt = "{$model->name} {$type} {$assoc['alias']}?";
  606. $response = $this->in($prompt, array('y', 'n'), 'y');
  607. if ('n' == strtolower($response)) {
  608. unset($associations[$type][$i]);
  609. } elseif ($type == 'hasMany') {
  610. unset($associations['hasOne'][$i]);
  611. }
  612. }
  613. $associations[$type] = array_merge($associations[$type]);
  614. }
  615. }
  616. return $associations;
  617. }
  618. /**
  619. * Interact with the user and generate additional non-conventional associations
  620. *
  621. * @param Model $model Temporary model instance
  622. * @param array $associations Array of associations.
  623. * @return array Array of associations.
  624. */
  625. public function doMoreAssociations(Model $model, $associations) {
  626. $prompt = __d('cake_console', 'Would you like to define some additional model associations?');
  627. $wannaDoMoreAssoc = $this->in($prompt, array('y', 'n'), 'n');
  628. $possibleKeys = $this->_generatePossibleKeys();
  629. while (strtolower($wannaDoMoreAssoc) == 'y') {
  630. $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  631. $this->out(__d('cake_console', 'What is the association type?'));
  632. $assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number')));
  633. $this->out(__d('cake_console', "For the following options be very careful to match your setup exactly.\n" .
  634. "Any spelling mistakes will cause errors."));
  635. $this->hr();
  636. $alias = $this->in(__d('cake_console', 'What is the alias for this association?'));
  637. $className = $this->in(__d('cake_console', 'What className will %s use?', $alias), null, $alias );
  638. if ($assocType == 0) {
  639. if (!empty($possibleKeys[$model->table])) {
  640. $showKeys = $possibleKeys[$model->table];
  641. } else {
  642. $showKeys = null;
  643. }
  644. $suggestedForeignKey = $this->_modelKey($alias);
  645. } else {
  646. $otherTable = Inflector::tableize($className);
  647. if (in_array($otherTable, $this->_tables)) {
  648. if ($assocType < 3) {
  649. if (!empty($possibleKeys[$otherTable])) {
  650. $showKeys = $possibleKeys[$otherTable];
  651. } else {
  652. $showKeys = null;
  653. }
  654. } else {
  655. $showKeys = null;
  656. }
  657. } else {
  658. $otherTable = $this->in(__d('cake_console', 'What is the table for this model?'));
  659. $showKeys = $possibleKeys[$otherTable];
  660. }
  661. $suggestedForeignKey = $this->_modelKey($model->name);
  662. }
  663. if (!empty($showKeys)) {
  664. $this->out(__d('cake_console', 'A helpful List of possible keys'));
  665. $foreignKey = $this->inOptions($showKeys, __d('cake_console', 'What is the foreignKey?'));
  666. $foreignKey = $showKeys[intval($foreignKey)];
  667. }
  668. if (!isset($foreignKey)) {
  669. $foreignKey = $this->in(__d('cake_console', 'What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
  670. }
  671. if ($assocType == 3) {
  672. $associationForeignKey = $this->in(__d('cake_console', 'What is the associationForeignKey?'), null, $this->_modelKey($model->name));
  673. $joinTable = $this->in(__d('cake_console', 'What is the joinTable?'));
  674. }
  675. $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
  676. $count = count($associations[$assocs[$assocType]]);
  677. $i = ($count > 0) ? $count : 0;
  678. $associations[$assocs[$assocType]][$i]['alias'] = $alias;
  679. $associations[$assocs[$assocType]][$i]['className'] = $className;
  680. $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
  681. if ($assocType == 3) {
  682. $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
  683. $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
  684. }
  685. $wannaDoMoreAssoc = $this->in(__d('cake_console', 'Define another association?'), array('y', 'n'), 'y');
  686. }
  687. return $associations;
  688. }
  689. /**
  690. * Finds all possible keys to use on custom associations.
  691. *
  692. * @return array array of tables and possible keys
  693. */
  694. protected function _generatePossibleKeys() {
  695. $possible = array();
  696. foreach ($this->_tables as $otherTable) {
  697. $tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
  698. $modelFieldsTemp = $tempOtherModel->schema(true);
  699. foreach ($modelFieldsTemp as $fieldName => $field) {
  700. if ($field['type'] == 'integer' || $field['type'] == 'string') {
  701. $possible[$otherTable][] = $fieldName;
  702. }
  703. }
  704. }
  705. return $possible;
  706. }
  707. /**
  708. * Assembles and writes a Model file.
  709. *
  710. * @param string|object $name Model name or object
  711. * @param array|boolean $data if array and $name is not an object assume bake data, otherwise boolean.
  712. * @return string
  713. */
  714. public function bake($name, $data = array()) {
  715. if (is_object($name)) {
  716. if ($data == false) {
  717. $data = array();
  718. $data['associations'] = $this->doAssociations($name);
  719. $data['validate'] = $this->doValidation($name);
  720. }
  721. $data['primaryKey'] = $name->primaryKey;
  722. $data['useTable'] = $name->table;
  723. $data['useDbConfig'] = $name->useDbConfig;
  724. $data['name'] = $name = $name->name;
  725. } else {
  726. $data['name'] = $name;
  727. }
  728. $defaults = array(
  729. 'associations' => array(),
  730. 'validate' => array(),
  731. 'primaryKey' => 'id',
  732. 'useTable' => null,
  733. 'useDbConfig' => 'default',
  734. 'displayField' => null
  735. );
  736. $data = array_merge($defaults, $data);
  737. $pluginPath = '';
  738. if ($this->plugin) {
  739. $pluginPath = $this->plugin . '.';
  740. }
  741. $this->Template->set($data);
  742. $this->Template->set(array(
  743. 'plugin' => $this->plugin,
  744. 'pluginPath' => $pluginPath
  745. ));
  746. $out = $this->Template->generate('classes', 'model');
  747. $path = $this->getPath();
  748. $filename = $path . $name . '.php';
  749. $this->out("\n" . __d('cake_console', 'Baking model class for %s...', $name), 1, Shell::QUIET);
  750. $this->createFile($filename, $out);
  751. ClassRegistry::flush();
  752. return $out;
  753. }
  754. /**
  755. * Assembles and writes a unit test file
  756. *
  757. * @param string $className Model class name
  758. * @return string
  759. */
  760. public function bakeTest($className) {
  761. $this->Test->interactive = $this->interactive;
  762. $this->Test->plugin = $this->plugin;
  763. $this->Test->connection = $this->connection;
  764. return $this->Test->bake('Model', $className);
  765. }
  766. /**
  767. * outputs the a list of possible models or controllers from database
  768. *
  769. * @param string $useDbConfig Database configuration name
  770. * @return array
  771. */
  772. public function listAll($useDbConfig = null) {
  773. $this->_tables = (array)$this->getAllTables($useDbConfig);
  774. $this->_modelNames = array();
  775. $count = count($this->_tables);
  776. for ($i = 0; $i < $count; $i++) {
  777. $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
  778. }
  779. if ($this->interactive === true) {
  780. $this->out(__d('cake_console', 'Possible Models based on your current database:'));
  781. $len = strlen(($count+1).'');
  782. for ($i = 0; $i < $count; $i++) {
  783. $this->out(sprintf("%${len}d. %s", $i+1, $this->_modelNames[$i]));
  784. }
  785. }
  786. return $this->_tables;
  787. }
  788. /**
  789. * Interact with the user to determine the table name of a particular model
  790. *
  791. * @param string $modelName Name of the model you want a table for.
  792. * @param string $useDbConfig Name of the database config you want to get tables from.
  793. * @return string Table name
  794. */
  795. public function getTable($modelName, $useDbConfig = null) {
  796. $useTable = Inflector::tableize($modelName);
  797. if (in_array($modelName, $this->_modelNames)) {
  798. $modelNames = array_flip($this->_modelNames);
  799. $useTable = $this->_tables[$modelNames[$modelName]];
  800. }
  801. if ($this->interactive === true) {
  802. if (!isset($useDbConfig)) {
  803. $useDbConfig = $this->connection;
  804. }
  805. $db = ConnectionManager::getDataSource($useDbConfig);
  806. $fullTableName = $db->fullTableName($useTable, false);
  807. $tableIsGood = false;
  808. if (array_search($useTable, $this->_tables) === false) {
  809. $this->out();
  810. $this->out(__d('cake_console', "Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
  811. $tableIsGood = $this->in(__d('cake_console', 'Do you want to use this table?'), array('y', 'n'), 'y');
  812. }
  813. if (strtolower($tableIsGood) == 'n') {
  814. $useTable = $this->in(__d('cake_console', 'What is the name of the table?'));
  815. }
  816. }
  817. return $useTable;
  818. }
  819. /**
  820. * Get an Array of all the tables in the supplied connection
  821. * will halt the script if no tables are found.
  822. *
  823. * @param string $useDbConfig Connection name to scan.
  824. * @return array Array of tables in the database.
  825. */
  826. public function getAllTables($useDbConfig = null) {
  827. if (!isset($useDbConfig)) {
  828. $useDbConfig = $this->connection;
  829. }
  830. $tables = array();
  831. $db = ConnectionManager::getDataSource($useDbConfig);
  832. $db->cacheSources = false;
  833. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  834. if ($usePrefix) {
  835. foreach ($db->listSources() as $table) {
  836. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  837. $tables[] = substr($table, strlen($usePrefix));
  838. }
  839. }
  840. } else {
  841. $tables = $db->listSources();
  842. }
  843. if (empty($tables)) {
  844. $this->err(__d('cake_console', 'Your database does not have any tables.'));
  845. $this->_stop();
  846. }
  847. return $tables;
  848. }
  849. /**
  850. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  851. *
  852. * @param string $useDbConfig Database config name
  853. * @return string the model name
  854. */
  855. public function getName($useDbConfig = null) {
  856. $this->listAll($useDbConfig);
  857. $enteredModel = '';
  858. while ($enteredModel == '') {
  859. $enteredModel = $this->in(__d('cake_console', "Enter a number from the list above,\n" .
  860. "type in the name of another model, or 'q' to exit"), null, 'q');
  861. if ($enteredModel === 'q') {
  862. $this->out(__d('cake_console', 'Exit'));
  863. $this->_stop();
  864. }
  865. if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
  866. $this->err(__d('cake_console', "The model name you supplied was empty,\n" .
  867. "or the number you selected was not an option. Please try again."));
  868. $enteredModel = '';
  869. }
  870. }
  871. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  872. $currentModelName = $this->_modelNames[intval($enteredModel) - 1];
  873. } else {
  874. $currentModelName = $enteredModel;
  875. }
  876. return $currentModelName;
  877. }
  878. /**
  879. * get the option parser.
  880. *
  881. * @return void
  882. */
  883. public function getOptionParser() {
  884. $parser = parent::getOptionParser();
  885. return $parser->description(
  886. __d('cake_console', 'Bake models.')
  887. )->addArgument('name', array(
  888. 'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
  889. ))->addSubcommand('all', array(
  890. 'help' => __d('cake_console', 'Bake all model files with associations and validation.')
  891. ))->addOption('plugin', array(
  892. 'short' => 'p',
  893. 'help' => __d('cake_console', 'Plugin to bake the model into.')
  894. ))->addOption('connection', array(
  895. 'short' => 'c',
  896. 'help' => __d('cake_console', 'The connection the model table is on.')
  897. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  898. }
  899. /**
  900. * Interact with FixtureTask to automatically bake fixtures when baking models.
  901. *
  902. * @param string $className Name of class to bake fixture for
  903. * @param string $useTable Optional table name for fixture to use.
  904. * @return void
  905. * @see FixtureTask::bake
  906. */
  907. public function bakeFixture($className, $useTable = null) {
  908. $this->Fixture->interactive = $this->interactive;
  909. $this->Fixture->connection = $this->connection;
  910. $this->Fixture->plugin = $this->plugin;
  911. $this->Fixture->bake($className, $useTable);
  912. }
  913. }