Author: Robert Hafner (tedivm@tedivm.com)
Inheritance: implements Stash\Interfaces\PoolInterface
Example #1
0
 /**
  * @return string
  */
 protected function generateId()
 {
     do {
         $id = Text::generateString(20);
         $item = $this->cache->getItem('_session/' . $id);
     } while (!$item->isMiss() || isset($this->sessions[$id]));
     return $id;
 }
 private function getRates(Currency $currency)
 {
     $rates = $this->pool->getItem($currency->getName());
     if ($rates->isMiss()) {
         $newRates = $this->rates->getRates($currency);
         $rates->set($newRates, $this->ttl);
     }
     return $newRates;
 }
Example #3
0
 public function testConstruction()
 {
     $key = array('apple', 'sauce');
     $driver = new Sqlite(array());
     $pool = new Pool();
     $pool->setDriver($driver);
     $item = $pool->getItem('testKey');
     $item->set($key);
     $this->assertTrue($pool->save($item), 'Able to load and store with unconfigured extension.');
 }
 /**
  * @param $item
  *
  * @return null
  */
 public function forget($item)
 {
     if (!$this->enabled) {
         return;
     }
     $item = $this->pool->getItem($item);
     if (!$item) {
         return;
     }
     $item->clear();
 }
 protected function setUp()
 {
     $this->redis = new Redis();
     $cachePool = new Pool();
     $cachePool->setDriver($this->redis);
     $this->repository = new RepositoryCache($cachePool, new InMemoryRepository(), rand(PHP_INT_MIN, PHP_INT_MAX), self::TTL_IN_SECONDS);
     $this->repository->add(new Customer(1, 'John Doe', 3, 25.125, new DateTime('2014-12-11')));
     $this->repository->add(new Customer(2, 'Junichi Masuda', 3, 50978.125, new DateTime('2013-02-22')));
     $this->repository->add(new Customer(3, 'Shigeru Miyamoto', 5, 47889850.125, new DateTime('2010-12-01')));
     $this->repository->add(new Customer(4, 'Ken Sugimori', 4, 69158.68700000001, new DateTime('2010-12-10')));
 }
Example #6
0
 /**
  * Returns the latest tweets from the defined user timeline.
  *
  * @return mixed
  */
 public function getLatestTweets()
 {
     $cache = $this->cache->getItem(__METHOD__);
     if (!$cache->isMiss()) {
         return $cache->get();
     }
     $latestTweets = $this->client->getTimeline(['count' => self::TIMELINE_COUNT]);
     if (isset($latestTweets['errors'])) {
         throw new \RuntimeException($latestTweets['errors'][0]->message);
     }
     $cache->set($latestTweets, self::FIVE_MINUTES);
     return $latestTweets;
 }
Example #7
0
 public function getNextEvent()
 {
     $cache = $this->cache->getItem(__METHOD__);
     if (!$cache->isMiss()) {
         return $cache->get();
     }
     $events = $this->client->getEvents(array('group_urlname' => self::GROUP_URLNAME));
     if ($events->isError()) {
         throw new \RuntimeException($events->getMessage());
     }
     $event = $events->getData()[0];
     $cache->set($event, self::FIVE_MINUTES);
     return $event;
 }
Example #8
0
 /**
  * @return array|\DMS\Service\Meetup\Response\MultiResultResponse|mixed|null
  */
 public function getRsvpListForNextEvent()
 {
     $cache = $this->cache->getItem(__METHOD__);
     if (!$cache->isMiss()) {
         return $cache->get();
     }
     $rsvpList = $this->client->getRsvps(array('group_urlname' => self::GROUP_URLNAME, 'event_id' => $this->getNextEvent()['id']));
     if ($rsvpList->isError()) {
         throw new \RuntimeException($rsvpList->getMessage());
     }
     $rsvpList = $rsvpList->getData();
     $cache->set($rsvpList, self::FIVE_MINUTES);
     return $rsvpList;
 }
Example #9
0
 function setup_cache_mocks(Pool $cache)
 {
     $cache->setDriver(Argument::any())->willReturn(true);
     $item = $this->prophet->prophesize('Stash\\Item');
     $item->get()->willReturn('data');
     $item->set(Argument::cetera())->willReturn(true);
     $item->isMiss()->willReturn(true);
     $item->lock()->willReturn(true);
     $item->clear()->willReturn(true);
     $item = $item->reveal();
     $cache->getItem(Argument::any())->willReturn($item);
     $cache->purge()->willReturn(true);
     $cache->flush()->willReturn(true);
     return ['cache' => $cache];
 }
Example #10
0
 /**
  * Вызывает соответствующий метод в конкретной реализации,
  * самостоятельно занимаясь кэшированием, логгированием
  * и измерением времени
  *
  * @param string $method Вызываемый метод
  * @param array  $args   Переданные в метод аргументы
  *
  * @return Response
  * @throws ConfigurationErrorException
  * @throws \InvalidArgumentException
  */
 public function __call($method, array $args = [])
 {
     $cacheKey = md5(serialize(func_get_args()));
     $args = $this->createArgs($args);
     $timer = $this->pinba->start(['call' => sprintf('%s->%s', get_class($this), $method), 'args' => $args]);
     $this->logger->info(sprintf('%s->%s', get_class($this), $method), $args);
     $this->checkIsConfigured();
     $item = $this->cacher->getItem($cacheKey);
     $inCache = !$item->isMiss();
     $this->logger->info(sprintf('item found in cache: %s', $inCache ? 'yes' : 'no'));
     if ($inCache) {
         $this->logger->info('get from cache');
         $response = $item->get();
     } else {
         $this->logger->info('get from source');
         $response = $this->implementation($method, $args);
         $expiresDefault = array_key_exists('default', $this->cacherExpires) ? $this->cacherExpires['default'] : 0;
         $expires = array_key_exists($method, $this->cacherExpires) ? $this->cacherExpires[$method] : $expiresDefault;
         $item->set($response, $expires);
         if (!$response->isOk()) {
             $this->logger->error('error response', [$response->getError()]);
         } else {
             $this->logger->debug('successful response', [$response->getContent()]);
         }
     }
     $this->pinba->stop($timer);
     $this->logger->info('pinba', $this->pinba->info($timer));
     return $response;
 }
 /**
  * Löscht den Cache eines Items und seine unter objekte
  * @param string|array $itemName eindeutigr Path zum Item
  */
 public function clearPath($itemName)
 {
     if (is_array($itemName)) {
         $itemName = $this->itemNameArrayToPath($itemName);
     }
     $item = $this->pool->getItem($itemName);
     $item->clear();
 }
 /**
  * {@inheritdoc}
  */
 public function getItem($key)
 {
     /** @var CacheItem $item */
     $item = parent::getItem($key);
     if (isset($this->tracker)) {
         $item->setCacheTracker($this->tracker);
     }
     return $item;
 }
Example #13
0
 /**
  * Disables the cache
  */
 public function disable()
 {
     // save the current driver if not yet black hole so it can be restored on enable()
     if (!$this->pool->getDriver() instanceof BlackHole) {
         $this->driver = $this->pool->getDriver();
     }
     $this->pool->setDriver(new BlackHole());
     $this->enabled = false;
 }
Example #14
0
 /**
  * {@inheritdoc}
  */
 public function getItem()
 {
     $args = func_get_args();
     // check to see if a single array was used instead of multiple arguments
     if (count($args) == 1 && is_array($args[0])) {
         $args = $args[0];
     }
     /** @var CacheItem $item */
     $item = parent::getItem($args);
     if (isset($this->tracker)) {
         $item->setCacheTracker($this->tracker);
     }
     return $item;
 }
Example #15
0
 /**
  * @depends testSaveWithTags
  * @covers Bankiru\Stash\TaggedItem::get
  * @covers Bankiru\Stash\TaggedItem::validateRecord
  */
 public function testGetWithInvalidTagVersion()
 {
     $key = uniqid('test/key/', true);
     $value = uniqid('test-value-', true);
     $tags = [uniqid('test-tag-', true), uniqid('test-tag-', true)];
     /** @var TaggedItem $item */
     $item = $this->pool->getItem($key);
     $item->set($value)->setTags($tags)->save();
     $tagToInvalidate = 'Bankiru\\Stash\\TaggedItem/' . TaggedItem::VERSION . '/' . $tags[0];
     $tagItem = $this->pool->getItem($tagToInvalidate);
     static::assertTrue($tagItem->isHit());
     $tagItem->set('INVALIDVERSION')->save();
     $item = $this->pool->getItem($key);
     static::assertTrue($item->isMiss());
 }
Example #16
0
 public function testPoolClear()
 {
     $pool = new Pool();
     $pool->setDriver(new DriverExceptionStub());
     $item = $pool->getItem('test');
     $this->assertFalse($item->isDisabled());
     $this->assertFalse($pool->clear());
     $item = $pool->getItem('test');
     $this->assertTrue($item->isDisabled(), 'Is disabled after exception is thrown in driver');
     $this->assertFalse($pool->clear());
 }
Example #17
0
 /**
  * @param AbstractRequest $request
  * @return string
  * @throws \Exception
  */
 function request(AbstractRequest $request)
 {
     $this->logger->info($request->getPath());
     $args = $this->buildRequestArgs($request);
     if ($this->cachepool) {
         do {
             $cacheKey = $this->buildCacheKey($request, $args);
             $cacheKeyLog = preg_replace('/key=[^&]+/', 'key=*****', $cacheKey);
             $cacheItem = $this->cachepool->getItem($cacheKey);
             // Disabled on a request basis?
             if (!$request->isUseCache()) {
                 break;
             }
             $this->logger->info('Cache enabled', ['key' => $cacheKeyLog]);
             $age = null;
             if (!$cacheItem->isMiss()) {
                 $age = time() - $cacheItem->getCreation()->getTimestamp();
                 $cachedData = $this->_deserialize($this->cfg->getFormat(), $cacheItem->get());
             }
             // Time to renew
             $ttr = $request->getTtr() !== null ? $request->getTtr() : $this->cfg->getCacheTtr();
             // Return the cached data if it's not time yet to renew
             $returnCached = !$cacheItem->isMiss() && $age < $ttr;
             //                if ($returnCached) {
             //                    // Check the latest hashes
             //                    $request->validateCache($this, $cachedData);
             //                }
             if ($returnCached) {
                 $msg = 'Using cache';
             } else {
                 if (!$age) {
                     $msg = 'Cache MISS';
                 } else {
                     $msg = 'NOT using cache';
                 }
             }
             $this->logger->info($msg, ['age' => $age, 'ttr' => $ttr, 'returnCached' => $returnCached]);
             if ($returnCached) {
                 return $request->handleResponse($cachedData);
             }
             // @todo lock cache
         } while (false);
     }
     try {
         $uri = $this->cfg->getEndpoint() . $request->getPath() . '.' . $this->cfg->getFormat();
         $this->logger->info('Refreshing resource', ['uri' => $uri, 'args' => http_build_query(array_merge($args, ['key' => '*****']))]);
         $body = $this->guzzle->get($uri, ['query' => $args])->getBody();
     } catch (\Exception $e) {
         // Log and report
         $this->logger->error((string) $e);
         if ($this->debug) {
             throw $e;
         }
         // Return stale data
         if (isset($cacheItem) && isset($cachedData)) {
             $this->logger->info('Returning stale data!');
             return $request->handleResponse($cachedData);
         } else {
             // Sad panda
             throw $e;
         }
     }
     $result = $body->getContents();
     $deserialized = $this->_deserialize($this->cfg->getFormat(), $result);
     // Cache might be disabled, but still renew if there was cached data so that the new result gets returned in
     // case caching might be enabled again in a later request.
     if (isset($cacheItem) && ($request->isUseCache() || !$request->isUseCache() && !$cacheItem->isMiss())) {
         $this->logger->info($cacheItem->isMiss() ? 'Saving cache' : 'Refreshing cache');
         $cacheItem->set($result, 365 * 60 * 60 * 24);
         // ttl not relevant
     }
     return $request->handleResponse($deserialized);
 }
Example #18
0
 /**
  * Deletes a cache entry
  *
  * @param $key
  * @return void
  */
 public function delete($key)
 {
     $item = $this->pool->getItem($key);
     $item->clear();
 }
Example #19
0
 /**
  * Flush the stash cache
  *
  * @return void
  */
 public function flushCache()
 {
     $this->pool->flush();
 }
Example #20
0
 protected function doFlush()
 {
     $this->_cache->flush();
 }
Example #21
0
 /** @inheritDoc */
 public function put($key, $value)
 {
     assert(is_string($key) || is_int($key));
     $this->stash->getItem((string) $key)->set($value);
 }
Example #22
0
 /**
  * {@inheritdoc}
  */
 public function save()
 {
     $contents = $this->getForStorage();
     $item = $this->pool->getItem($this->key);
     $item->set($contents, $this->expire);
 }
Example #23
0
 public function clearCache()
 {
     $this->cachePool->clear();
 }
Example #24
0
 /**
  * Clean the cache of all items.
  *
  * @return bool
  */
 public function clean()
 {
     return $this->_cache->flush();
 }
 /**
  * Registers services on the given container.
  *
  * This method should only be used to configure services and parameters.
  * It should not get services.
  *
  * @param Container $container A container instance.
  * @return void
  */
 public function register(Container $container)
 {
     /**
      * @param Container $container A container instance.
      * @return CacheConfig
      */
     $container['cache/config'] = function (Container $container) {
         $appConfig = $container['config'];
         $cacheConfig = new CacheConfig($appConfig->get('cache'));
         return $cacheConfig;
     };
     $container['cache/available-drivers'] = DriverList::getAvailableDrivers();
     /**
      * @param Container $container A container instance.
      * @return Container The Collection of cache drivers, in a Container.
      */
     $container['cache/drivers'] = function (Container $container) {
         $cacheConfig = $container['cache/config'];
         $drivers = new Container();
         $parentContainer = $container;
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\Apc
          */
         $drivers['apc'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             if (!isset($drivers['Apc'])) {
                 // Apc is not available on system
                 return null;
             }
             return new $drivers['Apc']();
         };
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\Sqlite
          */
         $drivers['db'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             if (!isset($drivers['SQLite'])) {
                 // SQLite is not available on system
                 return null;
             }
             return new $drivers['SQLite']();
         };
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\FileSystem
          */
         $drivers['file'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             return new $drivers['FileSystem']();
         };
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\Memcache
          */
         $drivers['memcache'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             if (!isset($drivers['Memcache'])) {
                 // Memcache is not available on system
                 return null;
             }
             $cacheConfig = $parentContainer['cache/config'];
             $driverOptions = ['servers' => []];
             if (isset($cacheConfig['servers'])) {
                 $servers = [];
                 foreach ($cacheConfig['servers'] as $server) {
                     $servers[] = array_values($server);
                 }
                 $driverOptions['servers'] = $servers;
             } else {
                 // Default Memcache options: locahost:11211
                 $driverOptions['servers'][] = ['127.0.0.1', 11211];
             }
             return new $drivers['Memcache']($driverOptions);
         };
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\Ephemeral
          */
         $drivers['memory'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             return new $drivers['Ephemeral']();
         };
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\BlackHole
          */
         $drivers['noop'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             return new $drivers['BlackHole']();
         };
         /**
          * @param Container $container A container instance.
          * @return \Stash\Driver\Redis
          */
         $drivers['redis'] = function (Container $container) use($parentContainer) {
             $drivers = $parentContainer['cache/available-drivers'];
             if (!isset($drivers['Redis'])) {
                 // Redis is not available on system
                 return null;
             }
             return new $drivers['Redis']();
         };
         return $drivers;
     };
     /**
      * @param Container $container A container instance.
      * @return Container The Collection of DatabaseSourceConfig, in a Container.
      */
     $container['cache/driver'] = function (Container $container) {
         $cacheConfig = $container['cache/config'];
         $types = $cacheConfig->get('types');
         foreach ($types as $type) {
             if (isset($container['cache/drivers'][$type])) {
                 return $container['cache/drivers'][$type];
             }
         }
         // If no working drivers were available, fallback to an Ephemeral (memory) driver.
         return $container['cache/drivers']['memory'];
     };
     /**
      * The cache pool, using Stash.
      *
      * @param Container $container A container instance.
      * @return \Stash\Pool
      */
     $container['cache'] = function (Container $container) {
         $cacheConfig = $container['cache/config'];
         $driver = $container['cache/driver'];
         $pool = new Pool($driver);
         $pool->setLogger($container['logger']);
         // Ensure an alphanumeric namespace (prefix)
         $namespace = preg_replace('/[^A-Za-z0-9 ]/', '', $cacheConfig['prefix']);
         $pool->setNamespace($namespace);
         return $pool;
     };
 }
Example #26
0
 /**
  * Clears all values in the namespace of this cache
  *
  * @return bool
  */
 public function clear()
 {
     // using stacks grouping http://www.stashphp.com/Grouping.html#stacks
     // this will clear all key keys beneath it
     return $this->stash_pool->getItem("/{$this->getNamespace()}")->clear();
 }
Example #27
0
 public function __construct()
 {
     $this->pool = new Pool(new Memcache([['127.0.0.1', '11211']]));
     $this->pool->setNamespace('hotflo20dev');
 }
Example #28
0
 /**
  * Помещает данные в кэш
  * @param string $key     ключ
  * @param mixed  $value   значение
  * @param int    $expires время жизни, сек
  * @return mixed
  */
 public function set($key, $value, $expires = 0)
 {
     $this->impl->getItem($key)->set($value, $expires);
 }