ControllerTask.php 16 KB

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