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. 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] = $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'] === 'float') {
  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. }