ControllerTask.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  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-2010, 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-2010, Cake Software Foundation, Inc. (http://cakefoundation.org)
  14. * @link http://cakephp.org CakePHP(tm) Project
  15. * @package cake.console.shells.tasks
  16. * @since CakePHP(tm) v 1.2
  17. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  18. */
  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.shells.tasks
  25. */
  26. class ControllerTask extends BakeTask {
  27. /**
  28. * Tasks to be loaded by this Task
  29. *
  30. * @var array
  31. * @access public
  32. */
  33. public $tasks = array('Model', 'Test', 'Template', 'DbConfig', 'Project');
  34. /**
  35. * path to CONTROLLERS directory
  36. *
  37. * @var array
  38. * @access public
  39. */
  40. public $path = CONTROLLERS;
  41. /**
  42. * Override initialize
  43. *
  44. */
  45. public function initialize() {
  46. }
  47. /**
  48. * Execution method always used for tasks
  49. *
  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. * @return void
  184. */
  185. public function confirmController($controllerName, $useDynamicScaffold, $helpers, $components) {
  186. $this->out();
  187. $this->hr();
  188. $this->out(__d('cake_console', 'The following controller will be created:'));
  189. $this->hr();
  190. $this->out(__d('cake_console', "Controller Name:\n\t%s", $controllerName));
  191. if (strtolower($useDynamicScaffold) == 'y') {
  192. $this->out("var \$scaffold;");
  193. }
  194. $properties = array(
  195. 'helpers' => __d('cake_console', 'Helpers:'),
  196. 'components' => __d('cake_console', 'Components:'),
  197. );
  198. foreach ($properties as $var => $title) {
  199. if (count($$var)) {
  200. $output = '';
  201. $length = count($$var);
  202. foreach ($$var as $i => $propElement) {
  203. if ($i != $length -1) {
  204. $output .= ucfirst($propElement) . ', ';
  205. } else {
  206. $output .= ucfirst($propElement);
  207. }
  208. }
  209. $this->out($title . "\n\t" . $output);
  210. }
  211. }
  212. $this->hr();
  213. }
  214. /**
  215. * Interact with the user and ask about which methods (admin or regular they want to bake)
  216. *
  217. * @return array Array containing (bakeRegular, bakeAdmin) answers
  218. */
  219. protected function _askAboutMethods() {
  220. $wannaBakeCrud = $this->in(
  221. __d('cake_console', "Would you like to create some basic class methods \n(index(), add(), view(), edit())?"),
  222. array('y','n'), 'n'
  223. );
  224. $wannaBakeAdminCrud = $this->in(
  225. __d('cake_console', "Would you like to create the basic class methods for admin routing?"),
  226. array('y','n'), 'n'
  227. );
  228. return array($wannaBakeCrud, $wannaBakeAdminCrud);
  229. }
  230. /**
  231. * Bake scaffold actions
  232. *
  233. * @param string $controllerName Controller name
  234. * @param string $admin Admin route to use
  235. * @param boolean $wannaUseSession Set to true to use sessions, false otherwise
  236. * @return string Baked actions
  237. * @access private
  238. */
  239. public function bakeActions($controllerName, $admin = null, $wannaUseSession = true) {
  240. $currentModelName = $modelImport = $this->_modelName($controllerName);
  241. $plugin = $this->plugin;
  242. if ($plugin) {
  243. $plugin .= '.';
  244. }
  245. App::uses($modelImport, $plugin . 'Model');
  246. if (!class_exists($modelImport)) {
  247. $this->err(__d('cake_console', 'You must have a model for this class to build basic methods. Please try again.'));
  248. $this->_stop();
  249. }
  250. $modelObj = ClassRegistry::init($currentModelName);
  251. $controllerPath = $this->_controllerPath($controllerName);
  252. $pluralName = $this->_pluralName($currentModelName);
  253. $singularName = Inflector::variable($currentModelName);
  254. $singularHumanName = $this->_singularHumanName($controllerName);
  255. $pluralHumanName = $this->_pluralName($controllerName);
  256. $displayField = $modelObj->displayField;
  257. $primaryKey = $modelObj->primaryKey;
  258. $this->Template->set(compact('plugin', 'admin', 'controllerPath', 'pluralName', 'singularName',
  259. 'singularHumanName', 'pluralHumanName', 'modelObj', 'wannaUseSession', 'currentModelName',
  260. 'displayField', 'primaryKey'
  261. ));
  262. $actions = $this->Template->generate('actions', 'controller_actions');
  263. return $actions;
  264. }
  265. /**
  266. * Assembles and writes a Controller file
  267. *
  268. * @param string $controllerName Controller name
  269. * @param string $actions Actions to add, or set the whole controller to use $scaffold (set $actions to 'scaffold')
  270. * @param array $helpers Helpers to use in controller
  271. * @param array $components Components to use in controller
  272. * @param array $uses Models to use in controller
  273. * @return string Baked controller
  274. */
  275. public function bake($controllerName, $actions = '', $helpers = null, $components = null) {
  276. $this->out("\n" . __d('cake_console', 'Baking controller class for %s...', $controllerName), 1, Shell::QUIET);
  277. $isScaffold = ($actions === 'scaffold') ? true : false;
  278. $this->Template->set('plugin', Inflector::camelize($this->plugin));
  279. $this->Template->set(compact('controllerName', 'actions', 'helpers', 'components', 'isScaffold'));
  280. $contents = $this->Template->generate('classes', 'controller');
  281. $path = $this->getPath();
  282. $filename = $path . $this->_controllerName($controllerName) . 'Controller.php';
  283. if ($this->createFile($filename, $contents)) {
  284. return $contents;
  285. }
  286. return false;
  287. }
  288. /**
  289. * Assembles and writes a unit test file
  290. *
  291. * @param string $className Controller class name
  292. * @return string Baked test
  293. */
  294. public function bakeTest($className) {
  295. $this->Test->plugin = $this->plugin;
  296. $this->Test->connection = $this->connection;
  297. $this->Test->interactive = $this->interactive;
  298. return $this->Test->bake('Controller', $className);
  299. }
  300. /**
  301. * Interact with the user and get a list of additional helpers
  302. *
  303. * @return array Helpers that the user wants to use.
  304. */
  305. public function doHelpers() {
  306. return $this->_doPropertyChoices(
  307. __d('cake_console', "Would you like this controller to use other helpers\nbesides HtmlHelper and FormHelper?"),
  308. __d('cake_console', "Please provide a comma separated list of the other\nhelper names you'd like to use.\nExample: 'Ajax, Javascript, Time'")
  309. );
  310. }
  311. /**
  312. * Interact with the user and get a list of additional components
  313. *
  314. * @return array Components the user wants to use.
  315. */
  316. public function doComponents() {
  317. return $this->_doPropertyChoices(
  318. __d('cake_console', "Would you like this controller to use any components?"),
  319. __d('cake_console', "Please provide a comma separated list of the component names you'd like to use.\nExample: 'Acl, Security, RequestHandler'")
  320. );
  321. }
  322. /**
  323. * Common code for property choice handling.
  324. *
  325. * @param string $prompt A yes/no question to precede the list
  326. * @param sting $example A question for a comma separated list, with examples.
  327. * @return array Array of values for property.
  328. */
  329. protected function _doPropertyChoices($prompt, $example) {
  330. $proceed = $this->in($prompt, array('y','n'), 'n');
  331. $property = array();
  332. if (strtolower($proceed) == 'y') {
  333. $propertyList = $this->in($example);
  334. $propertyListTrimmed = str_replace(' ', '', $propertyList);
  335. $property = explode(',', $propertyListTrimmed);
  336. }
  337. return array_filter($property);
  338. }
  339. /**
  340. * Outputs and gets the list of possible controllers from database
  341. *
  342. * @param string $useDbConfig Database configuration name
  343. * @param boolean $interactive Whether you are using listAll interactively and want options output.
  344. * @return array Set of controllers
  345. */
  346. public function listAll($useDbConfig = null) {
  347. if (is_null($useDbConfig)) {
  348. $useDbConfig = $this->connection;
  349. }
  350. $this->__tables = $this->Model->getAllTables($useDbConfig);
  351. if ($this->interactive == true) {
  352. $this->out(__d('cake_console', 'Possible Controllers based on your current database:'));
  353. $this->_controllerNames = array();
  354. $count = count($this->__tables);
  355. for ($i = 0; $i < $count; $i++) {
  356. $this->_controllerNames[] = $this->_controllerName($this->_modelName($this->__tables[$i]));
  357. $this->out($i + 1 . ". " . $this->_controllerNames[$i]);
  358. }
  359. return $this->_controllerNames;
  360. }
  361. return $this->__tables;
  362. }
  363. /**
  364. * Forces the user to specify the controller he wants to bake, and returns the selected controller name.
  365. *
  366. * @param string $useDbConfig Connection name to get a controller name for.
  367. * @return string Controller name
  368. */
  369. public function getName($useDbConfig = null) {
  370. $controllers = $this->listAll($useDbConfig);
  371. $enteredController = '';
  372. while ($enteredController == '') {
  373. $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');
  374. if ($enteredController === 'q') {
  375. $this->out(__d('cake_console', 'Exit'));
  376. return $this->_stop();
  377. }
  378. if ($enteredController == '' || intval($enteredController) > count($controllers)) {
  379. $this->err(__d('cake_console', "The Controller name you supplied was empty,\nor the number you selected was not an option. Please try again."));
  380. $enteredController = '';
  381. }
  382. }
  383. if (intval($enteredController) > 0 && intval($enteredController) <= count($controllers) ) {
  384. $controllerName = $controllers[intval($enteredController) - 1];
  385. } else {
  386. $controllerName = Inflector::camelize($enteredController);
  387. }
  388. return $controllerName;
  389. }
  390. /**
  391. * get the option parser.
  392. *
  393. * @return void
  394. */
  395. public function getOptionParser() {
  396. $parser = parent::getOptionParser();
  397. return $parser->description(
  398. __d('cake_console', 'Bake a controller for a model. Using options you can bake public, admin or both.')
  399. )->addArgument('name', array(
  400. 'help' => __d('cake_console', 'Name of the controller to bake. Can use Plugin.name to bake controllers into plugins.')
  401. ))->addOption('public', array(
  402. 'help' => __d('cake_console', 'Bake a controller with basic crud actions (index, view, add, edit, delete).'),
  403. 'boolean' => true
  404. ))->addOption('admin', array(
  405. 'help' => __d('cake_console', 'Bake a controller with crud actions for one of the Routing.prefixes.'),
  406. 'boolean' => true
  407. ))->addOption('plugin', array(
  408. 'short' => 'p',
  409. 'help' => __d('cake_console', 'Plugin to bake the controller into.')
  410. ))->addOption('connection', array(
  411. 'short' => 'c',
  412. 'help' => __d('cake_console', 'The connection the controller\'s model is on.')
  413. ))->addSubcommand('all', array(
  414. 'help' => __d('cake_console', 'Bake all controllers with CRUD methods.')
  415. ))->epilog(__d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.'));
  416. }
  417. /**
  418. * Displays help contents
  419. *
  420. */
  421. public function help() {
  422. $this->hr();
  423. $this->out("Usage: cake bake controller <arg1> <arg2>...");
  424. $this->hr();
  425. $this->out('Arguments:');
  426. $this->out();
  427. $this->out("<name>");
  428. $this->out("\tName of the controller to bake. Can use Plugin.name");
  429. $this->out("\tas a shortcut for plugin baking.");
  430. $this->out();
  431. $this->out('Commands:');
  432. $this->out();
  433. $this->out("controller <name>");
  434. $this->out("\tbakes controller with var \$scaffold");
  435. $this->out();
  436. $this->out("controller <name> public");
  437. $this->out("\tbakes controller with basic crud actions");
  438. $this->out("\t(index, view, add, edit, delete)");
  439. $this->out();
  440. $this->out("controller <name> admin");
  441. $this->out("\tbakes a controller with basic crud actions for one of the");
  442. $this->out("\tConfigure::read('Routing.prefixes') methods.");
  443. $this->out();
  444. $this->out("controller <name> public admin");
  445. $this->out("\tbakes a controller with basic crud actions for one");
  446. $this->out("\tConfigure::read('Routing.prefixes') and non admin methods.");
  447. $this->out("\t(index, view, add, edit, delete,");
  448. $this->out("\tadmin_index, admin_view, admin_edit, admin_add, admin_delete)");
  449. $this->out();
  450. $this->out("controller all");
  451. $this->out("\tbakes all controllers with CRUD methods.");
  452. $this->out();
  453. $this->_stop();
  454. }
  455. }