yii\filters\HttpCache::beforeAction PHP Метод

beforeAction() публичный Метод

This method is invoked right before an action is to be executed (after all possible filters.) You may override this method to do last-minute preparation for the action.
public beforeAction ( Action $action ) : boolean
$action yii\base\Action the action to be executed.
Результат boolean whether the action should continue to be executed.
    public function beforeAction($action)
    {
        if (!$this->enabled) {
            return true;
        }
        $verb = Yii::$app->getRequest()->getMethod();
        if ($verb !== 'GET' && $verb !== 'HEAD' || $this->lastModified === null && $this->etagSeed === null) {
            return true;
        }
        $lastModified = $etag = null;
        if ($this->lastModified !== null) {
            $lastModified = call_user_func($this->lastModified, $action, $this->params);
        }
        if ($this->etagSeed !== null) {
            $seed = call_user_func($this->etagSeed, $action, $this->params);
            if ($seed !== null) {
                $etag = $this->generateEtag($seed);
            }
        }
        $this->sendCacheControlHeader();
        $response = Yii::$app->getResponse();
        if ($etag !== null) {
            $response->getHeaders()->set('Etag', $etag);
        }
        $cacheValid = $this->validateCache($lastModified, $etag);
        // https://tools.ietf.org/html/rfc7232#section-4.1
        if ($lastModified !== null && (!$cacheValid || $cacheValid && $etag === null)) {
            $response->getHeaders()->set('Last-Modified', gmdate('D, d M Y H:i:s', $lastModified) . ' GMT');
        }
        if ($cacheValid) {
            $response->setStatusCode(304);
            return false;
        }
        return true;
    }

Usage Example

Пример #1
0
 /**
  * @covers yii\filters\HttpCache::generateEtag
  */
 public function testGenerateEtag()
 {
     $httpCache = new HttpCache();
     $httpCache->etagSeed = function ($action, $params) {
         return '';
     };
     $httpCache->beforeAction(null);
     $response = Yii::$app->getResponse();
     $this->assertTrue($response->getHeaders()->offsetExists('ETag'));
     $etag = $response->getHeaders()->get('ETag');
     $this->assertStringStartsWith('"', $etag);
     $this->assertStringEndsWith('"', $etag);
 }