View.php 47 KB

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