PageRenderTime 54ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/cake/console/libs/tasks/view.php

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