setLastModified example

$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());
        $this->assertEquals(new \DateTimeImmutable('Fri, 23 Aug 2014 00:00:00 GMT')$response->getLastModified());
        
return $this;
    }

    /** * Automatically sets the Last-Modified header according the file modification date. * * @return $this */
    public function setAutoLastModified()static
    {
        $this->setLastModified(\DateTime::createFromFormat('U', $this->file->getMTime()));

        return $this;
    }

    /** * Automatically sets the ETag header according to the checksum of the file. * * @return $this */
    public function setAutoEtag()static
    {
        
$response = new Response();
        $cacheStrategy->update($response);

        $this->assertFalse($response->headers->hasCacheControlDirective('s-maxage'));
    }

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

        $embeddedResponse = new Response();
        $embeddedResponse->setLastModified(new \DateTimeImmutable());
        $cacheStrategy->add($embeddedResponse);

        $mainResponse = new Response();
        $mainResponse->setSharedMaxAge(3600);
        $cacheStrategy->update($mainResponse);

        $this->assertTrue($mainResponse->headers->hasCacheControlDirective('no-cache'));
        $this->assertTrue($mainResponse->headers->hasCacheControlDirective('must-revalidate'));
        $this->assertFalse($mainResponse->isFresh());
    }

    


        $request->attributes->set('_cache', $attributes);
        $response = null;
        $lastModified = null;
        $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();

            
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'])) {
            $this->setSharedMaxAge($options['s_maxage']);
        }

        if (isset($options['stale_while_revalidate'])) {
            
$response->prepare($request);

        $this->assertNull($response->headers->get('Content-Length'));
    }

    public function testPrepareNotAddingContentTypeHeaderIfNoContentResponse()
    {
        $request = Request::create('/');
        $request->headers->set('If-Modified-Since', date('D, d M Y H:i:s').' GMT');

        $response = new BinaryFileResponse(__DIR__.'/File/Fixtures/test.gif', 200, ['Content-Type' => 'application/octet-stream']);
        $response->setLastModified(new \DateTimeImmutable('-1 day'));
        $response->isNotModified($request);

        $response->prepare($request);

        $this->assertSame(BinaryFileResponse::HTTP_NOT_MODIFIED, $response->getStatusCode());
        $this->assertFalse($response->headers->has('Content-Type'));
    }

    public function testContentTypeIsCorrectlyDetected()
    {
        $file = new File(__DIR__.'/File/Fixtures/test.gif');

        

  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. */
  
$this->removeHeader('Cache-Control');
        $this->removeHeader('ETag');

        // ETag         if (isset($options['etag'])) {
            $this->setHeader('ETag', $options['etag']);
            unset($options['etag']);
        }

        // Last Modified         if (isset($options['last-modified'])) {
            $this->setLastModified($options['last-modified']);

            unset($options['last-modified']);
        }

        $this->setHeader('Cache-Control', $options);

        return $this;
    }

    /** * Sets the Last-Modified date header. * * $date can be either a string representation of the date or, * preferably, an instance of DateTime. * * @param DateTime|string $date * * @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'])) {
            $this->setSharedMaxAge($options['s_maxage']);
        }

        if (isset($options['stale_while_revalidate'])) {
            
$response = new Response();

        $now = $this->createDateTimeImmutableNow();
        $response->setExpires($now);

        $this->assertEquals($response->getExpires()->getTimestamp()$now->getTimestamp());
    }

    public function testSetLastModified()
    {
        $response = new Response();
        $response->setLastModified($this->createDateTimeNow());
        $this->assertNotNull($response->getLastModified());

        $response->setLastModified(null);
        $this->assertNull($response->getLastModified());
    }

    public function testSetLastModifiedWithImmutable()
    {
        $response = new Response();
        $response->setLastModified($this->createDateTimeImmutableNow());
        $this->assertNotNull($response->getLastModified());

        


        $request->attributes->set('_cache', $attributes);
        $response = null;
        $lastModified = null;
        $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;
        }

        // 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->headers->set('Cache-Control', 'no-cache, must-revalidate');
            }

            return;
        }

        $response->setLastModified($this->lastModified ?: null);

        
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->headers->set('Cache-Control', 'no-cache, must-revalidate');
            }

            return;
        }

        $response->setLastModified($this->lastModified ?: null);

        
return $this;
    }

    /** * Automatically sets the Last-Modified header according the file modification date. * * @return $this */
    public function setAutoLastModified()static
    {
        $this->setLastModified(\DateTimeImmutable::createFromFormat('U', $this->file->getMTime()));

        return $this;
    }

    /** * Automatically sets the ETag header according to the checksum of the file. * * @return $this */
    public function setAutoEtag()static
    {
        
Home | Imprint | This part of the site doesn't use cookies.