View.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\base;
  8. use Yii;
  9. use yii\helpers\FileHelper;
  10. use yii\widgets\Block;
  11. use yii\widgets\ContentDecorator;
  12. use yii\widgets\FragmentCache;
  13. /**
  14. * View represents a view object in the MVC pattern.
  15. *
  16. * View provides a set of methods (e.g. [[render()]]) for rendering purpose.
  17. *
  18. * For more details and usage information on View, see the [guide article on views](guide:structure-views).
  19. *
  20. * @property-read DynamicContentAwareInterface[] $dynamicContents Class instances supporting dynamic contents.
  21. * @property-read string|bool $viewFile The view file currently being rendered. False if no view file is being
  22. * rendered.
  23. *
  24. * @author Qiang Xue <qiang.xue@gmail.com>
  25. * @since 2.0
  26. */
  27. class View extends Component implements DynamicContentAwareInterface
  28. {
  29. /**
  30. * @event Event an event that is triggered by [[beginPage()]].
  31. */
  32. const EVENT_BEGIN_PAGE = 'beginPage';
  33. /**
  34. * @event Event an event that is triggered by [[endPage()]].
  35. */
  36. const EVENT_END_PAGE = 'endPage';
  37. /**
  38. * @event ViewEvent an event that is triggered by [[renderFile()]] right before it renders a view file.
  39. */
  40. const EVENT_BEFORE_RENDER = 'beforeRender';
  41. /**
  42. * @event ViewEvent an event that is triggered by [[renderFile()]] right after it renders a view file.
  43. */
  44. const EVENT_AFTER_RENDER = 'afterRender';
  45. /**
  46. * @var ViewContextInterface the context under which the [[renderFile()]] method is being invoked.
  47. */
  48. public $context;
  49. /**
  50. * @var array custom parameters that are shared among view templates.
  51. */
  52. public $params = [];
  53. /**
  54. * @var array|null a list of available renderers indexed by their corresponding supported file extensions.
  55. * Each renderer may be a view renderer object or the configuration for creating the renderer object.
  56. * For example, the following configuration enables both Smarty and Twig view renderers:
  57. *
  58. * ```php
  59. * [
  60. * 'tpl' => ['class' => 'yii\smarty\ViewRenderer'],
  61. * 'twig' => ['class' => 'yii\twig\ViewRenderer'],
  62. * ]
  63. * ```
  64. *
  65. * If no renderer is available for the given view file, the view file will be treated as a normal PHP
  66. * and rendered via [[renderPhpFile()]].
  67. */
  68. public $renderers;
  69. /**
  70. * @var string the default view file extension. This will be appended to view file names if they don't have file extensions.
  71. */
  72. public $defaultExtension = 'php';
  73. /**
  74. * @var Theme|array|string|null the theme object or the configuration for creating the theme object.
  75. * If not set, it means theming is not enabled.
  76. */
  77. public $theme;
  78. /**
  79. * @var array a list of named output blocks. The keys are the block names and the values
  80. * are the corresponding block content. You can call [[beginBlock()]] and [[endBlock()]]
  81. * to capture small fragments of a view. They can be later accessed somewhere else
  82. * through this property.
  83. */
  84. public $blocks;
  85. /**
  86. * @var array|DynamicContentAwareInterface[] a list of currently active dynamic content class instances.
  87. * This property is used internally to implement the dynamic content caching feature. Do not modify it directly.
  88. * @internal
  89. * @deprecated Since 2.0.14. Do not use this property directly. Use methods [[getDynamicContents()]],
  90. * [[pushDynamicContent()]], [[popDynamicContent()]] instead.
  91. */
  92. public $cacheStack = [];
  93. /**
  94. * @var array a list of placeholders for embedding dynamic contents. This property
  95. * is used internally to implement the content caching feature. Do not modify it directly.
  96. * @internal
  97. * @deprecated Since 2.0.14. Do not use this property directly. Use methods [[getDynamicPlaceholders()]],
  98. * [[setDynamicPlaceholders()]], [[addDynamicPlaceholder()]] instead.
  99. */
  100. public $dynamicPlaceholders = [];
  101. /**
  102. * @var array the view files currently being rendered. There may be multiple view files being
  103. * rendered at a moment because one view may be rendered within another.
  104. */
  105. private $_viewFiles = [];
  106. /**
  107. * Initializes the view component.
  108. */
  109. public function init()
  110. {
  111. parent::init();
  112. if (is_array($this->theme)) {
  113. if (!isset($this->theme['class'])) {
  114. $this->theme['class'] = 'yii\base\Theme';
  115. }
  116. $this->theme = Yii::createObject($this->theme);
  117. } elseif (is_string($this->theme)) {
  118. $this->theme = Yii::createObject($this->theme);
  119. }
  120. }
  121. /**
  122. * Renders a view.
  123. *
  124. * The view to be rendered can be specified in one of the following formats:
  125. *
  126. * - [path alias](guide:concept-aliases) (e.g. "@app/views/site/index");
  127. * - absolute path within application (e.g. "//site/index"): the view name starts with double slashes.
  128. * The actual view file will be looked for under the [[Application::viewPath|view path]] of the application.
  129. * - absolute path within current module (e.g. "/site/index"): the view name starts with a single slash.
  130. * The actual view file will be looked for under the [[Module::viewPath|view path]] of the [[Controller::module|current module]].
  131. * - relative view (e.g. "index"): the view name does not start with `@` or `/`. The corresponding view file will be
  132. * looked for under the [[ViewContextInterface::getViewPath()|view path]] of the view `$context`.
  133. * If `$context` is not given, it will be looked for under the directory containing the view currently
  134. * being rendered (i.e., this happens when rendering a view within another view).
  135. *
  136. * @param string $view the view name.
  137. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  138. * @param object|null $context the context to be assigned to the view and can later be accessed via [[context]]
  139. * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate
  140. * the view file corresponding to a relative view name.
  141. * @return string the rendering result
  142. * @throws ViewNotFoundException if the view file does not exist.
  143. * @throws InvalidCallException if the view cannot be resolved.
  144. * @see renderFile()
  145. */
  146. public function render($view, $params = [], $context = null)
  147. {
  148. $viewFile = $this->findViewFile($view, $context);
  149. return $this->renderFile($viewFile, $params, $context);
  150. }
  151. /**
  152. * Finds the view file based on the given view name.
  153. * @param string $view the view name or the [path alias](guide:concept-aliases) of the view file. Please refer to [[render()]]
  154. * on how to specify this parameter.
  155. * @param object|null $context the context to be assigned to the view and can later be accessed via [[context]]
  156. * in the view. If the context implements [[ViewContextInterface]], it may also be used to locate
  157. * the view file corresponding to a relative view name.
  158. * @return string the view file path. Note that the file may not exist.
  159. * @throws InvalidCallException if a relative view name is given while there is no active context to
  160. * determine the corresponding view file.
  161. */
  162. protected function findViewFile($view, $context = null)
  163. {
  164. if (strncmp($view, '@', 1) === 0) {
  165. // e.g. "@app/views/main"
  166. $file = Yii::getAlias($view);
  167. } elseif (strncmp($view, '//', 2) === 0) {
  168. // e.g. "//layouts/main"
  169. $file = Yii::$app->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
  170. } elseif (strncmp($view, '/', 1) === 0) {
  171. // e.g. "/site/index"
  172. if (Yii::$app->controller !== null) {
  173. $file = Yii::$app->controller->module->getViewPath() . DIRECTORY_SEPARATOR . ltrim($view, '/');
  174. } else {
  175. throw new InvalidCallException("Unable to locate view file for view '$view': no active controller.");
  176. }
  177. } elseif ($context instanceof ViewContextInterface) {
  178. $file = $context->getViewPath() . DIRECTORY_SEPARATOR . $view;
  179. } elseif (($currentViewFile = $this->getRequestedViewFile()) !== false) {
  180. $file = dirname($currentViewFile) . DIRECTORY_SEPARATOR . $view;
  181. } else {
  182. throw new InvalidCallException("Unable to resolve view file for view '$view': no active view context.");
  183. }
  184. if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
  185. return $file;
  186. }
  187. $path = $file . '.' . $this->defaultExtension;
  188. if ($this->defaultExtension !== 'php' && !is_file($path)) {
  189. $path = $file . '.php';
  190. }
  191. return $path;
  192. }
  193. /**
  194. * Renders a view file.
  195. *
  196. * If [[theme]] is enabled (not null), it will try to render the themed version of the view file as long
  197. * as it is available.
  198. *
  199. * The method will call [[FileHelper::localize()]] to localize the view file.
  200. *
  201. * If [[renderers|renderer]] is enabled (not null), the method will use it to render the view file.
  202. * Otherwise, it will simply include the view file as a normal PHP file, capture its output and
  203. * return it as a string.
  204. *
  205. * @param string $viewFile the view file. This can be either an absolute file path or an alias of it.
  206. * @param array $params the parameters (name-value pairs) that will be extracted and made available in the view file.
  207. * @param object|null $context the context that the view should use for rendering the view. If null,
  208. * existing [[context]] will be used.
  209. * @return string the rendering result
  210. * @throws ViewNotFoundException if the view file does not exist
  211. */
  212. public function renderFile($viewFile, $params = [], $context = null)
  213. {
  214. $viewFile = $requestedFile = Yii::getAlias($viewFile);
  215. if ($this->theme !== null) {
  216. $viewFile = $this->theme->applyTo($viewFile);
  217. }
  218. if (is_file($viewFile)) {
  219. $viewFile = FileHelper::localize($viewFile);
  220. } else {
  221. throw new ViewNotFoundException("The view file does not exist: $viewFile");
  222. }
  223. $oldContext = $this->context;
  224. if ($context !== null) {
  225. $this->context = $context;
  226. }
  227. $output = '';
  228. $this->_viewFiles[] = [
  229. 'resolved' => $viewFile,
  230. 'requested' => $requestedFile
  231. ];
  232. if ($this->beforeRender($viewFile, $params)) {
  233. Yii::debug("Rendering view file: $viewFile", __METHOD__);
  234. $ext = pathinfo($viewFile, PATHINFO_EXTENSION);
  235. if (isset($this->renderers[$ext])) {
  236. if (is_array($this->renderers[$ext]) || is_string($this->renderers[$ext])) {
  237. $this->renderers[$ext] = Yii::createObject($this->renderers[$ext]);
  238. }
  239. /** @var ViewRenderer $renderer */
  240. $renderer = $this->renderers[$ext];
  241. $output = $renderer->render($this, $viewFile, $params);
  242. } else {
  243. $output = $this->renderPhpFile($viewFile, $params);
  244. }
  245. $this->afterRender($viewFile, $params, $output);
  246. }
  247. array_pop($this->_viewFiles);
  248. $this->context = $oldContext;
  249. return $output;
  250. }
  251. /**
  252. * @return string|bool the view file currently being rendered. False if no view file is being rendered.
  253. */
  254. public function getViewFile()
  255. {
  256. return empty($this->_viewFiles) ? false : end($this->_viewFiles)['resolved'];
  257. }
  258. /**
  259. * @return string|bool the requested view currently being rendered. False if no view file is being rendered.
  260. * @since 2.0.16
  261. */
  262. protected function getRequestedViewFile()
  263. {
  264. return empty($this->_viewFiles) ? false : end($this->_viewFiles)['requested'];
  265. }
  266. /**
  267. * This method is invoked right before [[renderFile()]] renders a view file.
  268. * The default implementation will trigger the [[EVENT_BEFORE_RENDER]] event.
  269. * If you override this method, make sure you call the parent implementation first.
  270. * @param string $viewFile the view file to be rendered.
  271. * @param array $params the parameter array passed to the [[render()]] method.
  272. * @return bool whether to continue rendering the view file.
  273. */
  274. public function beforeRender($viewFile, $params)
  275. {
  276. $event = new ViewEvent([
  277. 'viewFile' => $viewFile,
  278. 'params' => $params,
  279. ]);
  280. $this->trigger(self::EVENT_BEFORE_RENDER, $event);
  281. return $event->isValid;
  282. }
  283. /**
  284. * This method is invoked right after [[renderFile()]] renders a view file.
  285. * The default implementation will trigger the [[EVENT_AFTER_RENDER]] event.
  286. * If you override this method, make sure you call the parent implementation first.
  287. * @param string $viewFile the view file being rendered.
  288. * @param array $params the parameter array passed to the [[render()]] method.
  289. * @param string $output the rendering result of the view file. Updates to this parameter
  290. * will be passed back and returned by [[renderFile()]].
  291. */
  292. public function afterRender($viewFile, $params, &$output)
  293. {
  294. if ($this->hasEventHandlers(self::EVENT_AFTER_RENDER)) {
  295. $event = new ViewEvent([
  296. 'viewFile' => $viewFile,
  297. 'params' => $params,
  298. ]);
  299. $event->output =& $output;
  300. $this->trigger(self::EVENT_AFTER_RENDER, $event);
  301. }
  302. }
  303. /**
  304. * Renders a view file as a PHP script.
  305. *
  306. * This method treats the view file as a PHP script and includes the file.
  307. * It extracts the given parameters and makes them available in the view file.
  308. * The method captures the output of the included view file and returns it as a string.
  309. *
  310. * This method should mainly be called by view renderer or [[renderFile()]].
  311. *
  312. * @param string $_file_ the view file.
  313. * @param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
  314. * @return string the rendering result
  315. * @throws \Throwable
  316. */
  317. public function renderPhpFile($_file_, $_params_ = [])
  318. {
  319. $_obInitialLevel_ = ob_get_level();
  320. ob_start();
  321. ob_implicit_flush(false);
  322. extract($_params_, EXTR_OVERWRITE);
  323. try {
  324. require $_file_;
  325. return ob_get_clean();
  326. } catch (\Exception $e) {
  327. while (ob_get_level() > $_obInitialLevel_) {
  328. if (!@ob_end_clean()) {
  329. ob_clean();
  330. }
  331. }
  332. throw $e;
  333. } catch (\Throwable $e) {
  334. while (ob_get_level() > $_obInitialLevel_) {
  335. if (!@ob_end_clean()) {
  336. ob_clean();
  337. }
  338. }
  339. throw $e;
  340. }
  341. }
  342. /**
  343. * Renders dynamic content returned by the given PHP statements.
  344. * This method is mainly used together with content caching (fragment caching and page caching)
  345. * when some portions of the content (called *dynamic content*) should not be cached.
  346. * The dynamic content must be returned by some PHP statements.
  347. * @param string $statements the PHP statements for generating the dynamic content.
  348. * @return string the placeholder of the dynamic content, or the dynamic content if there is no
  349. * active content cache currently.
  350. *
  351. * Note that most methods that indirectly modify layout such as registerJS() or registerJSFile() do not
  352. * work with dynamic rendering.
  353. *
  354. * @see https://github.com/yiisoft/yii2/issues/17673
  355. */
  356. public function renderDynamic($statements)
  357. {
  358. if (!empty($this->cacheStack)) {
  359. $n = count($this->dynamicPlaceholders);
  360. $placeholder = "<![CDATA[YII-DYNAMIC-$n]]>";
  361. $this->addDynamicPlaceholder($placeholder, $statements);
  362. return $placeholder;
  363. }
  364. return $this->evaluateDynamicContent($statements);
  365. }
  366. /**
  367. * {@inheritdoc}
  368. */
  369. public function getDynamicPlaceholders()
  370. {
  371. return $this->dynamicPlaceholders;
  372. }
  373. /**
  374. * {@inheritdoc}
  375. */
  376. public function setDynamicPlaceholders($placeholders)
  377. {
  378. $this->dynamicPlaceholders = $placeholders;
  379. }
  380. /**
  381. * {@inheritdoc}
  382. */
  383. public function addDynamicPlaceholder($placeholder, $statements)
  384. {
  385. foreach ($this->cacheStack as $cache) {
  386. if ($cache instanceof DynamicContentAwareInterface) {
  387. $cache->addDynamicPlaceholder($placeholder, $statements);
  388. } else {
  389. // TODO: Remove in 2.1
  390. $cache->dynamicPlaceholders[$placeholder] = $statements;
  391. }
  392. }
  393. $this->dynamicPlaceholders[$placeholder] = $statements;
  394. }
  395. /**
  396. * Evaluates the given PHP statements.
  397. * This method is mainly used internally to implement dynamic content feature.
  398. * @param string $statements the PHP statements to be evaluated.
  399. * @return mixed the return value of the PHP statements.
  400. */
  401. public function evaluateDynamicContent($statements)
  402. {
  403. return eval($statements);
  404. }
  405. /**
  406. * Returns a list of currently active dynamic content class instances.
  407. * @return DynamicContentAwareInterface[] class instances supporting dynamic contents.
  408. * @since 2.0.14
  409. */
  410. public function getDynamicContents()
  411. {
  412. return $this->cacheStack;
  413. }
  414. /**
  415. * Adds a class instance supporting dynamic contents to the end of a list of currently active
  416. * dynamic content class instances.
  417. * @param DynamicContentAwareInterface $instance class instance supporting dynamic contents.
  418. * @since 2.0.14
  419. */
  420. public function pushDynamicContent(DynamicContentAwareInterface $instance)
  421. {
  422. $this->cacheStack[] = $instance;
  423. }
  424. /**
  425. * Removes a last class instance supporting dynamic contents from a list of currently active
  426. * dynamic content class instances.
  427. * @since 2.0.14
  428. */
  429. public function popDynamicContent()
  430. {
  431. array_pop($this->cacheStack);
  432. }
  433. /**
  434. * Begins recording a block.
  435. *
  436. * This method is a shortcut to beginning [[Block]].
  437. * @param string $id the block ID.
  438. * @param bool $renderInPlace whether to render the block content in place.
  439. * Defaults to false, meaning the captured block will not be displayed.
  440. * @return Block the Block widget instance
  441. */
  442. public function beginBlock($id, $renderInPlace = false)
  443. {
  444. return Block::begin([
  445. 'id' => $id,
  446. 'renderInPlace' => $renderInPlace,
  447. 'view' => $this,
  448. ]);
  449. }
  450. /**
  451. * Ends recording a block.
  452. */
  453. public function endBlock()
  454. {
  455. Block::end();
  456. }
  457. /**
  458. * Begins the rendering of content that is to be decorated by the specified view.
  459. *
  460. * This method can be used to implement nested layout. For example, a layout can be embedded
  461. * in another layout file specified as '@app/views/layouts/base.php' like the following:
  462. *
  463. * ```php
  464. * <?php $this->beginContent('@app/views/layouts/base.php'); ?>
  465. * //...layout content here...
  466. * <?php $this->endContent(); ?>
  467. * ```
  468. *
  469. * @param string $viewFile the view file that will be used to decorate the content enclosed by this widget.
  470. * This can be specified as either the view file path or [path alias](guide:concept-aliases).
  471. * @param array $params the variables (name => value) to be extracted and made available in the decorative view.
  472. * @return ContentDecorator the ContentDecorator widget instance
  473. * @see ContentDecorator
  474. */
  475. public function beginContent($viewFile, $params = [])
  476. {
  477. return ContentDecorator::begin([
  478. 'viewFile' => $viewFile,
  479. 'params' => $params,
  480. 'view' => $this,
  481. ]);
  482. }
  483. /**
  484. * Ends the rendering of content.
  485. */
  486. public function endContent()
  487. {
  488. ContentDecorator::end();
  489. }
  490. /**
  491. * Begins fragment caching.
  492. *
  493. * This method will display cached content if it is available.
  494. * If not, it will start caching and would expect an [[endCache()]]
  495. * call to end the cache and save the content into cache.
  496. * A typical usage of fragment caching is as follows,
  497. *
  498. * ```php
  499. * if ($this->beginCache($id)) {
  500. * // ...generate content here
  501. * $this->endCache();
  502. * }
  503. * ```
  504. *
  505. * @param string $id a unique ID identifying the fragment to be cached.
  506. * @param array $properties initial property values for [[FragmentCache]]
  507. * @return bool whether you should generate the content for caching.
  508. * False if the cached version is available.
  509. */
  510. public function beginCache($id, $properties = [])
  511. {
  512. $properties['id'] = $id;
  513. $properties['view'] = $this;
  514. /** @var FragmentCache $cache */
  515. $cache = FragmentCache::begin($properties);
  516. if ($cache->getCachedContent() !== false) {
  517. $this->endCache();
  518. return false;
  519. }
  520. return true;
  521. }
  522. /**
  523. * Ends fragment caching.
  524. */
  525. public function endCache()
  526. {
  527. FragmentCache::end();
  528. }
  529. /**
  530. * Marks the beginning of a page.
  531. */
  532. public function beginPage()
  533. {
  534. ob_start();
  535. ob_implicit_flush(false);
  536. $this->trigger(self::EVENT_BEGIN_PAGE);
  537. }
  538. /**
  539. * Marks the ending of a page.
  540. */
  541. public function endPage()
  542. {
  543. $this->trigger(self::EVENT_END_PAGE);
  544. ob_end_flush();
  545. }
  546. }