ControllerTask.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. <?php
  2. /**
  3. * The ControllerTask handles creating and updating controller 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('AppModel', 'Model');
  22. /**
  23. * Task class for creating and updating controller files.
  24. *
  25. * @package Cake.Console.Command.Task
  26. */
  27. class ControllerTask extends BakeTask {
  28. /**
  29. * Tasks to be loaded by this Task
  30. *
  31. * @var array
  32. */
  33. public $tasks = array('Model', 'Test', 'Template', 'DbConfig', 'Project');
  34. /**
  35. * path to Controller directory
  36. *
  37. * @var array
  38. */
  39. public $path = null;
  40. /**
  41. * Override initialize
  42. *
  43. * @return void
  44. */
  45. public function initialize() {
  46. $this->path = current(App::path('Controller'));
  47. }
  48. /**
  49. * Execution method always used for tasks
  50. *
  51. * @return void
  52. */
  53. public function execute() {
  54. parent::execute();
  55. if (empty($this->args)) {
  56. return $this->_interactive();
  57. }
  58. if (isset($this->args[0])) {
  59. if (!isset($this->connection)) {
  60. $this->connection = 'default';
  61. }
  62. if (strtolower($this->args[0]) === 'all') {
  63. return $this->all();
  64. }
  65. $controller = $this->_controllerName($this->args[0]);
  66. $actions = '';
  67. if (!empty($this->params['public'])) {
  68. $this->out(__d('cake_console', 'Baking basic crud methods for ') . $controller);
  69. $actions .= $this->bakeActions($controller);
  70. }
  71. if (!empty($this->params['admin'])) {
  72. $admin = $this->Project->getPrefix();
  73. if ($admin) {
  74. $this->out(__d('cake_console', 'Adding %s methods', $admin));
  75. $actions .= "\n" . $this->bakeActions($controller, $admin);
  76. }
  77. }
  78. if (empty($actions)) {
  79. $actions = 'scaffold';
  80. }
  81. if ($this->bake($controller, $actions)) {
  82. if ($this->_checkUnitTest()) {
  83. $this->bakeTest($controller);
  84. }
  85. }
  86. }
  87. }
  88. /**
  89. * Bake All the controllers at once. Will only bake controllers for models that exist.
  90. *
  91. * @return void
  92. */
  93. public function all() {
  94. $this->interactive = false;
  95. $this->listAll($this->connection, false);
  96. ClassRegistry::config('Model', array('ds' => $this->connection));
  97. $unitTestExists = $this->_checkUnitTest();
  98. $admin = false;
  99. if (!empty($this->params['admin'])) {
  100. $admin = $this->Project->getPrefix();
  101. }
  102. foreach ($this->__tables as $table) {
  103. $model = $this->_modelName($table);
  104. $controller = $this->_controllerName($model);
  105. App::uses($model, 'Model');
  106. if (class_exists($model)) {
  107. $actions = $this->bakeActions($controller);
  108. if ($admin) {
  109. $this->out(__d('cake_console', 'Adding %s methods', $admin));
  110. $actions .= "\n" . $this->bakeActions($controller, $admin);
  111. }
  112. if ($this->bake($controller, $actions) && $unitTestExists) {
  113. $this->bakeTest($controller);
  114. }
  115. }
  116. }
  117. }
  118. /**
  119. * Interactive
  120. *
  121. * @return void
  122. */
  123. protected function _interactive() {
  124. $this->interactive = true;
  125. $this->hr();
  126. $this->out(__d('cake_console', "Bake Controller\nPath: %s", $this->getPath()));
  127. $this->hr();
  128. if (empty($this->connection)) {
  129. $this->connection = $this->DbConfig->getConfig();
  130. }
  131. $controllerName = $this->getName();
  132. $this->hr();
  133. $this->out(__d('cake_console', 'Baking %sController', $controllerName));
  134. $this->hr();
  135. $helpers = $components = array();
  136. $actions = '';
  137. $wannaUseSession = 'y';
  138. $wannaBakeAdminCrud = 'n';
  139. $useDynamicScaffold = 'n';
  140. $wannaBakeCrud = 'y';
  141. $question[] = __d('cake_console', "Would you like to build your controller interactively?");
  142. if (file_exists($this->path . $controllerName . 'Controller.php')) {
  143. $question[] = __d('cake_console', "Warning: Choosing no will overwrite the %sController.", $controllerName);
  144. }
  145. $doItInteractive = $this->in(implode("\n", $question), array('y', 'n'), 'y');
  146. if (strtolower($doItInteractive) === 'y') {
  147. $this->interactive = true;
  148. $useDynamicScaffold = $this->in(
  149. __d('cake_console', "Would you like to use dynamic scaffolding?"), array('y', 'n'), 'n'
  150. );
  151. if (strtolower($useDynamicScaffold) === 'y') {
  152. $wannaBakeCrud = 'n';
  153. $actions = 'scaffold';
  154. } else {
  155. list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
  156. $helpers = $this->doHelpers();
  157. $components = $this->doComponents();
  158. $wannaUseSession = $this->in(
  159. __d('cake_console', "Would you like to use Session flash messages?"), array('y', 'n'), 'y'
  160. );
  161. }
  162. } else {
  163. list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
  164. }
  165. if (strtolower($wannaBakeCrud) === 'y') {
  166. $actions = $this->bakeActions($controllerName, null, strtolower($wannaUseSession) === 'y');
  167. }
  168. if (strtolower($wannaBakeAdminCrud) === 'y') {
  169. $admin = $this->Project->getPrefix();
  170. $actions .= $this->bakeActions($controllerName, $admin, strtolower($wannaUseSession) === 'y');
  171. }
  172. $baked = false;
  173. if ($this->interactive === true) {
  174. $this->confirmController($controllerName, $useDynamicScaffold, $helpers, $components);
  175. $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n'), 'y');
  176. if (strtolower($looksGood) === 'y') {
  177. $baked = $this->bake($controllerName, $actions, $helpers, $components);
  178. if ($baked && $this->_checkUnitTest()) {
  179. $this->bakeTest($controllerName);
  180. }
  181. }
  182. } else {
  183. $baked = $this->bake($controllerName, $actions, $helpers, $components);
  184. if ($baked && $this->_checkUnitTest()) {
  185. $this->bakeTest($controllerName);
  186. }
  187. }
  188. return $baked;
  189. }
  190. /**
  191. * Confirm a to be baked controller with the user
  192. *
  193. * @param string $controllerName
  194. * @param string $useDynamicScaffold
  195. * @param array $helpers
  196. * @param array $components
  197. * @return void
  198. */
  199. public function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
  200. $this->out();
  201. $this->hr();
  202. $this->out(__d('cake_console', 'The following controller will be created:'));
  203. $this->hr();
  204. $this->out(__d('cake_console', "Controller Name:\n\t%s", $controllerName));
  205. if (strtolower($useDynamicScaffold) === 'y') {
  206. $this->out("public \$scaffold;");
  207. }
  208. $properties = array(
  209. 'helpers' => __d('cake_console', 'Helpers:'),
  210. 'components' => __d('cake_console', 'Components:'),
  211. );
  212. foreach ($properties as $var => $title) {
  213. if (count($$var)) {
  214. $output = '';
  215. $length = count($$var);
  216. foreach ($$var as $i => $propElement) {
  217. if ($i != $length - 1) {
  218. $output .= ucfirst($propElement) . ', ';
  219. } else {
  220. $output .= ucfirst($propElement);
  221. }
  222. }
  223. $this->out($title . "\n\t" . $output);
  224. }
  225. }
  226. $this->hr();
  227. }
  228. /**
  229. * Interact with the user and ask about which methods (admin or regular they want to bake)
  230. *
  231. * @return array Array containing (bakeRegular, bakeAdmin) answers
  232. */
  233. protected function _askAboutMethods() {
  234. $wannaBakeCrud = $this->in(
  235. __d('cake_console', "Would you like to create some basic class methods \n(index(), add(), view(), edit())?"),
  236. array('y', 'n'), 'n'
  237. );
  238. $wannaBakeAdminCrud = $this->in(
  239. __d('cake_console', "Would you like to create the basic class methods for admin routing?"),
  240. array('y', 'n'), 'n'
  241. );
  242. return array($wannaBakeCrud, $wannaBakeAdminCrud);
  243. }
  244. /**
  245. * Bake scaffold actions
  246. *
  247. * @param string $controllerName Controller name
  248. * @param string $admin Admin route to use
  249. * @param boolean $wannaUseSession Set to true to use sessions, false otherwise
  250. * @return string Baked actions
  251. */
  252. public function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
  253. $currentModelName = $modelImport = $this->_modelName($controllerName);
  254. $plugin = $this->plugin;
  255. if ($plugin) {
  256. $plugin .= '.';
  257. }
  258. App::uses($modelImport, $plugin . 'Model');
  259. if (!class_exists($modelImport)) {
  260. $this->err(__d('cake_console', 'You must have a model for this class to build basic methods. Please try again.'));
  261. return $this->_stop();
  262. }
  263. $modelObj = ClassRegistry::init($currentModelName);
  264. $controllerPath = $this->_controllerPath($controllerName);
  265. $pluralName = $this->_pluralName($currentModelName);
  266. $singularName = Inflector::variable($currentModelName);
  267. $singularHumanName = $this->_singularHumanName($controllerName);
  268. $pluralHumanName = $this->_pluralName($controllerName);
  269. $displayField = $modelObj->displayField;
  270. $primaryKey = $modelObj->primaryKey;
  271. $this->Template->set(compact(
  272. 'plugin', 'admin', 'controllerPath', 'pluralName', 'singularName',
  273. 'singularHumanName', 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName',
  274. 'displayField', 'primaryKey'
  275. ));
  276. $actions = $this->Template->generate('actions', 'controller_actions');
  277. return $actions;
  278. }
  279. /**
  280. * Assembles and writes a Controller file
  281. *
  282. * @param string $controllerName Controller name already pluralized and correctly cased.
  283. * @param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
  284. * @param array $helpers Helpers to use in controller
  285. * @param array $components Components to use in controller
  286. * @return string Baked controller
  287. */
  288. public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
  289. $this->out("\n" . __d('cake_console', 'Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
  290. $isScaffold = ($actions === 'scaffold') ? true : false;
  291. $this->Template->set(array(
  292. 'plugin' => $this->plugin,
  293. 'pluginPath' => empty($this->plugin) ? '' : $this->plugin . '.'
  294. ));
  295. $this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
  296. $contents = $this->Template->generate('classes', 'controller');
  297. $path = $this->getPath();
  298. $filename = $path . $controllerName . 'Controller.php';
  299. if ($this->createFile($filename, $contents)) {
  300. return $contents;
  301. }
  302. return false;
  303. }
  304. /**
  305. * Assembles and writes a unit test file
  306. *
  307. * @param string $className Controller class name
  308. * @return string Baked test
  309. */
  310. public function bakeTest($className) {
  311. $this->Test->plugin = $this->plugin;
  312. $this->Test->connection = $this->connection;
  313. $this->Test->interactive = $this->interactive;
  314. return $this->Test->bake('Controller', $className);
  315. }
  316. /**
  317. * Interact with the user and get a list of additional helpers
  318. *
  319. * @return array Helpers that the user wants to use.
  320. */
  321. public function doHelpers() {
  322. return $this->_doPropertyChoices(
  323. __d('cake_console', "Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?"),
  324. __d('cake_console', "Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Text, Js, Time'")
  325. );
  326. }
  327. /**
  328. * Interact with the user and get a list of additional components
  329. *
  330. * @return array Components the user wants to use.
  331. */
  332. public function doComponents() {
  333. return $this->_doPropertyChoices(
  334. __d('cake_console', "Would you like this controller to use any components?"),
  335. __d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
  336. );
  337. }
  338. /**
  339. * Common code for property choice handling.
  340. *
  341. * @param string $prompt A yes/no question to precede the list
  342. * @param string $example A question for a comma separated list, with examples.
  343. * @return array Array of values for property.
  344. */
  345. protected function _doPropertyChoices($prompt, $example) {
  346. $proceed = $this->in($prompt, array('y', 'n'), 'n');
  347. $property = array();
  348. if (strtolower($proceed) === 'y') {
  349. $propertyList = $this->in($example);
  350. $propertyListTrimmed = str_replace(' ', '', $propertyList);
  351. $property = explode(',', $propertyListTrimmed);
  352. }
  353. return array_filter($property);
  354. }
  355. /**
  356. * Outputs and gets the list of possible controllers from database
  357. *
  358. * @param string $useDbConfig Database configuration name
  359. * @return array Set of controllers
  360. */
  361. public function listAll($useDbConfig = null) {
  362. if (is_null($useDbConfig)) {
  363. $useDbConfig = $this->connection;
  364. }
  365. $this->__tables = $this->Model->getAllTables($useDbConfig);
  366. if ($this->interactive) {
  367. $this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
  368. $this->hr();
  369. $this->_controllerNames = array();
  370. $count = count($this->__tables);
  371. for ($i = 0; $i < $count; $i++) {
  372. $this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
  373. $this->out(sprintf("%2d. %s", $i + 1, $this->_controllerNames[$i]));
  374. }
  375. return $this->_controllerNames;
  376. }
  377. return $this->__tables;
  378. }
  379. /**
  380. * Forces the user to specify the controller he wants to bake, and returns the selected controller name.
  381. *
  382. * @param string $useDbConfig Connection name to get a controller name for.
  383. * @return string Controller name
  384. */
  385. public function getName($useDbConfig = null) {
  386. $controllers = $this->listAll($useDbConfig);
  387. $enteredController = '';
  388. while (!$enteredController) {
  389. $enteredController = $this->in(__d('cake_console', "Enter a number from the list above,\ntype in the name of another controller, or 'q' to exit"), null, 'q');
  390. if ($enteredController === 'q') {
  391. $this->out(__d('cake_console', 'Exit'));
  392. return $this->_stop();
  393. }
  394. if (!$enteredController || intval($enteredController) > count($controllers)) {
  395. $this->err(__d('cake_console', "The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again."));
  396. $enteredController = '';
  397. }
  398. }
  399. if (intval($enteredController) > 0 && intval($enteredController) <= count($controllers)) {
  400. $controllerName = $controllers[intval($enteredController) - 1];
  401. } else {
  402. $controllerName = Inflector::camelize($enteredController);
  403. }
  404. return $controllerName;
  405. }
  406. /**
  407. * get the option parser.
  408. *
  409. * @return void
  410. */
  411. public function getOptionParser() {
  412. $parser = parent::getOptionParser();
  413. return $parser->description(
  414. __d('cake_console', 'Bake a controller for a model. Using options you can bake public, admin or both.')
  415. )->addArgument('name', array(
  416. 'help' => __d('cake_console', 'Name of the controller to bake. Can use Plugin.name to bake controllers into plugins.')
  417. ))->addOption('public', array(
  418. 'help' => __d('cake_console', 'Bake a controller with basic crud actions (index, view, add, edit, delete).'),
  419. 'boolean' => true
  420. ))->addOption('admin', array(
  421. 'help' => __d('cake_console', 'Bake a controller with crud actions for one of the Routing.prefixes.'),
  422. 'boolean' => true
  423. ))->addOption('plugin', array(
  424. 'short' => 'p',
  425. 'help' => __d('cake_console', 'Plugin to bake the controller into.')
  426. ))->addOption('connection', array(
  427. 'short' => 'c',
  428. 'help' => __d('cake_console', 'The connection the controller\'s model is on.')
  429. ))->addSubcommand('all', array(
  430. 'help' => __d('cake_console', 'Bake all controllers with CRUD methods.')
  431. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  432. }
  433. }