hasCacheControlDirective example

public function testSetTargetUrl()
    {
        $response = new RedirectResponse('foo.bar');
        $response->setTargetUrl('baz.beep');

        $this->assertEquals('baz.beep', $response->getTargetUrl());
    }

    public function testCacheHeaders()
    {
        $response = new RedirectResponse('foo.bar', 301);
        $this->assertFalse($response->headers->hasCacheControlDirective('no-cache'));

        $response = new RedirectResponse('foo.bar', 301, ['cache-control' => 'max-age=86400']);
        $this->assertFalse($response->headers->hasCacheControlDirective('no-cache'));
        $this->assertTrue($response->headers->hasCacheControlDirective('max-age'));

        $response = new RedirectResponse('foo.bar', 301, ['Cache-Control' => 'max-age=86400']);
        $this->assertFalse($response->headers->hasCacheControlDirective('no-cache'));
        $this->assertTrue($response->headers->hasCacheControlDirective('max-age'));

        $response = new RedirectResponse('foo.bar', 302);
        $this->assertTrue($response->headers->hasCacheControlDirective('no-cache'));
    }
$this->listener->onKernelResponse($this->event);

        $this->assertSame($response$this->event->getResponse());
    }

    public function testResponseIsPublicIfSharedMaxAgeSetAndPublicNotOverridden()
    {
        $request = $this->createRequest(new Cache(smaxage: 1));

        $this->listener->onKernelResponse($this->createEventMock($request$this->response));

        $this->assertTrue($this->response->headers->hasCacheControlDirective('public'));
        $this->assertFalse($this->response->headers->hasCacheControlDirective('private'));
    }

    public function testResponseIsPublicIfConfigurationIsPublicTrue()
    {
        $request = $this->createRequest(new Cache(public: true));

        $this->listener->onKernelResponse($this->createEventMock($request$this->response));

        $this->assertTrue($this->response->headers->hasCacheControlDirective('public'));
        $this->assertFalse($this->response->headers->hasCacheControlDirective('private'));
    }

    public function isCacheable(): bool
    {
        if (!\in_array($this->statusCode, [200, 203, 300, 301, 302, 404, 410])) {
            return false;
        }

        if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
            return false;
        }

        return $this->isValidateable() || $this->isFresh();
    }

    /** * Returns true if the response is "fresh". * * Fresh responses may be served from cache without any interaction with the * origin. A response is considered fresh when it includes a Cache-Control/max-age * indicator or Expires header and the calculated age is less than the freshness lifetime. * * @final */
'expires' => null,
    ];

    /** * @return void */
    public function add(Response $response)
    {
        ++$this->embeddedResponses;

        foreach (self::OVERRIDE_DIRECTIVES as $directive) {
            if ($response->headers->hasCacheControlDirective($directive)) {
                $this->flagDirectives[$directive] = true;
            }
        }

        foreach (self::INHERIT_DIRECTIVES as $directive) {
            if (false !== $this->flagDirectives[$directive]) {
                $this->flagDirectives[$directive] = $response->headers->hasCacheControlDirective($directive);
            }
        }

        $age = $response->getAge();
        
$allPreservedCase = $bag->allPreserveCase();

        foreach (array_keys($headers) as $headerName) {
            $this->assertArrayHasKey($headerName$allPreservedCase, '->allPreserveCase() gets all input keys in original case');
        }
    }

    public function testCacheControlHeader()
    {
        $bag = new ResponseHeaderBag([]);
        $this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('no-cache'));

        $bag = new ResponseHeaderBag(['Cache-Control' => 'public']);
        $this->assertEquals('public', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('public'));

        $bag = new ResponseHeaderBag(['ETag' => 'abcde']);
        $this->assertEquals('no-cache, private', $bag->get('Cache-Control'));
        $this->assertTrue($bag->hasCacheControlDirective('private'));
        $this->assertTrue($bag->hasCacheControlDirective('no-cache'));
        $this->assertFalse($bag->hasCacheControlDirective('max-age'));

        

    public function testNoStoreHeaderPresent(string $routeName, array $routeParameters): void
    {
        $router = $this->getContainer()->get('router');
        $route = $router->generate($routeName$routeParameters);

        $browser = KernelLifecycleManager::createBrowser(KernelLifecycleManager::getKernel());
        $browser->request('GET', $_SERVER['APP_URL'] . $route);
        $response = $browser->getResponse();

        static::assertTrue($response->headers->hasCacheControlDirective('no-store'));
        static::assertTrue($response->headers->hasCacheControlDirective('private'));
        static::assertFalse($response->isCacheable());
    }

    /** * @return iterable<string, array{string, array<string>}> */
    public static function dataProviderRevalidateRoutes(): iterable
    {
        foreach (self::REVALIDATE_ROUTES as $route => $parameters) {
            yield $route => [$route$parameters];
        }
else {
      $response = $this->fetch($request$type$catch);
    }

    // Only allow caching in the browser and prevent that the response is stored     // by an external proxy server when the following conditions apply:     // 1. There is a session cookie on the request.     // 2. The Vary: Cookie header is on the response.     // 3. The Cache-Control header does not contain the no-cache directive.     if ($request->cookies->has(session_name()) &&
      in_array('Cookie', $response->getVary()) &&
      !$response->headers->hasCacheControlDirective('no-cache')) {

      $response->setPrivate();
    }

    // Perform HTTP revalidation.     // @todo Use Response::isNotModified() as     // per https://www.drupal.org/node/2259489.     $last_modified = $response->getLastModified();
    if ($last_modified) {
      // See if the client has provided the required HTTP headers.       $if_modified_since = $request->server->has('HTTP_IF_MODIFIED_SINCE') ? strtotime($request->server->get('HTTP_IF_MODIFIED_SINCE')) : FALSE;
      
$this->record($request, 'miss');

            return $this->fetch($request$catch);
        }

        if (!$this->isFreshEnough($request$entry)) {
            $this->record($request, 'stale');

            return $this->validate($request$entry$catch);
        }

        if ($entry->headers->hasCacheControlDirective('no-cache')) {
            return $this->validate($request$entry$catch);
        }

        $this->record($request, 'fresh');

        $entry->headers->set('Age', $entry->getAge());

        return $entry;
    }

    /** * Validates that a cache entry is fresh. * * The original request is used as a template for a conditional * GET request with the backend. * * @param bool $catch Whether to process exceptions */
$kernel = $this->createMock(HttpKernelInterface::class);

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

        $request->getSession();

        $response = new Response();
        $listener->onKernelResponse(new ResponseEvent($kernel$request, HttpKernelInterface::MAIN_REQUEST, $response));

        $this->assertTrue($response->headers->has('Expires'));
        $this->assertTrue($response->headers->hasCacheControlDirective('private'));
        $this->assertTrue($response->headers->hasCacheControlDirective('must-revalidate'));
        $this->assertSame('0', $response->headers->getCacheControlDirective('max-age'));
        $this->assertLessThanOrEqual(new \DateTimeImmutable('now', new \DateTimeZone('UTC'))new \DateTimeImmutable($response->headers->get('Expires')));
        $this->assertFalse($response->headers->has(AbstractSessionListener::NO_AUTO_CACHE_CONTROL_HEADER));
    }

    public function testResponseIsStillPublicIfSessionStartedAndHeaderPresent()
    {
        $session = $this->createMock(Session::class);
        $session->expects($this->once())->method('getUsageIndex')->willReturn(1);

        

                    );
                }
            }
        }

        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;
        }

        
$response1 = new Response();
        $response1->setSharedMaxAge(60);
        $cacheStrategy->add($response1);

        $response2 = new Response();
        $cacheStrategy->add($response2);

        $response = new Response();
        $response->setSharedMaxAge(86400);
        $cacheStrategy->update($response);

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

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

        $response1 = new Response();
        $response1->setSharedMaxAge(60);
        $cacheStrategy->add($response1);

        $response2 = new Response();
        
public function testGetDateException()
    {
        $this->expectException(\RuntimeException::class);
        $bag = new HeaderBag(['foo' => 'Tue']);
        $bag->getDate('foo');
    }

    public function testGetCacheControlHeader()
    {
        $bag = new HeaderBag();
        $bag->addCacheControlDirective('public', '#a');
        $this->assertTrue($bag->hasCacheControlDirective('public'));
        $this->assertEquals('#a', $bag->getCacheControlDirective('public'));
    }

    public function testAll()
    {
        $bag = new HeaderBag(['foo' => 'bar']);
        $this->assertEquals(['foo' => ['bar']]$bag->all(), '->all() gets all the input');

        $bag = new HeaderBag(['FOO' => 'BAR']);
        $this->assertEquals(['foo' => ['BAR']]$bag->all(), '->all() gets all the input key are lower case');
    }

    
'status' => 200,
                'body' => 'My name is Bobby.',
                'headers' => ['Cache-Control' => 's-maxage=100'],
            ],
        ];

        $this->setNextResponses($responses);

        $this->request('GET', '/', [][], true);
        $this->assertEquals('Hello World! My name is Bobby.', $this->response->getContent());
        $this->assertNull($this->response->getTtl());
        $this->assertTrue($this->response->headers->hasCacheControlDirective('private'));
        $this->assertTrue($this->response->headers->hasCacheControlDirective('no-cache'));
    }

    public function testEsiCacheForceValidationForHeadRequests()
    {
        $responses = [
            [
                'status' => 200,
                'body' => 'I am the main response and use expiration caching, but I embed another resource: <esi:include src="/foo" />',
                'headers' => [
                    'Cache-Control' => 's-maxage=300',
                    

                    );
                }
            }
        }

        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;
        }

        
/** * Gets the Etags. */
    public function getETags(): array
    {
        return preg_split('/\s*,\s*/', $this->headers->get('If-None-Match', ''), -1, \PREG_SPLIT_NO_EMPTY);
    }

    public function isNoCache(): bool
    {
        return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
    }

    /** * Gets the preferred format for the response by inspecting, in the following order: * * the request format set using setRequestFormat; * * the values of the Accept HTTP header. * * Note that if you use this method, you should send the "Vary: Accept" header * in the response to prevent any issues with intermediary HTTP caches. */
    public function getPreferredFormat(?string $default = 'html'): ?string
    {
Home | Imprint | This part of the site doesn't use cookies.