getMaxAge example


                    );
                }
            }
        }

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

        
return max(time() - (int) $this->getDate()->format('U'), 0);
    }

    /** * Marks the response stale by setting the Age header to be equal to the maximum age of the response. * * @return $this */
    public function expire()static
    {
        if ($this->isFresh()) {
            $this->headers->set('Age', $this->getMaxAge());
            $this->headers->remove('Expires');
        }

        return $this;
    }

    /** * Returns the value of the Expires header as a DateTime instance. * * @final */
    
private function storeResponse(string $cacheKey, ResponseCacheConfiguration $cacheConfig, Response $symfonyResponse): void
    {
        $item = $this->cache->getItem($cacheKey);

        // add the header only for the response in cache and remove the header before the response is sent         $symfonyResponse->headers->set(self::INVALIDATION_STATES_HEADER, implode(',', $cacheConfig->getInvalidationStates()));
        $item = CacheCompressor::compress($item$symfonyResponse);
        $symfonyResponse->headers->remove(self::INVALIDATION_STATES_HEADER);

        $item->tag($cacheConfig->getCacheTags());
        $item->expiresAfter($cacheConfig->getMaxAge());

        $this->cache->save($item);
    }
}
$value = '"' . urlencode(str_replace('"', '', $value)) . '"';
        } else {
            $value = urlencode($value);
        }
        $fieldValue = $this->getName() . '=' . $value;

        $version = $this->getVersion();
        if ($version !== null) {
            $fieldValue .= '; Version=' . $version;
        }

        $maxAge = $this->getMaxAge();
        if ($maxAge !== null) {
            $fieldValue .= '; Max-Age=' . $maxAge;
        }

        $expires = $this->getExpires();
        if ($expires) {
            $fieldValue .= '; Expires=' . $expires;
        }

        $domain = $this->getDomain();
        if ($domain) {
            
return max(time() - (int) $this->getDate()->format('U'), 0);
    }

    /** * Marks the response stale by setting the Age header to be equal to the maximum age of the response. * * @return $this */
    public function expire()static
    {
        if ($this->isFresh()) {
            $this->headers->set('Age', $this->getMaxAge());
            $this->headers->remove('Expires');
        }

        return $this;
    }

    /** * Returns the value of the Expires header as a DateTime instance. * * @final */
    
->withValue('t+e+s+t')
            ->withHttpOnly(false)
            ->withRaw(true)
            ->withSameSite(null);
        $this->assertTrue($cookie->isRaw());
        $this->assertEquals('foo=t+e+s+t; path=/', (string) $cookie);
    }

    public function testGetMaxAge()
    {
        $cookie = Cookie::create('foo', 'bar');
        $this->assertEquals(0, $cookie->getMaxAge());

        $cookie = Cookie::create('foo', 'bar', $expire = time() + 100);
        $this->assertEquals($expire - time()$cookie->getMaxAge());

        $cookie = Cookie::create('foo', 'bar', $expire = time() - 100);
        $this->assertEquals(0, $cookie->getMaxAge());
    }

    public function testFromString()
    {
        $cookie = Cookie::fromString('foo=bar; expires=Fri, 20 May 2011 15:25:52 GMT; path=/; domain=.myfoodomain.com; secure; httponly');
        
$str = str_replace(self::RESERVED_CHARS_FROM, self::RESERVED_CHARS_TO, $this->getName());
        }

        $str .= '=';

        if ('' === (string) $this->getValue()) {
            $str .= 'deleted; expires='.gmdate('D, d M Y H:i:s T', time() - 31536001).'; Max-Age=0';
        } else {
            $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());

            if (0 !== $this->getExpiresTime()) {
                $str .= '; expires='.gmdate('D, d M Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
            }
        }

        if ($this->getPath()) {
            $str .= '; path='.$this->getPath();
        }

        if ($this->getDomain()) {
            $str .= '; domain='.$this->getDomain();
        }

        
&& !$entry->mustRevalidate()
        ) {
            if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
                $age = $this->options['stale_if_error'];
            }

            /* * stale-if-error gives the (extra) time that the Response may be used *after* it has become stale. * So we compare the time the $entry has been sitting in the cache already with the * time it was fresh plus the allowed grace period. */
            if ($entry->getAge() <= $entry->getMaxAge() + $age) {
                $this->record($request, 'stale-if-error');

                return $entry;
            }
        }

        /* RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate clock MUST NOT send a "Date" header, although it MUST send one in most other cases except for 1xx or 5xx responses where it MAY do so. Anyway, a client that received a message without a "Date" header MUST add it. */

                    );
                }
            }
        }

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

        
$response = new Response('', 200);
        $now = $this->createDateTimeNow();
        $response->headers->remove('Date');
        $date = $response->getDate();
        $this->assertEquals($now->getTimestamp()$date->getTimestamp(), '->getDate() returns the current Date when the header has previously been removed');
    }

    public function testGetMaxAge()
    {
        $response = new Response();
        $response->headers->set('Cache-Control', 's-maxage=600, max-age=0');
        $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() uses s-maxage cache control directive when present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'max-age=600');
        $this->assertEquals(600, $response->getMaxAge(), '->getMaxAge() falls back to max-age when no s-maxage directive present');

        $response = new Response();
        $response->headers->set('Cache-Control', 'must-revalidate');
        $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(\DATE_RFC2822));
        $this->assertEquals(3600, $response->getMaxAge(), '->getMaxAge() falls back to Expires when no max-age or s-maxage directive present');

        $response = new Response();
        


        $response = $hook->getScriptResponse();

        $symfonyResponse = $this->scriptResponseEncoder->encodeToSymfonyResponse(
            $response,
            $fields,
            \str_replace('-', '_', 'storefront_' . $hookName . '_response')
        );

        if ($response->getCache()->isEnabled()) {
            $request->attributes->set(PlatformRequest::ATTRIBUTE_HTTP_CACHE, ['maxAge' => $response->getCache()->getMaxAge(), 'states' => $response->getCache()->getInvalidationStates()]);
            $symfonyResponse->headers->set(CacheStore::TAG_HEADER, \json_encode($response->getCache()->getCacheTags(), \JSON_THROW_ON_ERROR));
        }

        return $symfonyResponse;
    }

    /** * @param array<string, mixed> $parameters */
    public function renderStorefrontForScript(string $view, array $parameters = []): Response
    {
        
&& !$entry->mustRevalidate()
        ) {
            if (null === $age = $entry->headers->getCacheControlDirective('stale-if-error')) {
                $age = $this->options['stale_if_error'];
            }

            /* * stale-if-error gives the (extra) time that the Response may be used *after* it has become stale. * So we compare the time the $entry has been sitting in the cache already with the * time it was fresh plus the allowed grace period. */
            if ($entry->getAge() <= $entry->getMaxAge() + $age) {
                $this->record($request, 'stale-if-error');

                return $entry;
            }
        }

        /* RFC 7231 Sect. 7.1.1.2 says that a server that does not have a reasonably accurate clock MUST NOT send a "Date" header, although it MUST send one in most other cases except for 1xx or 5xx responses where it MAY do so. Anyway, a client that received a message without a "Date" header MUST add it. */
if (isset($data['HttpOnly'])) {
            $this->setHttpOnly($data['HttpOnly']);
        }

        // Set the remaining values that don't have extra validation logic         foreach (array_diff(array_keys($data)array_keys(self::$defaults)) as $key) {
            $this->data[$key] = $data[$key];
        }

        // Extract the Expires value and turn it into a UNIX timestamp if needed         if (!$this->getExpires() && $this->getMaxAge()) {
            // Calculate the Expires date             $this->setExpires(\time() + $this->getMaxAge());
        } elseif (null !== ($expires = $this->getExpires()) && !\is_numeric($expires)) {
            $this->setExpires($expires);
        }
    }

    public function __toString()
    {
        $str = $this->data['Name'].'='.($this->data['Value'] ?? '').'; ';
        foreach ($this->data as $k => $v) {
            
$temporaryResponse = $firstFactory->createResponse($response);
        $finalResponse = $secondFactory->createResponse($temporaryResponse);

        if ($finalResponse instanceof Response) {
            $this->assertEquals($response->getAge()$finalResponse->getAge());
            $this->assertEquals($response->getCharset()$finalResponse->getCharset());
            $this->assertEquals($response->getContent()$finalResponse->getContent());
            $this->assertEquals($response->getDate()$finalResponse->getDate());
            $this->assertEquals($response->getEtag()$finalResponse->getEtag());
            $this->assertEquals($response->getExpires()$finalResponse->getExpires());
            $this->assertEquals($response->getLastModified()$finalResponse->getLastModified());
            $this->assertEquals($response->getMaxAge()$finalResponse->getMaxAge());
            $this->assertEquals($response->getProtocolVersion()$finalResponse->getProtocolVersion());
            $this->assertEquals($response->getStatusCode()$finalResponse->getStatusCode());
            $this->assertEquals($response->getTtl()$finalResponse->getTtl());
        } elseif ($finalResponse instanceof ResponseInterface) {
            $strToLower = function D$arr) {
                foreach ($arr as $key => $value) {
                    yield strtolower($key) => $value;
                }
            };
            $this->assertEquals($response->getStatusCode()$finalResponse->getStatusCode());
            $this->assertEquals($response->getReasonPhrase()$finalResponse->getReasonPhrase());
            
$str = str_replace(self::RESERVED_CHARS_FROM, self::RESERVED_CHARS_TO, $this->getName());
        }

        $str .= '=';

        if ('' === (string) $this->getValue()) {
            $str .= 'deleted; expires='.gmdate('D, d M Y H:i:s T', time() - 31536001).'; Max-Age=0';
        } else {
            $str .= $this->isRaw() ? $this->getValue() : rawurlencode($this->getValue());

            if (0 !== $this->getExpiresTime()) {
                $str .= '; expires='.gmdate('D, d M Y H:i:s T', $this->getExpiresTime()).'; Max-Age='.$this->getMaxAge();
            }
        }

        if ($this->getPath()) {
            $str .= '; path='.$this->getPath();
        }

        if ($this->getDomain()) {
            $str .= '; domain='.$this->getDomain();
        }

        
Home | Imprint | This part of the site doesn't use cookies.