ModelTask.php 31 KB

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