View.php 46 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526
  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 0.10.0
  13. * @license https://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View;
  16. use Cake\Cache\Cache;
  17. use Cake\Core\App;
  18. use Cake\Core\Plugin;
  19. use Cake\Event\EventDispatcherInterface;
  20. use Cake\Event\EventDispatcherTrait;
  21. use Cake\Event\EventManager;
  22. use Cake\Http\Response;
  23. use Cake\Http\ServerRequest;
  24. use Cake\Log\LogTrait;
  25. use Cake\Routing\RequestActionTrait;
  26. use Cake\Routing\Router;
  27. use Cake\Utility\Inflector;
  28. use Cake\View\Exception\MissingElementException;
  29. use Cake\View\Exception\MissingLayoutException;
  30. use Cake\View\Exception\MissingTemplateException;
  31. use InvalidArgumentException;
  32. use LogicException;
  33. use RuntimeException;
  34. /**
  35. * View, the V in the MVC triad. View interacts with Helpers and view variables passed
  36. * in from the controller to render the results of the controller action. Often this is HTML,
  37. * but can also take the form of JSON, XML, PDF's or streaming files.
  38. *
  39. * CakePHP uses a two-step-view pattern. This means that the template content is rendered first,
  40. * and then inserted into the selected layout. This also means you can pass data from the template to the
  41. * layout using `$this->set()`
  42. *
  43. * View class supports using plugins as themes. You can set
  44. *
  45. * ```
  46. * public function beforeRender(\Cake\Event\Event $event)
  47. * {
  48. * $this->viewBuilder()->setTheme('SuperHot');
  49. * }
  50. * ```
  51. *
  52. * in your Controller to use plugin `SuperHot` as a theme. Eg. If current action
  53. * is PostsController::index() then View class will look for template file
  54. * `plugins/SuperHot/Template/Posts/index.ctp`. If a theme template
  55. * is not found for the current action the default app template file is used.
  56. *
  57. * @property \Cake\View\Helper\FlashHelper $Flash
  58. * @property \Cake\View\Helper\FormHelper $Form
  59. * @property \Cake\View\Helper\HtmlHelper $Html
  60. * @property \Cake\View\Helper\NumberHelper $Number
  61. * @property \Cake\View\Helper\PaginatorHelper $Paginator
  62. * @property \Cake\View\Helper\RssHelper $Rss
  63. * @property \Cake\View\Helper\SessionHelper $Session
  64. * @property \Cake\View\Helper\TextHelper $Text
  65. * @property \Cake\View\Helper\TimeHelper $Time
  66. * @property \Cake\View\Helper\UrlHelper $Url
  67. * @property \Cake\View\ViewBlock $Blocks
  68. * @property string $view
  69. * @property string $viewPath
  70. */
  71. class View implements EventDispatcherInterface
  72. {
  73. use CellTrait {
  74. cell as public;
  75. }
  76. use EventDispatcherTrait;
  77. use LogTrait;
  78. use RequestActionTrait;
  79. use ViewVarsTrait;
  80. /**
  81. * Helpers collection
  82. *
  83. * @var \Cake\View\HelperRegistry
  84. */
  85. protected $_helpers;
  86. /**
  87. * ViewBlock instance.
  88. *
  89. * @var \Cake\View\ViewBlock
  90. */
  91. public $Blocks;
  92. /**
  93. * The name of the plugin.
  94. *
  95. * @var string
  96. */
  97. public $plugin;
  98. /**
  99. * Name of the controller that created the View if any.
  100. *
  101. * @var string
  102. */
  103. public $name;
  104. /**
  105. * Current passed params. Passed to View from the creating Controller for convenience.
  106. *
  107. * @var array
  108. * @deprecated 3.1.0 Use `$this->request->getParam('pass')` instead.
  109. */
  110. public $passedArgs = [];
  111. /**
  112. * An array of names of built-in helpers to include.
  113. *
  114. * @var array
  115. */
  116. public $helpers = [];
  117. /**
  118. * The name of the subfolder containing templates for this View.
  119. *
  120. * @var string
  121. */
  122. public $templatePath;
  123. /**
  124. * The name of the template file to render. The name specified
  125. * is the filename in /src/Template/<SubFolder> without the .ctp extension.
  126. *
  127. * @var string
  128. */
  129. public $template;
  130. /**
  131. * The name of the layout file to render the template inside of. The name specified
  132. * is the filename of the layout in /src/Template/Layout without the .ctp
  133. * extension.
  134. *
  135. * @var string
  136. */
  137. public $layout = 'default';
  138. /**
  139. * The name of the layouts subfolder containing layouts for this View.
  140. *
  141. * @var string
  142. */
  143. public $layoutPath;
  144. /**
  145. * Turns on or off CakePHP's conventional mode of applying layout files. On by default.
  146. * Setting to off means that layouts will not be automatically applied to rendered templates.
  147. *
  148. * @var bool
  149. */
  150. public $autoLayout = true;
  151. /**
  152. * File extension. Defaults to CakePHP's template ".ctp".
  153. *
  154. * @var string
  155. */
  156. protected $_ext = '.ctp';
  157. /**
  158. * Sub-directory for this template file. This is often used for extension based routing.
  159. * Eg. With an `xml` extension, $subDir would be `xml/`
  160. *
  161. * @var string|null
  162. */
  163. public $subDir;
  164. /**
  165. * The view theme to use.
  166. *
  167. * @var string|null
  168. */
  169. public $theme;
  170. /**
  171. * True when the view has been rendered.
  172. *
  173. * @var bool
  174. */
  175. public $hasRendered = false;
  176. /**
  177. * List of generated DOM UUIDs.
  178. *
  179. * @var array
  180. */
  181. public $uuids = [];
  182. /**
  183. * An instance of a \Cake\Http\ServerRequest object that contains information about the current request.
  184. * This object contains all the information about a request and several methods for reading
  185. * additional information about the request.
  186. *
  187. * @var \Cake\Http\ServerRequest
  188. */
  189. public $request;
  190. /**
  191. * Reference to the Response object
  192. *
  193. * @var \Cake\Http\Response
  194. */
  195. public $response;
  196. /**
  197. * The Cache configuration View will use to store cached elements. Changing this will change
  198. * the default configuration elements are stored under. You can also choose a cache config
  199. * per element.
  200. *
  201. * @var string
  202. * @see \Cake\View\View::element()
  203. */
  204. public $elementCache = 'default';
  205. /**
  206. * List of variables to collect from the associated controller.
  207. *
  208. * @var array
  209. */
  210. protected $_passedVars = [
  211. 'viewVars', 'autoLayout', 'helpers', 'template', 'layout', 'name', 'theme',
  212. 'layoutPath', 'templatePath', 'plugin', 'passedArgs'
  213. ];
  214. /**
  215. * Holds an array of paths.
  216. *
  217. * @var array
  218. */
  219. protected $_paths = [];
  220. /**
  221. * Holds an array of plugin paths.
  222. *
  223. * @var array
  224. */
  225. protected $_pathsForPlugin = [];
  226. /**
  227. * The names of views and their parents used with View::extend();
  228. *
  229. * @var array
  230. */
  231. protected $_parents = [];
  232. /**
  233. * The currently rendering view file. Used for resolving parent files.
  234. *
  235. * @var string
  236. */
  237. protected $_current;
  238. /**
  239. * Currently rendering an element. Used for finding parent fragments
  240. * for elements.
  241. *
  242. * @var string
  243. */
  244. protected $_currentType = '';
  245. /**
  246. * Content stack, used for nested templates that all use View::extend();
  247. *
  248. * @var array
  249. */
  250. protected $_stack = [];
  251. /**
  252. * Constant for view file type 'view'
  253. *
  254. * @var string
  255. * @deprecated 3.1.0 Use TYPE_TEMPLATE instead.
  256. */
  257. const TYPE_VIEW = 'view';
  258. /**
  259. * Constant for view file type 'template'.
  260. *
  261. * @var string
  262. */
  263. const TYPE_TEMPLATE = 'view';
  264. /**
  265. * Constant for view file type 'element'
  266. *
  267. * @var string
  268. */
  269. const TYPE_ELEMENT = 'element';
  270. /**
  271. * Constant for name of view file 'Element'
  272. *
  273. * @var string
  274. */
  275. const NAME_ELEMENT = 'Element';
  276. /**
  277. * Constant for view file type 'layout'
  278. *
  279. * @var string
  280. */
  281. const TYPE_LAYOUT = 'layout';
  282. /**
  283. * Constant for template folder 'Template'
  284. *
  285. * @var string
  286. */
  287. const NAME_TEMPLATE = 'Template';
  288. /**
  289. * Constructor
  290. *
  291. * @param \Cake\Http\ServerRequest|null $request Request instance.
  292. * @param \Cake\Http\Response|null $response Response instance.
  293. * @param \Cake\Event\EventManager|null $eventManager Event manager instance.
  294. * @param array $viewOptions View options. See View::$_passedVars for list of
  295. * options which get set as class properties.
  296. */
  297. public function __construct(
  298. ServerRequest $request = null,
  299. Response $response = null,
  300. EventManager $eventManager = null,
  301. array $viewOptions = []
  302. ) {
  303. if (isset($viewOptions['view'])) {
  304. $this->setTemplate($viewOptions['view']);
  305. }
  306. if (isset($viewOptions['viewPath'])) {
  307. $this->setTemplatePath($viewOptions['viewPath']);
  308. }
  309. foreach ($this->_passedVars as $var) {
  310. if (isset($viewOptions[$var])) {
  311. $this->{$var} = $viewOptions[$var];
  312. }
  313. }
  314. if ($eventManager !== null) {
  315. $this->setEventManager($eventManager);
  316. }
  317. $this->request = $request ?: Router::getRequest(true);
  318. $this->response = $response ?: new Response();
  319. if (!$this->request) {
  320. $this->request = new ServerRequest([
  321. 'base' => '',
  322. 'url' => '',
  323. 'webroot' => '/'
  324. ]);
  325. }
  326. $this->Blocks = new ViewBlock();
  327. $this->initialize();
  328. $this->loadHelpers();
  329. }
  330. /**
  331. * Initialization hook method.
  332. *
  333. * Properties like $helpers etc. cannot be initialized statically in your custom
  334. * view class as they are overwritten by values from controller in constructor.
  335. * So this method allows you to manipulate them as required after view instance
  336. * is constructed.
  337. *
  338. * @return void
  339. */
  340. public function initialize()
  341. {
  342. }
  343. /**
  344. * Get path for templates files.
  345. *
  346. * @return string
  347. */
  348. public function getTemplatePath()
  349. {
  350. return $this->templatePath;
  351. }
  352. /**
  353. * Set path for templates files.
  354. *
  355. * @param string $path Path for template files.
  356. * @return void
  357. */
  358. public function setTemplatePath($path)
  359. {
  360. $this->templatePath = $path;
  361. }
  362. /**
  363. * Get/set path for templates files.
  364. *
  365. * @deprecated 3.5.0 Use getTemplatePath()/setTemplatePath() instead.
  366. * @param string|null $path Path for template files. If null returns current path.
  367. * @return string|null
  368. */
  369. public function templatePath($path = null)
  370. {
  371. if ($path === null) {
  372. return $this->templatePath;
  373. }
  374. $this->templatePath = $path;
  375. }
  376. /**
  377. * Get path for layout files.
  378. *
  379. * @return string
  380. */
  381. public function getLayoutPath()
  382. {
  383. return $this->layoutPath;
  384. }
  385. /**
  386. * Set path for layout files.
  387. *
  388. * @param string $path Path for layout files.
  389. * @return void
  390. */
  391. public function setLayoutPath($path)
  392. {
  393. $this->layoutPath = $path;
  394. }
  395. /**
  396. * Get/set path for layout files.
  397. *
  398. * @deprecated 3.5.0 Use getLayoutPath()/setLayoutPath() instead.
  399. * @param string|null $path Path for layout files. If null returns current path.
  400. * @return string|null
  401. */
  402. public function layoutPath($path = null)
  403. {
  404. if ($path === null) {
  405. return $this->layoutPath;
  406. }
  407. $this->layoutPath = $path;
  408. }
  409. /**
  410. * Returns if CakePHP's conventional mode of applying layout files is enabled.
  411. * Disabled means that layouts will not be automatically applied to rendered views.
  412. *
  413. * @return bool
  414. */
  415. public function isAutoLayoutEnabled()
  416. {
  417. return $this->autoLayout;
  418. }
  419. /**
  420. * Turns on or off CakePHP's conventional mode of applying layout files.
  421. * On by default. Setting to off means that layouts will not be
  422. * automatically applied to rendered views.
  423. *
  424. * @param bool $enable Boolean to turn on/off.
  425. * @return void
  426. */
  427. public function enableAutoLayout($enable = true)
  428. {
  429. $this->autoLayout = (bool)$enable;
  430. }
  431. /**
  432. * Turns on or off CakePHP's conventional mode of applying layout files.
  433. * On by default. Setting to off means that layouts will not be
  434. * automatically applied to rendered templates.
  435. *
  436. * @deprecated 3.5.0 Use isAutoLayoutEnabled()/enableAutoLayout() instead.
  437. * @param bool|null $autoLayout Boolean to turn on/off. If null returns current value.
  438. * @return bool|null
  439. */
  440. public function autoLayout($autoLayout = null)
  441. {
  442. if ($autoLayout === null) {
  443. return $this->autoLayout;
  444. }
  445. $this->autoLayout = $autoLayout;
  446. }
  447. /**
  448. * Get the current view theme.
  449. *
  450. * @return string|null
  451. */
  452. public function getTheme()
  453. {
  454. return $this->theme;
  455. }
  456. /**
  457. * Set the view theme to use.
  458. *
  459. * @param string|null $theme Theme name.
  460. * @return void
  461. */
  462. public function setTheme($theme)
  463. {
  464. $this->theme = $theme;
  465. }
  466. /**
  467. * The view theme to use.
  468. *
  469. * @deprecated 3.5.0 Use getTheme()/setTheme() instead.
  470. * @param string|null $theme Theme name. If null returns current theme.
  471. * @return string|null
  472. */
  473. public function theme($theme = null)
  474. {
  475. if ($theme === null) {
  476. return $this->theme;
  477. }
  478. $this->theme = $theme;
  479. }
  480. /**
  481. * Get the name of the template file to render. The name specified is the
  482. * filename in /src/Template/<SubFolder> without the .ctp extension.
  483. *
  484. * @return string
  485. */
  486. public function getTemplate()
  487. {
  488. return $this->template;
  489. }
  490. /**
  491. * Set the name of the template file to render. The name specified is the
  492. * filename in /src/Template/<SubFolder> without the .ctp extension.
  493. *
  494. * @param string $name Template file name to set.
  495. * @return void
  496. */
  497. public function setTemplate($name)
  498. {
  499. $this->template = $name;
  500. }
  501. /**
  502. * Get/set the name of the template file to render. The name specified is the
  503. * filename in /src/Template/<SubFolder> without the .ctp extension.
  504. *
  505. * @deprecated 3.5.0 Use getTemplate()/setTemplate() instead.
  506. * @param string|null $name Template file name to set. If null returns current name.
  507. * @return string|null
  508. */
  509. public function template($name = null)
  510. {
  511. if ($name === null) {
  512. return $this->template;
  513. }
  514. $this->template = $name;
  515. }
  516. /**
  517. * Get the name of the layout file to render the template inside of.
  518. * The name specified is the filename of the layout in /src/Template/Layout
  519. * without the .ctp extension.
  520. *
  521. * @return string
  522. */
  523. public function getLayout()
  524. {
  525. return $this->layout;
  526. }
  527. /**
  528. * Set the name of the layout file to render the template inside of.
  529. * The name specified is the filename of the layout in /src/Template/Layout
  530. * without the .ctp extension.
  531. *
  532. * @param string $name Layout file name to set.
  533. * @return void
  534. */
  535. public function setLayout($name)
  536. {
  537. $this->layout = $name;
  538. }
  539. /**
  540. * Get/set the name of the layout file to render the template inside of.
  541. * The name specified is the filename of the layout in /src/Template/Layout
  542. * without the .ctp extension.
  543. *
  544. * @deprecated 3.5.0 Use getLayout()/setLayout() instead.
  545. * @param string|null $name Layout file name to set. If null returns current name.
  546. * @return string|null
  547. */
  548. public function layout($name = null)
  549. {
  550. if ($name === null) {
  551. return $this->layout;
  552. }
  553. $this->layout = $name;
  554. }
  555. /**
  556. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  557. *
  558. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  559. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  560. *
  561. * @param string $name Name of template file in the /src/Template/Element/ folder,
  562. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  563. * is not found in the plugin, the normal view path cascade will be searched.
  564. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  565. * @param array $options Array of options. Possible keys are:
  566. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  567. * If an array, the following keys can be used:
  568. * - `config` - Used to store the cached element in a custom cache configuration.
  569. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  570. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  571. * Defaults to false.
  572. * - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions.
  573. * - `plugin` - setting to false will force to use the application's element from plugin templates, when the
  574. * plugin has element with same name. Defaults to true
  575. * @return string Rendered Element
  576. * @throws \Cake\View\Exception\MissingElementException When an element is missing and `ignoreMissing`
  577. * is false.
  578. */
  579. public function element($name, array $data = [], array $options = [])
  580. {
  581. $options += ['callbacks' => false, 'cache' => null, 'plugin' => null];
  582. if (isset($options['cache'])) {
  583. $options['cache'] = $this->_elementCache($name, $data, $options);
  584. }
  585. $pluginCheck = $options['plugin'] !== false;
  586. $file = $this->_getElementFileName($name, $pluginCheck);
  587. if ($file && $options['cache']) {
  588. return $this->cache(function () use ($file, $data, $options) {
  589. echo $this->_renderElement($file, $data, $options);
  590. }, $options['cache']);
  591. }
  592. if ($file) {
  593. return $this->_renderElement($file, $data, $options);
  594. }
  595. if (empty($options['ignoreMissing'])) {
  596. list ($plugin, $name) = pluginSplit($name, true);
  597. $name = str_replace('/', DIRECTORY_SEPARATOR, $name);
  598. $file = $plugin . static::NAME_ELEMENT . DIRECTORY_SEPARATOR . $name . $this->_ext;
  599. throw new MissingElementException([$file]);
  600. }
  601. }
  602. /**
  603. * Create a cached block of view logic.
  604. *
  605. * This allows you to cache a block of view output into the cache
  606. * defined in `elementCache`.
  607. *
  608. * This method will attempt to read the cache first. If the cache
  609. * is empty, the $block will be run and the output stored.
  610. *
  611. * @param callable $block The block of code that you want to cache the output of.
  612. * @param array $options The options defining the cache key etc.
  613. * @return string The rendered content.
  614. * @throws \RuntimeException When $options is lacking a 'key' option.
  615. */
  616. public function cache(callable $block, array $options = [])
  617. {
  618. $options += ['key' => '', 'config' => $this->elementCache];
  619. if (empty($options['key'])) {
  620. throw new RuntimeException('Cannot cache content with an empty key');
  621. }
  622. $result = Cache::read($options['key'], $options['config']);
  623. if ($result) {
  624. return $result;
  625. }
  626. ob_start();
  627. $block();
  628. $result = ob_get_clean();
  629. Cache::write($options['key'], $result, $options['config']);
  630. return $result;
  631. }
  632. /**
  633. * Checks if an element exists
  634. *
  635. * @param string $name Name of template file in the /src/Template/Element/ folder,
  636. * or `MyPlugin.template` to check the template element from MyPlugin. If the element
  637. * is not found in the plugin, the normal view path cascade will be searched.
  638. * @return bool Success
  639. */
  640. public function elementExists($name)
  641. {
  642. return (bool)$this->_getElementFileName($name);
  643. }
  644. /**
  645. * Renders view for given template file and layout.
  646. *
  647. * Render triggers helper callbacks, which are fired before and after the template are rendered,
  648. * as well as before and after the layout. The helper callbacks are called:
  649. *
  650. * - `beforeRender`
  651. * - `afterRender`
  652. * - `beforeLayout`
  653. * - `afterLayout`
  654. *
  655. * If View::$autoRender is false and no `$layout` is provided, the template will be returned bare.
  656. *
  657. * Template and layout names can point to plugin templates/layouts. Using the `Plugin.template` syntax
  658. * a plugin template/layout can be used instead of the app ones. If the chosen plugin is not found
  659. * the template will be located along the regular view path cascade.
  660. *
  661. * @param string|false|null $view Name of view file to use
  662. * @param string|null $layout Layout to use.
  663. * @return string|null Rendered content or null if content already rendered and returned earlier.
  664. * @throws \Cake\Core\Exception\Exception If there is an error in the view.
  665. * @triggers View.beforeRender $this, [$viewFileName]
  666. * @triggers View.afterRender $this, [$viewFileName]
  667. */
  668. public function render($view = null, $layout = null)
  669. {
  670. if ($this->hasRendered) {
  671. return null;
  672. }
  673. $defaultLayout = null;
  674. if ($layout !== null) {
  675. $defaultLayout = $this->layout;
  676. $this->layout = $layout;
  677. }
  678. $viewFileName = $view !== false ? $this->_getViewFileName($view) : null;
  679. if ($viewFileName) {
  680. $this->_currentType = static::TYPE_TEMPLATE;
  681. $this->dispatchEvent('View.beforeRender', [$viewFileName]);
  682. $this->Blocks->set('content', $this->_render($viewFileName));
  683. $this->dispatchEvent('View.afterRender', [$viewFileName]);
  684. }
  685. if ($this->layout && $this->autoLayout) {
  686. $this->Blocks->set('content', $this->renderLayout('', $this->layout));
  687. }
  688. if ($layout !== null) {
  689. $this->layout = $defaultLayout;
  690. }
  691. $this->hasRendered = true;
  692. return $this->Blocks->get('content');
  693. }
  694. /**
  695. * Renders a layout. Returns output from _render(). Returns false on error.
  696. * Several variables are created for use in layout.
  697. *
  698. * @param string $content Content to render in a template, wrapped by the surrounding layout.
  699. * @param string|null $layout Layout name
  700. * @return mixed Rendered output, or false on error
  701. * @throws \Cake\Core\Exception\Exception if there is an error in the view.
  702. * @triggers View.beforeLayout $this, [$layoutFileName]
  703. * @triggers View.afterLayout $this, [$layoutFileName]
  704. */
  705. public function renderLayout($content, $layout = null)
  706. {
  707. $layoutFileName = $this->_getLayoutFileName($layout);
  708. if (empty($layoutFileName)) {
  709. return $this->Blocks->get('content');
  710. }
  711. if (!empty($content)) {
  712. $this->Blocks->set('content', $content);
  713. }
  714. $this->dispatchEvent('View.beforeLayout', [$layoutFileName]);
  715. $title = $this->Blocks->get('title');
  716. if ($title === '') {
  717. $title = Inflector::humanize($this->templatePath);
  718. $this->Blocks->set('title', $title);
  719. }
  720. $this->_currentType = static::TYPE_LAYOUT;
  721. $this->Blocks->set('content', $this->_render($layoutFileName));
  722. $this->dispatchEvent('View.afterLayout', [$layoutFileName]);
  723. return $this->Blocks->get('content');
  724. }
  725. /**
  726. * Returns a list of variables available in the current View context
  727. *
  728. * @return array Array of the set view variable names.
  729. */
  730. public function getVars()
  731. {
  732. return array_keys($this->viewVars);
  733. }
  734. /**
  735. * Returns the contents of the given View variable.
  736. *
  737. * @param string $var The view var you want the contents of.
  738. * @param mixed $default The default/fallback content of $var.
  739. * @return mixed The content of the named var if its set, otherwise $default.
  740. */
  741. public function get($var, $default = null)
  742. {
  743. if (!isset($this->viewVars[$var])) {
  744. return $default;
  745. }
  746. return $this->viewVars[$var];
  747. }
  748. /**
  749. * Get the names of all the existing blocks.
  750. *
  751. * @return array An array containing the blocks.
  752. * @see \Cake\View\ViewBlock::keys()
  753. */
  754. public function blocks()
  755. {
  756. return $this->Blocks->keys();
  757. }
  758. /**
  759. * Start capturing output for a 'block'
  760. *
  761. * You can use start on a block multiple times to
  762. * append or prepend content in a capture mode.
  763. *
  764. * ```
  765. * // Append content to an existing block.
  766. * $this->start('content');
  767. * echo $this->fetch('content');
  768. * echo 'Some new content';
  769. * $this->end();
  770. *
  771. * // Prepend content to an existing block
  772. * $this->start('content');
  773. * echo 'Some new content';
  774. * echo $this->fetch('content');
  775. * $this->end();
  776. * ```
  777. *
  778. * @param string $name The name of the block to capture for.
  779. * @return void
  780. * @see \Cake\View\ViewBlock::start()
  781. */
  782. public function start($name)
  783. {
  784. $this->Blocks->start($name);
  785. }
  786. /**
  787. * Append to an existing or new block.
  788. *
  789. * Appending to a new block will create the block.
  790. *
  791. * @param string $name Name of the block
  792. * @param mixed $value The content for the block. Value will be type cast
  793. * to string.
  794. * @return void
  795. * @see \Cake\View\ViewBlock::concat()
  796. */
  797. public function append($name, $value = null)
  798. {
  799. $this->Blocks->concat($name, $value);
  800. }
  801. /**
  802. * Prepend to an existing or new block.
  803. *
  804. * Prepending to a new block will create the block.
  805. *
  806. * @param string $name Name of the block
  807. * @param mixed $value The content for the block. Value will be type cast
  808. * to string.
  809. * @return void
  810. * @see \Cake\View\ViewBlock::concat()
  811. */
  812. public function prepend($name, $value)
  813. {
  814. $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
  815. }
  816. /**
  817. * Set the content for a block. This will overwrite any
  818. * existing content.
  819. *
  820. * @param string $name Name of the block
  821. * @param mixed $value The content for the block. Value will be type cast
  822. * to string.
  823. * @return void
  824. * @see \Cake\View\ViewBlock::set()
  825. */
  826. public function assign($name, $value)
  827. {
  828. $this->Blocks->set($name, $value);
  829. }
  830. /**
  831. * Reset the content for a block. This will overwrite any
  832. * existing content.
  833. *
  834. * @param string $name Name of the block
  835. * @return void
  836. * @see \Cake\View\ViewBlock::set()
  837. */
  838. public function reset($name)
  839. {
  840. $this->assign($name, '');
  841. }
  842. /**
  843. * Fetch the content for a block. If a block is
  844. * empty or undefined '' will be returned.
  845. *
  846. * @param string $name Name of the block
  847. * @param string $default Default text
  848. * @return string The block content or $default if the block does not exist.
  849. * @see \Cake\View\ViewBlock::get()
  850. */
  851. public function fetch($name, $default = '')
  852. {
  853. return $this->Blocks->get($name, $default);
  854. }
  855. /**
  856. * End a capturing block. The compliment to View::start()
  857. *
  858. * @return void
  859. * @see \Cake\View\ViewBlock::end()
  860. */
  861. public function end()
  862. {
  863. $this->Blocks->end();
  864. }
  865. /**
  866. * Check if a block exists
  867. *
  868. * @param string $name Name of the block
  869. *
  870. * @return bool
  871. */
  872. public function exists($name)
  873. {
  874. return $this->Blocks->exists($name);
  875. }
  876. /**
  877. * Provides template or element extension/inheritance. Views can extends a
  878. * parent view and populate blocks in the parent template.
  879. *
  880. * @param string $name The template or element to 'extend' the current one with.
  881. * @return void
  882. * @throws \LogicException when you extend a template with itself or make extend loops.
  883. * @throws \LogicException when you extend an element which doesn't exist
  884. */
  885. public function extend($name)
  886. {
  887. if ($name[0] === '/' || $this->_currentType === static::TYPE_TEMPLATE) {
  888. $parent = $this->_getViewFileName($name);
  889. } else {
  890. switch ($this->_currentType) {
  891. case static::TYPE_ELEMENT:
  892. $parent = $this->_getElementFileName($name);
  893. if (!$parent) {
  894. list($plugin, $name) = $this->pluginSplit($name);
  895. $paths = $this->_paths($plugin);
  896. $defaultPath = $paths[0] . static::NAME_ELEMENT . DIRECTORY_SEPARATOR;
  897. throw new LogicException(sprintf(
  898. 'You cannot extend an element which does not exist (%s).',
  899. $defaultPath . $name . $this->_ext
  900. ));
  901. }
  902. break;
  903. case static::TYPE_LAYOUT:
  904. $parent = $this->_getLayoutFileName($name);
  905. break;
  906. default:
  907. $parent = $this->_getViewFileName($name);
  908. }
  909. }
  910. if ($parent == $this->_current) {
  911. throw new LogicException('You cannot have views extend themselves.');
  912. }
  913. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  914. throw new LogicException('You cannot have views extend in a loop.');
  915. }
  916. $this->_parents[$this->_current] = $parent;
  917. }
  918. /**
  919. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  920. *
  921. * @param string $object Type of object, i.e. 'form' or 'link'
  922. * @param string $url The object's target URL
  923. * @return string
  924. */
  925. public function uuid($object, $url)
  926. {
  927. $c = 1;
  928. $url = Router::url($url);
  929. $hash = $object . substr(md5($object . $url), 0, 10);
  930. while (in_array($hash, $this->uuids)) {
  931. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  932. $c++;
  933. }
  934. $this->uuids[] = $hash;
  935. return $hash;
  936. }
  937. /**
  938. * Retrieve the current view type
  939. *
  940. * @return string
  941. */
  942. public function getCurrentType()
  943. {
  944. return $this->_currentType;
  945. }
  946. /**
  947. * Magic accessor for helpers.
  948. *
  949. * @param string $name Name of the attribute to get.
  950. * @return mixed
  951. */
  952. public function __get($name)
  953. {
  954. if ($name === 'view') {
  955. return $this->template;
  956. }
  957. if ($name === 'viewPath') {
  958. return $this->templatePath;
  959. }
  960. $registry = $this->helpers();
  961. if (isset($registry->{$name})) {
  962. $this->{$name} = $registry->{$name};
  963. return $registry->{$name};
  964. }
  965. return $this->{$name};
  966. }
  967. /**
  968. * Magic setter for deprecated properties.
  969. *
  970. * @param string $name Name to property.
  971. * @param mixed $value Value for property.
  972. * @return void
  973. */
  974. public function __set($name, $value)
  975. {
  976. if ($name === 'view') {
  977. $this->template = $value;
  978. return;
  979. }
  980. if ($name === 'viewPath') {
  981. $this->templatePath = $value;
  982. return;
  983. }
  984. $this->{$name} = $value;
  985. }
  986. /**
  987. * Interact with the HelperRegistry to load all the helpers.
  988. *
  989. * @return void
  990. */
  991. public function loadHelpers()
  992. {
  993. $registry = $this->helpers();
  994. $helpers = $registry->normalizeArray($this->helpers);
  995. foreach ($helpers as $properties) {
  996. $this->loadHelper($properties['class'], $properties['config']);
  997. }
  998. }
  999. /**
  1000. * Renders and returns output for given template filename with its
  1001. * array of data. Handles parent/extended templates.
  1002. *
  1003. * @param string $viewFile Filename of the view
  1004. * @param array $data Data to include in rendered view. If empty the current
  1005. * View::$viewVars will be used.
  1006. * @return string Rendered output
  1007. * @throws \LogicException When a block is left open.
  1008. * @triggers View.beforeRenderFile $this, [$viewFile]
  1009. * @triggers View.afterRenderFile $this, [$viewFile, $content]
  1010. */
  1011. protected function _render($viewFile, $data = [])
  1012. {
  1013. if (empty($data)) {
  1014. $data = $this->viewVars;
  1015. }
  1016. $this->_current = $viewFile;
  1017. $initialBlocks = count($this->Blocks->unclosed());
  1018. $this->dispatchEvent('View.beforeRenderFile', [$viewFile]);
  1019. $content = $this->_evaluate($viewFile, $data);
  1020. $afterEvent = $this->dispatchEvent('View.afterRenderFile', [$viewFile, $content]);
  1021. if ($afterEvent->getResult() !== null) {
  1022. $content = $afterEvent->getResult();
  1023. }
  1024. if (isset($this->_parents[$viewFile])) {
  1025. $this->_stack[] = $this->fetch('content');
  1026. $this->assign('content', $content);
  1027. $content = $this->_render($this->_parents[$viewFile]);
  1028. $this->assign('content', array_pop($this->_stack));
  1029. }
  1030. $remainingBlocks = count($this->Blocks->unclosed());
  1031. if ($initialBlocks !== $remainingBlocks) {
  1032. throw new LogicException(sprintf(
  1033. 'The "%s" block was left open. Blocks are not allowed to cross files.',
  1034. $this->Blocks->active()
  1035. ));
  1036. }
  1037. return $content;
  1038. }
  1039. /**
  1040. * Sandbox method to evaluate a template / view script in.
  1041. *
  1042. * @param string $viewFile Filename of the view
  1043. * @param array $dataForView Data to include in rendered view.
  1044. * @return string Rendered output
  1045. */
  1046. protected function _evaluate($viewFile, $dataForView)
  1047. {
  1048. extract($dataForView);
  1049. ob_start();
  1050. include func_get_arg(0);
  1051. return ob_get_clean();
  1052. }
  1053. /**
  1054. * Get the helper registry in use by this View class.
  1055. *
  1056. * @return \Cake\View\HelperRegistry
  1057. */
  1058. public function helpers()
  1059. {
  1060. if ($this->_helpers === null) {
  1061. $this->_helpers = new HelperRegistry($this);
  1062. }
  1063. return $this->_helpers;
  1064. }
  1065. /**
  1066. * Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
  1067. *
  1068. * @param string $name Name of the helper to load.
  1069. * @param array $config Settings for the helper
  1070. * @return \Cake\View\Helper a constructed helper object.
  1071. * @see \Cake\View\HelperRegistry::load()
  1072. */
  1073. public function loadHelper($name, array $config = [])
  1074. {
  1075. list(, $class) = pluginSplit($name);
  1076. $helpers = $this->helpers();
  1077. return $this->{$class} = $helpers->load($name, $config);
  1078. }
  1079. /**
  1080. * Returns filename of given action's template file (.ctp) as a string.
  1081. * CamelCased action names will be under_scored by default.
  1082. * This means that you can have LongActionNames that refer to
  1083. * long_action_names.ctp views. You can change the inflection rule by
  1084. * overriding _inflectViewFileName.
  1085. *
  1086. * @param string|null $name Controller action to find template filename for
  1087. * @return string Template filename
  1088. * @throws \Cake\View\Exception\MissingTemplateException when a view file could not be found.
  1089. */
  1090. protected function _getViewFileName($name = null)
  1091. {
  1092. $templatePath = $subDir = '';
  1093. if ($this->subDir !== null) {
  1094. $subDir = $this->subDir . DIRECTORY_SEPARATOR;
  1095. }
  1096. if ($this->templatePath) {
  1097. $templatePath = $this->templatePath . DIRECTORY_SEPARATOR;
  1098. }
  1099. if ($name === null) {
  1100. $name = $this->template;
  1101. }
  1102. list($plugin, $name) = $this->pluginSplit($name);
  1103. $name = str_replace('/', DIRECTORY_SEPARATOR, $name);
  1104. if (strpos($name, DIRECTORY_SEPARATOR) === false && $name !== '' && $name[0] !== '.') {
  1105. $name = $templatePath . $subDir . $this->_inflectViewFileName($name);
  1106. } elseif (strpos($name, DIRECTORY_SEPARATOR) !== false) {
  1107. if ($name[0] === DIRECTORY_SEPARATOR || $name[1] === ':') {
  1108. $name = trim($name, DIRECTORY_SEPARATOR);
  1109. } elseif (!$plugin || $this->templatePath !== $this->name) {
  1110. $name = $templatePath . $subDir . $name;
  1111. } else {
  1112. $name = DIRECTORY_SEPARATOR . $subDir . $name;
  1113. }
  1114. }
  1115. foreach ($this->_paths($plugin) as $path) {
  1116. if (file_exists($path . $name . $this->_ext)) {
  1117. return $this->_checkFilePath($path . $name . $this->_ext, $path);
  1118. }
  1119. }
  1120. throw new MissingTemplateException(['file' => $name . $this->_ext]);
  1121. }
  1122. /**
  1123. * Change the name of a view template file into underscored format.
  1124. *
  1125. * @param string $name Name of file which should be inflected.
  1126. * @return string File name after conversion
  1127. */
  1128. protected function _inflectViewFileName($name)
  1129. {
  1130. return Inflector::underscore($name);
  1131. }
  1132. /**
  1133. * Check that a view file path does not go outside of the defined template paths.
  1134. *
  1135. * Only paths that contain `..` will be checked, as they are the ones most likely to
  1136. * have the ability to resolve to files outside of the template paths.
  1137. *
  1138. * @param string $file The path to the template file.
  1139. * @param string $path Base path that $file should be inside of.
  1140. * @return string The file path
  1141. * @throws \InvalidArgumentException
  1142. */
  1143. protected function _checkFilePath($file, $path)
  1144. {
  1145. if (strpos($file, '..') === false) {
  1146. return $file;
  1147. }
  1148. $absolute = realpath($file);
  1149. if (strpos($absolute, $path) !== 0) {
  1150. throw new InvalidArgumentException(sprintf(
  1151. 'Cannot use "%s" as a template, it is not within any view template path.',
  1152. $file
  1153. ));
  1154. }
  1155. return $absolute;
  1156. }
  1157. /**
  1158. * Splits a dot syntax plugin name into its plugin and filename.
  1159. * If $name does not have a dot, then index 0 will be null.
  1160. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  1161. *
  1162. * @param string $name The name you want to plugin split.
  1163. * @param bool $fallback If true uses the plugin set in the current Request when parsed plugin is not loaded
  1164. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  1165. */
  1166. public function pluginSplit($name, $fallback = true)
  1167. {
  1168. $plugin = null;
  1169. list($first, $second) = pluginSplit($name);
  1170. if (Plugin::loaded($first) === true) {
  1171. $name = $second;
  1172. $plugin = $first;
  1173. }
  1174. if (isset($this->plugin) && !$plugin && $fallback) {
  1175. $plugin = $this->plugin;
  1176. }
  1177. return [$plugin, $name];
  1178. }
  1179. /**
  1180. * Returns layout filename for this template as a string.
  1181. *
  1182. * @param string|null $name The name of the layout to find.
  1183. * @return string Filename for layout file (.ctp).
  1184. * @throws \Cake\View\Exception\MissingLayoutException when a layout cannot be located
  1185. */
  1186. protected function _getLayoutFileName($name = null)
  1187. {
  1188. if ($name === null) {
  1189. $name = $this->layout;
  1190. }
  1191. $subDir = null;
  1192. if ($this->layoutPath) {
  1193. $subDir = $this->layoutPath . DIRECTORY_SEPARATOR;
  1194. }
  1195. list($plugin, $name) = $this->pluginSplit($name);
  1196. $layoutPaths = $this->_getSubPaths('Layout' . DIRECTORY_SEPARATOR . $subDir);
  1197. foreach ($this->_paths($plugin) as $path) {
  1198. foreach ($layoutPaths as $layoutPath) {
  1199. $currentPath = $path . $layoutPath;
  1200. if (file_exists($currentPath . $name . $this->_ext)) {
  1201. return $this->_checkFilePath($currentPath . $name . $this->_ext, $currentPath);
  1202. }
  1203. }
  1204. }
  1205. throw new MissingLayoutException([
  1206. 'file' => $layoutPaths[0] . $name . $this->_ext
  1207. ]);
  1208. }
  1209. /**
  1210. * Finds an element filename, returns false on failure.
  1211. *
  1212. * @param string $name The name of the element to find.
  1213. * @param bool $pluginCheck - if false will ignore the request's plugin if parsed plugin is not loaded
  1214. * @return string|false Either a string to the element filename or false when one can't be found.
  1215. */
  1216. protected function _getElementFileName($name, $pluginCheck = true)
  1217. {
  1218. list($plugin, $name) = $this->pluginSplit($name, $pluginCheck);
  1219. $paths = $this->_paths($plugin);
  1220. $elementPaths = $this->_getSubPaths(static::NAME_ELEMENT);
  1221. foreach ($paths as $path) {
  1222. foreach ($elementPaths as $elementPath) {
  1223. if (file_exists($path . $elementPath . DIRECTORY_SEPARATOR . $name . $this->_ext)) {
  1224. return $path . $elementPath . DIRECTORY_SEPARATOR . $name . $this->_ext;
  1225. }
  1226. }
  1227. }
  1228. return false;
  1229. }
  1230. /**
  1231. * Find all sub templates path, based on $basePath
  1232. * If a prefix is defined in the current request, this method will prepend
  1233. * the prefixed template path to the $basePath, cascading up in case the prefix
  1234. * is nested.
  1235. * This is essentially used to find prefixed template paths for elements
  1236. * and layouts.
  1237. *
  1238. * @param string $basePath Base path on which to get the prefixed one.
  1239. * @return array Array with all the templates paths.
  1240. */
  1241. protected function _getSubPaths($basePath)
  1242. {
  1243. $paths = [$basePath];
  1244. if ($this->request->getParam('prefix')) {
  1245. $prefixPath = explode('/', $this->request->getParam('prefix'));
  1246. $path = '';
  1247. foreach ($prefixPath as $prefixPart) {
  1248. $path .= Inflector::camelize($prefixPart) . DIRECTORY_SEPARATOR;
  1249. array_unshift(
  1250. $paths,
  1251. $path . $basePath
  1252. );
  1253. }
  1254. }
  1255. return $paths;
  1256. }
  1257. /**
  1258. * Return all possible paths to find view files in order
  1259. *
  1260. * @param string|null $plugin Optional plugin name to scan for view files.
  1261. * @param bool $cached Set to false to force a refresh of view paths. Default true.
  1262. * @return array paths
  1263. */
  1264. protected function _paths($plugin = null, $cached = true)
  1265. {
  1266. if ($cached === true) {
  1267. if ($plugin === null && !empty($this->_paths)) {
  1268. return $this->_paths;
  1269. }
  1270. if ($plugin !== null && isset($this->_pathsForPlugin[$plugin])) {
  1271. return $this->_pathsForPlugin[$plugin];
  1272. }
  1273. }
  1274. $templatePaths = App::path(static::NAME_TEMPLATE);
  1275. $pluginPaths = $themePaths = [];
  1276. if (!empty($plugin)) {
  1277. for ($i = 0, $count = count($templatePaths); $i < $count; $i++) {
  1278. $pluginPaths[] = $templatePaths[$i] . 'Plugin' . DIRECTORY_SEPARATOR . $plugin . DIRECTORY_SEPARATOR;
  1279. }
  1280. $pluginPaths = array_merge($pluginPaths, App::path(static::NAME_TEMPLATE, $plugin));
  1281. }
  1282. if (!empty($this->theme)) {
  1283. $themePaths = App::path(static::NAME_TEMPLATE, Inflector::camelize($this->theme));
  1284. if ($plugin) {
  1285. for ($i = 0, $count = count($themePaths); $i < $count; $i++) {
  1286. array_unshift($themePaths, $themePaths[$i] . 'Plugin' . DIRECTORY_SEPARATOR . $plugin . DIRECTORY_SEPARATOR);
  1287. }
  1288. }
  1289. }
  1290. $paths = array_merge(
  1291. $themePaths,
  1292. $pluginPaths,
  1293. $templatePaths,
  1294. [dirname(__DIR__) . DIRECTORY_SEPARATOR . static::NAME_TEMPLATE . DIRECTORY_SEPARATOR]
  1295. );
  1296. if ($plugin !== null) {
  1297. return $this->_pathsForPlugin[$plugin] = $paths;
  1298. }
  1299. return $this->_paths = $paths;
  1300. }
  1301. /**
  1302. * Generate the cache configuration options for an element.
  1303. *
  1304. * @param string $name Element name
  1305. * @param array $data Data
  1306. * @param array $options Element options
  1307. * @return array Element Cache configuration.
  1308. */
  1309. protected function _elementCache($name, $data, $options)
  1310. {
  1311. $plugin = null;
  1312. list($plugin, $name) = $this->pluginSplit($name);
  1313. $underscored = null;
  1314. if ($plugin) {
  1315. $underscored = Inflector::underscore($plugin);
  1316. }
  1317. $cache = $options['cache'];
  1318. unset($options['cache'], $options['callbacks'], $options['plugin']);
  1319. $keys = array_merge(
  1320. [$underscored, $name],
  1321. array_keys($options),
  1322. array_keys($data)
  1323. );
  1324. $config = [
  1325. 'config' => $this->elementCache,
  1326. 'key' => implode('_', $keys)
  1327. ];
  1328. if (is_array($cache)) {
  1329. $defaults = [
  1330. 'config' => $this->elementCache,
  1331. 'key' => $config['key']
  1332. ];
  1333. $config = $cache + $defaults;
  1334. }
  1335. $config['key'] = 'element_' . $config['key'];
  1336. return $config;
  1337. }
  1338. /**
  1339. * Renders an element and fires the before and afterRender callbacks for it
  1340. * and writes to the cache if a cache is used
  1341. *
  1342. * @param string $file Element file path
  1343. * @param array $data Data to render
  1344. * @param array $options Element options
  1345. * @return string
  1346. * @triggers View.beforeRender $this, [$file]
  1347. * @triggers View.afterRender $this, [$file, $element]
  1348. */
  1349. protected function _renderElement($file, $data, $options)
  1350. {
  1351. $current = $this->_current;
  1352. $restore = $this->_currentType;
  1353. $this->_currentType = static::TYPE_ELEMENT;
  1354. if ($options['callbacks']) {
  1355. $this->dispatchEvent('View.beforeRender', [$file]);
  1356. }
  1357. $element = $this->_render($file, array_merge($this->viewVars, $data));
  1358. if ($options['callbacks']) {
  1359. $this->dispatchEvent('View.afterRender', [$file, $element]);
  1360. }
  1361. $this->_currentType = $restore;
  1362. $this->_current = $current;
  1363. return $element;
  1364. }
  1365. }