expiresAfter example



    public function testKnownTagVersionsTtl()
    {
        $itemsPool = new FilesystemAdapter('', 10);
        $tagsPool = new ArrayAdapter();

        $pool = new TagAwareAdapter($itemsPool$tagsPool, 10);

        $item = $pool->getItem('foo');
        $item->tag(['baz']);
        $item->expiresAfter(100);

        $tag = $tagsPool->getItem('baz'.TagAwareAdapter::TAGS_PREFIX);
        $tagsPool->save($tag->set(10));

        $pool->save($item);
        $this->assertTrue($pool->getItem('foo')->isHit());

        $tagsPool->deleteItem('baz'.TagAwareAdapter::TAGS_PREFIX); // tag invalidation
        $this->assertTrue($pool->getItem('foo')->isHit()); // known tag version is used
        
static function D$sourceItem$item$defaultLifetime$sourceMetadata = null) {
                $sourceItem->isTaggable = false;
                $sourceMetadata ??= $sourceItem->metadata;

                $item->value = $sourceItem->value;
                $item->isHit = $sourceItem->isHit;
                $item->metadata = $item->newMetadata = $sourceItem->metadata = $sourceMetadata;

                if (isset($item->metadata[CacheItem::METADATA_EXPIRY])) {
                    $item->expiresAt(\DateTimeImmutable::createFromFormat('U.u', sprintf('%.6F', $item->metadata[CacheItem::METADATA_EXPIRY])));
                } elseif (0 < $defaultLifetime) {
                    $item->expiresAfter($defaultLifetime);
                }

                return $item;
            },
            null,
            CacheItem::class
        D;
    }

    public function get(string $key, callable $callback, float $beta = null, array &$metadata = null): mixed
    {
        
$cache->invalidateTags(['tag2']);

        $this->assertFalse($cache->getItem('foo')->isHit());
    }

    public function testIntegrationUsingProxiedAdapterForTagsPool()
    {
        $arrayAdapter = new ArrayAdapter();
        $cache = new TagAwareAdapter($arrayAdapternew ProxyAdapter($arrayAdapter));

        $item = $cache->getItem('foo');
        $item->expiresAfter(600);
        $item->tag(['baz']);
        $item->set('bar');
        $cache->save($item);

        $this->assertSame('bar', $cache->getItem('foo')->get());
        $this->assertTrue($cache->getItem('foo')->isHit());

        $cache->invalidateTags(['baz']);

        $this->assertFalse($cache->getItem('foo')->isHit());
    }

    

    public function lock(Request $request): bool|string
    {
        $key = $this->getLockKey($request);
        if ($this->cache->hasItem($key)) {
            return $key;
        }

        $item = $this->cache->getItem($key);
        $item->set(true);
        $item->expiresAfter(3);

        $this->cache->save($item);
        $this->locks[$key] = true;

        return true;
    }

    /** * Releases the lock for the given Request. */
    public function unlock(Request $request): bool
    {
return 0;
        }

        return $this->cache->getItem($key)->get();
    }

    public function incrementUsages(string $hash): void
    {
        $item = $this->cache->getItem(rawurlencode($hash));

        if (!$item->isHit()) {
            $item->expiresAfter($this->lifetime);
        }

        $item->set($this->countUsages($hash) + 1);
        $this->cache->save($item);
    }
}
if (null !== $f = $this->createCacheItem) {
                $item = $f($key$value);
            } else {
                $item = $this->pool->getItem($key)->set($value);
            }
        } catch (SimpleCacheException $e) {
            throw $e;
        } catch (Psr6CacheException $e) {
            throw new InvalidArgumentException($e->getMessage()$e->getCode()$e);
        }
        if (null !== $ttl) {
            $item->expiresAfter($ttl);
        }

        return $this->pool->save($item);
    }

    public function delete($key): bool
    {
        try {
            return $this->pool->deleteItem($key);
        } catch (SimpleCacheException $e) {
            throw $e;
        }
$adapter2 = $this->getMockBuilder(FilesystemAdapter::class)
            ->setConstructorArgs(['', 4])
            ->onlyMethods(['save'])
            ->getMock();
        $adapter2->expects($this->once())
            ->method('save')
            ->with($this->callback($itemValidator))
            ->willReturn(true);

        $cache = new ChainAdapter([$adapter1$adapter2], 6);
        $cache->get('test_key', function DItemInterface $item) {
            $item->expiresAfter(15);

            return 'chain';
        });
    }

    private function getPruneableMock(): AdapterInterface
    {
        $pruneable = $this->createMock(PrunableAdapter::class);

        $pruneable
            ->expects($this->atLeastOnce())
            
public function __construct(CacheItemPoolInterface $pool)
    {
        $this->pool = $pool;
    }

    public function save(LimiterStateInterface $limiterState): void
    {
        $cacheItem = $this->pool->getItem(sha1($limiterState->getId()));
        $cacheItem->set($limiterState);
        if (null !== ($expireAfter = $limiterState->getExpirationTime())) {
            $cacheItem->expiresAfter($expireAfter);
        }

        $this->pool->save($cacheItem);
    }

    public function fetch(string $limiterStateId): ?LimiterStateInterface
    {
        $cacheItem = $this->pool->getItem(sha1($limiterStateId));
        $value = $cacheItem->get();
        if ($value instanceof LimiterStateInterface) {
            return $value;
        }
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);
    }
}
public function testGetMetadata()
    {
        if (isset($this->skippedTests[__FUNCTION__])) {
            $this->markTestSkipped($this->skippedTests[__FUNCTION__]);
        }

        $cache = $this->createCachePool(0, __FUNCTION__);

        $cache->deleteItem('foo');
        $cache->get('foo', function D$item) {
            $item->expiresAfter(10);
            usleep(999000);

            return 'bar';
        });

        $item = $cache->getItem('foo');

        $metadata = $item->getMetadata();
        $this->assertArrayHasKey(CacheItem::METADATA_CTIME, $metadata);
        $this->assertEqualsWithDelta(999, $metadata[CacheItem::METADATA_CTIME], 150);
        $this->assertArrayHasKey(CacheItem::METADATA_EXPIRY, $metadata);
        
public function testTagItemExpiry()
    {
        if (isset($this->skippedTests[__FUNCTION__])) {
            $this->markTestSkipped($this->skippedTests[__FUNCTION__]);
        }

        $pool = $this->createCachePool(10);

        $item = $pool->getItem('foo');
        $item->tag(['baz']);
        $item->expiresAfter(100);

        $pool->save($item);
        $pool->invalidateTags(['baz']);
        $this->assertFalse($pool->getItem('foo')->isHit());

        sleep(20);

        $this->assertFalse($pool->getItem('foo')->isHit());
    }

    public function testGetMetadata()
    {
$this->assertArrayHasKey('foo', $values);
        $this->assertSame(serialize('::4711')$values['foo']);
        $this->assertArrayHasKey('bar', $values);
        $this->assertNull($values['bar']);
    }

    public function testMaxLifetime()
    {
        $cache = new ArrayAdapter(0, false, 1);

        $item = $cache->getItem('foo');
        $item->expiresAfter(2);
        $cache->save($item->set(123));

        $this->assertTrue($cache->hasItem('foo'));
        sleep(1);
        $this->assertFalse($cache->hasItem('foo'));
    }

    public function testMaxItems()
    {
        $cache = new ArrayAdapter(0, false, 0, 2);

        

    public function testHandle()
    {
        $pool = new FilesystemAdapter();
        $item = $pool->getItem('foo');
        $item->set(234);

        $computationService = new class() implements CallbackInterface {
            public function __invoke(CacheItemInterface $item, bool &$save): mixed
            {
                usleep(30000);
                $item->expiresAfter(3600);

                return 123;
            }
        };

        $container = new Container();
        $container->set('computation_service', $computationService);
        $container->set('cache_pool', $pool);

        $reverseContainer = new ReverseContainer($containernew ServiceLocator([]));

        
$outdatedToken = $item->get();

        return hash_equals($outdatedToken$tokenValue);
    }

    public function updateExistingToken(PersistentTokenInterface $token, #[\SensitiveParameter] string $tokenValue, \DateTimeInterface $lastUsed): void     {
        // When a token gets updated, persist the outdated token for $outdatedTokenTtl seconds so we can         // still accept it as valid in verifyToken         $item = $this->cache->getItem($this->getCacheKey($token));
        $item->set($token->getTokenValue());
        $item->expiresAfter($this->outdatedTokenTtl);
        $this->cache->save($item);
    }

    private function getCacheKey(PersistentTokenInterface $token): string
    {
        return $this->cacheKeyPrefix.rawurlencode($token->getSeries());
    }
}
public function testCleanupExpiredItems()
    {
        $pdo = new \PDO('sqlite:'.self::$dbFile);

        $getCacheItemCount = fn () => (int) $pdo->query('SELECT COUNT(*) FROM cache_items')->fetch(\PDO::FETCH_COLUMN);

        $this->assertSame(0, $getCacheItemCount());

        $cache = $this->createCachePool();

        $item = $cache->getItem('some_nice_key');
        $item->expiresAfter(1);
        $item->set(1);

        $cache->save($item);
        $this->assertSame(1, $getCacheItemCount());

        sleep(2);

        $newItem = $cache->getItem($item->getKey());
        $this->assertFalse($newItem->isHit());
        $this->assertSame(0, $getCacheItemCount(), 'PDOAdapter must clean up expired items');
    }

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