View.php 21 KB

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