getExpires example

public function testConvertResponseMultipleTimes(ResponseInterface|Response $response, HttpMessageFactoryInterface|HttpFoundationFactoryInterface $firstFactory, HttpMessageFactoryInterface|HttpFoundationFactoryInterface $secondFactory)
    {
        $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;
                }
            };
            

    public function testGenerateAndGetToken(int $expiration, bool $expired): void
    {
        $transaction = self::createTransaction();
        $tokenStruct = new TokenStruct(null, null, $transaction->getPaymentMethodId()$transaction->getId(), null, $expiration);
        $token = $this->tokenFactory->generateToken($tokenStruct);
        $tokenStruct = $this->tokenFactory->parseToken($token);

        static::assertEquals($transaction->getId()$tokenStruct->getTransactionId());
        static::assertEquals($transaction->getPaymentMethodId()$tokenStruct->getPaymentMethodId());
        static::assertEquals($token$tokenStruct->getToken());
        static::assertEqualsWithDelta(time() + $expiration$tokenStruct->getExpires(), 1);
        static::assertSame($expired$tokenStruct->isExpired());
    }

    public function testGetInvalidFormattedToken(): void
    {
        $token = Uuid::randomHex();
        if (!Feature::isActive('v6.6.0.0')) {
            $this->expectException(InvalidTokenException::class);
        }

        $this->expectException(PaymentException::class);
        

    public function getMaxAge(): ?int
    {
        if ($this->headers->hasCacheControlDirective('s-maxage')) {
            return (int) $this->headers->getCacheControlDirective('s-maxage');
        }

        if ($this->headers->hasCacheControlDirective('max-age')) {
            return (int) $this->headers->getCacheControlDirective('max-age');
        }

        if (null !== $expires = $this->getExpires()) {
            $maxAge = (int) $expires->format('U') - (int) $this->getDate()->format('U');

            return max($maxAge, 0);
        }

        return null;
    }

    /** * Sets the number of seconds after which the response should no longer be considered fresh. * * This methods sets the Cache-Control max-age directive. * * @return $this * * @final */
$this->assertNull($response->headers->get('Age'), '->expire() does not set the Age when the response is expired');

        $response = new Response();
        $response->headers->set('Expires', date(\DATE_RFC2822, time() + 600));
        $response->expire();
        $this->assertNull($response->headers->get('Expires'), '->expire() removes the Expires header when the response is fresh');
    }

    public function testNullExpireHeader()
    {
        $response = new Response(null, 200, ['Expires' => null]);
        $this->assertNull($response->getExpires());
    }

    public function testGetTtl()
    {
        $response = new Response();
        $this->assertNull($response->getTtl(), '->getTtl() returns null when no Expires or Cache-Control headers are present');

        $response = new Response();
        $response->headers->set('Expires', $this->createDateTimeOneHourLater()->format(\DATE_RFC2822));
        $this->assertEquals(3600, $response->getTtl(), '->getTtl() uses the Expires header when no max-age is present');

        
$this->isNotCacheableResponseEmbedded = true;

            return;
        }

        $isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public');
        $maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
        $this->storeRelativeAgeDirective('max-age', $maxAge$age$isHeuristicallyCacheable);
        $sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
        $this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge$age$isHeuristicallyCacheable);

        $expires = $response->getExpires();
        $expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
        $this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);

        if (false !== $this->lastModified) {
            $lastModified = $response->getLastModified();
            $this->lastModified = $lastModified ? max($this->lastModified, $lastModified) : false;
        }
    }

    /** * @return void */


        foreach ($surrogates as $config) {
            $cacheStrategy->add($buildResponse($config));
        }

        $response = $buildResponse($master);
        $cacheStrategy->update($response);

        foreach ($expects as $key => $value) {
            if ('expires' === $key) {
                $this->assertSame($value$response->getExpires()->format('U') - $response->getDate()->format('U'));
            } elseif ('age' === $key) {
                $this->assertSame($value$response->getAge());
            } elseif (true === $value) {
                $this->assertTrue($response->headers->hasCacheControlDirective($key)sprintf('Cache-Control header must have "%s" flag', $key));
            } elseif (false === $value) {
                $this->assertFalse(
                    $response->headers->hasCacheControlDirective($key),
                    sprintf('Cache-Control header must NOT have "%s" flag', $key)
                );
            } else {
                $this->assertSame($value$response->headers->getCacheControlDirective($key)sprintf('Cache-Control flag "%s" should be "%s"', $key$value));
            }
$this->isNotCacheableResponseEmbedded = true;

            return;
        }

        $isHeuristicallyCacheable = $response->headers->hasCacheControlDirective('public');
        $maxAge = $response->headers->hasCacheControlDirective('max-age') ? (int) $response->headers->getCacheControlDirective('max-age') : null;
        $this->storeRelativeAgeDirective('max-age', $maxAge$age$isHeuristicallyCacheable);
        $sharedMaxAge = $response->headers->hasCacheControlDirective('s-maxage') ? (int) $response->headers->getCacheControlDirective('s-maxage') : $maxAge;
        $this->storeRelativeAgeDirective('s-maxage', $sharedMaxAge$age$isHeuristicallyCacheable);

        $expires = $response->getExpires();
        $expires = null !== $expires ? (int) $expires->format('U') - (int) $response->getDate()->format('U') : null;
        $this->storeRelativeAgeDirective('expires', $expires >= 0 ? $expires : null, 0, $isHeuristicallyCacheable);

        if (false !== $this->lastModified) {
            $lastModified = $response->getLastModified();
            $this->lastModified = $lastModified ? max($this->lastModified, $lastModified) : false;
        }
    }

    /** * @return void */

        $request = $this->createRequest(new Cache());

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

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

    public function testAttributeConfigurationsAreSetOnResponse()
    {
        $this->assertNull($this->response->getMaxAge());
        $this->assertNull($this->response->getExpires());
        $this->assertFalse($this->response->headers->hasCacheControlDirective('s-maxage'));
        $this->assertFalse($this->response->headers->hasCacheControlDirective('max-stale'));
        $this->assertFalse($this->response->headers->hasCacheControlDirective('stale-while-revalidate'));
        $this->assertFalse($this->response->headers->hasCacheControlDirective('stale-if-error'));

        $this->request->attributes->set('_cache', [new Cache(
            expires: 'tomorrow',
            maxage: '15',
            smaxage: '15',
            maxStale: '5',
            staleWhileRevalidate: '6',
            
$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) {
            $fieldValue .= '; Domain=' . $domain;
        }

        $path = $this->getPath();
        if ($path) {
            

        $cacheResponse = clone $response;
        $cacheResponse->headers = clone $response->headers;

        foreach ($cacheResponse->headers->getCookies() as $cookie) {
            if ($cookie->getName() === $this->sessionName) {
                $cacheResponse->headers->removeCookie($cookie->getName()$cookie->getPath()$cookie->getDomain());
            }
        }

        $item = CacheCompressor::compress($item$cacheResponse);
        $item->expiresAt($cacheResponse->getExpires());

        $item->tag($tags);

        $this->cache->save($item);

        $this->eventDispatcher->dispatch(
            new HttpCacheItemWrittenEvent($item$tags$request$response)
        );

        return $key;
    }

    


    /** * Evaluate if this cookie should be persisted to storage * that survives between requests. * * @param SetCookie $cookie Being evaluated. * @param bool $allowSessionCookies If we should persist session cookies */
    public static function shouldPersist(SetCookie $cookie, bool $allowSessionCookies = false): bool
    {
        if ($cookie->getExpires() || $allowSessionCookies) {
            if (!$cookie->getDiscard()) {
                return true;
            }
        }

        return false;
    }

    /** * Finds and returns the cookie based on the name * * @param string $name cookie name to search for * * @return SetCookie|null cookie that was found or null if not found */
Configuration $configuration,
        private readonly Connection $connection
    ) {
        $this->configuration = $configuration;
    }

    public function generateToken(TokenStruct $tokenStruct): string
    {
        $expires = new \DateTimeImmutable('@' . time());

        // @see https://github.com/php/php-src/issues/9950         if ($tokenStruct->getExpires() > 0) {
            $expires = $expires->modify(
                sprintf('+%d seconds', $tokenStruct->getExpires())
            );
        } else {
            $expires = $expires->modify(
                sprintf('-%d seconds', abs($tokenStruct->getExpires()))
            );
        }

        $jwtToken = $this->configuration->builder()
            ->identifiedBy(Uuid::randomHex())
            
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) {
            

        $expires = time() + $this->options['lifetime'];
        $value = $this->signatureHasher->computeSignatureHash($user$expires);

        $details = new RememberMeDetails($user::class$user->getUserIdentifier()$expires$value);
        $this->createCookie($details);
    }

    public function consumeRememberMeCookie(RememberMeDetails $rememberMeDetails): UserInterface
    {
        try {
            $this->signatureHasher->acceptSignatureHash($rememberMeDetails->getUserIdentifier()$rememberMeDetails->getExpires()$rememberMeDetails->getValue());
        } catch (InvalidSignatureException $e) {
            throw new AuthenticationException('The cookie\'s hash is invalid.', 0, $e);
        } catch (ExpiredSignatureException $e) {
            throw new AuthenticationException('The cookie has expired.', 0, $e);
        }

        return parent::consumeRememberMeCookie($rememberMeDetails);
    }

    public function processRememberMe(RememberMeDetails $rememberMeDetails, UserInterface $user): void
    {
        
    // likely to have a low cache hit rate. So do not cache them permanently.     if ($response->isClientError()) {
      // Cache for an hour by default. If the 'cache_ttl_4xx' setting is       // set to 0 then do not cache the response.       $cache_ttl_4xx = Settings::get('cache_ttl_4xx', 3600);
      if ($cache_ttl_4xx > 0) {
        $expire = $request_time + $cache_ttl_4xx;
      }
    }
    // The getExpires method could return NULL if Expires header is not set, so     // the returned value needs to be checked before calling getTimestamp.     elseif ($expires = $response->getExpires()) {
      $date = $expires->getTimestamp();
      $expire = ($date > $request_time) ? $date : Cache::PERMANENT;
    }
    else {
      $expire = Cache::PERMANENT;
    }

    if ($expire === Cache::PERMANENT || $expire > $request_time) {
      $tags = $response->getCacheableMetadata()->getCacheTags();
      $this->set($request$response$expire$tags);
    }

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