ViewTask.php 14 KB

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