ViewTask.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 1.2.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\Console\Command\Task;
  16. use Cake\Console\Shell;
  17. use Cake\Core\App;
  18. use Cake\Core\Configure;
  19. use Cake\ORM\Table;
  20. use Cake\ORM\TableRegistry;
  21. use Cake\Utility\Inflector;
  22. /**
  23. * Task class for creating and updating view files.
  24. *
  25. */
  26. class ViewTask extends BakeTask {
  27. /**
  28. * Tasks to be loaded by this Task
  29. *
  30. * @var array
  31. */
  32. public $tasks = ['Model', 'Template'];
  33. /**
  34. * path to View directory
  35. *
  36. * @var array
  37. */
  38. public $pathFragment = 'Template/';
  39. /**
  40. * Name of the controller being used
  41. *
  42. * @var string
  43. */
  44. public $controllerName = null;
  45. /**
  46. * Classname of the controller being used
  47. *
  48. * @var string
  49. */
  50. public $controllerClass = null;
  51. /**
  52. * Name with plugin of the model being used
  53. *
  54. * @var string
  55. */
  56. public $modelName = null;
  57. /**
  58. * The template file to use
  59. *
  60. * @var string
  61. */
  62. public $template = null;
  63. /**
  64. * Actions to use for scaffolding
  65. *
  66. * @var array
  67. */
  68. public $scaffoldActions = ['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. */
  75. public $noTemplateActions = ['delete'];
  76. /**
  77. * Override initialize
  78. *
  79. * @return void
  80. */
  81. public function initialize() {
  82. $this->path = current(App::path('Template'));
  83. }
  84. /**
  85. * Execution method always used for tasks
  86. *
  87. * @param string $name The name of the controller to bake views for.
  88. * @param string $template The template to bake with.
  89. * @param string $action The action to bake with.
  90. * @return mixed
  91. */
  92. public function main($name = null, $template = null, $action = null) {
  93. parent::main();
  94. if (empty($name)) {
  95. $this->out(__d('cake_console', 'Possible tables to bake views for based on your current database:'));
  96. $this->Model->connection = $this->connection;
  97. foreach ($this->Model->listAll() as $table) {
  98. $this->out('- ' . $this->_controllerName($table));
  99. }
  100. return true;
  101. }
  102. $name = $this->_getName($name);
  103. $controller = null;
  104. if (!empty($this->params['controller'])) {
  105. $controller = $this->params['controller'];
  106. }
  107. $this->controller($name, $controller);
  108. $this->model($name);
  109. if (isset($template)) {
  110. $this->template = $template;
  111. }
  112. if (!$action) {
  113. $action = $this->template;
  114. }
  115. if ($action) {
  116. return $this->bake($action, true);
  117. }
  118. $vars = $this->_loadController();
  119. $methods = $this->_methodsToBake();
  120. foreach ($methods as $method) {
  121. $content = $this->getContent($method, $vars);
  122. if ($content) {
  123. $this->bake($method, $content);
  124. }
  125. }
  126. }
  127. /**
  128. * Set the model class for the table.
  129. *
  130. * @param string $table The table/model that is being baked.
  131. * @return void
  132. */
  133. public function model($table) {
  134. $tableName = $this->_controllerName($table);
  135. $plugin = null;
  136. if (!empty($this->params['plugin'])) {
  137. $plugin = $this->params['plugin'] . '.';
  138. }
  139. $this->modelName = $plugin . $tableName;
  140. }
  141. /**
  142. * Set the controller related properties.
  143. *
  144. * @param string $table The table/model that is being baked.
  145. * @param string $controller The controller name if specified.
  146. * @return void
  147. */
  148. public function controller($table, $controller = null) {
  149. $tableName = $this->_controllerName($table);
  150. if (empty($controller)) {
  151. $controller = $tableName;
  152. }
  153. $this->controllerName = $controller;
  154. $plugin = $prefix = null;
  155. if (!empty($this->params['plugin'])) {
  156. $plugin = $this->params['plugin'] . '.';
  157. }
  158. if (!empty($this->params['prefix'])) {
  159. $prefix = $this->params['prefix'] . '/';
  160. }
  161. $this->controllerClass = App::className($plugin . $prefix . $controller, 'Controller', 'Controller');
  162. }
  163. /**
  164. * Get the path base for views.
  165. *
  166. * @return string
  167. */
  168. public function getPath() {
  169. $path = parent::getPath();
  170. if (!empty($this->params['prefix'])) {
  171. $path .= $this->_camelize($this->params['prefix']) . DS;
  172. }
  173. $path .= $this->controllerName . DS;
  174. return $path;
  175. }
  176. /**
  177. * Get a list of actions that can / should have views baked for them.
  178. *
  179. * @return array Array of action names that should be baked
  180. */
  181. protected function _methodsToBake() {
  182. $base = Configure::read('App.namespace');
  183. $methods = [];
  184. if (class_exists($this->controllerClass)) {
  185. $methods = array_diff(
  186. array_map('strtolower', get_class_methods($this->controllerClass)),
  187. array_map('strtolower', get_class_methods($base . '\Controller\AppController'))
  188. );
  189. }
  190. if (empty($methods)) {
  191. $methods = $this->scaffoldActions;
  192. }
  193. foreach ($methods as $i => $method) {
  194. if ($method[0] === '_') {
  195. unset($methods[$i]);
  196. }
  197. }
  198. return $methods;
  199. }
  200. /**
  201. * Bake All views for All controllers.
  202. *
  203. * @return void
  204. */
  205. public function all() {
  206. $this->Model->connection = $this->connection;
  207. $tables = $this->Model->listAll();
  208. foreach ($tables as $table) {
  209. $this->main($table);
  210. }
  211. }
  212. /**
  213. * Loads Controller and sets variables for the template
  214. * Available template variables:
  215. *
  216. * - 'modelClass'
  217. * - 'primaryKey'
  218. * - 'displayField'
  219. * - 'singularVar'
  220. * - 'pluralVar'
  221. * - 'singularHumanName'
  222. * - 'pluralHumanName'
  223. * - 'fields'
  224. * - 'keyFields'
  225. * - 'schema'
  226. *
  227. * @return array Returns an variables to be made available to a view template
  228. */
  229. protected function _loadController() {
  230. $modelObj = TableRegistry::get($this->modelName);
  231. $primaryKey = (array)$modelObj->primaryKey();
  232. $displayField = $modelObj->displayField();
  233. $singularVar = $this->_singularName($this->controllerName);
  234. $singularHumanName = $this->_singularHumanName($this->controllerName);
  235. $schema = $modelObj->schema();
  236. $fields = $schema->columns();
  237. $associations = $this->_associations($modelObj);
  238. $keyFields = [];
  239. if (!empty($associations['BelongsTo'])) {
  240. foreach ($associations['BelongsTo'] as $assoc) {
  241. $keyFields[$assoc['foreignKey']] = $assoc['variable'];
  242. }
  243. }
  244. $pluralVar = Inflector::variable($this->controllerName);
  245. $pluralHumanName = $this->_pluralHumanName($this->controllerName);
  246. return compact(
  247. 'modelClass', 'schema',
  248. 'primaryKey', 'displayField',
  249. 'singularVar', 'pluralVar',
  250. 'singularHumanName', 'pluralHumanName',
  251. 'fields', 'associations', 'keyFields'
  252. );
  253. }
  254. /**
  255. * Bake a view file for each of the supplied actions
  256. *
  257. * @param array $actions Array of actions to make files for.
  258. * @param array $vars The context for generating views.
  259. * @return void
  260. */
  261. public function bakeActions(array $actions, $vars) {
  262. foreach ($actions as $action) {
  263. $content = $this->getContent($action, $vars);
  264. $this->bake($action, $content);
  265. }
  266. }
  267. /**
  268. * handle creation of baking a custom action view file
  269. *
  270. * @return void
  271. */
  272. public function customAction() {
  273. $action = '';
  274. while (!$action) {
  275. $action = $this->in(__d('cake_console', 'Action Name? (use lowercase_underscored function name)'));
  276. if (!$action) {
  277. $this->out(__d('cake_console', 'The action name you supplied was empty. Please try again.'));
  278. }
  279. }
  280. $this->out();
  281. $this->hr();
  282. $this->out(__d('cake_console', 'The following view will be created:'));
  283. $this->hr();
  284. $this->out(__d('cake_console', 'Controller Name: %s', $this->controllerName));
  285. $this->out(__d('cake_console', 'Action Name: %s', $action));
  286. $this->out(__d('cake_console', 'Path: %s', $this->getPath() . $this->controllerName . DS . Inflector::underscore($action) . ".ctp"));
  287. $this->hr();
  288. $looksGood = $this->in(__d('cake_console', 'Look okay?'), ['y', 'n'], 'y');
  289. if (strtolower($looksGood) === 'y') {
  290. $this->bake($action, ' ');
  291. return $this->_stop();
  292. }
  293. $this->out(__d('cake_console', 'Bake Aborted.'));
  294. }
  295. /**
  296. * Assembles and writes bakes the view file.
  297. *
  298. * @param string $action Action to bake.
  299. * @param string $content Content to write.
  300. * @return string Generated file content.
  301. */
  302. public function bake($action, $content = '') {
  303. if ($content === true) {
  304. $content = $this->getContent($action);
  305. }
  306. if (empty($content)) {
  307. return false;
  308. }
  309. $this->out("\n" . __d('cake_console', 'Baking `%s` view file...', $action), 1, Shell::QUIET);
  310. $path = $this->getPath();
  311. $filename = $path . Inflector::underscore($action) . '.ctp';
  312. $this->createFile($filename, $content);
  313. return $content;
  314. }
  315. /**
  316. * Builds content from template and variables
  317. *
  318. * @param string $action name to generate content to
  319. * @param array $vars passed for use in templates
  320. * @return string content from template
  321. */
  322. public function getContent($action, $vars = null) {
  323. if (!$vars) {
  324. $vars = $this->_loadController();
  325. }
  326. $this->Template->set('action', $action);
  327. $this->Template->set('plugin', $this->plugin);
  328. $this->Template->set($vars);
  329. $template = $this->getTemplate($action);
  330. if ($template) {
  331. return $this->Template->generate('views', $template);
  332. }
  333. return false;
  334. }
  335. /**
  336. * Gets the template name based on the action name
  337. *
  338. * @param string $action name
  339. * @return string template name
  340. */
  341. public function getTemplate($action) {
  342. if ($action != $this->template && in_array($action, $this->noTemplateActions)) {
  343. return false;
  344. }
  345. if (!empty($this->template) && $action != $this->template) {
  346. return $this->template;
  347. }
  348. $themePath = $this->Template->getThemePath();
  349. if (!empty($this->params['prefix'])) {
  350. $prefixed = Inflector::underscore($this->params['prefix']) . '_' . $action;
  351. if (file_exists($themePath . 'views/' . $prefixed . '.ctp')) {
  352. return $prefixed;
  353. }
  354. $generic = preg_replace('/(.*)(_add|_edit)$/', '\1_form', $prefixed);
  355. if (file_exists($themePath . 'views/' . $generic . '.ctp')) {
  356. return $generic;
  357. }
  358. }
  359. if (file_exists($themePath . 'views/' . $action . '.ctp')) {
  360. return $action;
  361. }
  362. if (in_array($action, ['add', 'edit'])) {
  363. return 'form';
  364. }
  365. return $action;
  366. }
  367. /**
  368. * Gets the option parser instance and configures it.
  369. *
  370. * @return \Cake\Console\ConsoleOptionParser
  371. */
  372. public function getOptionParser() {
  373. $parser = parent::getOptionParser();
  374. $parser->description(
  375. __d('cake_console', 'Bake views for a controller, using built-in or custom templates. ')
  376. )->addArgument('controller', [
  377. 'help' => __d('cake_console', 'Name of the controller views to bake. Can be Plugin.name as a shortcut for plugin baking.')
  378. ])->addArgument('action', [
  379. 'help' => __d('cake_console', "Will bake a single action's file. core templates are (index, add, edit, view)")
  380. ])->addArgument('alias', [
  381. 'help' => __d('cake_console', 'Will bake the template in <action> but create the filename after <alias>.')
  382. ])->addOption('controller', [
  383. 'help' => __d('cake_console', 'The controller name if you have a controller that does not follow conventions.')
  384. ])->addOption('prefix', [
  385. 'help' => __d('cake_console', 'The routing prefix to generate views for.'),
  386. ])->addSubcommand('all', [
  387. 'help' => __d('cake_console', 'Bake all CRUD action views for all controllers. Requires models and controllers to exist.')
  388. ]);
  389. return $parser;
  390. }
  391. /**
  392. * Returns associations for controllers models.
  393. *
  394. * @param Table $model The model to build associations for.
  395. * @return array associations
  396. */
  397. protected function _associations(Table $model) {
  398. $keys = ['BelongsTo', 'HasOne', 'HasMany', 'BelongsToMany'];
  399. $associations = [];
  400. foreach ($keys as $type) {
  401. foreach ($model->associations()->type($type) as $assoc) {
  402. $target = $assoc->target();
  403. $assocName = $assoc->name();
  404. $alias = $target->alias();
  405. $associations[$type][$assocName] = [
  406. 'property' => $assoc->property(),
  407. 'variable' => Inflector::variable($assocName),
  408. 'primaryKey' => (array)$target->primaryKey(),
  409. 'displayField' => $target->displayField(),
  410. 'foreignKey' => $assoc->foreignKey(),
  411. 'controller' => $alias,
  412. 'fields' => $target->schema()->columns(),
  413. ];
  414. }
  415. }
  416. return $associations;
  417. }
  418. }