PageRenderTime 41ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/Cake/Console/Command/Task/ControllerTask.php

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