ViewTask.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. <?php
  2. /**
  3. * The View Tasks handles creating and updating view 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('Controller', 'Controller');
  19. App::uses('BakeTask', 'Console/Command/Task');
  20. /**
  21. * Task class for creating and updating view files.
  22. *
  23. * @package Cake.Console.Command.Task
  24. */
  25. class ViewTask extends BakeTask {
  26. /**
  27. * Tasks to be loaded by this Task
  28. *
  29. * @var array
  30. */
  31. public $tasks = array('Project', 'Controller', 'DbConfig', 'Template');
  32. /**
  33. * path to View directory
  34. *
  35. * @var array
  36. */
  37. public $path = null;
  38. /**
  39. * Name of the controller being used
  40. *
  41. * @var string
  42. */
  43. public $controllerName = null;
  44. /**
  45. * The template file to use
  46. *
  47. * @var string
  48. */
  49. public $template = null;
  50. /**
  51. * Actions to use for scaffolding
  52. *
  53. * @var array
  54. */
  55. public $scaffoldActions = array('index', 'view', 'add', 'edit');
  56. /**
  57. * An array of action names that don't require templates. These
  58. * actions will not emit errors when doing bakeActions()
  59. *
  60. * @var array
  61. */
  62. public $noTemplateActions = array('delete');
  63. /**
  64. * Override initialize
  65. *
  66. * @return void
  67. */
  68. public function initialize() {
  69. $this->path = current(App::path('View'));
  70. }
  71. /**
  72. * Execution method always used for tasks
  73. *
  74. * @return mixed
  75. */
  76. public function execute() {
  77. parent::execute();
  78. if (empty($this->args)) {
  79. $this->_interactive();
  80. }
  81. if (empty($this->args[0])) {
  82. return;
  83. }
  84. if (!isset($this->connection)) {
  85. $this->connection = 'default';
  86. }
  87. $action = null;
  88. $this->controllerName = $this->_controllerName($this->args[0]);
  89. $this->Project->interactive = false;
  90. if (strtolower($this->args[0]) === 'all') {
  91. return $this->all();
  92. }
  93. if (isset($this->args[1])) {
  94. $this->template = $this->args[1];
  95. }
  96. if (isset($this->args[2])) {
  97. $action = $this->args[2];
  98. }
  99. if (!$action) {
  100. $action = $this->template;
  101. }
  102. if ($action) {
  103. return $this->bake($action, true);
  104. }
  105. $vars = $this->_loadController();
  106. $methods = $this->_methodsToBake();
  107. foreach ($methods as $method) {
  108. $content = $this->getContent($method, $vars);
  109. if ($content) {
  110. $this->bake($method, $content);
  111. }
  112. }
  113. }
  114. /**
  115. * Get a list of actions that can / should have views baked for them.
  116. *
  117. * @return array Array of action names that should be baked
  118. */
  119. protected function _methodsToBake() {
  120. $methods = array_diff(
  121. array_map('strtolower', get_class_methods($this->controllerName . 'Controller')),
  122. array_map('strtolower', get_class_methods('AppController'))
  123. );
  124. $scaffoldActions = false;
  125. if (empty($methods)) {
  126. $scaffoldActions = true;
  127. $methods = $this->scaffoldActions;
  128. }
  129. $adminRoute = $this->Project->getPrefix();
  130. foreach ($methods as $i => $method) {
  131. if ($adminRoute && !empty($this->params['admin'])) {
  132. if ($scaffoldActions) {
  133. $methods[$i] = $adminRoute . $method;
  134. continue;
  135. } elseif (strpos($method, $adminRoute) === false) {
  136. unset($methods[$i]);
  137. }
  138. }
  139. if ($method[0] === '_' || $method === strtolower($this->controllerName . 'Controller')) {
  140. unset($methods[$i]);
  141. }
  142. }
  143. return $methods;
  144. }
  145. /**
  146. * Bake All views for All controllers.
  147. *
  148. * @return void
  149. */
  150. public function all() {
  151. $this->Controller->interactive = false;
  152. $tables = $this->Controller->listAll($this->connection, false);
  153. $actions = null;
  154. if (isset($this->args[1])) {
  155. $actions = array($this->args[1]);
  156. }
  157. $this->interactive = false;
  158. foreach ($tables as $table) {
  159. $model = $this->_modelName($table);
  160. $this->controllerName = $this->_controllerName($model);
  161. App::uses($model, 'Model');
  162. if (class_exists($model)) {
  163. $vars = $this->_loadController();
  164. if (!$actions) {
  165. $actions = $this->_methodsToBake();
  166. }
  167. $this->bakeActions($actions, $vars);
  168. $actions = null;
  169. }
  170. }
  171. }
  172. /**
  173. * Handles interactive baking
  174. *
  175. * @return void
  176. */
  177. protected function _interactive() {
  178. $this->hr();
  179. $this->out(sprintf("Bake View\nPath: %s", $this->getPath()));
  180. $this->hr();
  181. $this->DbConfig->interactive = $this->Controller->interactive = $this->interactive = true;
  182. if (empty($this->connection)) {
  183. $this->connection = $this->DbConfig->getConfig();
  184. }
  185. $this->Controller->connection = $this->connection;
  186. $this->controllerName = $this->Controller->getName();
  187. $prompt = __d('cake_console', "Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", $this->controllerName);
  188. $interactive = $this->in($prompt, array('y', 'n'), 'n');
  189. if (strtolower($interactive) === 'n') {
  190. $this->interactive = false;
  191. }
  192. $prompt = __d('cake_console', "Would you like to create some CRUD views\n(index, add, view, edit) for this controller?\nNOTE: Before doing so, you'll need to create your controller\nand model classes (including associated models).");
  193. $wannaDoScaffold = $this->in($prompt, array('y', 'n'), 'y');
  194. $wannaDoAdmin = $this->in(__d('cake_console', "Would you like to create the views for admin routing?"), array('y', 'n'), 'n');
  195. if (strtolower($wannaDoScaffold) === 'y' || strtolower($wannaDoAdmin) === 'y') {
  196. $vars = $this->_loadController();
  197. if (strtolower($wannaDoScaffold) === 'y') {
  198. $actions = $this->scaffoldActions;
  199. $this->bakeActions($actions, $vars);
  200. }
  201. if (strtolower($wannaDoAdmin) === 'y') {
  202. $admin = $this->Project->getPrefix();
  203. $regularActions = $this->scaffoldActions;
  204. $adminActions = array();
  205. foreach ($regularActions as $action) {
  206. $adminActions[] = $admin . $action;
  207. }
  208. $this->bakeActions($adminActions, $vars);
  209. }
  210. $this->hr();
  211. $this->out();
  212. $this->out(__d('cake_console', "View Scaffolding Complete.\n"));
  213. } else {
  214. $this->customAction();
  215. }
  216. }
  217. /**
  218. * Loads Controller and sets variables for the template
  219. * Available template variables
  220. * 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  221. * 'singularHumanName', 'pluralHumanName', 'fields', 'foreignKeys',
  222. * 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  223. *
  224. * @return array Returns an variables to be made available to a view template
  225. */
  226. protected function _loadController() {
  227. if (!$this->controllerName) {
  228. $this->err(__d('cake_console', 'Controller not found'));
  229. }
  230. $plugin = null;
  231. if ($this->plugin) {
  232. $plugin = $this->plugin . '.';
  233. }
  234. $controllerClassName = $this->controllerName . 'Controller';
  235. App::uses($controllerClassName, $plugin . 'Controller');
  236. if (!class_exists($controllerClassName)) {
  237. $file = $controllerClassName . '.php';
  238. $this->err(__d('cake_console', "The file '%s' could not be found.\nIn order to bake a view, you'll need to first create the controller.", $file));
  239. return $this->_stop();
  240. }
  241. $controllerObj = new $controllerClassName();
  242. $controllerObj->plugin = $this->plugin;
  243. $controllerObj->constructClasses();
  244. $modelClass = $controllerObj->modelClass;
  245. $modelObj = $controllerObj->{$controllerObj->modelClass};
  246. if ($modelObj) {
  247. $primaryKey = $modelObj->primaryKey;
  248. $displayField = $modelObj->displayField;
  249. $singularVar = Inflector::variable($modelClass);
  250. $singularHumanName = $this->_singularHumanName($this->controllerName);
  251. $schema = $modelObj->schema(true);
  252. $fields = array_keys($schema);
  253. $associations = $this->_associations($modelObj);
  254. } else {
  255. $primaryKey = $displayField = null;
  256. $singularVar = Inflector::variable(Inflector::singularize($this->controllerName));
  257. $singularHumanName = $this->_singularHumanName($this->controllerName);
  258. $fields = $schema = $associations = array();
  259. }
  260. $pluralVar = Inflector::variable($this->controllerName);
  261. $pluralHumanName = $this->_pluralHumanName($this->controllerName);
  262. return compact('modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  263. 'singularHumanName', 'pluralHumanName', 'fields', 'associations');
  264. }
  265. /**
  266. * Bake a view file for each of the supplied actions
  267. *
  268. * @param array $actions Array of actions to make files for.
  269. * @param array $vars The template variables.
  270. * @return void
  271. */
  272. public function bakeActions($actions, $vars) {
  273. foreach ($actions as $action) {
  274. $content = $this->getContent($action, $vars);
  275. $this->bake($action, $content);
  276. }
  277. }
  278. /**
  279. * handle creation of baking a custom action view file
  280. *
  281. * @return void
  282. */
  283. public function customAction() {
  284. $action = '';
  285. while (!$action) {
  286. $action = $this->in(__d('cake_console', 'Action Name? (use lowercase_underscored function name)'));
  287. if (!$action) {
  288. $this->out(__d('cake_console', 'The action name you supplied was empty. Please try again.'));
  289. }
  290. }
  291. $this->out();
  292. $this->hr();
  293. $this->out(__d('cake_console', 'The following view will be created:'));
  294. $this->hr();
  295. $this->out(__d('cake_console', 'Controller Name: %s', $this->controllerName));
  296. $this->out(__d('cake_console', 'Action Name: %s', $action));
  297. $this->out(__d('cake_console', 'Path: %s', $this->getPath() . $this->controllerName . DS . Inflector::underscore($action) . ".ctp"));
  298. $this->hr();
  299. $looksGood = $this->in(__d('cake_console', 'Look okay?'), array('y', 'n'), 'y');
  300. if (strtolower($looksGood) === 'y') {
  301. $this->bake($action, ' ');
  302. return $this->_stop();
  303. }
  304. $this->out(__d('cake_console', 'Bake Aborted.'));
  305. }
  306. /**
  307. * Assembles and writes bakes the view file.
  308. *
  309. * @param string $action Action to bake
  310. * @param string $content Content to write
  311. * @return boolean Success
  312. */
  313. public function bake($action, $content = '') {
  314. if ($content === true) {
  315. $content = $this->getContent($action);
  316. }
  317. if (empty($content)) {
  318. return false;
  319. }
  320. $this->out("\n" . __d('cake_console', 'Baking `%s` view file...', $action), 1, Shell::QUIET);
  321. $path = $this->getPath();
  322. $filename = $path . $this->controllerName . DS . Inflector::underscore($action) . '.ctp';
  323. return $this->createFile($filename, $content);
  324. }
  325. /**
  326. * Builds content from template and variables
  327. *
  328. * @param string $action name to generate content to
  329. * @param array $vars passed for use in templates
  330. * @return string content from template
  331. */
  332. public function getContent($action, $vars = null) {
  333. if (!$vars) {
  334. $vars = $this->_loadController();
  335. }
  336. $this->Template->set('action', $action);
  337. $this->Template->set('plugin', $this->plugin);
  338. $this->Template->set($vars);
  339. $template = $this->getTemplate($action);
  340. if ($template) {
  341. return $this->Template->generate('views', $template);
  342. }
  343. return false;
  344. }
  345. /**
  346. * Gets the template name based on the action name
  347. *
  348. * @param string $action name
  349. * @return string template name
  350. */
  351. public function getTemplate($action) {
  352. if ($action != $this->template && in_array($action, $this->noTemplateActions)) {
  353. return false;
  354. }
  355. if (!empty($this->template) && $action != $this->template) {
  356. return $this->template;
  357. }
  358. $themePath = $this->Template->getThemePath();
  359. if (file_exists($themePath . 'views' . DS . $action . '.ctp')) {
  360. return $action;
  361. }
  362. $template = $action;
  363. $prefixes = Configure::read('Routing.prefixes');
  364. foreach ((array)$prefixes as $prefix) {
  365. if (strpos($template, $prefix) !== false) {
  366. $template = str_replace($prefix . '_', '', $template);
  367. }
  368. }
  369. if (in_array($template, array('add', 'edit'))) {
  370. $template = 'form';
  371. } elseif (preg_match('@(_add|_edit)$@', $template)) {
  372. $template = str_replace(array('_add', '_edit'), '_form', $template);
  373. }
  374. return $template;
  375. }
  376. /**
  377. * Gets the option parser instance and configures it.
  378. *
  379. * @return ConsoleOptionParser
  380. */
  381. public function getOptionParser() {
  382. $parser = parent::getOptionParser();
  383. $parser->description(
  384. __d('cake_console', 'Bake views for a controller, using built-in or custom templates.')
  385. )->addArgument('controller', array(
  386. 'help' => __d('cake_console', 'Name of the controller views to bake. Can be Plugin.name as a shortcut for plugin baking.')
  387. ))->addArgument('action', array(
  388. 'help' => __d('cake_console', "Will bake a single action's file. core templates are (index, add, edit, view)")
  389. ))->addArgument('alias', array(
  390. 'help' => __d('cake_console', 'Will bake the template in <action> but create the filename after <alias>.')
  391. ))->addOption('plugin', array(
  392. 'short' => 'p',
  393. 'help' => __d('cake_console', 'Plugin to bake the view into.')
  394. ))->addOption('admin', array(
  395. 'help' => __d('cake_console', 'Set to only bake views for a prefix in Routing.prefixes'),
  396. 'boolean' => true
  397. ))->addOption('theme', array(
  398. 'short' => 't',
  399. 'help' => __d('cake_console', 'Theme to use when baking code.')
  400. ))->addOption('connection', array(
  401. 'short' => 'c',
  402. 'help' => __d('cake_console', 'The connection the connected model is on.')
  403. ))->addOption('force', array(
  404. 'short' => 'f',
  405. 'help' => __d('cake_console', 'Force overwriting existing files without prompting.')
  406. ))->addSubcommand('all', array(
  407. 'help' => __d('cake_console', 'Bake all CRUD action views for all controllers. Requires models and controllers to exist.')
  408. ))->epilog(
  409. __d('cake_console', 'Omitting all arguments and options will enter into an interactive mode.')
  410. );
  411. return $parser;
  412. }
  413. /**
  414. * Returns associations for controllers models.
  415. *
  416. * @param Model $model The Model instance.
  417. * @return array $associations
  418. */
  419. protected function _associations(Model $model) {
  420. $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  421. $associations = array();
  422. foreach ($keys as $type) {
  423. foreach ($model->{$type} as $assocKey => $assocData) {
  424. list(, $modelClass) = pluginSplit($assocData['className']);
  425. $associations[$type][$assocKey]['primaryKey'] = $model->{$assocKey}->primaryKey;
  426. $associations[$type][$assocKey]['displayField'] = $model->{$assocKey}->displayField;
  427. $associations[$type][$assocKey]['foreignKey'] = $assocData['foreignKey'];
  428. $associations[$type][$assocKey]['controller'] = Inflector::pluralize(Inflector::underscore($modelClass));
  429. $associations[$type][$assocKey]['fields'] = array_keys($model->{$assocKey}->schema(true));
  430. }
  431. }
  432. return $associations;
  433. }
  434. }