ModelTask.php 32 KB

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