ModelTask.php 31 KB

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