createCachePool example


class NullAdapterTest extends TestCase
{
    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 = [];
        
use Psr\Cache\CacheItemPoolInterface;
use Symfony\Component\Cache\CacheItem;
use Symfony\Component\Cache\PruneableInterface;
use Symfony\Contracts\Cache\CallbackInterface;

abstract class AdapterTestCase extends CachePoolTest
{
    protected function setUp(): void
    {
        parent::setUp();

        if (!\array_key_exists('testPrune', $this->skippedTests) && !$this->createCachePool() instanceof PruneableInterface) {
            $this->skippedTests['testPrune'] = 'Not a pruneable cache pool.';
        }

        try {
            \assert(false === true, new \Exception());
            $this->skippedTests['testGetItemInvalidKeys'] =
            $this->skippedTests['testGetItemsInvalidKeys'] =
            $this->skippedTests['testHasItemInvalidKeys'] =
            $this->skippedTests['testDeleteItemInvalidKeys'] =
            $this->skippedTests['testDeleteItemsInvalidKeys'] = 'Keys are checked only when assert() is enabled.';
        } catch (\Exception $e) {
        }

        parent::setUpBeforeClass();
        self::$redis = AbstractAdapter::createConnection('redis://'.getenv('REDIS_HOST')['lazy' => true]);
    }

    public function createCachePool(int $defaultLifetime = 0, string $testMethod = null): CacheItemPoolInterface
    {
        if ('testClearWithPrefix' === $testMethod && \defined('Redis::SCAN_PREFIX')) {
            self::$redis->setOption(\Redis::OPT_SCAN, \Redis::SCAN_PREFIX);
        }

        $adapter = parent::createCachePool($defaultLifetime$testMethod);
        $this->assertInstanceOf(RedisProxy::class, self::$redis);

        return $adapter;
    }

    public function testCreateHostConnection()
    {
        $redis = RedisAdapter::createConnection('redis:?host[h1]&host[h2]&host[/foo:]');
        $this->assertInstanceOf(\RedisArray::class$redis);
        $this->assertSame(['h1:6379', 'h2:6379', '/foo']$redis->_hosts());
        @$redis = null; // some versions of phpredis connect on destruct, let's silence the warning
private function getNonPruneableMock(): AdapterInterface&MockObject
    {
        return $this->createMock(AdapterInterface::class);
    }

    /** * @doesNotPerformAssertions */
    public function testToleranceForStringsAsTagVersionsCase1()
    {
        $pool = $this->createCachePool();
        $adapter = new FilesystemAdapter();

        $itemKey = 'foo';
        $tag = $adapter->getItem('bar'.TagAwareAdapter::TAGS_PREFIX);
        $adapter->save($tag->set("\x00abc\xff"));
        $item = $pool->getItem($itemKey);
        $pool->save($item->tag('bar'));
        $pool->hasItem($itemKey);
        $pool->getItem($itemKey);
    }

    
new \Redis())->connect(...explode(':', getenv('REDIS_HOST')));
        } catch (\Exception $e) {
            throw new SkippedTestSuiteError(getenv('REDIS_HOST').': '.$e->getMessage());
        }
    }

    /** * @runInSeparateProcess */
    public function testClearWithPrefix()
    {
        $cache = $this->createCachePool(0, __FUNCTION__);

        $cache->save($cache->getItem('foo')->set('bar'));
        $this->assertTrue($cache->hasItem('foo'));

        $cache->clear();
        $this->assertFalse($cache->hasItem('foo'));
    }
}


    protected static string $file;

    public static function setUpBeforeClass(): void
    {
        self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php';
    }

    protected function tearDown(): void
    {
        $this->createCachePool()->clear();

        if (file_exists(sys_get_temp_dir().'/symfony-cache')) {
            (new Filesystem())->remove(sys_get_temp_dir().'/symfony-cache');
        }
    }

    public function createCachePool(int $defaultLifetime = 0, string $testMethod = null): CacheItemPoolInterface
    {
        if ('testGetMetadata' === $testMethod || 'testClearPrefix' === $testMethod) {
            return new PhpArrayAdapter(self::$filenew FilesystemAdapter());
        }

        
protected $skippedTests = [
        'testPrune' => 'TraceableAdapter just proxies',
    ];

    public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface
    {
        return new TraceableAdapter(new FilesystemAdapter('', $defaultLifetime));
    }

    public function testGetItemMissTrace()
    {
        $pool = $this->createCachePool();
        $pool->getItem('k');
        $calls = $pool->getCalls();
        $this->assertCount(1, $calls);

        $call = $calls[0];
        $this->assertSame('getItem', $call->name);
        $this->assertSame(['k' => false]$call->result);
        $this->assertSame(0, $call->hits);
        $this->assertSame(1, $call->misses);
        $this->assertNotEmpty($call->start);
        $this->assertNotEmpty($call->end);
    }
\Memcached::OPT_RETRY_TIMEOUT => 10],
        ];
        yield [
            'memcached://localhost:11222?socket_recv_size=1&socket_send_size=2',
            [\Memcached::OPT_RETRY_TIMEOUT => 8],
            [\Memcached::OPT_SOCKET_RECV_SIZE => 1, \Memcached::OPT_SOCKET_SEND_SIZE => 2, \Memcached::OPT_RETRY_TIMEOUT => 8],
        ];
    }

    public function testClear()
    {
        $this->assertTrue($this->createCachePool()->clear());
    }

    public function testMultiServerDsn()
    {
        $dsn = 'memcached:?host[localhost]&host[localhost:12345]&host[/some/memcached.sock:]=3';
        $client = MemcachedAdapter::createConnection($dsn);

        $expected = [
            0 => [
                'host' => 'localhost',
                'port' => 11211,
                
/** * Common assertions for TagAware adapters. * * @method \Symfony\Component\Cache\Adapter\TagAwareAdapterInterface createCachePool(int $defaultLifetime = 0) Must be implemented by TestCase */
trait TagAwareTestTrait
{
    public function testInvalidTag()
    {
        $this->expectException(\Psr\Cache\InvalidArgumentException::class);
        $pool = $this->createCachePool();
        $item = $pool->getItem('foo');
        $item->tag(':');
    }

    public function testInvalidateTags()
    {
        $pool = $this->createCachePool();

        $i0 = $pool->getItem('i0');
        $i1 = $pool->getItem('i1');
        $i2 = $pool->getItem('i2');
        

        }
        if ('\\' === \DIRECTORY_SEPARATOR) {
            $this->markTestSkipped('Fails transiently on Windows.');
        }

        return new ApcuAdapter(str_replace('\\', '.', __CLASS__)$defaultLifetime);
    }

    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()
    {

        $setCacheItemExpiry = \Closure::bind(
            static function DCacheItem $item$expiry) {
                $item->expiry = $expiry;

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

        $cache = $this->createCachePool(1);
        $cache->clear();
        $value = rand();
        $item = $cache->getItem('foo');
        $setCacheItemExpiry($item, 0);
        $cache->save($item->set($value));
        $item = $cache->getItem('bar');
        $setCacheItemExpiry($item, 0.0);
        $cache->save($item->set($value));
        $item = $cache->getItem('baz');
        $cache->save($item->set($value));

        
'testSaveWithoutExpire' => 'Assumes a shared cache which ArrayAdapter is not.',
    ];

    public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface
    {
        return new ArrayAdapter($defaultLifetime);
    }

    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)
return new PdoAdapter('sqlite:'.self::$dbFile, 'ns', $defaultLifetime);
    }

    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());
        


    protected static string $file;

    public static function setUpBeforeClass(): void
    {
        self::$file = sys_get_temp_dir().'/symfony-cache/php-array-adapter-test.php';
    }

    protected function tearDown(): void
    {
        $this->createCachePool()->clear();

        if (file_exists(sys_get_temp_dir().'/symfony-cache')) {
            (new Filesystem())->remove(sys_get_temp_dir().'/symfony-cache');
        }
    }

    public function createCachePool(int $defaultLifetime = 0): CacheItemPoolInterface
    {
        return new PhpArrayAdapter(self::$filenew FilesystemAdapter('php-array-fallback', $defaultLifetime));
    }
}
$adapter = new DoctrineDbalAdapter($connection);
        $adapter->configureSchema($schema$connectionfn () => true);
        $this->assertTrue($schema->hasTable('cache_items'));
    }

    public function testConfigureSchemaDifferentDbalConnection()
    {
        $otherConnection = $this->createConnectionMock();
        $schema = new Schema();

        $adapter = $this->createCachePool();
        $adapter->configureSchema($schema$otherConnectionfn () => false);
        $this->assertFalse($schema->hasTable('cache_items'));
    }

    public function testConfigureSchemaTableExists()
    {
        $connection = DriverManager::getConnection(['driver' => 'pdo_sqlite', 'path' => self::$dbFile]$this->getDbalConfig());
        $schema = new Schema();
        $schema->createTable('cache_items');

        $adapter = new DoctrineDbalAdapter($connection);
        
Home | Imprint | This part of the site doesn't use cookies.