PageRenderTime 56ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

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

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