Cell.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://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. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View;
  16. use BadMethodCallException;
  17. use Cake\Cache\Cache;
  18. use Cake\Datasource\ModelAwareTrait;
  19. use Cake\Event\EventDispatcherTrait;
  20. use Cake\Event\EventManager;
  21. use Cake\Http\Response;
  22. use Cake\Http\ServerRequest;
  23. use Cake\ORM\Locator\LocatorAwareTrait;
  24. use Cake\Utility\Inflector;
  25. use Cake\View\Exception\MissingCellViewException;
  26. use Cake\View\Exception\MissingTemplateException;
  27. use Error;
  28. use Exception;
  29. use ReflectionException;
  30. use ReflectionMethod;
  31. /**
  32. * Cell base.
  33. */
  34. abstract class Cell
  35. {
  36. use EventDispatcherTrait;
  37. use LocatorAwareTrait;
  38. use ModelAwareTrait;
  39. use ViewVarsTrait;
  40. /**
  41. * Instance of the View created during rendering. Won't be set until after
  42. * Cell::__toString()/render() is called.
  43. *
  44. * @var \Cake\View\View
  45. */
  46. protected $View;
  47. /**
  48. * An instance of a Cake\Http\ServerRequest object that contains information about the current request.
  49. * This object contains all the information about a request and several methods for reading
  50. * additional information about the request.
  51. *
  52. * @var \Cake\Http\ServerRequest
  53. */
  54. protected $request;
  55. /**
  56. * An instance of a Response object that contains information about the impending response
  57. *
  58. * @var \Cake\Http\Response
  59. */
  60. protected $response;
  61. /**
  62. * The cell's action to invoke.
  63. *
  64. * @var string
  65. */
  66. protected $action;
  67. /**
  68. * Arguments to pass to cell's action.
  69. *
  70. * @var array
  71. */
  72. protected $args = [];
  73. /**
  74. * These properties can be set directly on Cell and passed to the View as options.
  75. *
  76. * @var array
  77. * @see \Cake\View\View
  78. * @deprecated 3.7.0 Use ViewBuilder::setOptions() or any one of it's setter methods instead.
  79. */
  80. protected $_validViewOptions = [
  81. 'viewPath'
  82. ];
  83. /**
  84. * List of valid options (constructor's fourth arguments)
  85. * Override this property in subclasses to whitelist
  86. * which options you want set as properties in your Cell.
  87. *
  88. * @var array
  89. */
  90. protected $_validCellOptions = [];
  91. /**
  92. * Caching setup.
  93. *
  94. * @var array|bool
  95. */
  96. protected $_cache = false;
  97. /**
  98. * Constructor.
  99. *
  100. * @param \Cake\Http\ServerRequest|null $request The request to use in the cell.
  101. * @param \Cake\Http\Response|null $response The response to use in the cell.
  102. * @param \Cake\Event\EventManager|null $eventManager The eventManager to bind events to.
  103. * @param array $cellOptions Cell options to apply.
  104. */
  105. public function __construct(
  106. ServerRequest $request = null,
  107. Response $response = null,
  108. EventManager $eventManager = null,
  109. array $cellOptions = []
  110. ) {
  111. if ($eventManager !== null) {
  112. $this->setEventManager($eventManager);
  113. }
  114. $this->request = $request;
  115. $this->response = $response;
  116. $this->modelFactory('Table', [$this->getTableLocator(), 'get']);
  117. $this->_validCellOptions = array_merge(['action', 'args'], $this->_validCellOptions);
  118. foreach ($this->_validCellOptions as $var) {
  119. if (isset($cellOptions[$var])) {
  120. $this->{$var} = $cellOptions[$var];
  121. }
  122. }
  123. if (!empty($cellOptions['cache'])) {
  124. $this->_cache = $cellOptions['cache'];
  125. }
  126. $this->initialize();
  127. }
  128. /**
  129. * Initialization hook method.
  130. *
  131. * Implement this method to avoid having to overwrite
  132. * the constructor and calling parent::__construct().
  133. *
  134. * @return void
  135. */
  136. public function initialize()
  137. {
  138. }
  139. /**
  140. * Render the cell.
  141. *
  142. * @param string|null $template Custom template name to render. If not provided (null), the last
  143. * value will be used. This value is automatically set by `CellTrait::cell()`.
  144. * @return string The rendered cell.
  145. * @throws \Cake\View\Exception\MissingCellViewException When a MissingTemplateException is raised during rendering.
  146. */
  147. public function render($template = null)
  148. {
  149. $cache = [];
  150. if ($this->_cache) {
  151. $cache = $this->_cacheConfig($this->action, $template);
  152. }
  153. $render = function () use ($template) {
  154. try {
  155. $reflect = new ReflectionMethod($this, $this->action);
  156. $reflect->invokeArgs($this, $this->args);
  157. } catch (ReflectionException $e) {
  158. throw new BadMethodCallException(sprintf(
  159. 'Class %s does not have a "%s" method.',
  160. get_class($this),
  161. $this->action
  162. ));
  163. }
  164. $builder = $this->viewBuilder()->setLayout(false);
  165. if ($template !== null &&
  166. strpos($template, '/') === false &&
  167. strpos($template, '.') === false
  168. ) {
  169. $template = Inflector::underscore($template);
  170. }
  171. if ($template !== null) {
  172. $builder->setTemplate($template);
  173. }
  174. $className = get_class($this);
  175. $namePrefix = '\View\Cell\\';
  176. $name = substr($className, strpos($className, $namePrefix) + strlen($namePrefix));
  177. $name = substr($name, 0, -4);
  178. if (!$builder->getTemplatePath()) {
  179. $builder->setTemplatePath('Cell' . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $name));
  180. }
  181. $this->View = $this->createView();
  182. try {
  183. return $this->View->render($template);
  184. } catch (MissingTemplateException $e) {
  185. throw new MissingCellViewException(['file' => $template, 'name' => $name], null, $e);
  186. }
  187. };
  188. if ($cache) {
  189. return Cache::remember($cache['key'], $render, $cache['config']);
  190. }
  191. return $render();
  192. }
  193. /**
  194. * Generate the cache key to use for this cell.
  195. *
  196. * If the key is undefined, the cell class and action name will be used.
  197. *
  198. * @param string $action The action invoked.
  199. * @param string|null $template The name of the template to be rendered.
  200. * @return array The cache configuration.
  201. */
  202. protected function _cacheConfig($action, $template = null)
  203. {
  204. if (empty($this->_cache)) {
  205. return [];
  206. }
  207. $template = $template ?: 'default';
  208. $key = 'cell_' . Inflector::underscore(get_class($this)) . '_' . $action . '_' . $template;
  209. $key = str_replace('\\', '_', $key);
  210. $default = [
  211. 'config' => 'default',
  212. 'key' => $key
  213. ];
  214. if ($this->_cache === true) {
  215. return $default;
  216. }
  217. return $this->_cache + $default;
  218. }
  219. /**
  220. * Magic method.
  221. *
  222. * Starts the rendering process when Cell is echoed.
  223. *
  224. * *Note* This method will trigger an error when view rendering has a problem.
  225. * This is because PHP will not allow a __toString() method to throw an exception.
  226. *
  227. * @return string Rendered cell
  228. * @throws \Error Include error details for PHP 7 fatal errors.
  229. */
  230. public function __toString()
  231. {
  232. try {
  233. return $this->render();
  234. } catch (Exception $e) {
  235. trigger_error(sprintf('Could not render cell - %s [%s, line %d]', $e->getMessage(), $e->getFile(), $e->getLine()), E_USER_WARNING);
  236. return '';
  237. } catch (Error $e) {
  238. throw new Error(sprintf('Could not render cell - %s [%s, line %d]', $e->getMessage(), $e->getFile(), $e->getLine()));
  239. }
  240. }
  241. /**
  242. * Magic accessor for removed properties.
  243. *
  244. * @param string $name Property name
  245. * @return mixed
  246. */
  247. public function __get($name)
  248. {
  249. $deprecated = [
  250. 'template' => 'getTemplate',
  251. 'plugin' => 'getPlugin',
  252. 'helpers' => 'getHelpers',
  253. ];
  254. if (isset($deprecated[$name])) {
  255. $method = $deprecated[$name];
  256. deprecationWarning(sprintf(
  257. 'Cell::$%s is deprecated. Use $cell->viewBuilder()->%s() instead.',
  258. $name,
  259. $method
  260. ));
  261. return $this->viewBuilder()->{$method}();
  262. }
  263. $protected = [
  264. 'action',
  265. 'args',
  266. 'request',
  267. 'response',
  268. 'View',
  269. ];
  270. if (in_array($name, $protected, true)) {
  271. deprecationWarning(sprintf(
  272. 'Cell::$%s is now protected and shouldn\'t be accessed from outside a child class.',
  273. $name
  274. ));
  275. }
  276. return $this->{$name};
  277. }
  278. /**
  279. * Magic setter for removed properties.
  280. *
  281. * @param string $name Property name.
  282. * @param mixed $value Value to set.
  283. * @return void
  284. */
  285. public function __set($name, $value)
  286. {
  287. $deprecated = [
  288. 'template' => 'setTemplate',
  289. 'plugin' => 'setPlugin',
  290. 'helpers' => 'setHelpers',
  291. ];
  292. if (isset($deprecated[$name])) {
  293. $method = $deprecated[$name];
  294. deprecationWarning(sprintf(
  295. 'Cell::$%s is deprecated. Use $cell->viewBuilder()->%s() instead.',
  296. $name,
  297. $method
  298. ));
  299. $this->viewBuilder()->{$method}($value);
  300. return;
  301. }
  302. $protected = [
  303. 'action',
  304. 'args',
  305. 'request',
  306. 'response',
  307. 'View',
  308. ];
  309. if (in_array($name, $protected, true)) {
  310. deprecationWarning(sprintf(
  311. 'Cell::$%s is now protected and shouldn\'t be accessed from outside a child class.',
  312. $name
  313. ));
  314. }
  315. $this->{$name} = $value;
  316. }
  317. /**
  318. * Debug info.
  319. *
  320. * @return array
  321. */
  322. public function __debugInfo()
  323. {
  324. return [
  325. 'action' => $this->action,
  326. 'args' => $this->args,
  327. 'request' => $this->request,
  328. 'response' => $this->response,
  329. 'viewBuilder' => $this->viewBuilder(),
  330. ];
  331. }
  332. }