PageRenderTime 66ms CodeModel.GetById 35ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Console/Command/Task/ModelTask.php

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