setEtag example

throw new NotFoundHttpException(sprintf('Asset with public path "%s" not found.', $pathInfo));
        }

        $mediaType = $this->getMediaType($asset->publicPath);
        $response = (new Response(
            $asset->content,
            headers: $mediaType ? ['Content-Type' => $mediaType] : [],
        ))
            ->setPublic()
            ->setMaxAge(604800)
            ->setImmutable()
            ->setEtag($asset->digest)
        ;

        $event->setResponse($response);
    }

    public static function getSubscribedEvents(): array
    {
        return [
            // priority higher than RouterListener             KernelEvents::REQUEST => [['onKernelRequest', 35]],
        ];
    }
$this->assertTrue($mainResponse->headers->hasCacheControlDirective('must-revalidate'));
        $this->assertFalse($mainResponse->isFresh());
    }

    public function testValidationOnMainResponseIsNotPossibleWhenItContainsEmbeddedResponses()
    {
        $cacheStrategy = new ResponseCacheStrategy();

        // This main response uses the "validation" model         $mainResponse = new Response();
        $mainResponse->setLastModified(new \DateTimeImmutable());
        $mainResponse->setEtag('foo');

        // Embedded response uses "expiry" model         $embeddedResponse = new Response();
        $mainResponse->setSharedMaxAge(3600);
        $cacheStrategy->add($embeddedResponse);

        $cacheStrategy->update($mainResponse);

        $this->assertFalse($mainResponse->isValidateable());
        $this->assertFalse($mainResponse->headers->has('Last-Modified'));
        $this->assertFalse($mainResponse->headers->has('ETag'));
        
$etag = null;

        /** @var Cache[] $attributes */
        foreach ($attributes as $cache) {
            if (null !== $cache->lastModified) {
                $lastModified = $this->getExpressionLanguage()->evaluate($cache->lastModified, array_merge($request->attributes->all()$event->getNamedArguments()));
                ($response ??= new Response())->setLastModified($lastModified);
            }

            if (null !== $cache->etag) {
                $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($cache->etag, array_merge($request->attributes->all()$event->getNamedArguments())));
                ($response ??= new Response())->setEtag($etag);
            }
        }

        if ($response?->isNotModified($request)) {
            $event->setController(static fn () => $response);
            $event->stopPropagation();

            return;
        }

        if (null !== $etag) {
            
/** * @return void */
    public function update(Response $response)
    {
        // if we have no embedded Response, do nothing         if (0 === $this->embeddedResponses) {
            return;
        }

        // Remove Etag since it cannot be merged from embedded responses.         $response->setEtag(null);

        $this->add($response);

        $response->headers->set('Age', $this->age);

        if ($this->isNotCacheableResponseEmbedded) {
            $response->setLastModified(null);

            if ($this->flagDirectives['no-store']) {
                $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
            } else {
                
$etag = null;

        /** @var Cache[] $attributes */
        foreach ($attributes as $cache) {
            if (null !== $cache->lastModified) {
                $lastModified = $this->getExpressionLanguage()->evaluate($cache->lastModified, array_merge($request->attributes->all()$event->getNamedArguments()));
                ($response ??= new Response())->setLastModified($lastModified);
            }

            if (null !== $cache->etag) {
                $etag = hash('sha256', $this->getExpressionLanguage()->evaluate($cache->etag, array_merge($request->attributes->all()$event->getNamedArguments())));
                ($response ??= new Response())->setEtag($etag);
            }
        }

        if ($response?->isNotModified($request)) {
            $event->setController(static fn () => $response);
            $event->stopPropagation();

            return;
        }

        if (null !== $etag) {
            
return $this;
    }

    /** * Automatically sets the ETag header according to the checksum of the file. * * @return $this */
    public function setAutoEtag()static
    {
        $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));

        return $this;
    }

    /** * Sets the Content-Disposition header with the given filename. * * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename * * @return $this */

    public function setCache(array $options)static
    {
        if ($diff = array_diff(array_keys($options)array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) {
            throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
        }

        if (isset($options['etag'])) {
            $this->setEtag($options['etag']);
        }

        if (isset($options['last_modified'])) {
            $this->setLastModified($options['last_modified']);
        }

        if (isset($options['max_age'])) {
            $this->setMaxAge($options['max_age']);
        }

        if (isset($options['s_maxage'])) {
            
return $this;
    }

    /** * Automatically sets the ETag header according to the checksum of the file. * * @return $this */
    public function setAutoEtag()static
    {
        $this->setEtag(base64_encode(hash_file('sha256', $this->file->getPathname(), true)));

        return $this;
    }

    /** * Sets the Content-Disposition header with the given filename. * * @param string $disposition ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT * @param string $filename Optionally use this UTF-8 encoded filename instead of the real name of the file * @param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename * * @return $this */
/** * @return void */
    public function update(Response $response)
    {
        // if we have no embedded Response, do nothing         if (0 === $this->embeddedResponses) {
            return;
        }

        // Remove Etag since it cannot be merged from embedded responses.         $response->setEtag(null);

        $this->add($response);

        $response->headers->set('Age', $this->age);

        if ($this->isNotCacheableResponseEmbedded) {
            $response->setLastModified(null);

            if ($this->flagDirectives['no-store']) {
                $response->headers->set('Cache-Control', 'no-cache, no-store, must-revalidate');
            } else {
                

        $response = new Response();
        $this->assertFalse($response->hasVary());

        $response->setVary('User-Agent');
        $this->assertTrue($response->hasVary());
    }

    public function testSetEtag()
    {
        $response = new Response('', 200, ['ETag' => '"12345"']);
        $response->setEtag(null);

        $this->assertNull($response->headers->get('Etag'), '->setEtag() removes Etags when call with null');
    }

    /** * @dataProvider validContentProvider */
    public function testSetContent($content)
    {
        $response = new Response();
        $response->setContent($content);
        

  protected function setResponseNotCacheable(Response $response, Request $request) {
    $this->setCacheControlNoCache($response);
    $this->setExpiresNoCache($response);

    // There is no point in sending along headers necessary for cache     // revalidation, if caching by proxies and browsers is denied in the first     // place. Therefore remove ETag, Last-Modified and Vary in that case.     $response->setEtag(NULL);
    $response->setLastModified(NULL);
    $response->headers->remove('Vary');
  }

  /** * Add Cache-Control and Expires headers to a cacheable response. * * @param \Symfony\Component\HttpFoundation\Response $response * A response object. * @param \Symfony\Component\HttpFoundation\Request $request * A request object. */

    public function setCache(array $options)static
    {
        if ($diff = array_diff(array_keys($options)array_keys(self::HTTP_RESPONSE_CACHE_CONTROL_DIRECTIVES))) {
            throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', $diff)));
        }

        if (isset($options['etag'])) {
            $this->setEtag($options['etag']);
        }

        if (isset($options['last_modified'])) {
            $this->setLastModified($options['last_modified']);
        }

        if (isset($options['max_age'])) {
            $this->setMaxAge($options['max_age']);
        }

        if (isset($options['s_maxage'])) {
            

        $request = $this->createRequest(new Cache(
            expires: 'Fri, 24 Aug 2013 00:00:00 GMT',
            maxage: '15',
            smaxage: '15',
            vary: ['foobar'],
            lastModified: 'Fri, 24 Aug 2013 00:00:00 GMT',
            etag: '"12345"',
        ));

        $response = new Response();
        $response->setEtag('"54321"');
        $response->setLastModified(new \DateTimeImmutable('Fri, 23 Aug 2014 00:00:00 GMT'));
        $response->setExpires(new \DateTimeImmutable('Fri, 24 Aug 2014 00:00:00 GMT'));
        $response->setSharedMaxAge(30);
        $response->setMaxAge(30);
        $response->setVary(['foobaz']);

        $listener = new CacheAttributeListener();
        $responseEvent = new ResponseEvent($this->getKernel()$request, HttpKernelInterface::MAIN_REQUEST, $response);
        $listener->onKernelResponse($responseEvent);

        $this->assertSame('"54321"', $response->getEtag());
        
Home | Imprint | This part of the site doesn't use cookies.