ModelTask.php 31 KB

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