ViewTask.php 14 KB

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