PageRenderTime 49ms CodeModel.GetById 24ms RepoModel.GetById 1ms app.codeStats 0ms

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

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