ModelTask.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978
  1. <?php
  2. /**
  3. * The ModelTask handles creating and updating models files.
  4. *
  5. * PHP 5
  6. *
  7. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  8. * Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  9. *
  10. * Licensed under The MIT License
  11. * Redistributions of files must retain the above copyright notice.
  12. *
  13. * @copyright Copyright 2005-2011, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @since CakePHP(tm) v 1.2
  16. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  17. */
  18. App::uses('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; $i < count($associations[$type]); $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(), 'hasMany' => array(), 'hasOne' => array(), 'hasAndBelongsToMany' => array()
  462. );
  463. $associations = $this->findBelongsTo($model, $associations);
  464. $associations = $this->findHasOneAndMany($model, $associations);
  465. $associations = $this->findHasAndBelongsToMany($model, $associations);
  466. if ($this->interactive !== true) {
  467. unset($associations['hasOne']);
  468. }
  469. if ($this->interactive === true) {
  470. $this->hr();
  471. if (empty($associations)) {
  472. $this->out(__d('cake_console', 'None found.'));
  473. } else {
  474. $this->out(__d('cake_console', 'Please confirm the following associations:'));
  475. $this->hr();
  476. $associations = $this->confirmAssociations($model, $associations);
  477. }
  478. $associations = $this->doMoreAssociations($model, $associations);
  479. }
  480. return $associations;
  481. }
  482. /**
  483. * Find belongsTo relations and add them to the associations list.
  484. *
  485. * @param Model $model Model instance of model being generated.
  486. * @param array $associations Array of in progress associations
  487. * @return array $associations with belongsTo added in.
  488. */
  489. public function findBelongsTo($model, $associations) {
  490. $fields = $model->schema(true);
  491. foreach ($fields as $fieldName => $field) {
  492. $offset = strpos($fieldName, '_id');
  493. if ($fieldName != $model->primaryKey && $fieldName != 'parent_id' && $offset !== false) {
  494. $tmpModelName = $this->_modelNameFromKey($fieldName);
  495. $associations['belongsTo'][] = array(
  496. 'alias' => $tmpModelName,
  497. 'className' => $tmpModelName,
  498. 'foreignKey' => $fieldName,
  499. );
  500. } elseif ($fieldName == 'parent_id') {
  501. $associations['belongsTo'][] = array(
  502. 'alias' => 'Parent' . $model->name,
  503. 'className' => $model->name,
  504. 'foreignKey' => $fieldName,
  505. );
  506. }
  507. }
  508. return $associations;
  509. }
  510. /**
  511. * Find the hasOne and HasMany relations and add them to associations list
  512. *
  513. * @param Model $model Model instance being generated
  514. * @param array $associations Array of in progress associations
  515. * @return array $associations with hasOne and hasMany added in.
  516. */
  517. public function findHasOneAndMany($model, $associations) {
  518. $foreignKey = $this->_modelKey($model->name);
  519. foreach ($this->_tables as $otherTable) {
  520. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  521. $modelFieldsTemp = $tempOtherModel->schema(true);
  522. $pattern = '/_' . preg_quote($model->table, '/') . '|' . preg_quote($model->table, '/') . '_/';
  523. $possibleJoinTable = preg_match($pattern, $otherTable);
  524. if ($possibleJoinTable == true) {
  525. continue;
  526. }
  527. foreach ($modelFieldsTemp as $fieldName => $field) {
  528. $assoc = false;
  529. if ($fieldName != $model->primaryKey && $fieldName == $foreignKey) {
  530. $assoc = array(
  531. 'alias' => $tempOtherModel->name,
  532. 'className' => $tempOtherModel->name,
  533. 'foreignKey' => $fieldName
  534. );
  535. } elseif ($otherTable == $model->table && $fieldName == 'parent_id') {
  536. $assoc = array(
  537. 'alias' => 'Child' . $model->name,
  538. 'className' => $model->name,
  539. 'foreignKey' => $fieldName
  540. );
  541. }
  542. if ($assoc) {
  543. $associations['hasOne'][] = $assoc;
  544. $associations['hasMany'][] = $assoc;
  545. }
  546. }
  547. }
  548. return $associations;
  549. }
  550. /**
  551. * Find the hasAndBelongsToMany relations and add them to associations list
  552. *
  553. * @param Model $model Model instance being generated
  554. * @param array $associations Array of in-progress associations
  555. * @return array $associations with hasAndBelongsToMany added in.
  556. */
  557. public function findHasAndBelongsToMany($model, $associations) {
  558. $foreignKey = $this->_modelKey($model->name);
  559. foreach ($this->_tables as $otherTable) {
  560. $tempOtherModel = $this->_getModelObject($this->_modelName($otherTable), $otherTable);
  561. $modelFieldsTemp = $tempOtherModel->schema(true);
  562. $offset = strpos($otherTable, $model->table . '_');
  563. $otherOffset = strpos($otherTable, '_' . $model->table);
  564. if ($offset !== false) {
  565. $offset = strlen($model->table . '_');
  566. $habtmName = $this->_modelName(substr($otherTable, $offset));
  567. $associations['hasAndBelongsToMany'][] = array(
  568. 'alias' => $habtmName,
  569. 'className' => $habtmName,
  570. 'foreignKey' => $foreignKey,
  571. 'associationForeignKey' => $this->_modelKey($habtmName),
  572. 'joinTable' => $otherTable
  573. );
  574. } elseif ($otherOffset !== false) {
  575. $habtmName = $this->_modelName(substr($otherTable, 0, $otherOffset));
  576. $associations['hasAndBelongsToMany'][] = array(
  577. 'alias' => $habtmName,
  578. 'className' => $habtmName,
  579. 'foreignKey' => $foreignKey,
  580. 'associationForeignKey' => $this->_modelKey($habtmName),
  581. 'joinTable' => $otherTable
  582. );
  583. }
  584. }
  585. return $associations;
  586. }
  587. /**
  588. * Interact with the user and confirm associations.
  589. *
  590. * @param array $model Temporary Model instance.
  591. * @param array $associations Array of associations to be confirmed.
  592. * @return array Array of confirmed associations
  593. */
  594. public function confirmAssociations($model, $associations) {
  595. foreach ($associations as $type => $settings) {
  596. if (!empty($associations[$type])) {
  597. foreach ($associations[$type] as $i => $assoc) {
  598. $prompt = "{$model->name} {$type} {$assoc['alias']}?";
  599. $response = $this->in($prompt, array('y', 'n'), 'y');
  600. if ('n' == strtolower($response)) {
  601. unset($associations[$type][$i]);
  602. } elseif ($type == 'hasMany') {
  603. unset($associations['hasOne'][$i]);
  604. }
  605. }
  606. $associations[$type] = array_merge($associations[$type]);
  607. }
  608. }
  609. return $associations;
  610. }
  611. /**
  612. * Interact with the user and generate additional non-conventional associations
  613. *
  614. * @param Model $model Temporary model instance
  615. * @param array $associations Array of associations.
  616. * @return array Array of associations.
  617. */
  618. public function doMoreAssociations($model, $associations) {
  619. $prompt = __d('cake_console', 'Would you like to define some additional model associations?');
  620. $wannaDoMoreAssoc = $this->in($prompt, array('y', 'n'), 'n');
  621. $possibleKeys = $this->_generatePossibleKeys();
  622. while (strtolower($wannaDoMoreAssoc) == 'y') {
  623. $assocs = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  624. $this->out(__d('cake_console', 'What is the association type?'));
  625. $assocType = intval($this->inOptions($assocs, __d('cake_console', 'Enter a number')));
  626. $this->out(__d('cake_console', "For the following options be very careful to match your setup exactly.\n" .
  627. "Any spelling mistakes will cause errors."));
  628. $this->hr();
  629. $alias = $this->in(__d('cake_console', 'What is the alias for this association?'));
  630. $className = $this->in(__d('cake_console', 'What className will %s use?', $alias), null, $alias );
  631. if ($assocType == 0) {
  632. if (!empty($possibleKeys[$model->table])) {
  633. $showKeys = $possibleKeys[$model->table];
  634. } else {
  635. $showKeys = null;
  636. }
  637. $suggestedForeignKey = $this->_modelKey($alias);
  638. } else {
  639. $otherTable = Inflector::tableize($className);
  640. if (in_array($otherTable, $this->_tables)) {
  641. if ($assocType < 3) {
  642. if (!empty($possibleKeys[$otherTable])) {
  643. $showKeys = $possibleKeys[$otherTable];
  644. } else {
  645. $showKeys = null;
  646. }
  647. } else {
  648. $showKeys = null;
  649. }
  650. } else {
  651. $otherTable = $this->in(__d('cake_console', 'What is the table for this model?'));
  652. $showKeys = $possibleKeys[$otherTable];
  653. }
  654. $suggestedForeignKey = $this->_modelKey($model->name);
  655. }
  656. if (!empty($showKeys)) {
  657. $this->out(__d('cake_console', 'A helpful List of possible keys'));
  658. $foreignKey = $this->inOptions($showKeys, __d('cake_console', 'What is the foreignKey?'));
  659. $foreignKey = $showKeys[intval($foreignKey)];
  660. }
  661. if (!isset($foreignKey)) {
  662. $foreignKey = $this->in(__d('cake_console', 'What is the foreignKey? Specify your own.'), null, $suggestedForeignKey);
  663. }
  664. if ($assocType == 3) {
  665. $associationForeignKey = $this->in(__d('cake_console', 'What is the associationForeignKey?'), null, $this->_modelKey($model->name));
  666. $joinTable = $this->in(__d('cake_console', 'What is the joinTable?'));
  667. }
  668. $associations[$assocs[$assocType]] = array_values((array)$associations[$assocs[$assocType]]);
  669. $count = count($associations[$assocs[$assocType]]);
  670. $i = ($count > 0) ? $count : 0;
  671. $associations[$assocs[$assocType]][$i]['alias'] = $alias;
  672. $associations[$assocs[$assocType]][$i]['className'] = $className;
  673. $associations[$assocs[$assocType]][$i]['foreignKey'] = $foreignKey;
  674. if ($assocType == 3) {
  675. $associations[$assocs[$assocType]][$i]['associationForeignKey'] = $associationForeignKey;
  676. $associations[$assocs[$assocType]][$i]['joinTable'] = $joinTable;
  677. }
  678. $wannaDoMoreAssoc = $this->in(__d('cake_console', 'Define another association?'), array('y', 'n'), 'y');
  679. }
  680. return $associations;
  681. }
  682. /**
  683. * Finds all possible keys to use on custom associations.
  684. *
  685. * @return array array of tables and possible keys
  686. */
  687. protected function _generatePossibleKeys() {
  688. $possible = array();
  689. foreach ($this->_tables as $otherTable) {
  690. $tempOtherModel = new Model(array('table' => $otherTable, 'ds' => $this->connection));
  691. $modelFieldsTemp = $tempOtherModel->schema(true);
  692. foreach ($modelFieldsTemp as $fieldName => $field) {
  693. if ($field['type'] == 'integer' || $field['type'] == 'string') {
  694. $possible[$otherTable][] = $fieldName;
  695. }
  696. }
  697. }
  698. return $possible;
  699. }
  700. /**
  701. * Assembles and writes a Model file.
  702. *
  703. * @param mixed $name Model name or object
  704. * @param mixed $data if array and $name is not an object assume bake data, otherwise boolean.
  705. * @return string
  706. */
  707. public function bake($name, $data = array()) {
  708. if (is_object($name)) {
  709. if ($data == false) {
  710. $data = array();
  711. $data['associations'] = $this->doAssociations($name);
  712. $data['validate'] = $this->doValidation($name);
  713. }
  714. $data['primaryKey'] = $name->primaryKey;
  715. $data['useTable'] = $name->table;
  716. $data['useDbConfig'] = $name->useDbConfig;
  717. $data['name'] = $name = $name->name;
  718. } else {
  719. $data['name'] = $name;
  720. }
  721. $defaults = array('associations' => array(), 'validate' => array(), 'primaryKey' => 'id',
  722. 'useTable' => null, 'useDbConfig' => 'default', 'displayField' => null);
  723. $data = array_merge($defaults, $data);
  724. $pluginPath = '';
  725. if ($this->plugin) {
  726. $pluginPath = $this->plugin . '.';
  727. }
  728. $this->Template->set($data);
  729. $this->Template->set(array(
  730. 'plugin' => $this->plugin,
  731. 'pluginPath' => $pluginPath
  732. ));
  733. $out = $this->Template->generate('classes', 'model');
  734. $path = $this->getPath();
  735. $filename = $path . $name . '.php';
  736. $this->out("\n" . __d('cake_console', 'Baking model class for %s...', $name), 1, Shell::QUIET);
  737. $this->createFile($filename, $out);
  738. ClassRegistry::flush();
  739. return $out;
  740. }
  741. /**
  742. * Assembles and writes a unit test file
  743. *
  744. * @param string $className Model class name
  745. * @return string
  746. */
  747. public function bakeTest($className) {
  748. $this->Test->interactive = $this->interactive;
  749. $this->Test->plugin = $this->plugin;
  750. $this->Test->connection = $this->connection;
  751. return $this->Test->bake('Model', $className);
  752. }
  753. /**
  754. * outputs the a list of possible models or controllers from database
  755. *
  756. * @param string $useDbConfig Database configuration name
  757. * @return array
  758. */
  759. public function listAll($useDbConfig = null) {
  760. $this->_tables = (array) $this->getAllTables($useDbConfig);
  761. $this->_modelNames = array();
  762. $count = count($this->_tables);
  763. for ($i = 0; $i < $count; $i++) {
  764. $this->_modelNames[] = $this->_modelName($this->_tables[$i]);
  765. }
  766. if ($this->interactive === true) {
  767. $this->out(__d('cake_console', 'Possible Models based on your current database:'));
  768. for ($i = 0; $i < $count; $i++) {
  769. $this->out($i + 1 . ". " . $this->_modelNames[$i]);
  770. }
  771. }
  772. return $this->_tables;
  773. }
  774. /**
  775. * Interact with the user to determine the table name of a particular model
  776. *
  777. * @param string $modelName Name of the model you want a table for.
  778. * @param string $useDbConfig Name of the database config you want to get tables from.
  779. * @return string Table name
  780. */
  781. public function getTable($modelName, $useDbConfig = null) {
  782. $useTable = Inflector::tableize($modelName);
  783. if (in_array($modelName, $this->_modelNames)) {
  784. $modelNames = array_flip($this->_modelNames);
  785. $useTable = $this->_tables[$modelNames[$modelName]];
  786. }
  787. if ($this->interactive === true) {
  788. if (!isset($useDbConfig)) {
  789. $useDbConfig = $this->connection;
  790. }
  791. $db = ConnectionManager::getDataSource($useDbConfig);
  792. $fullTableName = $db->fullTableName($useTable, false);
  793. $tableIsGood = false;
  794. if (array_search($useTable, $this->_tables) === false) {
  795. $this->out();
  796. $this->out(__d('cake_console', "Given your model named '%s',\nCake would expect a database table named '%s'", $modelName, $fullTableName));
  797. $tableIsGood = $this->in(__d('cake_console', 'Do you want to use this table?'), array('y', 'n'), 'y');
  798. }
  799. if (strtolower($tableIsGood) == 'n') {
  800. $useTable = $this->in(__d('cake_console', 'What is the name of the table?'));
  801. }
  802. }
  803. return $useTable;
  804. }
  805. /**
  806. * Get an Array of all the tables in the supplied connection
  807. * will halt the script if no tables are found.
  808. *
  809. * @param string $useDbConfig Connection name to scan.
  810. * @return array Array of tables in the database.
  811. */
  812. public function getAllTables($useDbConfig = null) {
  813. if (!isset($useDbConfig)) {
  814. $useDbConfig = $this->connection;
  815. }
  816. $tables = array();
  817. $db = ConnectionManager::getDataSource($useDbConfig);
  818. $db->cacheSources = false;
  819. $usePrefix = empty($db->config['prefix']) ? '' : $db->config['prefix'];
  820. if ($usePrefix) {
  821. foreach ($db->listSources() as $table) {
  822. if (!strncmp($table, $usePrefix, strlen($usePrefix))) {
  823. $tables[] = substr($table, strlen($usePrefix));
  824. }
  825. }
  826. } else {
  827. $tables = $db->listSources();
  828. }
  829. if (empty($tables)) {
  830. $this->err(__d('cake_console', 'Your database does not have any tables.'));
  831. $this->_stop();
  832. }
  833. return $tables;
  834. }
  835. /**
  836. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  837. *
  838. * @param string $useDbConfig Database config name
  839. * @return string the model name
  840. */
  841. public function getName($useDbConfig = null) {
  842. $this->listAll($useDbConfig);
  843. $enteredModel = '';
  844. while ($enteredModel == '') {
  845. $enteredModel = $this->in(__d('cake_console', "Enter a number from the list above,\n" .
  846. "type in the name of another model, or 'q' to exit"), null, 'q');
  847. if ($enteredModel === 'q') {
  848. $this->out(__d('cake_console', 'Exit'));
  849. $this->_stop();
  850. }
  851. if ($enteredModel == '' || intval($enteredModel) > count($this->_modelNames)) {
  852. $this->err(__d('cake_console', "The model name you supplied was empty,\n" .
  853. "or the number you selected was not an option. Please try again."));
  854. $enteredModel = '';
  855. }
  856. }
  857. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  858. $currentModelName = $this->_modelNames[intval($enteredModel) - 1];
  859. } else {
  860. $currentModelName = $enteredModel;
  861. }
  862. return $currentModelName;
  863. }
  864. /**
  865. * get the option parser.
  866. *
  867. * @return void
  868. */
  869. public function getOptionParser() {
  870. $parser = parent::getOptionParser();
  871. return $parser->description(
  872. __d('cake_console', 'Bake models.')
  873. )->addArgument('name', array(
  874. 'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
  875. ))->addSubcommand('all', array(
  876. 'help' => __d('cake_console', 'Bake all model files with associations and validation.')
  877. ))->addOption('plugin', array(
  878. 'short' => 'p',
  879. 'help' => __d('cake_console', 'Plugin to bake the model into.')
  880. ))->addOption('connection', array(
  881. 'short' => 'c',
  882. 'help' => __d('cake_console', 'The connection the model table is on.')
  883. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  884. }
  885. /**
  886. * Interact with FixtureTask to automatically bake fixtures when baking models.
  887. *
  888. * @param string $className Name of class to bake fixture for
  889. * @param string $useTable Optional table name for fixture to use.
  890. * @return void
  891. * @see FixtureTask::bake
  892. */
  893. public function bakeFixture($className, $useTable = null) {
  894. $this->Fixture->interactive = $this->interactive;
  895. $this->Fixture->connection = $this->connection;
  896. $this->Fixture->plugin = $this->plugin;
  897. $this->Fixture->bake($className, $useTable);
  898. }
  899. }