ModelTask.php 31 KB

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