From c097dd57596cbc8020d678669ddca0ee2418bf39 Mon Sep 17 00:00:00 2001 From: Saiat Kalbiev Date: Thu, 25 Apr 2019 15:02:02 +0400 Subject: [PATCH] Add GlobalPageCacheBehaviour class --- behaviours/GlobalPageCacheBehaviour.php | 136 ++++++++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100755 behaviours/GlobalPageCacheBehaviour.php diff --git a/behaviours/GlobalPageCacheBehaviour.php b/behaviours/GlobalPageCacheBehaviour.php new file mode 100755 index 0000000..d1f4b31 --- /dev/null +++ b/behaviours/GlobalPageCacheBehaviour.php @@ -0,0 +1,136 @@ + + */ + public function events() + { + return [ + Controller::EVENT_BEFORE_ACTION => 'beforeAction' + ]; + } + + /** + * @author Saiat Kalbiev + * @throws GlobalPageCacheException + */ + public function beforeAction() + { + if (!$this->rules) { + throw new GlobalPageCacheException('Invalid rules provided'); + } + + $currentControllerId = Yii::$app->controller->id; + $currentActionId = Yii::$app->controller->action->id; + + foreach ($this->rules as $rule) { + + if (!isset($rule['controller']) || !$rule['controller']) { + throw new GlobalPageCacheException('Invalid rule. Controller id not provided.'); + } + + if ($rule['controller'] == $currentControllerId) { + + if (isset($rule['duration']) && $rule['duration']) { + $this->duration = $rule['duration']; + } + + if (!isset($rule['actions']) || !$rule['actions']) { + throw new GlobalPageCacheException('Invalid rule. Action id(s) not provided.'); + } + + if (isset($rule['except'])) { + + if (!is_array($rule['except'])) { + throw new GlobalPageCacheException('Invalid rule. Except parameter should be of type array.'); + } + + if (in_array($currentActionId, $rule['except'])) { + return; + } + } + + if (in_array('*', $rule['actions']) || in_array($currentActionId, $rule['actions'])) { + $this->attachBehavior($rule); + } + } + } + } + + /** + * @param $rule array + * @return array + * @author Saiat Kalbiev + * @throws GlobalPageCacheException + */ + private function generateVariations($rule) + { + $variations = []; + + if (isset($rule['variations'])) { + + if (!is_array($rule['variations'])) { + throw new GlobalPageCacheException('Invalid rule. Variations parameter should be of type array.'); + } + + foreach ($rule['variations'] as $variation) { + if ($variation == self::VARIATION_BY_LANGUAGE) { + $variations[] = \Yii::$app->language; + } else if ($variation == self::VARIATION_BY_URL) { + $variations[] = Yii::$app->request->absoluteUrl; + } + } + } + + return $variations; + } + + /** + * @param $rule array + * @author Saiat Kalbiev + * @throws GlobalPageCacheException + */ + private function attachBehavior($rule) + { + $variations = $this->generateVariations($rule); + + Yii::$app->controller->attachBehavior('pageCacheBehaviour', [ + 'class' => 'yii\filters\PageCache', + 'duration' => $this->duration, + 'variations' => $variations + ]); + } +}