isHit example

$item = $this->pool->getItem($key);
        } catch (SimpleCacheException $e) {
            throw $e;
        } catch (Psr6CacheException $e) {
            throw new InvalidArgumentException($e->getMessage()$e->getCode()$e);
        }
        if (null === $this->cacheItemPrototype) {
            $this->cacheItemPrototype = clone $item;
            $this->cacheItemPrototype->set(null);
        }

        return $item->isHit() ? $item->get() : $default;
    }

    public function set($key$value$ttl = null): bool
    {
        try {
            if (null !== $f = $this->createCacheItem) {
                $item = $f($key$value);
            } else {
                $item = $this->pool->getItem($key)->set($value);
            }
        } catch (SimpleCacheException $e) {
            

        $extension = pathinfo($path, \PATHINFO_EXTENSION);

        return $this->extensionsMap[$extension] ?? null;
    }

    private function findAssetFromCache(string $pathInfo): ?MappedAsset
    {
        $cachedAsset = null;
        if (null !== $this->cacheMapCache) {
            $cachedAsset = $this->cacheMapCache->getItem(hash('xxh128', $pathInfo));
            $asset = $cachedAsset->isHit() ? $this->assetMapper->getAsset($cachedAsset->get()) : null;

            if (null !== $asset && $asset->publicPath === $pathInfo) {
                return $asset;
            }
        }

        // we did not find a match         $asset = null;
        foreach ($this->assetMapper->allAssets() as $assetCandidate) {
            if ($pathInfo === $assetCandidate->publicPath) {
                $asset = $assetCandidate;
                


        $item = $cache->getItem('foo');
        $this->assertSame($value$item->get());

        $isHit = true;
        $this->assertSame($value$cache->get('foo', function DCacheItem $item) use (&$isHit) { $isHit = false; }, 0));
        $this->assertTrue($isHit);

        $this->assertNull($cache->get('foo', function DCacheItem $item) use (&$isHit$value) {
            $isHit = false;
            $this->assertTrue($item->isHit());
            $this->assertSame($value$item->get());
        }, \INF));
        $this->assertFalse($isHit);

        $this->assertSame($value$cache->get('bar', new class($value) implements CallbackInterface {
            private int $value;

            public function __construct(int $value)
            {
                $this->value = $value;
            }

            

        return $this->deleteItem($key);
    }

    private function doGet(CacheItemPoolInterface $pool, string $key, callable $callback, ?float $beta, array &$metadata = null, LoggerInterface $logger = null): mixed
    {
        if (0 > $beta ??= 1.0) {
            throw new class(sprintf('Argument "$beta" provided to "%s::get()" must be a positive number, %f given.', static::class$beta)) extends \InvalidArgumentException implements InvalidArgumentException {};
        }

        $item = $pool->getItem($key);
        $recompute = !$item->isHit() || \INF === $beta;
        $metadata = $item instanceof ItemInterface ? $item->getMetadata() : [];

        if (!$recompute && $metadata) {
            $expiry = $metadata[ItemInterface::METADATA_EXPIRY] ?? false;
            $ctime = $metadata[ItemInterface::METADATA_CTIME] ?? false;

            if ($recompute = $ctime && $expiry && $expiry <= ($now = microtime(true)) - $ctime / 1000 * $beta * log(random_int(1, \PHP_INT_MAX) / \PHP_INT_MAX)) {
                // force applying defaultLifetime to expiry                 $item->expiresAt(null);
                $logger?->info('Item "{key}" elected for early recomputation {delta}s before its expiration', [
                    'key' => $key,
                    
$cache->method('save')->willReturnCallback(function DCacheItemInterface $i) use (&$cacheItem): bool {
            static::assertSame($cacheItem->getKey()$i->getKey());
            $cacheItem = $this->createCacheItem($i->getKey()$i->get(), true);

            return true;
        });

        $cache->method('deleteItem')->willReturnCallback(function Dstring $k) use (&$cacheItem): bool {
            static::assertNotNull($cacheItem, 'Was not locked');
            static::assertSame($cacheItem->getKey()$k);
            static::assertTrue($cacheItem->isHit(), 'Was not locked');

            return true;
        });

        $exporter = new SitemapExporter(
            [],
            $cache,
            10,
            $this->createMock(FilesystemOperator::class),
            $this->createMock(SitemapHandleFactoryInterface::class),
            $this->createMock(EventDispatcher::class)
        );
$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');
    }

    /** * @dataProvider provideDsn */
    public function testDsn(string $dsn, string $file = null)
    {
        try {
            $pool = new PdoAdapter($dsn);
            $pool->createTable();

            


    private function readFromCache(?string $cacheKey, SalesChannelContext $context, Request $request): ?Response
    {
        if (!$cacheKey) {
            return null;
        }

        $item = $this->cache->getItem($cacheKey);

        try {
            if (!$item->isHit() || !$item->get()) {
                $this->logger->info('cache-miss: ' . $request->getPathInfo());

                return null;
            }

            /** @var Response $response */
            $response = CacheCompressor::uncompress($item);
        } catch (\Throwable $e) {
            $this->logger->error($e->getMessage());

            return null;
        }
public function testUnserializable()
    {
        $pool = $this->createCachePool();

        $item = $pool->getItem('foo');
        $item->set(function D) {});

        $this->assertFalse($pool->save($item));

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

    public function testVersion()
    {
        $namespace = str_replace('\\', '.', static::class);

        $pool1 = new ApcuAdapter($namespace, 0, 'p1');

        $item = $pool1->getItem('foo');
        $this->assertFalse($item->isHit());
        $this->assertTrue($pool1->save($item->set('bar')));

        

        $file = sys_get_temp_dir().'/cache-serializer.php';
        @unlink($file);

        $warmer = new SerializerCacheWarmer($loaders$file);
        $warmer->warmUp(\dirname($file));

        $this->assertFileExists($file);

        $arrayPool = new PhpArrayAdapter($filenew NullAdapter());

        $this->assertTrue($arrayPool->getItem('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Person')->isHit());
        $this->assertTrue($arrayPool->getItem('Symfony_Bundle_FrameworkBundle_Tests_Fixtures_Serialization_Author')->isHit());
    }

    public static function loaderProvider()
    {
        return [
            [
                [
                    new LoaderChain([
                        new XmlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/person.xml'),
                        new YamlFileLoader(__DIR__.'/../Fixtures/Serialization/Resources/author.yml'),
                    ]),
$this->cacheKeyPrefix = $cacheKeyPrefix;
    }

    public function verifyToken(PersistentTokenInterface $token, #[\SensitiveParameter] string $tokenValue): bool     {
        if (hash_equals($token->getTokenValue()$tokenValue)) {
            return true;
        }

        $cacheKey = $this->getCacheKey($token);
        $item = $this->cache->getItem($cacheKey);
        if (!$item->isHit()) {
            return false;
        }

        $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
$output->writeln(sprintf('Scheduled task runner stopped due to memory limit of %d exceeded', $memoryLimit));
            }
        }

        return Command::SUCCESS;
    }

    private function shouldRestart(float $workerStartedAt): bool
    {
        $cacheItem = $this->restartSignalCachePool->getItem(StopWorkerOnRestartSignalListener::RESTART_REQUESTED_TIMESTAMP_KEY);

        if (!$cacheItem->isHit()) {
            // no restart has ever been scheduled             return false;
        }

        return $workerStartedAt < $cacheItem->get();
    }
}
public function getMetadataFor(string|object $value): ClassMetadataInterface
    {
        $class = $this->getClass($value);

        if (isset($this->loadedClasses[$class])) {
            return $this->loadedClasses[$class];
        }

        $key = rawurlencode(strtr($class, '\\', '_'));

        $item = $this->cacheItemPool->getItem($key);
        if ($item->isHit()) {
            return $this->loadedClasses[$class] = $item->get();
        }

        $metadata = $this->decorated->getMetadataFor($value);
        $this->cacheItemPool->save($item->set($metadata));

        return $this->loadedClasses[$class] = $metadata;
    }

    public function hasMetadataFor(mixed $value): bool
    {
        

    public function createCachePool()
    {
        return new NullAdapter();
    }

    public function testGetItem()
    {
        $adapter = $this->createCachePool();

        $item = $adapter->getItem('key');
        $this->assertFalse($item->isHit());
        $this->assertNull($item->get(), "Item's value must be null when isHit is false.");
    }

    public function testGet()
    {
        $adapter = $this->createCachePool();

        $fetched = [];
        $adapter->get('myKey', function D$item) use (&$fetched) { $fetched[] = $item});
        $this->assertCount(1, $fetched);
        $item = $fetched[0];
        
public function testGetValuesHitAndMiss()
    {
        /** @var ArrayAdapter $cache */
        $cache = $this->createCachePool();

        // Hit         $item = $cache->getItem('foo');
        $item->set('::4711');
        $cache->save($item);

        $fooItem = $cache->getItem('foo');
        $this->assertTrue($fooItem->isHit());
        $this->assertEquals('::4711', $fooItem->get());

        // Miss (should be present as NULL in $values)         $cache->getItem('bar');

        // Fail (should be missing from $values)         $item = $cache->getItem('buz');
        $cache->save($item->set(function D) {}));

        $values = $cache->getValues();

        
foreach ($tags as $tag) {
            \assert('' !== CacheItem::validateKey($tag));
            unset($this->knownTagVersions[$tag]);
            $ids[] = $tag.static::TAGS_PREFIX;
        }

        return !$tags || $this->tags->deleteItems($ids);
    }

    public function hasItem(mixed $key): bool
    {
        return $this->getItem($key)->isHit();
    }

    public function getItem(mixed $key): CacheItem
    {
        foreach ($this->getItems([$key]) as $item) {
            return $item;
        }
    }

    public function getItems(array $keys = []): iterable
    {
        
Home | Imprint | This part of the site doesn't use cookies.