View.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595
  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 $this
  357. */
  358. public function setTemplatePath($path)
  359. {
  360. $this->templatePath = $path;
  361. return $this;
  362. }
  363. /**
  364. * Get/set path for templates files.
  365. *
  366. * @deprecated 3.5.0 Use getTemplatePath()/setTemplatePath() instead.
  367. * @param string|null $path Path for template files. If null returns current path.
  368. * @return string|null
  369. */
  370. public function templatePath($path = null)
  371. {
  372. deprecationWarning(
  373. 'View::templatePath() is deprecated. ' .
  374. 'Use getTemplatePath()/setTemplatePath() instead.'
  375. );
  376. if ($path === null) {
  377. return $this->templatePath;
  378. }
  379. $this->templatePath = $path;
  380. }
  381. /**
  382. * Get path for layout files.
  383. *
  384. * @return string
  385. */
  386. public function getLayoutPath()
  387. {
  388. return $this->layoutPath;
  389. }
  390. /**
  391. * Set path for layout files.
  392. *
  393. * @param string $path Path for layout files.
  394. * @return $this
  395. */
  396. public function setLayoutPath($path)
  397. {
  398. $this->layoutPath = $path;
  399. return $this;
  400. }
  401. /**
  402. * Get/set path for layout files.
  403. *
  404. * @deprecated 3.5.0 Use getLayoutPath()/setLayoutPath() instead.
  405. * @param string|null $path Path for layout files. If null returns current path.
  406. * @return string|null
  407. */
  408. public function layoutPath($path = null)
  409. {
  410. deprecationWarning(
  411. 'View::layoutPath() is deprecated. ' .
  412. 'Use getLayoutPath()/setLayoutPath() instead.'
  413. );
  414. if ($path === null) {
  415. return $this->layoutPath;
  416. }
  417. $this->layoutPath = $path;
  418. }
  419. /**
  420. * Returns if CakePHP's conventional mode of applying layout files is enabled.
  421. * Disabled means that layouts will not be automatically applied to rendered views.
  422. *
  423. * @return bool
  424. */
  425. public function isAutoLayoutEnabled()
  426. {
  427. return $this->autoLayout;
  428. }
  429. /**
  430. * Turns on or off CakePHP's conventional mode of applying layout files.
  431. * On by default. Setting to off means that layouts will not be
  432. * automatically applied to rendered views.
  433. *
  434. * @param bool $enable Boolean to turn on/off.
  435. * @return $this
  436. */
  437. public function enableAutoLayout($enable = true)
  438. {
  439. $this->autoLayout = (bool)$enable;
  440. return $this;
  441. }
  442. /**
  443. * Turns on or off CakePHP's conventional mode of applying layout files.
  444. * On by default. Setting to off means that layouts will not be
  445. * automatically applied to rendered templates.
  446. *
  447. * @deprecated 3.5.0 Use isAutoLayoutEnabled()/enableAutoLayout() instead.
  448. * @param bool|null $autoLayout Boolean to turn on/off. If null returns current value.
  449. * @return bool|null
  450. */
  451. public function autoLayout($autoLayout = null)
  452. {
  453. deprecationWarning(
  454. 'View::autoLayout() is deprecated. ' .
  455. 'Use isAutoLayoutEnabled()/enableAutoLayout() instead.'
  456. );
  457. if ($autoLayout === null) {
  458. return $this->autoLayout;
  459. }
  460. $this->autoLayout = $autoLayout;
  461. }
  462. /**
  463. * Get the current view theme.
  464. *
  465. * @return string|null
  466. */
  467. public function getTheme()
  468. {
  469. return $this->theme;
  470. }
  471. /**
  472. * Set the view theme to use.
  473. *
  474. * @param string|null $theme Theme name.
  475. * @return $this
  476. */
  477. public function setTheme($theme)
  478. {
  479. $this->theme = $theme;
  480. return $this;
  481. }
  482. /**
  483. * The view theme to use.
  484. *
  485. * @deprecated 3.5.0 Use getTheme()/setTheme() instead.
  486. * @param string|null $theme Theme name. If null returns current theme.
  487. * @return string|null
  488. */
  489. public function theme($theme = null)
  490. {
  491. deprecationWarning(
  492. 'View::theme() is deprecated. ' .
  493. 'Use getTheme()/setTheme() instead.'
  494. );
  495. if ($theme === null) {
  496. return $this->theme;
  497. }
  498. $this->theme = $theme;
  499. }
  500. /**
  501. * Get the name of the template file to render. The name specified is the
  502. * filename in /src/Template/<SubFolder> without the .ctp extension.
  503. *
  504. * @return string
  505. */
  506. public function getTemplate()
  507. {
  508. return $this->template;
  509. }
  510. /**
  511. * Set the name of the template file to render. The name specified is the
  512. * filename in /src/Template/<SubFolder> without the .ctp extension.
  513. *
  514. * @param string $name Template file name to set.
  515. * @return $this
  516. */
  517. public function setTemplate($name)
  518. {
  519. $this->template = $name;
  520. return $this;
  521. }
  522. /**
  523. * Get/set the name of the template file to render. The name specified is the
  524. * filename in /src/Template/<SubFolder> without the .ctp extension.
  525. *
  526. * @deprecated 3.5.0 Use getTemplate()/setTemplate() instead.
  527. * @param string|null $name Template file name to set. If null returns current name.
  528. * @return string|null
  529. */
  530. public function template($name = null)
  531. {
  532. deprecationWarning(
  533. 'View::template() is deprecated. ' .
  534. 'Use getTemplate()/setTemplate() instead.'
  535. );
  536. if ($name === null) {
  537. return $this->template;
  538. }
  539. $this->template = $name;
  540. }
  541. /**
  542. * Get the name of the layout file to render the template inside of.
  543. * The name specified is the filename of the layout in /src/Template/Layout
  544. * without the .ctp extension.
  545. *
  546. * @return string
  547. */
  548. public function getLayout()
  549. {
  550. return $this->layout;
  551. }
  552. /**
  553. * Set the name of the layout file to render the template inside of.
  554. * The name specified is the filename of the layout in /src/Template/Layout
  555. * without the .ctp extension.
  556. *
  557. * @param string $name Layout file name to set.
  558. * @return $this
  559. */
  560. public function setLayout($name)
  561. {
  562. $this->layout = $name;
  563. return $this;
  564. }
  565. /**
  566. * Get/set the name of the layout file to render the template inside of.
  567. * The name specified is the filename of the layout in /src/Template/Layout
  568. * without the .ctp extension.
  569. *
  570. * @deprecated 3.5.0 Use getLayout()/setLayout() instead.
  571. * @param string|null $name Layout file name to set. If null returns current name.
  572. * @return string|null
  573. */
  574. public function layout($name = null)
  575. {
  576. deprecationWarning(
  577. 'View::layout() is deprecated. ' .
  578. 'Use getLayout()/setLayout() instead.'
  579. );
  580. if ($name === null) {
  581. return $this->layout;
  582. }
  583. $this->layout = $name;
  584. }
  585. /**
  586. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  587. *
  588. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  589. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  590. *
  591. * @param string $name Name of template file in the /src/Template/Element/ folder,
  592. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  593. * is not found in the plugin, the normal view path cascade will be searched.
  594. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  595. * @param array $options Array of options. Possible keys are:
  596. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  597. * If an array, the following keys can be used:
  598. * - `config` - Used to store the cached element in a custom cache configuration.
  599. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  600. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  601. * Defaults to false.
  602. * - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions.
  603. * - `plugin` - setting to false will force to use the application's element from plugin templates, when the
  604. * plugin has element with same name. Defaults to true
  605. * @return string Rendered Element
  606. * @throws \Cake\View\Exception\MissingElementException When an element is missing and `ignoreMissing`
  607. * is false.
  608. */
  609. public function element($name, array $data = [], array $options = [])
  610. {
  611. $options += ['callbacks' => false, 'cache' => null, 'plugin' => null];
  612. if (isset($options['cache'])) {
  613. $options['cache'] = $this->_elementCache($name, $data, $options);
  614. }
  615. $pluginCheck = $options['plugin'] !== false;
  616. $file = $this->_getElementFileName($name, $pluginCheck);
  617. if ($file && $options['cache']) {
  618. return $this->cache(function () use ($file, $data, $options) {
  619. echo $this->_renderElement($file, $data, $options);
  620. }, $options['cache']);
  621. }
  622. if ($file) {
  623. return $this->_renderElement($file, $data, $options);
  624. }
  625. if (empty($options['ignoreMissing'])) {
  626. list ($plugin, $name) = pluginSplit($name, true);
  627. $name = str_replace('/', DIRECTORY_SEPARATOR, $name);
  628. $file = $plugin . static::NAME_ELEMENT . DIRECTORY_SEPARATOR . $name . $this->_ext;
  629. throw new MissingElementException([$file]);
  630. }
  631. }
  632. /**
  633. * Create a cached block of view logic.
  634. *
  635. * This allows you to cache a block of view output into the cache
  636. * defined in `elementCache`.
  637. *
  638. * This method will attempt to read the cache first. If the cache
  639. * is empty, the $block will be run and the output stored.
  640. *
  641. * @param callable $block The block of code that you want to cache the output of.
  642. * @param array $options The options defining the cache key etc.
  643. * @return string The rendered content.
  644. * @throws \RuntimeException When $options is lacking a 'key' option.
  645. */
  646. public function cache(callable $block, array $options = [])
  647. {
  648. $options += ['key' => '', 'config' => $this->elementCache];
  649. if (empty($options['key'])) {
  650. throw new RuntimeException('Cannot cache content with an empty key');
  651. }
  652. $result = Cache::read($options['key'], $options['config']);
  653. if ($result) {
  654. return $result;
  655. }
  656. ob_start();
  657. $block();
  658. $result = ob_get_clean();
  659. Cache::write($options['key'], $result, $options['config']);
  660. return $result;
  661. }
  662. /**
  663. * Checks if an element exists
  664. *
  665. * @param string $name Name of template file in the /src/Template/Element/ folder,
  666. * or `MyPlugin.template` to check the template element from MyPlugin. If the element
  667. * is not found in the plugin, the normal view path cascade will be searched.
  668. * @return bool Success
  669. */
  670. public function elementExists($name)
  671. {
  672. return (bool)$this->_getElementFileName($name);
  673. }
  674. /**
  675. * Renders view for given template file and layout.
  676. *
  677. * Render triggers helper callbacks, which are fired before and after the template are rendered,
  678. * as well as before and after the layout. The helper callbacks are called:
  679. *
  680. * - `beforeRender`
  681. * - `afterRender`
  682. * - `beforeLayout`
  683. * - `afterLayout`
  684. *
  685. * If View::$autoRender is false and no `$layout` is provided, the template will be returned bare.
  686. *
  687. * Template and layout names can point to plugin templates/layouts. Using the `Plugin.template` syntax
  688. * a plugin template/layout can be used instead of the app ones. If the chosen plugin is not found
  689. * the template will be located along the regular view path cascade.
  690. *
  691. * @param string|false|null $view Name of view file to use
  692. * @param string|null $layout Layout to use.
  693. * @return string|null Rendered content or null if content already rendered and returned earlier.
  694. * @throws \Cake\Core\Exception\Exception If there is an error in the view.
  695. * @triggers View.beforeRender $this, [$viewFileName]
  696. * @triggers View.afterRender $this, [$viewFileName]
  697. */
  698. public function render($view = null, $layout = null)
  699. {
  700. if ($this->hasRendered) {
  701. return null;
  702. }
  703. $defaultLayout = null;
  704. if ($layout !== null) {
  705. $defaultLayout = $this->layout;
  706. $this->layout = $layout;
  707. }
  708. $viewFileName = $view !== false ? $this->_getViewFileName($view) : null;
  709. if ($viewFileName) {
  710. $this->_currentType = static::TYPE_TEMPLATE;
  711. $this->dispatchEvent('View.beforeRender', [$viewFileName]);
  712. $this->Blocks->set('content', $this->_render($viewFileName));
  713. $this->dispatchEvent('View.afterRender', [$viewFileName]);
  714. }
  715. if ($this->layout && $this->autoLayout) {
  716. $this->Blocks->set('content', $this->renderLayout('', $this->layout));
  717. }
  718. if ($layout !== null) {
  719. $this->layout = $defaultLayout;
  720. }
  721. $this->hasRendered = true;
  722. return $this->Blocks->get('content');
  723. }
  724. /**
  725. * Renders a layout. Returns output from _render(). Returns false on error.
  726. * Several variables are created for use in layout.
  727. *
  728. * @param string $content Content to render in a template, wrapped by the surrounding layout.
  729. * @param string|null $layout Layout name
  730. * @return mixed Rendered output, or false on error
  731. * @throws \Cake\Core\Exception\Exception if there is an error in the view.
  732. * @triggers View.beforeLayout $this, [$layoutFileName]
  733. * @triggers View.afterLayout $this, [$layoutFileName]
  734. */
  735. public function renderLayout($content, $layout = null)
  736. {
  737. $layoutFileName = $this->_getLayoutFileName($layout);
  738. if (empty($layoutFileName)) {
  739. return $this->Blocks->get('content');
  740. }
  741. if (!empty($content)) {
  742. $this->Blocks->set('content', $content);
  743. }
  744. $this->dispatchEvent('View.beforeLayout', [$layoutFileName]);
  745. $title = $this->Blocks->get('title');
  746. if ($title === '') {
  747. $title = Inflector::humanize($this->templatePath);
  748. $this->Blocks->set('title', $title);
  749. }
  750. $this->_currentType = static::TYPE_LAYOUT;
  751. $this->Blocks->set('content', $this->_render($layoutFileName));
  752. $this->dispatchEvent('View.afterLayout', [$layoutFileName]);
  753. return $this->Blocks->get('content');
  754. }
  755. /**
  756. * Returns a list of variables available in the current View context
  757. *
  758. * @return array Array of the set view variable names.
  759. */
  760. public function getVars()
  761. {
  762. return array_keys($this->viewVars);
  763. }
  764. /**
  765. * Returns the contents of the given View variable.
  766. *
  767. * @param string $var The view var you want the contents of.
  768. * @param mixed $default The default/fallback content of $var.
  769. * @return mixed The content of the named var if its set, otherwise $default.
  770. */
  771. public function get($var, $default = null)
  772. {
  773. if (!isset($this->viewVars[$var])) {
  774. return $default;
  775. }
  776. return $this->viewVars[$var];
  777. }
  778. /**
  779. * Get the names of all the existing blocks.
  780. *
  781. * @return array An array containing the blocks.
  782. * @see \Cake\View\ViewBlock::keys()
  783. */
  784. public function blocks()
  785. {
  786. return $this->Blocks->keys();
  787. }
  788. /**
  789. * Start capturing output for a 'block'
  790. *
  791. * You can use start on a block multiple times to
  792. * append or prepend content in a capture mode.
  793. *
  794. * ```
  795. * // Append content to an existing block.
  796. * $this->start('content');
  797. * echo $this->fetch('content');
  798. * echo 'Some new content';
  799. * $this->end();
  800. *
  801. * // Prepend content to an existing block
  802. * $this->start('content');
  803. * echo 'Some new content';
  804. * echo $this->fetch('content');
  805. * $this->end();
  806. * ```
  807. *
  808. * @param string $name The name of the block to capture for.
  809. * @return $this
  810. * @see \Cake\View\ViewBlock::start()
  811. */
  812. public function start($name)
  813. {
  814. $this->Blocks->start($name);
  815. return $this;
  816. }
  817. /**
  818. * Append to an existing or new block.
  819. *
  820. * Appending to a new block will create the block.
  821. *
  822. * @param string $name Name of the block
  823. * @param mixed $value The content for the block. Value will be type cast
  824. * to string.
  825. * @return $this
  826. * @see \Cake\View\ViewBlock::concat()
  827. */
  828. public function append($name, $value = null)
  829. {
  830. $this->Blocks->concat($name, $value);
  831. return $this;
  832. }
  833. /**
  834. * Prepend to an existing or new block.
  835. *
  836. * Prepending to a new block will create the block.
  837. *
  838. * @param string $name Name of the block
  839. * @param mixed $value The content for the block. Value will be type cast
  840. * to string.
  841. * @return $this
  842. * @see \Cake\View\ViewBlock::concat()
  843. */
  844. public function prepend($name, $value)
  845. {
  846. $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
  847. return $this;
  848. }
  849. /**
  850. * Set the content for a block. This will overwrite any
  851. * existing content.
  852. *
  853. * @param string $name Name of the block
  854. * @param mixed $value The content for the block. Value will be type cast
  855. * to string.
  856. * @return $this
  857. * @see \Cake\View\ViewBlock::set()
  858. */
  859. public function assign($name, $value)
  860. {
  861. $this->Blocks->set($name, $value);
  862. return $this;
  863. }
  864. /**
  865. * Reset the content for a block. This will overwrite any
  866. * existing content.
  867. *
  868. * @param string $name Name of the block
  869. * @return $this
  870. * @see \Cake\View\ViewBlock::set()
  871. */
  872. public function reset($name)
  873. {
  874. $this->assign($name, '');
  875. return $this;
  876. }
  877. /**
  878. * Fetch the content for a block. If a block is
  879. * empty or undefined '' will be returned.
  880. *
  881. * @param string $name Name of the block
  882. * @param string $default Default text
  883. * @return string The block content or $default if the block does not exist.
  884. * @see \Cake\View\ViewBlock::get()
  885. */
  886. public function fetch($name, $default = '')
  887. {
  888. return $this->Blocks->get($name, $default);
  889. }
  890. /**
  891. * End a capturing block. The compliment to View::start()
  892. *
  893. * @return $this
  894. * @see \Cake\View\ViewBlock::end()
  895. */
  896. public function end()
  897. {
  898. $this->Blocks->end();
  899. return $this;
  900. }
  901. /**
  902. * Check if a block exists
  903. *
  904. * @param string $name Name of the block
  905. *
  906. * @return bool
  907. */
  908. public function exists($name)
  909. {
  910. return $this->Blocks->exists($name);
  911. }
  912. /**
  913. * Provides template or element extension/inheritance. Views can extends a
  914. * parent view and populate blocks in the parent template.
  915. *
  916. * @param string $name The template or element to 'extend' the current one with.
  917. * @return $this
  918. * @throws \LogicException when you extend a template with itself or make extend loops.
  919. * @throws \LogicException when you extend an element which doesn't exist
  920. */
  921. public function extend($name)
  922. {
  923. if ($name[0] === '/' || $this->_currentType === static::TYPE_TEMPLATE) {
  924. $parent = $this->_getViewFileName($name);
  925. } else {
  926. switch ($this->_currentType) {
  927. case static::TYPE_ELEMENT:
  928. $parent = $this->_getElementFileName($name);
  929. if (!$parent) {
  930. list($plugin, $name) = $this->pluginSplit($name);
  931. $paths = $this->_paths($plugin);
  932. $defaultPath = $paths[0] . static::NAME_ELEMENT . DIRECTORY_SEPARATOR;
  933. throw new LogicException(sprintf(
  934. 'You cannot extend an element which does not exist (%s).',
  935. $defaultPath . $name . $this->_ext
  936. ));
  937. }
  938. break;
  939. case static::TYPE_LAYOUT:
  940. $parent = $this->_getLayoutFileName($name);
  941. break;
  942. default:
  943. $parent = $this->_getViewFileName($name);
  944. }
  945. }
  946. if ($parent == $this->_current) {
  947. throw new LogicException('You cannot have views extend themselves.');
  948. }
  949. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  950. throw new LogicException('You cannot have views extend in a loop.');
  951. }
  952. $this->_parents[$this->_current] = $parent;
  953. return $this;
  954. }
  955. /**
  956. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  957. *
  958. * @param string $object Type of object, i.e. 'form' or 'link'
  959. * @param string $url The object's target URL
  960. * @return string
  961. */
  962. public function uuid($object, $url)
  963. {
  964. $c = 1;
  965. $url = Router::url($url);
  966. $hash = $object . substr(md5($object . $url), 0, 10);
  967. while (in_array($hash, $this->uuids)) {
  968. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  969. $c++;
  970. }
  971. $this->uuids[] = $hash;
  972. return $hash;
  973. }
  974. /**
  975. * Retrieve the current view type
  976. *
  977. * @return string
  978. */
  979. public function getCurrentType()
  980. {
  981. return $this->_currentType;
  982. }
  983. /**
  984. * Magic accessor for helpers.
  985. *
  986. * @param string $name Name of the attribute to get.
  987. * @return mixed
  988. */
  989. public function __get($name)
  990. {
  991. if ($name === 'view') {
  992. deprecationWarning('The `view` property is deprecated. Use View::getTemplate() instead.');
  993. return $this->template;
  994. }
  995. if ($name === 'viewPath') {
  996. deprecationWarning('The `viewPath` property is deprecated. Use View::getTemplatePath() instead.');
  997. return $this->templatePath;
  998. }
  999. $registry = $this->helpers();
  1000. if (isset($registry->{$name})) {
  1001. $this->{$name} = $registry->{$name};
  1002. return $registry->{$name};
  1003. }
  1004. return $this->{$name};
  1005. }
  1006. /**
  1007. * Magic setter for deprecated properties.
  1008. *
  1009. * @param string $name Name to property.
  1010. * @param mixed $value Value for property.
  1011. * @return void
  1012. */
  1013. public function __set($name, $value)
  1014. {
  1015. if ($name === 'view') {
  1016. deprecationWarning('The `view` property is deprecated. Use View::setTemplate() instead.');
  1017. $this->template = $value;
  1018. return;
  1019. }
  1020. if ($name === 'viewPath') {
  1021. deprecationWarning('The `viewPath` property is deprecated. Use View::setTemplatePath() instead.');
  1022. $this->templatePath = $value;
  1023. return;
  1024. }
  1025. $this->{$name} = $value;
  1026. }
  1027. /**
  1028. * Interact with the HelperRegistry to load all the helpers.
  1029. *
  1030. * @return $this
  1031. */
  1032. public function loadHelpers()
  1033. {
  1034. $registry = $this->helpers();
  1035. $helpers = $registry->normalizeArray($this->helpers);
  1036. foreach ($helpers as $properties) {
  1037. $this->loadHelper($properties['class'], $properties['config']);
  1038. }
  1039. return $this;
  1040. }
  1041. /**
  1042. * Renders and returns output for given template filename with its
  1043. * array of data. Handles parent/extended templates.
  1044. *
  1045. * @param string $viewFile Filename of the view
  1046. * @param array $data Data to include in rendered view. If empty the current
  1047. * View::$viewVars will be used.
  1048. * @return string Rendered output
  1049. * @throws \LogicException When a block is left open.
  1050. * @triggers View.beforeRenderFile $this, [$viewFile]
  1051. * @triggers View.afterRenderFile $this, [$viewFile, $content]
  1052. */
  1053. protected function _render($viewFile, $data = [])
  1054. {
  1055. if (empty($data)) {
  1056. $data = $this->viewVars;
  1057. }
  1058. $this->_current = $viewFile;
  1059. $initialBlocks = count($this->Blocks->unclosed());
  1060. $this->dispatchEvent('View.beforeRenderFile', [$viewFile]);
  1061. $content = $this->_evaluate($viewFile, $data);
  1062. $afterEvent = $this->dispatchEvent('View.afterRenderFile', [$viewFile, $content]);
  1063. if ($afterEvent->getResult() !== null) {
  1064. $content = $afterEvent->getResult();
  1065. }
  1066. if (isset($this->_parents[$viewFile])) {
  1067. $this->_stack[] = $this->fetch('content');
  1068. $this->assign('content', $content);
  1069. $content = $this->_render($this->_parents[$viewFile]);
  1070. $this->assign('content', array_pop($this->_stack));
  1071. }
  1072. $remainingBlocks = count($this->Blocks->unclosed());
  1073. if ($initialBlocks !== $remainingBlocks) {
  1074. throw new LogicException(sprintf(
  1075. 'The "%s" block was left open. Blocks are not allowed to cross files.',
  1076. $this->Blocks->active()
  1077. ));
  1078. }
  1079. return $content;
  1080. }
  1081. /**
  1082. * Sandbox method to evaluate a template / view script in.
  1083. *
  1084. * @param string $viewFile Filename of the view
  1085. * @param array $dataForView Data to include in rendered view.
  1086. * @return string Rendered output
  1087. */
  1088. protected function _evaluate($viewFile, $dataForView)
  1089. {
  1090. extract($dataForView);
  1091. ob_start();
  1092. include func_get_arg(0);
  1093. return ob_get_clean();
  1094. }
  1095. /**
  1096. * Get the helper registry in use by this View class.
  1097. *
  1098. * @return \Cake\View\HelperRegistry
  1099. */
  1100. public function helpers()
  1101. {
  1102. if ($this->_helpers === null) {
  1103. $this->_helpers = new HelperRegistry($this);
  1104. }
  1105. return $this->_helpers;
  1106. }
  1107. /**
  1108. * Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
  1109. *
  1110. * @param string $name Name of the helper to load.
  1111. * @param array $config Settings for the helper
  1112. * @return \Cake\View\Helper a constructed helper object.
  1113. * @see \Cake\View\HelperRegistry::load()
  1114. */
  1115. public function loadHelper($name, array $config = [])
  1116. {
  1117. list(, $class) = pluginSplit($name);
  1118. $helpers = $this->helpers();
  1119. return $this->{$class} = $helpers->load($name, $config);
  1120. }
  1121. /**
  1122. * Returns filename of given action's template file (.ctp) as a string.
  1123. * CamelCased action names will be under_scored by default.
  1124. * This means that you can have LongActionNames that refer to
  1125. * long_action_names.ctp views. You can change the inflection rule by
  1126. * overriding _inflectViewFileName.
  1127. *
  1128. * @param string|null $name Controller action to find template filename for
  1129. * @return string Template filename
  1130. * @throws \Cake\View\Exception\MissingTemplateException when a view file could not be found.
  1131. */
  1132. protected function _getViewFileName($name = null)
  1133. {
  1134. $templatePath = $subDir = '';
  1135. if ($this->subDir !== null) {
  1136. $subDir = $this->subDir . DIRECTORY_SEPARATOR;
  1137. }
  1138. if ($this->templatePath) {
  1139. $templatePath = $this->templatePath . DIRECTORY_SEPARATOR;
  1140. }
  1141. if ($name === null) {
  1142. $name = $this->template;
  1143. }
  1144. list($plugin, $name) = $this->pluginSplit($name);
  1145. $name = str_replace('/', DIRECTORY_SEPARATOR, $name);
  1146. if (strpos($name, DIRECTORY_SEPARATOR) === false && $name !== '' && $name[0] !== '.') {
  1147. $name = $templatePath . $subDir . $this->_inflectViewFileName($name);
  1148. } elseif (strpos($name, DIRECTORY_SEPARATOR) !== false) {
  1149. if ($name[0] === DIRECTORY_SEPARATOR || $name[1] === ':') {
  1150. $name = trim($name, DIRECTORY_SEPARATOR);
  1151. } elseif (!$plugin || $this->templatePath !== $this->name) {
  1152. $name = $templatePath . $subDir . $name;
  1153. } else {
  1154. $name = DIRECTORY_SEPARATOR . $subDir . $name;
  1155. }
  1156. }
  1157. foreach ($this->_paths($plugin) as $path) {
  1158. if (file_exists($path . $name . $this->_ext)) {
  1159. return $this->_checkFilePath($path . $name . $this->_ext, $path);
  1160. }
  1161. }
  1162. throw new MissingTemplateException(['file' => $name . $this->_ext]);
  1163. }
  1164. /**
  1165. * Change the name of a view template file into underscored format.
  1166. *
  1167. * @param string $name Name of file which should be inflected.
  1168. * @return string File name after conversion
  1169. */
  1170. protected function _inflectViewFileName($name)
  1171. {
  1172. return Inflector::underscore($name);
  1173. }
  1174. /**
  1175. * Check that a view file path does not go outside of the defined template paths.
  1176. *
  1177. * Only paths that contain `..` will be checked, as they are the ones most likely to
  1178. * have the ability to resolve to files outside of the template paths.
  1179. *
  1180. * @param string $file The path to the template file.
  1181. * @param string $path Base path that $file should be inside of.
  1182. * @return string The file path
  1183. * @throws \InvalidArgumentException
  1184. */
  1185. protected function _checkFilePath($file, $path)
  1186. {
  1187. if (strpos($file, '..') === false) {
  1188. return $file;
  1189. }
  1190. $absolute = realpath($file);
  1191. if (strpos($absolute, $path) !== 0) {
  1192. throw new InvalidArgumentException(sprintf(
  1193. 'Cannot use "%s" as a template, it is not within any view template path.',
  1194. $file
  1195. ));
  1196. }
  1197. return $absolute;
  1198. }
  1199. /**
  1200. * Splits a dot syntax plugin name into its plugin and filename.
  1201. * If $name does not have a dot, then index 0 will be null.
  1202. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  1203. *
  1204. * @param string $name The name you want to plugin split.
  1205. * @param bool $fallback If true uses the plugin set in the current Request when parsed plugin is not loaded
  1206. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  1207. */
  1208. public function pluginSplit($name, $fallback = true)
  1209. {
  1210. $plugin = null;
  1211. list($first, $second) = pluginSplit($name);
  1212. if (Plugin::loaded($first) === true) {
  1213. $name = $second;
  1214. $plugin = $first;
  1215. }
  1216. if (isset($this->plugin) && !$plugin && $fallback) {
  1217. $plugin = $this->plugin;
  1218. }
  1219. return [$plugin, $name];
  1220. }
  1221. /**
  1222. * Returns layout filename for this template as a string.
  1223. *
  1224. * @param string|null $name The name of the layout to find.
  1225. * @return string Filename for layout file (.ctp).
  1226. * @throws \Cake\View\Exception\MissingLayoutException when a layout cannot be located
  1227. */
  1228. protected function _getLayoutFileName($name = null)
  1229. {
  1230. if ($name === null) {
  1231. $name = $this->layout;
  1232. }
  1233. $subDir = null;
  1234. if ($this->layoutPath) {
  1235. $subDir = $this->layoutPath . DIRECTORY_SEPARATOR;
  1236. }
  1237. list($plugin, $name) = $this->pluginSplit($name);
  1238. $layoutPaths = $this->_getSubPaths('Layout' . DIRECTORY_SEPARATOR . $subDir);
  1239. foreach ($this->_paths($plugin) as $path) {
  1240. foreach ($layoutPaths as $layoutPath) {
  1241. $currentPath = $path . $layoutPath;
  1242. if (file_exists($currentPath . $name . $this->_ext)) {
  1243. return $this->_checkFilePath($currentPath . $name . $this->_ext, $currentPath);
  1244. }
  1245. }
  1246. }
  1247. throw new MissingLayoutException([
  1248. 'file' => $layoutPaths[0] . $name . $this->_ext
  1249. ]);
  1250. }
  1251. /**
  1252. * Finds an element filename, returns false on failure.
  1253. *
  1254. * @param string $name The name of the element to find.
  1255. * @param bool $pluginCheck - if false will ignore the request's plugin if parsed plugin is not loaded
  1256. * @return string|false Either a string to the element filename or false when one can't be found.
  1257. */
  1258. protected function _getElementFileName($name, $pluginCheck = true)
  1259. {
  1260. list($plugin, $name) = $this->pluginSplit($name, $pluginCheck);
  1261. $paths = $this->_paths($plugin);
  1262. $elementPaths = $this->_getSubPaths(static::NAME_ELEMENT);
  1263. foreach ($paths as $path) {
  1264. foreach ($elementPaths as $elementPath) {
  1265. if (file_exists($path . $elementPath . DIRECTORY_SEPARATOR . $name . $this->_ext)) {
  1266. return $path . $elementPath . DIRECTORY_SEPARATOR . $name . $this->_ext;
  1267. }
  1268. }
  1269. }
  1270. return false;
  1271. }
  1272. /**
  1273. * Find all sub templates path, based on $basePath
  1274. * If a prefix is defined in the current request, this method will prepend
  1275. * the prefixed template path to the $basePath, cascading up in case the prefix
  1276. * is nested.
  1277. * This is essentially used to find prefixed template paths for elements
  1278. * and layouts.
  1279. *
  1280. * @param string $basePath Base path on which to get the prefixed one.
  1281. * @return array Array with all the templates paths.
  1282. */
  1283. protected function _getSubPaths($basePath)
  1284. {
  1285. $paths = [$basePath];
  1286. if ($this->request->getParam('prefix')) {
  1287. $prefixPath = explode('/', $this->request->getParam('prefix'));
  1288. $path = '';
  1289. foreach ($prefixPath as $prefixPart) {
  1290. $path .= Inflector::camelize($prefixPart) . DIRECTORY_SEPARATOR;
  1291. array_unshift(
  1292. $paths,
  1293. $path . $basePath
  1294. );
  1295. }
  1296. }
  1297. return $paths;
  1298. }
  1299. /**
  1300. * Return all possible paths to find view files in order
  1301. *
  1302. * @param string|null $plugin Optional plugin name to scan for view files.
  1303. * @param bool $cached Set to false to force a refresh of view paths. Default true.
  1304. * @return array paths
  1305. */
  1306. protected function _paths($plugin = null, $cached = true)
  1307. {
  1308. if ($cached === true) {
  1309. if ($plugin === null && !empty($this->_paths)) {
  1310. return $this->_paths;
  1311. }
  1312. if ($plugin !== null && isset($this->_pathsForPlugin[$plugin])) {
  1313. return $this->_pathsForPlugin[$plugin];
  1314. }
  1315. }
  1316. $templatePaths = App::path(static::NAME_TEMPLATE);
  1317. $pluginPaths = $themePaths = [];
  1318. if (!empty($plugin)) {
  1319. for ($i = 0, $count = count($templatePaths); $i < $count; $i++) {
  1320. $pluginPaths[] = $templatePaths[$i] . 'Plugin' . DIRECTORY_SEPARATOR . $plugin . DIRECTORY_SEPARATOR;
  1321. }
  1322. $pluginPaths = array_merge($pluginPaths, App::path(static::NAME_TEMPLATE, $plugin));
  1323. }
  1324. if (!empty($this->theme)) {
  1325. $themePaths = App::path(static::NAME_TEMPLATE, Inflector::camelize($this->theme));
  1326. if ($plugin) {
  1327. for ($i = 0, $count = count($themePaths); $i < $count; $i++) {
  1328. array_unshift($themePaths, $themePaths[$i] . 'Plugin' . DIRECTORY_SEPARATOR . $plugin . DIRECTORY_SEPARATOR);
  1329. }
  1330. }
  1331. }
  1332. $paths = array_merge(
  1333. $themePaths,
  1334. $pluginPaths,
  1335. $templatePaths,
  1336. [dirname(__DIR__) . DIRECTORY_SEPARATOR . static::NAME_TEMPLATE . DIRECTORY_SEPARATOR]
  1337. );
  1338. if ($plugin !== null) {
  1339. return $this->_pathsForPlugin[$plugin] = $paths;
  1340. }
  1341. return $this->_paths = $paths;
  1342. }
  1343. /**
  1344. * Generate the cache configuration options for an element.
  1345. *
  1346. * @param string $name Element name
  1347. * @param array $data Data
  1348. * @param array $options Element options
  1349. * @return array Element Cache configuration.
  1350. */
  1351. protected function _elementCache($name, $data, $options)
  1352. {
  1353. if (isset($options['cache']['key'], $options['cache']['config'])) {
  1354. $cache = $options['cache'];
  1355. $cache['key'] = 'element_' . $cache['key'];
  1356. return $cache;
  1357. }
  1358. $plugin = null;
  1359. list($plugin, $name) = $this->pluginSplit($name);
  1360. $underscored = null;
  1361. if ($plugin) {
  1362. $underscored = Inflector::underscore($plugin);
  1363. }
  1364. $cache = $options['cache'];
  1365. unset($options['cache'], $options['callbacks'], $options['plugin']);
  1366. $keys = array_merge(
  1367. [$underscored, $name],
  1368. array_keys($options),
  1369. array_keys($data)
  1370. );
  1371. $config = [
  1372. 'config' => $this->elementCache,
  1373. 'key' => implode('_', $keys)
  1374. ];
  1375. if (is_array($cache)) {
  1376. $defaults = [
  1377. 'config' => $this->elementCache,
  1378. 'key' => $config['key']
  1379. ];
  1380. $config = $cache + $defaults;
  1381. }
  1382. $config['key'] = 'element_' . $config['key'];
  1383. return $config;
  1384. }
  1385. /**
  1386. * Renders an element and fires the before and afterRender callbacks for it
  1387. * and writes to the cache if a cache is used
  1388. *
  1389. * @param string $file Element file path
  1390. * @param array $data Data to render
  1391. * @param array $options Element options
  1392. * @return string
  1393. * @triggers View.beforeRender $this, [$file]
  1394. * @triggers View.afterRender $this, [$file, $element]
  1395. */
  1396. protected function _renderElement($file, $data, $options)
  1397. {
  1398. $current = $this->_current;
  1399. $restore = $this->_currentType;
  1400. $this->_currentType = static::TYPE_ELEMENT;
  1401. if ($options['callbacks']) {
  1402. $this->dispatchEvent('View.beforeRender', [$file]);
  1403. }
  1404. $element = $this->_render($file, array_merge($this->viewVars, $data));
  1405. if ($options['callbacks']) {
  1406. $this->dispatchEvent('View.afterRender', [$file, $element]);
  1407. }
  1408. $this->_currentType = $restore;
  1409. $this->_current = $current;
  1410. return $element;
  1411. }
  1412. }