public function testHandles404RevalidationResponses()
 {
     $request = new Request('GET', 'http://foo.com');
     $request->setClient(new Client());
     $badResponse = new Response(404, array(), 'Oh no!');
     $badRequest = clone $request;
     $badRequest->setResponse($badResponse, true);
     $response = new Response(200, array(), 'foo');
     $plugin = new CachePlugin();
     $c = new ArrayCache();
     $c->save('foo', array(200, array(), 'foo'));
     $s = new DefaultCacheStorage(new DoctrineCacheAdapter($c));
     $k = new CallbackCacheKeyProvider(function () {
         return 'foo';
     });
     $rev = $this->getMockBuilder('Guzzle\\Plugin\\Cache\\DefaultRevalidation')->setConstructorArgs(array($k, $s, $plugin))->setMethods(array('createRevalidationRequest'))->getMock();
     $rev->expects($this->once())->method('createRevalidationRequest')->will($this->returnValue($badRequest));
     try {
         $rev->revalidate($request, $response);
         $this->fail('Should have thrown an exception');
     } catch (BadResponseException $e) {
         $this->assertSame($badResponse, $e->getResponse());
         $this->assertFalse($c->fetch('foo'));
     }
 }
Example #2
0
 public function testCache()
 {
     $cache = new ArrayCache();
     $torInfo = new TorInfo($cache);
     $this->assertTrue($torInfo->torCheckIp('176.58.100.98')->count() == 2, "Tor exit node not detected");
     $this->assertTrue($cache->contains('tuxcoder_tor_info_exit_addresses'));
 }
 public function testProxiesCallsOnCacheMiss()
 {
     $endpoint = $this->provider->getEndpoint('s3', 'us-east-1');
     $this->assertInstanceOf('Aws\\Common\\Region\\Endpoint', $endpoint);
     $this->assertSame($endpoint, $this->cache->fetch('s3_us-east-1'));
     $this->assertSame($endpoint, $this->provider->getEndpoint('s3', 'us-east-1'));
 }
 public function testContainsWhenStringExistsInCache()
 {
     $arrayCache = new ArrayCache();
     $arrayCache->save("test", "string_test");
     $cache = new DoctrineCacheProvider($arrayCache);
     $this->assertTrue($cache->contains("test"));
 }
Example #5
0
 /**
  * @return Exchanger
  */
 protected function createExchanger()
 {
     $cache = new ArrayCache();
     $cache->save(EuropeanCentralBank::URI, file_get_contents(__DIR__ . '/fixtures/eurofxref-daily.xml'));
     $exchanger = new Exchanger(new EuropeanCentralBank(new Downloader($cache)));
     return $exchanger;
 }
 function testKeysDoNotInterfere()
 {
     $cache = new ArrayCache();
     $ns = new CacheNamespace('foo', $cache);
     $ns->save('foo', 'bar');
     $this->assertFalse($cache->fetch('foo'));
     $this->assertEquals('bar', $ns->fetch('foo'));
 }
 public function testGetCachedMetadata()
 {
     $metadata = $this->getMock('Doctrine\\Common\\Persistence\\Mapping\\ClassMetadata');
     $cache = new ArrayCache();
     $cache->save(__NAMESPACE__ . '\\ChildEntity$CLASSMETADATA', $metadata);
     $this->cmf->setCacheDriver($cache);
     $loadedMetadata = $this->cmf->getMetadataFor(__NAMESPACE__ . '\\ChildEntity');
     $this->assertSame($loadedMetadata, $metadata);
 }
 public function testNamespaceIsPropagatedToAllProviders()
 {
     $cache1 = new ArrayCache();
     $cache2 = new ArrayCache();
     $chainCache = new ChainCache(array($cache1, $cache2));
     $chainCache->setNamespace('bar');
     $this->assertEquals('bar', $cache1->getNamespace());
     $this->assertEquals('bar', $cache2->getNamespace());
 }
Example #9
0
 /**
  *
  * @return MetadataBag
  */
 public function getMetadatas()
 {
     $key = realpath($this->file);
     if ($this->cache->contains($key)) {
         return $this->cache->fetch($key);
     }
     $metadatas = $this->parser->ParseMetadatas();
     $this->cache->save($key, $metadatas);
     return $metadatas;
 }
Example #10
0
 public function testWrapsMethods()
 {
     $a = new ArrayCache();
     $a->save('foo', '123');
     $c = new DoctrineCacheAdapter($a);
     $s = new DefaultCacheStorage($c, 100);
     $this->assertEquals('123', $s->fetch('foo'));
     $s->delete('foo');
     $this->assertNotEquals('123', $s->fetch('foo'));
 }
 public function testGetCachedGeocodedData()
 {
     $address = 'Paris, France';
     $coordinates = array('lat' => 48.857049, 'lng' => 2.35223);
     $delegate = $this->getMock('Geocoder\\Provider\\ProviderInterface');
     $delegate->expects($this->once())->method('getGeocodedData')->with($address)->will($this->returnValue($coordinates));
     $provider = new CacheProvider($cache = new ArrayCache(), $delegate);
     $provider->getGeocodedData($address);
     $provider->getGeocodedData($address);
     $this->assertTrue($cache->contains(crc32($address)));
 }
 public function testCachedMetadataFromFactory()
 {
     $cache = new ArrayCache();
     $this->factory = new ClassMetadataFactory($this->loader, $cache);
     $metadata = $this->factory->getClassMetadata('DMS\\Tests\\Dummy\\Classes\\AnnotatedClass');
     $this->assertTrue($cache->contains(ltrim('DMS\\Tests\\Dummy\\Classes\\AnnotatedClass', '\\')));
     //Get new Factory to retrieve from cache
     $this->factory = new ClassMetadataFactory($this->loader, $cache);
     $metadataCached = $this->factory->getClassMetadata('DMS\\Tests\\Dummy\\Classes\\AnnotatedClass');
     $this->assertEquals($metadata, $metadataCached);
 }
Example #13
0
 public function testWithArrayCache()
 {
     $class = $this->getClass();
     $className = get_class($class);
     $arrayCache = new ArrayCache();
     $this->_standard = new Standard($this->getLoader(), $arrayCache);
     $classMetadata = $this->_standard->getClassMetadata($className);
     $this->assertTrue($arrayCache->contains($className));
     $this->_standard = new Standard($this->getLoader(), $arrayCache);
     $cachedClassMetadata = $this->_standard->getCache()->fetch($className);
     $this->assertSame($classMetadata, $cachedClassMetadata);
 }
 public function testCache()
 {
     $cacheProvider = new ArrayCache();
     $loader = new JSONLoader(__DIR__ . '/../fixtures');
     $defaultConfig = $loader->getClassMetadataConfig('metadata.defaults');
     $lazyLoader = new LazyMetadataLoader($loader);
     $factory = new CacheMetadataFactory($lazyLoader, $cacheProvider, $defaultConfig);
     $class = 'a15l\\serialization\\metadata\\tests\\fixtures\\Dummy';
     $dummyData = $factory->getClassMetadata($class);
     $this->assertArrayHasKey('readonly', $dummyData);
     $rawData = json_decode(file_get_contents(__DIR__ . '../../fixtures' . DIRECTORY_SEPARATOR . 'a15l.serialization.metadata.tests.fixtures.Dummy.json'), true);
     $this->assertEquals(json_encode($rawData), json_encode($dummyData));
     $this->assertTrue($cacheProvider->contains('class-metadata::' . $class));
     $this->assertEquals(json_encode($rawData), json_encode($cacheProvider->fetch('class-metadata::' . $class)));
 }
 public function testHydrationCache()
 {
     $cache = new ArrayCache();
     $dql = "SELECT u FROM Doctrine\\Tests\\Models\\Cms\\CmsUser u";
     $users = $this->_em->createQuery($dql)->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))->getResult();
     $c = $this->getCurrentQueryCount();
     $users = $this->_em->createQuery($dql)->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))->getResult();
     $this->assertEquals($c, $this->getCurrentQueryCount(), "Should not execute query. Its cached!");
     $users = $this->_em->createQuery($dql)->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))->getArrayResult();
     $this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration is part of cache key.");
     $users = $this->_em->createQuery($dql)->setHydrationCacheProfile(new QueryCacheProfile(null, null, $cache))->getArrayResult();
     $this->assertEquals($c + 1, $this->getCurrentQueryCount(), "Hydration now cached");
     $users = $this->_em->createQuery($dql)->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache))->getArrayResult();
     $this->assertTrue($cache->contains('cachekey'), 'Explicit cache key');
     $users = $this->_em->createQuery($dql)->setHydrationCacheProfile(new QueryCacheProfile(null, 'cachekey', $cache))->getArrayResult();
     $this->assertEquals($c + 2, $this->getCurrentQueryCount(), "Hydration now cached");
 }
Example #16
0
 public function testClearCache()
 {
     $acl = $this->getAcl(0);
     $this->aclCache->putInCache($acl);
     $this->aclCache->clearCache();
     $this->assertFalse($this->cacheProvider->contains('foo5_class'));
     $this->assertFalse($this->cacheProvider->contains('oid5'));
 }
 private function buildMemcachedCache()
 {
     if (null === $this->host) {
         throw new HostShouldBeProvidedException();
     }
     if (null === $this->port) {
         $this->port = Memcached::DEFAULT_PORT;
     }
     $this->server->addserver($this->host, $this->port);
     $this->cacheProvider->setMemcached($this->server);
 }
Example #18
0
 /**
  * @covers Guzzle\Http\Plugin\CachePlugin::revalidate
  * @expectedException Guzzle\Http\Exception\BadResponseException
  */
 public function testRemovesMissingEntitesFromCacheWhenRevalidating()
 {
     $server = $this->getServer();
     $server->enqueue(array("HTTP/1.1 200 OK\r\nCache-Control: max-age=1000, no-cache\r\nContent-Length: 4\r\n\r\nData", "HTTP/1.1 404 NOT FOUND\r\nContent-Length: 0\r\n\r\n"));
     $plugin = new CachePlugin($this->adapter);
     $client = new Client($server->getUrl());
     $client->getEventDispatcher()->addSubscriber($plugin);
     $request1 = $client->get('/');
     $request1->send();
     $this->assertTrue($this->cache->contains($plugin->getCacheKey($request1)));
     $client->get('/')->send();
 }
Example #19
0
 /**
  * Creates cache by name.
  *
  * @param string $name    Name.
  * @param array  $options Options.
  *
  * @return CacheProvider
  * @throws \InvalidArgumentException When cache provider with given name not found.
  * @throws \LogicException When no caches provided for "chain" cache.
  */
 public function create($name, array $options = array())
 {
     switch ($name) {
         case 'chain':
             $valid_caches = array();
             foreach (array_filter($options) as $cache_name) {
                 $valid_caches[] = self::create($cache_name);
             }
             if (!$valid_caches) {
                 throw new \LogicException('No valid caches provided for "chain" cache.');
             }
             $cache_driver = new ChainCache($valid_caches);
             $cache_driver->setNamespace($this->_namespace);
             return $cache_driver;
         case 'array':
             $cache_driver = new ArrayCache();
             $cache_driver->setNamespace($this->_namespace);
             return $cache_driver;
         case 'apc':
             $cache_driver = new ApcCache();
             $cache_driver->setNamespace($this->_namespace);
             return $cache_driver;
         case 'memcache':
             $memcache = new \Memcache();
             $memcache->connect('localhost', 11211);
             $cache_driver = new MemcacheCache();
             $cache_driver->setMemcache($memcache);
             $cache_driver->setNamespace($this->_namespace);
             return $cache_driver;
         case 'memcached':
             $memcached = new \Memcached();
             $memcached->addServer('memcache_host', 11211);
             $cache_driver = new MemcachedCache();
             $cache_driver->setMemcached($memcached);
             $cache_driver->setNamespace($this->_namespace);
             return $cache_driver;
     }
     throw new \InvalidArgumentException('Cache provider "' . $name . '" not found.');
 }
 public function testGetStructuresCached()
 {
     $cache = new ArrayCache();
     $cache->save('sulu_io', ['t1', 't3']);
     $structures = [$this->generateStructure('t1', 'MyBundle:default:t1'), $this->generateStructure('t2', 'MyBundle:default:t2'), $this->generateStructure('t3', 'MyBundle:default:t3')];
     $twig = $this->prophesize('\\Twig_Environment');
     $twig->getLoader()->shouldNotBeCalled();
     $structureManager = $this->prophesize('Sulu\\Component\\Content\\Compat\\StructureManagerInterface');
     $structureManager->getStructures()->shouldNotBeCalled();
     $structureManager->getStructure('t1')->willReturn($structures[0]);
     $structureManager->getStructure('t2')->shouldNotBeCalled();
     $structureManager->getStructure('t3')->willReturn($structures[2]);
     $webspaceManager = $this->prophesize('Sulu\\Component\\Webspace\\Manager\\WebspaceManagerInterface');
     $webspaceManager->findWebspaceByKey('sulu_io')->shouldNotBeCalled();
     $activeTheme = $this->prophesize('Liip\\ThemeBundle\\ActiveTheme');
     $activeTheme->getName()->shouldNotBeCalled();
     $activeTheme->setName('test')->shouldNotBeCalled();
     $activeTheme->setName('before')->shouldNotBeCalled();
     $structureProvider = new WebspaceStructureProvider($twig->reveal(), $structureManager->reveal(), $webspaceManager->reveal(), $activeTheme->reveal(), $cache);
     $result = $structureProvider->getStructures('sulu_io');
     $this->assertCount(2, $result);
     $this->assertEquals($structures[0]->getKey(), $result[0]->getKey());
     $this->assertEquals($structures[2]->getKey(), $result[1]->getKey());
 }
Example #21
0
 public function testGarbageCollectAll()
 {
     $ts = 0;
     $time = $this->getMock('\\MS\\Throttle\\Time');
     $time->expects($this->any())->method('getTimestamp')->will($this->returnCallback(function () use(&$ts) {
         return $ts;
     }));
     $cache = new ArrayCache();
     $throttle = new Throttle($cache, $time);
     $throttle->addInterval(100, 25);
     $ts = 100;
     $throttle->increment('id1');
     $throttle->increment('id2');
     $ts = 150;
     $throttle->increment('id1');
     $ts = 220;
     $throttle->increment('id1');
     $ts = 240;
     $throttle->increment('id1');
     $throttle->increment('id2');
     $throttle->garbageCollect();
     $this->assertCount(3, $cache->fetch('id1'));
     $this->assertCount(1, $cache->fetch('id2'));
 }
 /**
  * Create service with name.
  *
  * @param ServiceLocatorInterface $services
  * @param string $name
  * @param string $requestedName
  * @return mixed
  */
 public function createServiceWithName(ServiceLocatorInterface $services, $name, $requestedName)
 {
     // Note that we already checked for existence in canCreateServiceWithName()
     $options = $this->getOptions($services, $requestedName);
     $storageName = $options->getStorage();
     if (!$storageName) {
         throw new Exception\ConfigException(sprintf('Missing configuration option "storage" for cache "%s"', $requestedName));
     }
     if (!$services->has($storageName)) {
         throw new Exception\ConfigException(sprintf('Cache storage "%s" does not exist for cache "%s"', $storageName, $requestedName));
     }
     /** @var StorageInterface $storage */
     $storage = $services->get($storageName);
     $namespace = $options->getNamespace() ?: 'DetailPersistence';
     $cache = new ZendStorageCache($storage);
     $cache->setNamespace($namespace);
     if ($options->chainToArrayCache() !== false) {
         $arrayCache = new ArrayCache();
         $arrayCache->setNamespace($namespace);
         // Use same namespace
         $cache = new ChainCache(array($arrayCache, $cache));
     }
     return $cache;
 }
Example #23
0
 /**
  * Creates a configuration without a metadata driver.
  *
  * @param bool   $isDevMode
  * @param string $proxyDir
  * @param Cache  $cache
  *
  * @return Configuration
  */
 public static function createConfiguration($isDevMode = false, $proxyDir = null, Cache $cache = null)
 {
     $proxyDir = $proxyDir ?: sys_get_temp_dir();
     if ($isDevMode === false && $cache === null) {
         if (extension_loaded('apc')) {
             $cache = new \Doctrine\Common\Cache\ApcCache();
         } elseif (extension_loaded('xcache')) {
             $cache = new \Doctrine\Common\Cache\XcacheCache();
         } elseif (extension_loaded('memcache')) {
             $memcache = new \Memcache();
             $memcache->connect('127.0.0.1');
             $cache = new \Doctrine\Common\Cache\MemcacheCache();
             $cache->setMemcache($memcache);
         } elseif (extension_loaded('redis')) {
             $redis = new \Redis();
             $redis->connect('127.0.0.1');
             $cache = new \Doctrine\Common\Cache\RedisCache();
             $cache->setRedis($redis);
         } else {
             $cache = new ArrayCache();
         }
     } elseif ($cache === null) {
         $cache = new ArrayCache();
     }
     if ($cache instanceof CacheProvider) {
         $cache->setNamespace("dc2_" . md5($proxyDir) . "_");
         // to avoid collisions
     }
     $config = new Configuration();
     $config->setMetadataCacheImpl($cache);
     $config->setQueryCacheImpl($cache);
     $config->setResultCacheImpl($cache);
     $config->setProxyDir($proxyDir);
     $config->setProxyNamespace('DoctrineProxies');
     $config->setAutoGenerateProxyClasses($isDevMode);
     return $config;
 }
 public function testCachedTokenDoNotPerformAditionalRequests()
 {
     $cache = new ArrayCache();
     $cache->save(Client::TOKEN_KEY, 'foobar');
     $this->client = new Client(new Credentials('123'), 'es', $cache);
     $history = new History();
     $this->client->getEmitter()->attach($history);
     $subscriber = new Mock();
     $this->client->getEmitter()->attach($subscriber);
     // Set mocked response
     $body = new Stream(fopen(__DIR__ . '/../dummy_response_data/getUsers.json', 'r'));
     $subscriber->addResponse(new Response(200, [], $body));
     $this->client->getUsers();
     $this->assertCount(1, $history);
 }
 public function fetch($id)
 {
     $this->fetchedIDs[$id] = true;
     return parent::fetch($id);
 }
 protected function doFlush()
 {
     $this->doFlushHasBeenCalled = true;
     return parent::doFlush();
 }
 /**
  * @Given /^failover status should be cleaned$/
  */
 public function failoverStatusShouldBeCleaned()
 {
     \assertFalse($this->cache->contains($this->failoverStatusVar()));
 }
Example #28
0
 public function getStats()
 {
     $this->getStatsHasBeenCalled = true;
     return $this->cacheProvider->getStats();
 }
 /**
  * Get cache driver according to config.yml entry.
  *
  * Logic from Doctrine setup method
  * https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Tools/Setup.php#L122
  *
  * @param  array      $cacheConfig
  * @param  boolean    $isDevMode
  * @param  string|null $proxyDir
  * @return Cache
  */
 protected function getManuallyDefinedCache(array $cacheConfig, $isDevMode = false, $proxyDir = null)
 {
     $proxyDir = $proxyDir ?: sys_get_temp_dir();
     if ($isDevMode === false) {
         if (extension_loaded('apc') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'apc') {
             $cache = new \Doctrine\Common\Cache\ApcCache();
         } elseif (extension_loaded('xcache') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'xcache') {
             $cache = new \Doctrine\Common\Cache\XcacheCache();
         } elseif (extension_loaded('memcache') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'memcache') {
             $memcache = new \Memcache();
             $host = !empty($cacheConfig['host']) ? $cacheConfig['host'] : '127.0.0.1';
             if (!empty($cacheConfig['port'])) {
                 $memcache->connect($host, $cacheConfig['port']);
             } else {
                 $memcache->connect($host);
             }
             $cache = new \Doctrine\Common\Cache\MemcacheCache();
             $cache->setMemcache($memcache);
         } elseif (extension_loaded('redis') && !empty($cacheConfig['type']) && $cacheConfig['type'] == 'redis') {
             $redis = new \Redis();
             $host = !empty($cacheConfig['host']) ? $cacheConfig['host'] : '127.0.0.1';
             if (!empty($cacheConfig['port'])) {
                 $redis->connect($host, $cacheConfig['port']);
             } else {
                 $redis->connect($host);
             }
             $cache = new \Doctrine\Common\Cache\RedisCache();
             $cache->setRedis($redis);
         } else {
             $cache = new ArrayCache();
         }
     } else {
         $cache = new ArrayCache();
     }
     if ($cache instanceof CacheProvider) {
         $cache->setNamespace("dc2_" . md5($proxyDir) . "_");
         // to avoid collisions
     }
     return $cache;
 }
Example #30
-1
 public function testDoesNotModifyCacheNamespace()
 {
     $cache = new ArrayCache();
     $cache->setNamespace('foo');
     new DefaultRegion('bar', $cache);
     new DefaultRegion('baz', $cache);
     $this->assertSame('foo', $cache->getNamespace());
 }