PageRenderTime 65ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/Cake/Console/Command/Task/ViewTask.php

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