public function deleteFromCache(string $platform, string $pageName) { $item = $this->pool->getItem($platform . "/" . $pageName); $item->clear(); $item = $this->pool->getItem("common/" . $pageName); $item->clear(); }
/** * @return AircraftCollection */ public function getAllAircraft() { if ($this->cacheEnabled) { $cacheItem = $this->cachePool->getItem('aircraftCollection'); $aircraftCollection = $cacheItem->get(); if ($cacheItem->isHit()) { return $aircraftCollection; } } $fileObjects = $this->recursiveIterator; $aircraftCollection = $this->aircraftCollection; foreach ($fileObjects as $file) { if ($file->getFilename() === 'aircraft.json') { $json = file_get_contents($file->getPathName()); if ($json) { $aircraftConfig = json_decode($json); $aircraftConfig->path = $file->getPath(); $aircraftCollection->push($aircraftConfig); } } } if ($this->cacheEnabled) { $this->cachePool->save($cacheItem->set($aircraftCollection)); } return $aircraftCollection; }
/** * @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; }
/** * @param $item * * @return null */ public function forget($item) { if (!$this->enabled) { return; } $item = $this->pool->getItem($item); if (!$item) { return; } $item->clear(); }
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()); }
/** * 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; }
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; }
/** * @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; }
/** * Вызывает соответствующий метод в конкретной реализации, * самостоятельно занимаясь кэшированием, логгированием * и измерением времени * * @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; }
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.'); }
/** * {@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; }
/** * @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()); }
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]; }
/** * Помещает данные в кэш * @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); }
/** * Deletes a cache entry * * @param $key * @return void */ public function delete($key) { $item = $this->pool->getItem($key); $item->clear(); }
/** * @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); }
/** * Gets a value from the cache * @param string $key Name of the cache item ID * @return \Stash\Interfaces\ItemInterface */ public function getItem($key) { return $this->pool->getItem($key); }
/** * {@inheritdoc} */ public function save() { $contents = $this->getForStorage(); $item = $this->pool->getItem($this->key); $item->set($contents, $this->expire); }
protected function doDelete($id) { $id = $this->_filterCacheId($id); $item = $this->_cache->getItem($id); return $item->clear(); }
/** @inheritDoc */ public function put($key, $value) { assert(is_string($key) || is_int($key)); $this->stash->getItem((string) $key)->set($value); }
/** * 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(); }
/** * Delete an item from the cache. * * @param $id * @return bool */ public function remove($id) { $item = $this->_cache->getItem($id); return $item->clear(); }