PageRenderTime 42ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/msadouni/cakephp2x
PHP | 473 lines | 305 code | 30 blank | 138 comment | 45 complexity | 1c7ab2f989aecdeb02740a0bfc903bb1 MD5 | raw file
  1. <?php
  2. /**
  3. * The View Tasks handles creating and updating view files.
  4. *
  5. * Long description for file
  6. *
  7. * PHP Version 5.x
  8. *
  9. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  10. * Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. *
  12. * Licensed under The MIT License
  13. * Redistributions of files must retain the above copyright notice.
  14. *
  15. * @copyright Copyright 2005-2009, Cake Software Foundation, Inc. (http://cakefoundation.org)
  16. * @link http://cakephp.org CakePHP(tm) Project
  17. * @package cake
  18. * @subpackage cake.cake.console.libs.tasks
  19. * @since CakePHP(tm) v 1.2
  20. * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
  21. */
  22. App::import('Controller', 'Controller', false);
  23. /**
  24. * Task class for creating and updating view files.
  25. *
  26. * @package cake
  27. * @subpackage cake.cake.console.libs.tasks
  28. */
  29. class ViewTask extends Shell {
  30. /**
  31. * Name of plugin
  32. *
  33. * @var string
  34. * @access public
  35. */
  36. var $plugin = null;
  37. /**
  38. * Tasks to be loaded by this Task
  39. *
  40. * @var array
  41. * @access public
  42. */
  43. var $tasks = array('Project', 'Controller', 'DbConfig', 'Template');
  44. /**
  45. * path to VIEWS directory
  46. *
  47. * @var array
  48. * @access public
  49. */
  50. var $path = VIEWS;
  51. /**
  52. * Name of the controller being used
  53. *
  54. * @var string
  55. * @access public
  56. */
  57. var $controllerName = null;
  58. /**
  59. * Path to controller to put views
  60. *
  61. * @var string
  62. * @access public
  63. */
  64. var $controllerPath = null;
  65. /**
  66. * The template file to use
  67. *
  68. * @var string
  69. * @access public
  70. */
  71. var $template = null;
  72. /**
  73. * Actions to use for scaffolding
  74. *
  75. * @var array
  76. * @access public
  77. */
  78. var $scaffoldActions = array('index', 'view', 'add', 'edit');
  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 = Inflector::camelize($this->args[0]);
  103. $this->controllerPath = Inflector::underscore($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. $this->interactive = false;
  169. foreach ($tables as $table) {
  170. $model = $this->_modelName($table);
  171. $this->controllerName = $this->_controllerName($model);
  172. $this->controllerPath = Inflector::underscore($this->controllerName);
  173. if (App::import('Model', $model)) {
  174. $vars = $this->__loadController();
  175. $actions = $this->_methodsToBake();
  176. $this->bakeActions($actions, $vars);
  177. }
  178. }
  179. }
  180. /**
  181. * Handles interactive baking
  182. *
  183. * @access private
  184. */
  185. function __interactive() {
  186. $this->hr();
  187. $this->out(sprintf("Bake View\nPath: %s", $this->path));
  188. $this->hr();
  189. if (empty($this->connection)) {
  190. $this->connection = $this->DbConfig->getConfig();
  191. }
  192. $this->Controller->connection = $this->connection;
  193. $this->controllerName = $this->Controller->getName();
  194. $this->controllerPath = strtolower(Inflector::underscore($this->controllerName));
  195. $prompt = sprintf(__("Would you like bake to build your views interactively?\nWarning: Choosing no will overwrite %s views if it exist.", true), $this->controllerName);
  196. $interactive = $this->in($prompt, array('y', 'n'), 'n');
  197. if (strtolower($interactive) == 'n') {
  198. $this->interactive = false;
  199. }
  200. $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);
  201. $wannaDoScaffold = $this->in($prompt, array('y','n'), 'y');
  202. $wannaDoAdmin = $this->in(__("Would you like to create the views for admin routing?", true), array('y','n'), 'n');
  203. if (strtolower($wannaDoScaffold) == 'y' || strtolower($wannaDoAdmin) == 'y') {
  204. $vars = $this->__loadController();
  205. if (strtolower($wannaDoScaffold) == 'y') {
  206. $actions = $this->scaffoldActions;
  207. $this->bakeActions($actions, $vars);
  208. }
  209. if (strtolower($wannaDoAdmin) == 'y') {
  210. $admin = $this->Project->getPrefix();
  211. $regularActions = $this->scaffoldActions;
  212. $adminActions = array();
  213. foreach ($regularActions as $action) {
  214. $adminActions[] = $admin . $action;
  215. }
  216. $this->bakeActions($adminActions, $vars);
  217. }
  218. $this->hr();
  219. $this->out();
  220. $this->out(__("View Scaffolding Complete.\n", true));
  221. } else {
  222. $this->customAction();
  223. }
  224. }
  225. /**
  226. * Loads Controller and sets variables for the template
  227. * Available template variables
  228. * 'modelClass', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  229. * 'singularHumanName', 'pluralHumanName', 'fields', 'foreignKeys',
  230. * 'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
  231. *
  232. * @return array Returns an variables to be made available to a view template
  233. * @access private
  234. */
  235. function __loadController() {
  236. if (!$this->controllerName) {
  237. $this->err(__('Controller not found', true));
  238. }
  239. $import = $this->controllerName;
  240. if ($this->plugin) {
  241. $import = $this->plugin . '.' . $this->controllerName;
  242. }
  243. if (!App::import('Controller', $import)) {
  244. $file = $this->controllerPath . '_controller.php';
  245. $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));
  246. $this->_stop();
  247. }
  248. $controllerClassName = $this->controllerName . 'Controller';
  249. $controllerObj = new $controllerClassName();
  250. $controllerObj->constructClasses();
  251. $modelClass = $controllerObj->modelClass;
  252. $modelObj = ClassRegistry::getObject($controllerObj->modelKey);
  253. if ($modelObj) {
  254. $primaryKey = $modelObj->primaryKey;
  255. $displayField = $modelObj->displayField;
  256. $singularVar = Inflector::variable($modelClass);
  257. $singularHumanName = $this->_singularHumanName($modelClass);
  258. $schema = $modelObj->schema();
  259. $fields = array_keys($schema);
  260. $associations = $this->__associations($modelObj);
  261. } else {
  262. $primaryKey = null;
  263. $displayField = null;
  264. $singularVar = Inflector::variable(Inflector::singularize($this->controllerName));
  265. $singularHumanName = $this->_singularHumanName($this->controllerName);
  266. $fields = array();
  267. $schema = array();
  268. $associations = array();
  269. }
  270. $pluralVar = Inflector::variable($this->controllerName);
  271. $pluralHumanName = $this->_pluralHumanName($this->controllerName);
  272. return compact('modelClass', 'schema', 'primaryKey', 'displayField', 'singularVar', 'pluralVar',
  273. 'singularHumanName', 'pluralHumanName', 'fields','associations');
  274. }
  275. /**
  276. * Bake a view file for each of the supplied actions
  277. *
  278. * @param array $actions Array of actions to make files for.
  279. * @return void
  280. */
  281. function bakeActions($actions, $vars) {
  282. foreach ($actions as $action) {
  283. $content = $this->getContent($action, $vars);
  284. $this->bake($action, $content);
  285. }
  286. }
  287. /**
  288. * handle creation of baking a custom action view file
  289. *
  290. * @return void
  291. */
  292. function customAction() {
  293. $action = '';
  294. while ($action == '') {
  295. $action = $this->in(__('Action Name? (use lowercase_underscored function name)', true));
  296. if ($action == '') {
  297. $this->out(__('The action name you supplied was empty. Please try again.', true));
  298. }
  299. }
  300. $this->out();
  301. $this->hr();
  302. $this->out(__('The following view will be created:', true));
  303. $this->hr();
  304. $this->out(sprintf(__('Controller Name: %s', true), $this->controllerName));
  305. $this->out(sprintf(__('Action Name: %s', true), $action));
  306. $this->out(sprintf(__('Path: %s', true), $this->params['app'] . DS . $this->controllerPath . DS . Inflector::underscore($action) . ".ctp"));
  307. $this->hr();
  308. $looksGood = $this->in(__('Look okay?', true), array('y','n'), 'y');
  309. if (strtolower($looksGood) == 'y') {
  310. $this->bake($action);
  311. $this->_stop();
  312. } else {
  313. $this->out(__('Bake Aborted.', true));
  314. }
  315. }
  316. /**
  317. * Assembles and writes bakes the view file.
  318. *
  319. * @param string $action Action to bake
  320. * @param string $content Content to write
  321. * @return boolean Success
  322. * @access public
  323. */
  324. function bake($action, $content = '') {
  325. if ($content === true) {
  326. $content = $this->getContent($action);
  327. }
  328. $path = $this->path;
  329. if (isset($this->plugin)) {
  330. $path = $this->_pluginPath($this->plugin) . 'views' . DS;
  331. }
  332. $filename = $path . $this->controllerPath . DS . Inflector::underscore($action) . '.ctp';
  333. return $this->createFile($filename, $content);
  334. }
  335. /**
  336. * Builds content from template and variables
  337. *
  338. * @param string $action name to generate content to
  339. * @param array $vars passed for use in templates
  340. * @return string content from template
  341. * @access public
  342. */
  343. function getContent($action, $vars = null) {
  344. if (!$vars) {
  345. $vars = $this->__loadController();
  346. }
  347. $this->Template->set('action', $action);
  348. $this->Template->set('plugin', $this->plugin);
  349. $this->Template->set($vars);
  350. $output = $this->Template->generate('views', $this->getTemplate($action));
  351. if (!empty($output)) {
  352. return $output;
  353. }
  354. return false;
  355. }
  356. /**
  357. * Gets the template name based on the action name
  358. *
  359. * @param string $action name
  360. * @return string template name
  361. * @access public
  362. */
  363. function getTemplate($action) {
  364. if (!empty($this->template) && $action != $this->template) {
  365. return $this->template;
  366. }
  367. $template = $action;
  368. $prefixes = Configure::read('Routing.prefixes');
  369. foreach ((array)$prefixes as $prefix) {
  370. if (strpos($template, $prefix) !== false) {
  371. $template = str_replace($prefix . '_', '', $template);
  372. }
  373. }
  374. if (in_array($template, array('add', 'edit'))) {
  375. $template = 'form';
  376. } elseif (preg_match('@(_add|_edit)$@', $template)) {
  377. $template = str_replace(array('_add', '_edit'), '_form', $template);
  378. }
  379. return $template;
  380. }
  381. /**
  382. * Displays help contents
  383. *
  384. * @access public
  385. */
  386. function help() {
  387. $this->hr();
  388. $this->out("Usage: cake bake view <arg1> <arg2>...");
  389. $this->hr();
  390. $this->out('Arguments:');
  391. $this->out();
  392. $this->out("<controller>");
  393. $this->out("\tName of the controller views to bake. Can use Plugin.name");
  394. $this->out("\tas a shortcut for plugin baking.");
  395. $this->out();
  396. $this->out('Commands:');
  397. $this->out();
  398. $this->out("view <controller>");
  399. $this->out("\tWill read the given controller for methods");
  400. $this->out("\tand bake corresponding views.");
  401. $this->out("\tUsing the -admin flag will only bake views for actions");
  402. $this->out("\tthat begin with Routing.admin.");
  403. $this->out("\tIf var scaffold is found it will bake the CRUD actions");
  404. $this->out("\t(index,view,add,edit)");
  405. $this->out();
  406. $this->out("view <controller> <action>");
  407. $this->out("\tWill bake a template. core templates: (index, add, edit, view)");
  408. $this->out();
  409. $this->out("view <controller> <template> <alias>");
  410. $this->out("\tWill use the template specified");
  411. $this->out("\tbut name the file based on the alias");
  412. $this->out();
  413. $this->out("view all");
  414. $this->out("\tBake all CRUD action views for all controllers.");
  415. $this->out("\tRequires that models and controllers exist.");
  416. $this->_stop();
  417. }
  418. /**
  419. * Returns associations for controllers models.
  420. *
  421. * @return array $associations
  422. * @access private
  423. */
  424. function __associations($model) {
  425. $keys = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');
  426. $associations = array();
  427. foreach ($keys as $key => $type) {
  428. foreach ($model->{$type} as $assocKey => $assocData) {
  429. $associations[$type][$assocKey]['primaryKey'] = $model->{$assocKey}->primaryKey;
  430. $associations[$type][$assocKey]['displayField'] = $model->{$assocKey}->displayField;
  431. $associations[$type][$assocKey]['foreignKey'] = $assocData['foreignKey'];
  432. $associations[$type][$assocKey]['controller'] = Inflector::pluralize(Inflector::underscore($assocData['className']));
  433. $associations[$type][$assocKey]['fields'] = array_keys($model->{$assocKey}->schema());
  434. }
  435. }
  436. return $associations;
  437. }
  438. }
  439. ?>