DynamicContentAwareTrait.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. /**
  9. * DynamicContentAwareTrait implements common methods for classes
  10. * which support a [[View]] dynamic content feature.
  11. *
  12. * @author Sergey Makinen <sergey@makinen.ru>
  13. * @since 2.0.14
  14. */
  15. trait DynamicContentAwareTrait
  16. {
  17. /**
  18. * @var string[] a list of placeholders for dynamic content
  19. */
  20. private $_dynamicPlaceholders;
  21. /**
  22. * Returns the view object that can be used to render views or view files using dynamic contents.
  23. * @return View the view object that can be used to render views or view files.
  24. */
  25. abstract protected function getView();
  26. /**
  27. * {@inheritdoc}
  28. */
  29. public function getDynamicPlaceholders()
  30. {
  31. return $this->_dynamicPlaceholders;
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. public function setDynamicPlaceholders($placeholders)
  37. {
  38. $this->_dynamicPlaceholders = $placeholders;
  39. }
  40. /**
  41. * {@inheritdoc}
  42. */
  43. public function addDynamicPlaceholder($name, $statements)
  44. {
  45. $this->_dynamicPlaceholders[$name] = $statements;
  46. }
  47. /**
  48. * Replaces placeholders in $content with results of evaluated dynamic statements.
  49. * @param string $content content to be parsed.
  50. * @param string[] $placeholders placeholders and their values.
  51. * @param bool $isRestoredFromCache whether content is going to be restored from cache.
  52. * @return string final content.
  53. */
  54. protected function updateDynamicContent($content, $placeholders, $isRestoredFromCache = false)
  55. {
  56. if (empty($placeholders) || !is_array($placeholders)) {
  57. return $content;
  58. }
  59. if (count($this->getView()->getDynamicContents()) === 0) {
  60. // outermost cache: replace placeholder with dynamic content
  61. foreach ($placeholders as $name => $statements) {
  62. $placeholders[$name] = $this->getView()->evaluateDynamicContent($statements);
  63. }
  64. $content = strtr($content, $placeholders);
  65. }
  66. if ($isRestoredFromCache) {
  67. $view = $this->getView();
  68. foreach ($placeholders as $name => $statements) {
  69. $view->addDynamicPlaceholder($name, $statements);
  70. }
  71. }
  72. return $content;
  73. }
  74. }