123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167 |
- <?php
- namespace yii\widgets;
- use Yii;
- use yii\base\DynamicContentAwareInterface;
- use yii\base\DynamicContentAwareTrait;
- use yii\base\Widget;
- use yii\caching\CacheInterface;
- use yii\caching\Dependency;
- use yii\di\Instance;
- class FragmentCache extends Widget implements DynamicContentAwareInterface
- {
- use DynamicContentAwareTrait;
-
- public $cache = 'cache';
-
- public $duration = 60;
-
- public $dependency;
-
- public $variations;
-
- public $enabled = true;
-
- public function init()
- {
- parent::init();
- $this->cache = $this->enabled ? Instance::ensure($this->cache, 'yii\caching\CacheInterface') : null;
- if ($this->cache instanceof CacheInterface && $this->getCachedContent() === false) {
- $this->getView()->pushDynamicContent($this);
- ob_start();
- ob_implicit_flush(false);
- }
- }
-
- public function run()
- {
- if (($content = $this->getCachedContent()) !== false) {
- echo $content;
- } elseif ($this->cache instanceof CacheInterface) {
- $this->getView()->popDynamicContent();
- $content = ob_get_clean();
- if ($content === false || $content === '') {
- return;
- }
- if (is_array($this->dependency)) {
- $this->dependency = Yii::createObject($this->dependency);
- }
- $data = [$content, $this->getDynamicPlaceholders()];
- $this->cache->set($this->calculateKey(), $data, $this->duration, $this->dependency);
- echo $this->updateDynamicContent($content, $this->getDynamicPlaceholders());
- }
- }
-
- private $_content;
-
- public function getCachedContent()
- {
- if ($this->_content !== null) {
- return $this->_content;
- }
- $this->_content = false;
- if (!($this->cache instanceof CacheInterface)) {
- return $this->_content;
- }
- $key = $this->calculateKey();
- $data = $this->cache->get($key);
- if (!is_array($data) || count($data) !== 2) {
- return $this->_content;
- }
- list($this->_content, $placeholders) = $data;
- if (!is_array($placeholders) || count($placeholders) === 0) {
- return $this->_content;
- }
- $this->_content = $this->updateDynamicContent($this->_content, $placeholders, true);
- return $this->_content;
- }
-
- protected function calculateKey()
- {
- return array_merge([__CLASS__, $this->getId()], (array)$this->variations);
- }
- }
|