ModelTask.php 29 KB

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