setMaxAge example

foreach (self::REMOVAL_HEADERS as $headerKey) {
            $response->headers->remove($headerKey);
        }
    }

    private function addNoStoreHeader(Request $request, Response $response): void
    {
        if (!$request->attributes->has(PlatformRequest::ATTRIBUTE_NO_STORE)) {
            return;
        }

        $response->setMaxAge(0);
        $response->headers->addCacheControlDirective('no-cache');
        $response->headers->addCacheControlDirective('no-store');
        $response->headers->addCacheControlDirective('must-revalidate');
        $response->setExpires(new \DateTime('@0'));
    }
}


        if ($session instanceof Session ? 0 === $session->getUsageIndex() : !$session->isStarted()) {
            return;
        }

        if ($autoCacheControl) {
            $maxAge = $response->headers->hasCacheControlDirective('public') ? 0 : (int) $response->getMaxAge();
            $response
                ->setExpires(new \DateTimeImmutable('+'.$maxAge.' seconds'))
                ->setPrivate()
                ->setMaxAge($maxAge)
                ->headers->addCacheControlDirective('must-revalidate');
        }

        if (!$event->getRequest()->attributes->get('_stateless', false)) {
            return;
        }

        if ($this->debug) {
            throw new UnexpectedSessionUsageException('Session was used while the request was declared stateless.');
        }

        


        if ($value) {
            $this->setValue($value); // in parent         }

        if ($version) {
            $this->setVersion($version);
        }

        if ($maxAge) {
            $this->setMaxAge($maxAge);
        }

        if ($domain) {
            $this->setDomain($domain);
        }

        if ($expires) {
            $this->setExpires($expires);
        }

        if ($path) {
            


    // Note that we intentionally do not use:     // - \Drupal\Core\Cache\CacheableResponse because caching it on the server     // side is wasteful, hence there is no need for cacheability metadata.     // - \Drupal\Core\Render\HtmlResponse because there is no need for     // attachments nor cacheability metadata.     return (new Response($html, 200, $headers))
      // Do not allow any intermediary to cache the response, only the end user.       ->setPrivate()
      // Allow the end user to cache it for up to 5 minutes.       ->setMaxAge(300);
  }

  /** * Checks access based on media_embed filter status on the text format. * * @param \Drupal\filter\FilterFormatInterface $filter_format * The text format for which to check access. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */
  
$listener = new SessionListener($container);
        $kernel = $this->createMock(HttpKernelInterface::class);

        $request = new Request();
        $listener->onKernelRequest(new RequestEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST));

        $request->getSession();

        $response = new Response();
        $response->setPrivate();
        $expiresHeader = gmdate('D, d M Y H:i:s', time() + 600).' GMT';
        $response->setMaxAge(600);
        $listener->onKernelResponse(new ResponseEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, $response));

        $this->assertTrue($response->headers->has('expires'));
        $this->assertSame($expiresHeader$response->headers->get('expires'));
        $this->assertFalse($response->headers->has('max-age'));
        $this->assertSame('600', $response->headers->getCacheControlDirective('max-age'));
        $this->assertFalse($response->headers->hasCacheControlDirective('public'));
        $this->assertTrue($response->headers->hasCacheControlDirective('private'));
        $this->assertTrue($response->headers->hasCacheControlDirective('must-revalidate'));
        $this->assertFalse($response->headers->has(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER));
    }

    
public function subtreesAjax() {
    [$subtrees] = toolbar_get_rendered_subtrees();
    $response = new AjaxResponse();
    $response->addCommand(new SetSubtreesCommand($subtrees));

    // The Expires HTTP header is the heart of the client-side HTTP caching. The     // additional server-side page cache only takes effect when the client     // accesses the callback URL again (e.g., after clearing the browser cache     // or when force-reloading a Drupal page).     $max_age = 365 * 24 * 60 * 60;
    $response->setPrivate();
    $response->setMaxAge($max_age);

    $expires = new \DateTime();
    $expires->setTimestamp(REQUEST_TIME + $max_age);
    $response->setExpires($expires);

    return $response;
  }

  /** * Checks access for the subtree controller. * * @param string $hash * The hash of the toolbar subtrees. * * @return \Drupal\Core\Access\AccessResultInterface * The access result. */
/** * A simple page callback that uses a plain Symfony response object. */
  public function respondWithResponse(Request $request) {
    return new Response('test');
  }

  /** * A plain Symfony response with Cache-Control: public, max-age=60. */
  public function respondWithPublicResponse() {
    return (new Response('test'))->setPublic()->setMaxAge(60);
  }

  /** * A simple page callback that uses a CacheableResponse object. */
  public function respondWithCacheableResponse(Request $request) {
    return new CacheableResponse('test');
  }

  /** * A simple page callback which adds a register shutdown function. */
foreach (array_reverse($attributes) as $cache) {
            if (null !== $cache->smaxage && !$response->headers->hasCacheControlDirective('s-maxage')) {
                $response->setSharedMaxAge($this->toSeconds($cache->smaxage));
            }

            if ($cache->mustRevalidate) {
                $response->headers->addCacheControlDirective('must-revalidate');
            }

            if (null !== $cache->maxage && !$response->headers->hasCacheControlDirective('max-age')) {
                $response->setMaxAge($this->toSeconds($cache->maxage));
            }

            if (null !== $cache->maxStale && !$response->headers->hasCacheControlDirective('max-stale')) {
                $response->headers->addCacheControlDirective('max-stale', $this->toSeconds($cache->maxStale));
            }

            if (null !== $cache->staleWhileRevalidate && !$response->headers->hasCacheControlDirective('stale-while-revalidate')) {
                $response->headers->addCacheControlDirective('stale-while-revalidate', $this->toSeconds($cache->staleWhileRevalidate));
            }

            if (null !== $cache->staleIfError && !$response->headers->hasCacheControlDirective('stale-if-error')) {
                
/** * Sets the response's time-to-live for private/client caches in seconds. * * This method adjusts the Cache-Control/max-age directive. * * @return $this * * @final */
    public function setClientTtl(int $seconds)static
    {
        $this->setMaxAge($this->getAge() + $seconds);

        return $this;
    }

    /** * Returns the Last-Modified HTTP header as a DateTime instance. * * @throws \RuntimeException When the HTTP header is not parseable * * @final */
    
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());
        $this->assertEquals(new \DateTimeImmutable('Fri, 24 Aug 2014 00:00:00 GMT')$response->getExpires());
        $this->assertSame('30', $response->headers->getCacheControlDirective('s-maxage'));
        $this->assertSame(30, $response->getMaxAge());
        
foreach (array_reverse($attributes) as $cache) {
            if (null !== $cache->smaxage && !$response->headers->hasCacheControlDirective('s-maxage')) {
                $response->setSharedMaxAge($this->toSeconds($cache->smaxage));
            }

            if ($cache->mustRevalidate) {
                $response->headers->addCacheControlDirective('must-revalidate');
            }

            if (null !== $cache->maxage && !$response->headers->hasCacheControlDirective('max-age')) {
                $response->setMaxAge($this->toSeconds($cache->maxage));
            }

            if (null !== $cache->maxStale && !$response->headers->hasCacheControlDirective('max-stale')) {
                $response->headers->addCacheControlDirective('max-stale', $this->toSeconds($cache->maxStale));
            }

            if (null !== $cache->staleWhileRevalidate && !$response->headers->hasCacheControlDirective('stale-while-revalidate')) {
                $response->headers->addCacheControlDirective('stale-while-revalidate', $this->toSeconds($cache->staleWhileRevalidate));
            }

            if (null !== $cache->staleIfError && !$response->headers->hasCacheControlDirective('stale-if-error')) {
                

    public function templateAction(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null, array $context = [], int $statusCode = 200): Response
    {
        if (null === $this->twig) {
            throw new \LogicException('You cannot use the TemplateController if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
        }

        $response = new Response($this->twig->render($template$context)$statusCode);

        if ($maxAge) {
            $response->setMaxAge($maxAge);
        }

        if (null !== $sharedAge) {
            $response->setSharedMaxAge($sharedAge);
        }

        if ($private) {
            $response->setPrivate();
        } elseif (false === $private || (null === $private && (null !== $maxAge || null !== $sharedAge))) {
            $response->setPublic();
        }

        
      // added metadata is bubbled up to the response.       // @see \Drupal\Core\Theme\ThemeManager::render()       if (!$context->isEmpty()) {
        $bubbleable_metadata = $context->pop();
        assert($bubbleable_metadata instanceof BubbleableMetadata);
        $response->addCacheableDependency($bubbleable_metadata);
        $response->addAttachments($bubbleable_metadata->getAttachments());
      }
    }
    catch (ResourceException $e) {
      // Prevent the response from being cached.       $response->setMaxAge(0);

      // The oEmbed system makes heavy use of exception wrapping, so log the       // entire exception chain to help with troubleshooting.       do {
        // @todo Log additional information from ResourceException, to help with         // debugging, in https://www.drupal.org/project/drupal/issues/2972846.         $this->logger->error($e->getMessage());
        $e = $e->getPrevious();
      } while ($e);
    }

    


        if (isset($data['Domain'])) {
            $this->setDomain($data['Domain']);
        }

        if (isset($data['Path'])) {
            $this->setPath($data['Path']);
        }

        if (isset($data['Max-Age'])) {
            $this->setMaxAge($data['Max-Age']);
        }

        if (isset($data['Expires'])) {
            $this->setExpires($data['Expires']);
        }

        if (isset($data['Secure'])) {
            $this->setSecure($data['Secure']);
        }

        if (isset($data['Discard'])) {
            
if (!$asset) {
            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
Home | Imprint | This part of the site doesn't use cookies.