ModelTask.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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 MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  19. App::uses('AppShell', 'Console/Command');
  20. App::uses('BakeTask', 'Console/Command/Task');
  21. App::uses('ConnectionManager', 'Model');
  22. App::uses('Model', 'Model');
  23. App::uses('Validation', 'Utility');
  24. /**
  25. * Task class for creating and updating model files.
  26. *
  27. * @package Cake.Console.Command.Task
  28. */
  29. class ModelTask extends BakeTask {
  30. /**
  31. * path to Model directory
  32. *
  33. * @var string
  34. */
  35. public $path = null;
  36. /**
  37. * tasks
  38. *
  39. * @var array
  40. */
  41. public $tasks = array('DbConfig', 'Fixture', 'Test', 'Template');
  42. /**
  43. * Tables to skip when running all()
  44. *
  45. * @var array
  46. */
  47. public $skipTables = array('i18n');
  48. /**
  49. * Holds tables found on connection.
  50. *
  51. * @var array
  52. */
  53. protected $_tables = array();
  54. /**
  55. * Holds the model names
  56. *
  57. * @var array
  58. */
  59. protected $_modelNames = array();
  60. /**
  61. * Holds validation method map.
  62. *
  63. * @var array
  64. */
  65. protected $_validations = array();
  66. /**
  67. * Override initialize
  68. *
  69. * @return void
  70. */
  71. public function initialize() {
  72. $this->path = current(App::path('Model'));
  73. }
  74. /**
  75. * Execution method always used for tasks
  76. *
  77. * @return void
  78. */
  79. public function execute() {
  80. parent::execute();
  81. if (empty($this->args)) {
  82. $this->_interactive();
  83. }
  84. if (!empty($this->args[0])) {
  85. $this->interactive = false;
  86. if (!isset($this->connection)) {
  87. $this->connection = 'default';
  88. }
  89. if (strtolower($this->args[0]) === 'all') {
  90. return $this->all();
  91. }
  92. $model = $this->_modelName($this->args[0]);
  93. $this->listAll($this->connection);
  94. $useTable = $this->getTable($model);
  95. $object = $this->_getModelObject($model, $useTable);
  96. if ($this->bake($object, false)) {
  97. if ($this->_checkUnitTest()) {
  98. $this->bakeFixture($model, $useTable);
  99. $this->bakeTest($model);
  100. }
  101. }
  102. }
  103. }
  104. /**
  105. * Bake all models at once.
  106. *
  107. * @return void
  108. */
  109. public function all() {
  110. $this->listAll($this->connection, false);
  111. $unitTestExists = $this->_checkUnitTest();
  112. foreach ($this->_tables as $table) {
  113. if (in_array($table, $this->skipTables)) {
  114. continue;
  115. }
  116. $modelClass = Inflector::classify($table);
  117. $this->out(__d('cake_console', 'Baking %s', $modelClass));
  118. $object = $this->_getModelObject($modelClass, $table);
  119. if ($this->bake($object, false) && $unitTestExists) {
  120. $this->bakeFixture($modelClass, $table);
  121. $this->bakeTest($modelClass);
  122. }
  123. }
  124. }
  125. /**
  126. * Get a model object for a class name.
  127. *
  128. * @param string $className Name of class you want model to be.
  129. * @param string $table Table name
  130. * @return Model Model instance
  131. */
  132. protected function _getModelObject($className, $table = null) {
  133. if (!$table) {
  134. $table = Inflector::tableize($className);
  135. }
  136. $object = new Model(array('name' => $className, 'table' => $table, 'ds' => $this->connection));
  137. $fields = $object->schema(true);
  138. foreach ($fields as $name => $field) {
  139. if (isset($field['key']) && $field['key'] === 'primary') {
  140. $object->primaryKey = $name;
  141. break;
  142. }
  143. }
  144. return $object;
  145. }
  146. /**
  147. * Generate a key value list of options and a prompt.
  148. *
  149. * @param array $options Array of options to use for the selections. indexes must start at 0
  150. * @param string $prompt Prompt to use for options list.
  151. * @param integer $default The default option for the given prompt.
  152. * @return integer Result of user choice.
  153. */
  154. public function inOptions($options, $prompt = null, $default = null) {
  155. $valid = false;
  156. $max = count($options);
  157. while (!$valid) {
  158. $len = strlen(count($options) + 1);
  159. foreach ($options as $i => $option) {
  160. $this->out(sprintf("%${len}d. %s", $i + 1, $option));
  161. }
  162. if (empty($prompt)) {
  163. $prompt = __d('cake_console', 'Make a selection from the choices above');
  164. }
  165. $choice = $this->in($prompt, null, $default);
  166. if (intval($choice) > 0 && intval($choice) <= $max) {
  167. $valid = true;
  168. }
  169. }
  170. return $choice - 1;
  171. }
  172. /**
  173. * Handles interactive baking
  174. *
  175. * @return boolean
  176. */
  177. protected function _interactive() {
  178. $this->hr();
  179. $this->out(__d('cake_console', "Bake Model\nPath: %s", $this->getPath()));
  180. $this->hr();
  181. $this->interactive = true;
  182. $primaryKey = 'id';
  183. $validate = $associations = array();
  184. if (empty($this->connection)) {
  185. $this->connection = $this->DbConfig->getConfig();
  186. }
  187. $currentModelName = $this->getName();
  188. $useTable = $this->getTable($currentModelName);
  189. $db = ConnectionManager::getDataSource($this->connection);
  190. $fullTableName = $db->fullTableName($useTable);
  191. if (!in_array($useTable, $this->_tables)) {
  192. $prompt = __d('cake_console', "The table %s doesn't exist or could not be automatically detected\ncontinue anyway?", $useTable);
  193. $continue = $this->in($prompt, array('y', 'n'));
  194. if (strtolower($continue) === 'n') {
  195. return false;
  196. }
  197. }
  198. $tempModel = new Model(array('name' => $currentModelName, 'table' => $useTable, 'ds' => $this->connection));
  199. $knownToExist = false;
  200. try {
  201. $fields = $tempModel->schema(true);
  202. $knownToExist = true;
  203. } catch (Exception $e) {
  204. $fields = array($tempModel->primaryKey);
  205. }
  206. if (!array_key_exists('id', $fields)) {
  207. $primaryKey = $this->findPrimaryKey($fields);
  208. }
  209. if ($knownToExist) {
  210. $displayField = $tempModel->hasField(array('name', 'title'));
  211. if (!$displayField) {
  212. $displayField = $this->findDisplayField($tempModel->schema());
  213. }
  214. $prompt = __d('cake_console', "Would you like to supply validation criteria \nfor the fields in your model?");
  215. $wannaDoValidation = $this->in($prompt, array('y','n'), 'y');
  216. if (array_search($useTable, $this->_tables) !== false && strtolower($wannaDoValidation) === 'y') {
  217. $validate = $this->doValidation($tempModel);
  218. }
  219. $prompt = __d('cake_console', "Would you like to define model associations\n(hasMany, hasOne, belongsTo, etc.)?");
  220. $wannaDoAssoc = $this->in($prompt, array('y','n'), 'y');
  221. if (strtolower($wannaDoAssoc) === 'y') {
  222. $associations = $this->doAssociations($tempModel);
  223. }
  224. }
  225. $this->out();
  226. $this->hr();
  227. $this->out(__d('cake_console', 'The following Model will be created:'));
  228. $this->hr();
  229. $this->out(__d('cake_console', "Name: %s", $currentModelName));
  230. if ($this->connection !== 'default') {
  231. $this->out(__d('cake_console', "DB Config: %s", $this->connection));
  232. }
  233. if ($fullTableName !== Inflector::tableize($currentModelName)) {
  234. $this->out(__d('cake_console', 'DB Table: %s', $fullTableName));
  235. }
  236. if ($primaryKey !== 'id') {
  237. $this->out(__d('cake_console', 'Primary Key: %s', $primaryKey));
  238. }
  239. if (!empty($validate)) {
  240. $this->out(__d('cake_console', 'Validation: %s', print_r($validate, true)));
  241. }
  242. if (!empty($associations)) {
  243. $this->out(__d('cake_console', 'Associations:'));
  244. $assocKeys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  245. foreach ($assocKeys as $assocKey) {
  246. $this->_printAssociation($currentModelName, $assocKey, $associations);
  247. }
  248. }
  249. $this->hr();
  250. $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n'), 'y');
  251. if (strtolower($looksGood) === 'y') {
  252. $vars = compact('associations', 'validate', 'primaryKey', 'useTable', 'displayField');
  253. $vars['useDbConfig'] = $this->connection;
  254. if ($this->bake($currentModelName, $vars)) {
  255. if ($this->_checkUnitTest()) {
  256. $this->bakeFixture($currentModelName, $useTable);
  257. $this->bakeTest($currentModelName, $useTable, $associations);
  258. }
  259. }
  260. } else {
  261. return false;
  262. }
  263. }
  264. /**
  265. * Print out all the associations of a particular type
  266. *
  267. * @param string $modelName Name of the model relations belong to.
  268. * @param string $type Name of association you want to see. i.e. 'belongsTo'
  269. * @param string $associations Collection of associations.
  270. * @return void
  271. */
  272. protected function _printAssociation($modelName, $type, $associations) {
  273. if (!empty($associations[$type])) {
  274. for ($i = 0, $len = count($associations[$type]); $i < $len; $i++) {
  275. $out = "\t" . $modelName . ' ' . $type . ' ' . $associations[$type][$i]['alias'];
  276. $this->out($out);
  277. }
  278. }
  279. }
  280. /**
  281. * Finds a primary Key in a list of fields.
  282. *
  283. * @param array $fields Array of fields that might have a primary key.
  284. * @return string Name of field that is a primary key.
  285. */
  286. public function findPrimaryKey($fields) {
  287. $name = 'id';
  288. foreach ($fields as $name => $field) {
  289. if (isset($field['key']) && $field['key'] === 'primary') {
  290. break;
  291. }
  292. }
  293. return $this->in(__d('cake_console', 'What is the primaryKey?'), null, $name);
  294. }
  295. /**
  296. * interact with the user to find the displayField value for a model.
  297. *
  298. * @param array $fields Array of fields to look for and choose as a displayField
  299. * @return mixed Name of field to use for displayField or false if the user declines to choose
  300. */
  301. public function findDisplayField($fields) {
  302. $fieldNames = array_keys($fields);
  303. $prompt = __d('cake_console', "A displayField could not be automatically detected\nwould you like to choose one?");
  304. $continue = $this->in($prompt, array('y', 'n'));
  305. if (strtolower($continue) === 'n') {
  306. return false;
  307. }
  308. $prompt = __d('cake_console', 'Choose a field from the options above:');
  309. $choice = $this->inOptions($fieldNames, $prompt);
  310. return $fieldNames[$choice];
  311. }
  312. /**
  313. * Handles Generation and user interaction for creating validation.
  314. *
  315. * @param Model $model Model to have validations generated for.
  316. * @return array $validate Array of user selected validations.
  317. */
  318. public function doValidation($model) {
  319. if (!$model instanceof Model) {
  320. return false;
  321. }
  322. $fields = $model->schema();
  323. if (empty($fields)) {
  324. return false;
  325. }
  326. $validate = array();
  327. $this->initValidations();
  328. foreach ($fields as $fieldName => $field) {
  329. $validation = $this->fieldValidation($fieldName, $field, $model->primaryKey);
  330. if (!empty($validation)) {
  331. $validate[$fieldName] = $validation;
  332. }
  333. }
  334. return $validate;
  335. }
  336. /**
  337. * Populate the _validations array
  338. *
  339. * @return void
  340. */
  341. public function initValidations() {
  342. $options = $choices = array();
  343. if (class_exists('Validation')) {
  344. $options = get_class_methods('Validation');
  345. }
  346. sort($options);
  347. $default = 1;
  348. foreach ($options as $option) {
  349. if ($option{0} !== '_') {
  350. $choices[$default] = strtolower($option);
  351. $default++;
  352. }
  353. }
  354. $choices[$default] = 'none'; // Needed since index starts at 1
  355. $this->_validations = $choices;
  356. return $choices;
  357. }
  358. /**
  359. * Does individual field validation handling.
  360. *
  361. * @param string $fieldName Name of field to be validated.
  362. * @param array $metaData metadata for field
  363. * @param string $primaryKey
  364. * @return array Array of validation for the field.
  365. */
  366. public function fieldValidation($fieldName, $metaData, $primaryKey = 'id') {
  367. $defaultChoice = count($this->_validations);
  368. $validate = $alreadyChosen = array();
  369. $anotherValidator = 'y';
  370. while ($anotherValidator === 'y') {
  371. if ($this->interactive) {
  372. $this->out();
  373. $this->out(__d('cake_console', 'Field: <info>%s</info>', $fieldName));
  374. $this->out(__d('cake_console', 'Type: <info>%s</info>', $metaData['type']));
  375. $this->hr();
  376. $this->out(__d('cake_console', 'Please select one of the following validation options:'));
  377. $this->hr();
  378. $optionText = '';
  379. for ($i = 1, $m = $defaultChoice / 2; $i <= $m; $i++) {
  380. $line = sprintf("%2d. %s", $i, $this->_validations[$i]);
  381. $optionText .= $line . str_repeat(" ", 31 - strlen($line));
  382. if ($m + $i !== $defaultChoice) {
  383. $optionText .= sprintf("%2d. %s\n", $m + $i, $this->_validations[$m + $i]);
  384. }
  385. }
  386. $this->out($optionText);
  387. $this->out(__d('cake_console', "%s - Do not do any validation on this field.", $defaultChoice));
  388. $this->hr();
  389. }
  390. $prompt = __d('cake_console', "... or enter in a valid regex validation string.\n");
  391. $methods = array_flip($this->_validations);
  392. $guess = $defaultChoice;
  393. if ($metaData['null'] != 1 && !in_array($fieldName, array($primaryKey, 'created', 'modified', 'updated'))) {
  394. if ($fieldName === 'email') {
  395. $guess = $methods['email'];
  396. } elseif ($metaData['type'] === 'string' && $metaData['length'] == 36) {
  397. $guess = $methods['uuid'];
  398. } elseif ($metaData['type'] === 'string') {
  399. $guess = $methods['notempty'];
  400. } elseif ($metaData['type'] === 'text') {
  401. $guess = $methods['notempty'];
  402. } elseif ($metaData['type'] === 'integer') {
  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 = strpos($fieldName, '_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 ('n' == strtolower($response)) {
  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 = (array)$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. $this->_stop();
  868. }
  869. return $tables;
  870. }
  871. /**
  872. * Forces the user to specify the model he wants to bake, and returns the selected model name.
  873. *
  874. * @param string $useDbConfig Database config name
  875. * @return string The model name
  876. */
  877. public function getName($useDbConfig = null) {
  878. $this->listAll($useDbConfig);
  879. $enteredModel = '';
  880. while (!$enteredModel) {
  881. $enteredModel = $this->in(__d('cake_console', "Enter a number from the list above,\n" .
  882. "type in the name of another model, or 'q' to exit"), null, 'q');
  883. if ($enteredModel === 'q') {
  884. $this->out(__d('cake_console', 'Exit'));
  885. $this->_stop();
  886. }
  887. if (!$enteredModel || intval($enteredModel) > count($this->_modelNames)) {
  888. $this->err(__d('cake_console', "The model name you supplied was empty,\n" .
  889. "or the number you selected was not an option. Please try again."));
  890. $enteredModel = '';
  891. }
  892. }
  893. if (intval($enteredModel) > 0 && intval($enteredModel) <= count($this->_modelNames)) {
  894. return $this->_modelNames[intval($enteredModel) - 1];
  895. }
  896. return $enteredModel;
  897. }
  898. /**
  899. * get the option parser.
  900. *
  901. * @return void
  902. */
  903. public function getOptionParser() {
  904. $parser = parent::getOptionParser();
  905. return $parser->description(
  906. __d('cake_console', 'Bake models.')
  907. )->addArgument('name', array(
  908. 'help' => __d('cake_console', 'Name of the model to bake. Can use Plugin.name to bake plugin models.')
  909. ))->addSubcommand('all', array(
  910. 'help' => __d('cake_console', 'Bake all model files with associations and validation.')
  911. ))->addOption('plugin', array(
  912. 'short' => 'p',
  913. 'help' => __d('cake_console', 'Plugin to bake the model into.')
  914. ))->addOption('theme', array(
  915. 'short' => 't',
  916. 'help' => __d('cake_console', 'Theme to use when baking code.')
  917. ))->addOption('connection', array(
  918. 'short' => 'c',
  919. 'help' => __d('cake_console', 'The connection the model table is on.')
  920. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  921. }
  922. /**
  923. * Interact with FixtureTask to automatically bake fixtures when baking models.
  924. *
  925. * @param string $className Name of class to bake fixture for
  926. * @param string $useTable Optional table name for fixture to use.
  927. * @return void
  928. * @see FixtureTask::bake
  929. */
  930. public function bakeFixture($className, $useTable = null) {
  931. $this->Fixture->interactive = $this->interactive;
  932. $this->Fixture->connection = $this->connection;
  933. $this->Fixture->plugin = $this->plugin;
  934. $this->Fixture->bake($className, $useTable);
  935. }
  936. }