PageRenderTime 48ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

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

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