ViewTask.php 14 KB

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