ViewTask.php 14 KB

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