ControllerTask.php 15 KB

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