ControllerTask.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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-2011, 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-2011, 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('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. foreach ($this->__tables as $table) {
  97. $model = $this->_modelName($table);
  98. $controller = $this->_controllerName($model);
  99. App::uses($model, 'Model');
  100. if (class_exists($model)) {
  101. $actions = $this->bakeActions($controller);
  102. if ($this->bake($controller, $actions) && $unitTestExists) {
  103. $this->bakeTest($controller);
  104. }
  105. }
  106. }
  107. }
  108. /**
  109. * Interactive
  110. *
  111. * @return void
  112. */
  113. protected function _interactive() {
  114. $this->interactive = true;
  115. $this->hr();
  116. $this->out(__d('cake_console', "Bake Controller\nPath: %s", $this->path));
  117. $this->hr();
  118. if (empty($this->connection)) {
  119. $this->connection = $this->DbConfig->getConfig();
  120. }
  121. $controllerName = $this->getName();
  122. $this->hr();
  123. $this->out(__d('cake_console', 'Baking %sController', $controllerName));
  124. $this->hr();
  125. $helpers = $components = array();
  126. $actions = '';
  127. $wannaUseSession = 'y';
  128. $wannaBakeAdminCrud = 'n';
  129. $useDynamicScaffold = 'n';
  130. $wannaBakeCrud = 'y';
  131. $question[] = __d('cake_console', "Would you like to build your controller interactively?");
  132. if (file_exists($this->path . $controllerName .'Controller.php')) {
  133. $question[] = __d('cake_console', "Warning: Choosing no will overwrite the %sController.", $controllerName);
  134. }
  135. $doItInteractive = $this->in(implode("\n", $question), array('y','n'), 'y');
  136. if (strtolower($doItInteractive) == 'y') {
  137. $this->interactive = true;
  138. $useDynamicScaffold = $this->in(
  139. __d('cake_console', "Would you like to use dynamic scaffolding?"), array('y','n'), 'n'
  140. );
  141. if (strtolower($useDynamicScaffold) == 'y') {
  142. $wannaBakeCrud = 'n';
  143. $actions = 'scaffold';
  144. } else {
  145. list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
  146. $helpers = $this->doHelpers();
  147. $components = $this->doComponents();
  148. $wannaUseSession = $this->in(
  149. __d('cake_console', "Would you like to use Session flash messages?"), array('y','n'), 'y'
  150. );
  151. }
  152. } else {
  153. list($wannaBakeCrud, $wannaBakeAdminCrud) = $this->_askAboutMethods();
  154. }
  155. if (strtolower($wannaBakeCrud) == 'y') {
  156. $actions = $this->bakeActions($controllerName, null, strtolower($wannaUseSession) == 'y');
  157. }
  158. if (strtolower($wannaBakeAdminCrud) == 'y') {
  159. $admin = $this->Project->getPrefix();
  160. $actions .= $this->bakeActions($controllerName, $admin, strtolower($wannaUseSession) == 'y');
  161. }
  162. $baked = false;
  163. if ($this->interactive === true) {
  164. $this->confirmController($controllerName, $useDynamicScaffold, $helpers, $components);
  165. $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y','n'), 'y');
  166. if (strtolower($looksGood) == 'y') {
  167. $baked = $this->bake($controllerName, $actions, $helpers, $components);
  168. if ($baked && $this->_checkUnitTest()) {
  169. $this->bakeTest($controllerName);
  170. }
  171. }
  172. } else {
  173. $baked = $this->bake($controllerName, $actions, $helpers, $components);
  174. if ($baked && $this->_checkUnitTest()) {
  175. $this->bakeTest($controllerName);
  176. }
  177. }
  178. return $baked;
  179. }
  180. /**
  181. * Confirm a to be baked controller with the user
  182. *
  183. * @param string $controllerName
  184. * @param string $useDynamicScaffold
  185. * @param array $helpers
  186. * @param array $components
  187. * @return void
  188. */
  189. public function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
  190. $this->out();
  191. $this->hr();
  192. $this->out(__d('cake_console', 'The following controller will be created:'));
  193. $this->hr();
  194. $this->out(__d('cake_console', "Controller Name:\n\t%s", $controllerName));
  195. if (strtolower($useDynamicScaffold) == 'y') {
  196. $this->out("var \$scaffold;");
  197. }
  198. $properties = array(
  199. 'helpers' => __d('cake_console', 'Helpers:'),
  200. 'components' => __d('cake_console', 'Components:'),
  201. );
  202. foreach ($properties as $var => $title) {
  203. if (count($$var)) {
  204. $output = '';
  205. $length = count($$var);
  206. foreach ($$var as $i => $propElement) {
  207. if ($i != $length -1) {
  208. $output .= ucfirst($propElement) . ', ';
  209. } else {
  210. $output .= ucfirst($propElement);
  211. }
  212. }
  213. $this->out($title . "\n\t" . $output);
  214. }
  215. }
  216. $this->hr();
  217. }
  218. /**
  219. * Interact with the user and ask about which methods (admin or regular they want to bake)
  220. *
  221. * @return array Array containing (bakeRegular, bakeAdmin) answers
  222. */
  223. protected function _askAboutMethods() {
  224. $wannaBakeCrud = $this->in(
  225. __d('cake_console', "Would you like to create some basic class methods \n(index(), add(), view(), edit())?"),
  226. array('y','n'), 'n'
  227. );
  228. $wannaBakeAdminCrud = $this->in(
  229. __d('cake_console', "Would you like to create the basic class methods for admin routing?"),
  230. array('y','n'), 'n'
  231. );
  232. return array($wannaBakeCrud, $wannaBakeAdminCrud);
  233. }
  234. /**
  235. * Bake scaffold actions
  236. *
  237. * @param string $controllerName Controller name
  238. * @param string $admin Admin route to use
  239. * @param boolean $wannaUseSession Set to true to use sessions, false otherwise
  240. * @return string Baked actions
  241. */
  242. public function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
  243. $currentModelName = $modelImport = $this->_modelName($controllerName);
  244. $plugin = $this->plugin;
  245. if ($plugin) {
  246. $plugin .= '.';
  247. }
  248. App::uses($modelImport, $plugin . 'Model');
  249. if (!class_exists($modelImport)) {
  250. $this->err(__d('cake_console', 'You must have a model for this class to build basic methods. Please try again.'));
  251. $this->_stop();
  252. }
  253. $modelObj = ClassRegistry::init($currentModelName);
  254. $controllerPath = $this->_controllerPath($controllerName);
  255. $pluralName = $this->_pluralName($currentModelName);
  256. $singularName = Inflector::variable($currentModelName);
  257. $singularHumanName = $this->_singularHumanName($controllerName);
  258. $pluralHumanName = $this->_pluralName($controllerName);
  259. $displayField = $modelObj->displayField;
  260. $primaryKey = $modelObj->primaryKey;
  261. $this->Template->set(compact(
  262. 'plugin', 'admin', 'controllerPath', 'pluralName', 'singularName',
  263. 'singularHumanName', 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName',
  264. 'displayField', 'primaryKey'
  265. ));
  266. $actions = $this->Template->generate('actions', 'controller_actions');
  267. return $actions;
  268. }
  269. /**
  270. * Assembles and writes a Controller file
  271. *
  272. * @param string $controllerName Controller name already pluralized and correctly cased.
  273. * @param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
  274. * @param array $helpers Helpers to use in controller
  275. * @param array $components Components to use in controller
  276. * @return string Baked controller
  277. */
  278. public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
  279. $this->out("\n" . __d('cake_console', 'Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
  280. $isScaffold = ($actions === 'scaffold') ? true : false;
  281. $this->Template->set(array(
  282. 'plugin' => $this->plugin,
  283. 'pluginPath' => empty($this->plugin) ? '' : $this->plugin . '.'
  284. ));
  285. $this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
  286. $contents = $this->Template->generate('classes', 'controller');
  287. $path = $this->getPath();
  288. $filename = $path . $controllerName . 'Controller.php';
  289. if ($this->createFile($filename, $contents)) {
  290. return $contents;
  291. }
  292. return false;
  293. }
  294. /**
  295. * Assembles and writes a unit test file
  296. *
  297. * @param string $className Controller class name
  298. * @return string Baked test
  299. */
  300. public function bakeTest($className) {
  301. $this->Test->plugin = $this->plugin;
  302. $this->Test->connection = $this->connection;
  303. $this->Test->interactive = $this->interactive;
  304. return $this->Test->bake('Controller', $className);
  305. }
  306. /**
  307. * Interact with the user and get a list of additional helpers
  308. *
  309. * @return array Helpers that the user wants to use.
  310. */
  311. public function doHelpers() {
  312. return $this->_doPropertyChoices(
  313. __d('cake_console', "Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?"),
  314. __d('cake_console', "Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Ajax, Javascript, Time'")
  315. );
  316. }
  317. /**
  318. * Interact with the user and get a list of additional components
  319. *
  320. * @return array Components the user wants to use.
  321. */
  322. public function doComponents() {
  323. return $this->_doPropertyChoices(
  324. __d('cake_console', "Would you like this controller to use any components?"),
  325. __d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
  326. );
  327. }
  328. /**
  329. * Common code for property choice handling.
  330. *
  331. * @param string $prompt A yes/no question to precede the list
  332. * @param string $example A question for a comma separated list, with examples.
  333. * @return array Array of values for property.
  334. */
  335. protected function _doPropertyChoices($prompt, $example) {
  336. $proceed = $this->in($prompt, array('y','n'), 'n');
  337. $property = array();
  338. if (strtolower($proceed) == 'y') {
  339. $propertyList = $this->in($example);
  340. $propertyListTrimmed = str_replace(' ', '', $propertyList);
  341. $property = explode(',', $propertyListTrimmed);
  342. }
  343. return array_filter($property);
  344. }
  345. /**
  346. * Outputs and gets the list of possible controllers from database
  347. *
  348. * @param string $useDbConfig Database configuration name
  349. * @return array Set of controllers
  350. */
  351. public function listAll($useDbConfig = null) {
  352. if (is_null($useDbConfig)) {
  353. $useDbConfig = $this->connection;
  354. }
  355. $this->__tables = $this->Model->getAllTables($useDbConfig);
  356. if ($this->interactive == true) {
  357. $this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
  358. $this->_controllerNames = array();
  359. $count = count($this->__tables);
  360. for ($i = 0; $i < $count; $i++) {
  361. $this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
  362. $this->out($i + 1 . ". " . $this->_controllerNames[$i]);
  363. }
  364. return $this->_controllerNames;
  365. }
  366. return $this->__tables;
  367. }
  368. /**
  369. * Forces the user to specify the controller he wants to bake, and returns the selected controller name.
  370. *
  371. * @param string $useDbConfig Connection name to get a controller name for.
  372. * @return string Controller name
  373. */
  374. public function getName($useDbConfig = null) {
  375. $controllers = $this->listAll($useDbConfig);
  376. $enteredController = '';
  377. while ($enteredController == '') {
  378. $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');
  379. if ($enteredController === 'q') {
  380. $this->out(__d('cake_console', 'Exit'));
  381. return $this->_stop();
  382. }
  383. if ($enteredController == '' || intval($enteredController) > count($controllers)) {
  384. $this->err(__d('cake_console', "The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again."));
  385. $enteredController = '';
  386. }
  387. }
  388. if (intval($enteredController) > 0 && intval($enteredController) <= count($controllers) ) {
  389. $controllerName = $controllers[intval($enteredController) - 1];
  390. } else {
  391. $controllerName = Inflector::camelize($enteredController);
  392. }
  393. return $controllerName;
  394. }
  395. /**
  396. * get the option parser.
  397. *
  398. * @return void
  399. */
  400. public function getOptionParser() {
  401. $parser = parent::getOptionParser();
  402. return $parser->description(
  403. __d('cake_console', 'Bake a controller for a model. Using options you can bake public, admin or both.')
  404. )->addArgument('name', array(
  405. 'help' => __d('cake_console', 'Name of the controller to bake. Can use Plugin.name to bake controllers into plugins.')
  406. ))->addOption('public', array(
  407. 'help' => __d('cake_console', 'Bake a controller with basic crud actions (index, view, add, edit, delete).'),
  408. 'boolean' => true
  409. ))->addOption('admin', array(
  410. 'help' => __d('cake_console', 'Bake a controller with crud actions for one of the Routing.prefixes.'),
  411. 'boolean' => true
  412. ))->addOption('plugin', array(
  413. 'short' => 'p',
  414. 'help' => __d('cake_console', 'Plugin to bake the controller into.')
  415. ))->addOption('connection', array(
  416. 'short' => 'c',
  417. 'help' => __d('cake_console', 'The connection the controller\'s model is on.')
  418. ))->addSubcommand('all', array(
  419. 'help' => __d('cake_console', 'Bake all controllers with CRUD methods.')
  420. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  421. }
  422. /**
  423. * Displays help contents
  424. *
  425. * @return void
  426. */
  427. public function help() {
  428. $this->hr();
  429. $this->out("Usage: cake bake controller <arg1> <arg2>...");
  430. $this->hr();
  431. $this->out('Arguments:');
  432. $this->out();
  433. $this->out("<name>");
  434. $this->out("\tName of the controller to bake. Can use Plugin.name");
  435. $this->out("\tas a shortcut for plugin baking.");
  436. $this->out();
  437. $this->out('Params:');
  438. $this->out();
  439. $this->out('-connection <config>');
  440. $this->out("\tset db config <config>. uses 'default' if none is specified");
  441. $this->out();
  442. $this->out('Commands:');
  443. $this->out();
  444. $this->out("controller <name>");
  445. $this->out("\tbakes controller with var \$scaffold");
  446. $this->out();
  447. $this->out("controller <name> public");
  448. $this->out("\tbakes controller with basic crud actions");
  449. $this->out("\t(index, view, add, edit, delete)");
  450. $this->out();
  451. $this->out("controller <name> admin");
  452. $this->out("\tbakes a controller with basic crud actions for one of the");
  453. $this->out("\tConfigure::read('Routing.prefixes') methods.");
  454. $this->out();
  455. $this->out("controller <name> public admin");
  456. $this->out("\tbakes a controller with basic crud actions for one");
  457. $this->out("\tConfigure::read('Routing.prefixes') and non admin methods.");
  458. $this->out("\t(index, view, add, edit, delete,");
  459. $this->out("\tadmin_index, admin_view, admin_edit, admin_add, admin_delete)");
  460. $this->out();
  461. $this->out("controller all");
  462. $this->out("\tbakes all controllers with CRUD methods.");
  463. $this->out();
  464. $this->_stop();
  465. }
  466. }