/** * {@inheritdoc} */ public function handleRequest(RequestInterface $request, callable $next, callable $first) { $method = strtoupper($request->getMethod()); // if the request not is cachable, move to $next if ($method !== 'GET' && $method !== 'HEAD') { return $next($request); } // If we can cache the request $key = $this->createCacheKey($request); $cacheItem = $this->pool->getItem($key); if ($cacheItem->isHit()) { // return cached response $data = $cacheItem->get(); $response = $data['response']; $response = $response->withBody($this->streamFactory->createStream($data['body'])); return new FulfilledPromise($response); } return $next($request)->then(function (ResponseInterface $response) use($cacheItem) { if ($this->isCacheable($response)) { $bodyStream = $response->getBody(); $body = $bodyStream->__toString(); if ($bodyStream->isSeekable()) { $bodyStream->rewind(); } else { $response = $response->withBody($this->streamFactory->createStream($body)); } $cacheItem->set(['response' => $response, 'body' => $body])->expiresAfter($this->getMaxAge($response)); $this->pool->save($cacheItem); } return $response; }); }
/** * {@inheritdoc} */ public function load() { $item = $this->pool->getItem($this->key); if ($item->isHit()) { $this->setFromStorage($item->get()); } }
/** * @param string $key * @param string $value * @param int|\DateInterval $lifetime * @return bool */ public function save($key, $value, $lifetime = 0) { $item = $this->cache->getItem($key); $item->set($value); $item->expiresAfter($lifetime); return $this->cache->save($item); }
/** * Attempt to retrieve a result for a given namespace. * * @param $template * @param $namespace * @return Result|null */ private function fetchResultForNamespace($template, $namespace) { $key = $namespace . '::' . $template; $cacheItem = $this->cacheItemPool->getItem($key); if ($cacheItem->isHit()) { return new Result($key, $cacheItem->get(), true, $this->isCompiled()); } return null; }
public function testDeferredStateOfItems() { $key = uniqid(); $item = $this->_pool->getItem($key); $this->_pool->saveDeferred($item); /** @var CacheItem $cacheItem */ $cacheItem = $item; $this->assertEquals(CacheItemState::DEFERRED, $cacheItem->getState()); }
/** * {@inheritdoc} */ public function handleRequest(RequestInterface $request, callable $next, callable $first) { $method = strtoupper($request->getMethod()); // if the request not is cachable, move to $next if ($method !== 'GET' && $method !== 'HEAD') { return $next($request); } // If we can cache the request $key = $this->createCacheKey($request); $cacheItem = $this->pool->getItem($key); if ($cacheItem->isHit()) { $data = $cacheItem->get(); // The array_key_exists() is to be removed in 2.0. if (array_key_exists('expiresAt', $data) && ($data['expiresAt'] === null || time() < $data['expiresAt'])) { // This item is still valid according to previous cache headers return new FulfilledPromise($this->createResponseFromCacheItem($cacheItem)); } // Add headers to ask the server if this cache is still valid if ($modifiedSinceValue = $this->getModifiedSinceHeaderValue($cacheItem)) { $request = $request->withHeader('If-Modified-Since', $modifiedSinceValue); } if ($etag = $this->getETag($cacheItem)) { $request = $request->withHeader('If-None-Match', $etag); } } return $next($request)->then(function (ResponseInterface $response) use($cacheItem) { if (304 === $response->getStatusCode()) { if (!$cacheItem->isHit()) { /* * We do not have the item in cache. This plugin did not add If-Modified-Since * or If-None-Match headers. Return the response from server. */ return $response; } // The cached response we have is still valid $data = $cacheItem->get(); $maxAge = $this->getMaxAge($response); $data['expiresAt'] = $this->calculateResponseExpiresAt($maxAge); $cacheItem->set($data)->expiresAfter($this->calculateCacheItemExpiresAfter($maxAge)); $this->pool->save($cacheItem); return $this->createResponseFromCacheItem($cacheItem); } if ($this->isCacheable($response)) { $bodyStream = $response->getBody(); $body = $bodyStream->__toString(); if ($bodyStream->isSeekable()) { $bodyStream->rewind(); } else { $response = $response->withBody($this->streamFactory->createStream($body)); } $maxAge = $this->getMaxAge($response); $cacheItem->expiresAfter($this->calculateCacheItemExpiresAfter($maxAge))->set(['response' => $response, 'body' => $body, 'expiresAt' => $this->calculateResponseExpiresAt($maxAge), 'createdAt' => time(), 'etag' => $response->getHeader('ETag')]); $this->pool->save($cacheItem); } return $response; }); }
protected function extractParamNames($pattern, array $values) { $key = $this->keyPrefix . ':' . $pattern . ':' . $this->stateKey; $item = $this->pool->getItem($key); if (!$item->isHit()) { $item->set(parent::extractParamNames($pattern, $values)); $item->expiresAfter($this->ttl); $this->pool->save($item); } return $item->get(); }
/** * @param string $language * @return array */ public function getNavigation($language) { $item = $this->cache->getItem('navigation_' . $language); if ($item->isHit()) { return $item->get(); } list($keys, $navigation) = $this->getData($language); $item->set($navigation); $this->cache->save($item); return $navigation; }
public function createSchema($schemaFile) { $cacheKey = hash('sha1', $schemaFile); $item = $this->cache->getItem($cacheKey); if ($item->isHit()) { $schema = $item->get(); } else { $schema = $this->schemaFactory->createSchema($schemaFile); $this->cache->save($item->set($schema)); } return $schema; }
/** * {@inheritdoc} */ public function getIterator() { return new \CallbackFilterIterator($this->currencies->getIterator(), function (Currency $currency) { $item = $this->pool->getItem('currency|availability|' . $currency->getCode()); $item->set(true); if ($item instanceof TaggableItemInterface) { $item->addTag('currency.availability'); } $this->pool->save($item); return true; }); }
protected function query($url) { if ($this->cacheItemPool === null) { return $this->httpClient->get($url)->getBody()->getContents(); } $cacheItem = $this->cacheItemPool->getItem('game-feed/' . md5($url)); if (!$cacheItem->isHit()) { $cacheItem->set($this->httpClient->get($url)->getBody()->getContents())->expiresAfter($this->cacheExpiresAfter); $this->cacheItemPool->save($cacheItem); } return $cacheItem->get(); }
/** {@inheritdoc} */ public function getResponse(RpcRequestInterface $request) { $key = $this->extractor->getKey($request); /** @var CacheItemInterface $item */ $item = $this->items[$key]['item']; if ($item->isHit()) { return $item->get(); } $item->expiresAfter($this->ttl); $item->set($this->proxiedCollection->getResponse($request)); $this->cache->save($item); return $item->get(); }
/** * {@inheritdoc} */ public function getMetadataFor($value) { $class = $this->getClass($value); // Key cannot contain backslashes according to PSR-6 $key = strtr($class, '\\', '_'); $item = $this->cacheItemPool->getItem($key); if ($item->isHit()) { return $item->get(); } $metadata = $this->decorated->getMetadataFor($value); $this->cacheItemPool->save($item->set($metadata)); return $metadata; }
/** * @param string $pathInfo * * @return array */ public function match($pathInfo) { $host = strtr($this->context->getHost(), '.', '_'); $method = strtolower($this->context->getMethod()); $key = 'route_' . $method . '_' . $host . '_' . $pathInfo; if ($this->cache->hasItem($key)) { return $this->cache->getItem($key)->get(); } $match = parent::match($pathInfo); $item = $this->cache->getItem($key); $item->set($match)->expiresAfter(self::CACHE_LIFETIME); return $match; }
/** * Stores entity to cache * * @param mixed $data Entity source data * @param ApiMetadata $metadata * @param array $identifiers */ public function set($data, ApiMetadata $metadata, array $identifiers) { $item = $this->cache->getItem($this->getEntityKey($metadata, $identifiers)); $configuration = $this->manager->getConfiguration()->getCacheConfiguration($metadata->getName()); if (null === $configuration || $configuration['enabled'] === false) { $this->logger->debug(sprintf('Skipping entity cache for %s: not configured', $metadata->getName())); return; } $item->set($data); $item->expiresAfter($configuration['ttl']); $this->cache->save($item); $this->logger->debug(sprintf('Storing entity %s', $item->isHit() ? 'HIT' : 'MISS'), ['class' => $metadata->getName(), 'identifiers' => $identifiers]); }
public function fetch($source, EncapsulatedOptions $options = null) { $optionsCopy = $options ? $options->copy() : []; if ($this->isCacheEnabled()) { ksort($optionsCopy); $hash = $this->hash([$source, $optionsCopy]); if ($this->cache->hasItem($hash)) { return $this->cache->getItem($hash)->get(); } } $data = $this->fetchFreshData($source, $options); isset($hash) && $this->cache->save($this->cache->getItem($hash)->set($data)); return $data; }
/** * Load content and cache it * * @param $url * @return null|string */ public function get($url) { $url = $this->host . $url; $hash = 'url-parser' . md5($url); $cache = $this->cacheItemPool->getItem($hash); if ($cache->isHit()) { return $cache->get(); } // no error handling; trust and cache every request $content = @file_get_contents($url); $cache->set($content); $cache->expiresAfter($this->lifetime); $this->cacheItemPool->save($cache); return $content; }
/** * @param string $url * @param array $options * * @return array */ protected function makeRequest($url, array $options = []) { if ($this->client === null) { $this->client = new GuzzleClient(); } $item = null; if ($this->cache !== null) { $item = $this->cache->getItem($this->getRequestKey($url, $options)); $data = $item->get(); if ($item->isHit() === true) { $options = array_replace_recursive($options, ['headers' => ['If-Modified-Since' => $data['modified']]]); } } $options = array_replace_recursive($options, ['headers' => ['Accept' => 'application/json', 'Accept-Encoding' => 'gzip', 'User-Agent' => $this->getUserAgent()], 'query' => ['apikey' => $this->apiKey, 'locale' => $this->region->getLocale()], 'timeout' => 60]); try { $response = $this->client->get($url, $options); } catch (ClientException $exception) { switch ($exception->getCode()) { case 404: return; default: $data = json_decode($exception->getResponse()->getBody(), true); throw new BattleNetException($data['detail'], $exception->getCode()); } } return $this->handleSuccessfulResponse($response, $item); }
/** * Returns the value associated with the given cache key from the given cache. * * Uses the given callback to load the value associated with the given cache * key in case the value is not cached yet. * * @param \Psr\Cache\CacheItemPoolInterface $cache The cache to use * @param string $cacheKey Key of the cache value to return * @param callable $cacheLoaderCallback Callback used to load the cache if necessary * @return mixed */ public static function getFromCache(CacheItemPoolInterface $cache, string $cacheKey, callable $cacheLoaderCallback) { // try to get value from cache $cacheItem = $cache->getItem($cacheKey); // populate cache if cache item was not found if (!$cacheItem->isHit()) { // create cache item $newCacheItem = new BasicCacheItem($cacheKey, $cacheLoaderCallback()); // save new cache item $cache->save($newCacheItem); // return value from cache item return $newCacheItem->get(); } // return value from cache return $cacheItem->get(); }
/** * @return SysStatusType */ public function getWebApiVersion() { /** * @var $apiVersion SysStatusType */ static $apiVersion = null; if (is_null($apiVersion)) { $cacheItem = $this->cache->getItem(__CLASS__ . '\\' . __METHOD__); if (!$cacheItem->isHit()) { $session = $this->client->getSession(); $countryId = $session->country->id; $req = new DoQueryAllSysStatusRequest(); $req->setCountryId($countryId)->setWebapiKey($session->credentials->webapiKey); $ret = $this->soapClient->doQueryAllSysStatus($req); foreach ($ret->getSysCountryStatus()->getItem() as $i => $sysStatus) { if ($sysStatus->getCountryId() == $countryId) { $apiVersion = $sysStatus; break; } } $cacheItem->set($apiVersion, Period::SECONDS_PER_DAY); $this->cache->save($cacheItem); } else { $apiVersion = $cacheItem->get(); } } return $apiVersion; }
/** * @return $this */ public function unlock() { if ($this->isLocked()) { $this->cache->deleteItems([$this->getKey()]); } return $this; }
/** * Load a localization for the current language from a directory. * * @param string $dir * Directory path. * @param bool $extend * Whether to extend the existing localization object * (true) or replace it (false). * @return bool True if language file found, false otherwise. */ public static function loadFrom($dir, $extend = true) { $file = $dir . '/' . self::$language . '.'; if (isset(self::$cache)) { $cached = self::$cache->getItem($file); if ($cached->isHit()) { $value = $cached->get(); if (is_array($value)) { $localization = new Locale($value); self::load($localization, $extend); return true; } else { self::$cache->deleteItems(array($file)); } } } if (file_exists($file . 'pot')) { return true; } elseif (file_exists($file . 'mo')) { $localization = Locale::readMo($file . 'mo'); } elseif (file_exists($file . 'po')) { $localization = Locale::readPo($file . 'po'); } else { return false; } if (isset(self::$cache)) { // self::$cache->set($file, $localization->getMessages(), 3600); $item = self::$cache->getItem($file); $item->set($localization->getMessages()); $item->expiresAfter(3600); self::$cache->save($item); } self::load($localization, $extend); return true; }
protected function store($cacheKey, $data, $ttl) { if ($this->enableCache) { $item = $this->cache->getItem($cacheKey)->set($data)->expiresAfter($ttl); $this->cache->save($item); } }
public function getMetadata(string $entityClassName) : Entity { if (array_key_exists($entityClassName, $this->metadata)) { return $this->metadata[$entityClassName]; } $cacheKey = sprintf('simplefm.metadata.%s', md5($entityClassName)); if ($this->cache->hasItem($cacheKey)) { return $this->metadata[$entityClassName] = $this->cache->getItem($cacheKey)->get(); } $xmlPath = sprintf('%s/%s', $this->xmlFolder, $this->buildFilename($entityClassName)); if (!file_exists($xmlPath)) { throw InvalidFileException::fromNonExistentFile($xmlPath, $entityClassName); } $entityMetadata = $this->buildMetadata($xmlPath); $this->cache->save(new CacheItem($cacheKey, true, $entityMetadata)); return $this->metadata[$entityClassName] = $entityMetadata; }
/** * {@inheritdoc} */ public function getRouteCollection() { $key = 'route_collection'; if (null === $this->collection) { if ($this->cache->hasItem($key)) { $collection = $this->cache->getItem($key)->get(); if ($collection !== null) { $this->collection = $collection; return $this->collection; } } $this->collection = parent::getRouteCollection(); $item = $this->cache->getItem($key); $item->set($this->collection)->expiresAfter(self::CACHE_LIFETIME); } return $this->collection; }
/** * Store data. * * @param string $gatewayId The gateway ID. * @param string $hash The data hash. * @param string $data The data to be stored. * * @return void * * @since 1.0 */ public function put($gatewayId, $hash, $data) { $container = new GenericDataContainer($data); $key = $this->createKey($gatewayId, $hash); $item = $this->cache->getItem($key); $item->set($container); $this->cache->save($item); }
/** * {@inheritdoc} */ public function save($key, CacheEntry $data) { if ($this->lastItem && $this->lastItem->getKey() == $key) { $item = $this->lastItem; } else { $item = $this->cachePool->getItem($key); } $this->lastItem = null; $item->set($data); $ttl = $data->getTTL(); if ($ttl === 0) { // No expiration $item->expiresAfter(null); } else { $item->expiresAfter($ttl); } return $this->cachePool->save($item); }
/** * @return string */ protected function getContent() { $cache_key = sprintf('JWKFactory-Content-%s', hash('sha512', $this->url)); if (null !== $this->cache) { $item = $this->cache->getItem($cache_key); if (!$item->isHit()) { $content = $this->downloadContent(); $item->set($content); if (0 !== $this->ttl) { $item->expiresAfter($this->ttl); } $this->cache->save($item); return $content; } else { return $item->get(); } } return $this->downloadContent(); }
/** * @param Request $request * * @return \Psr\Cache\CacheItemInterface */ private function getCacheItem(Request $request) { $key = $this->createCacheKey($request); if ($this->cache instanceof TaggablePoolInterface) { $item = $this->cache->getItem($key, ['routing']); } else { $item = $this->cache->getItem($key); } return $item; }
/** * @param string $secret * @param int $code * @return bool */ public function authenticate($secret, $code) { $correct = false; for ($i = -1; $i <= 1; $i++) { if ($this->calculateCode($secret) == $code) { $correct = true; break; } } // If they're not using a cache to prevent people being able to use the same code twice or if they were wrong anyway... if (!isset($this->cachePool) || $correct == false) { return $correct; } // If we're here then we must be using a cache, and we must be right // We generate the key as securely as possible, then salt it using something that will always be replicatable. // We're doing this hashing for de-duplication (aka, we want to know if it exists), but as we're also possibly // securing the secret somewhere, we want to try and have as secure as possible // // If someone has any better suggestions on how to achieve this, please send in a PR! :P $key = crypt($secret . "|" . $code, md5($code)); // If it existed, then we want this function to return false if ($this->cachePool->hasItem($key)) { return false; } // If it didn't, then we want this function to add it to the cache // In PSR-6 getItem will always contain an CacheItemInterface and that seems to be the only way to add stuff // to the cachePool $item = $this->cachePool->getItem($key); // It's a quick expiry thing, 30 seconds is more than long enough $item->expiresAfter(new \DateInterval("PT30S")); // We don't care about the value at all, it's just something that's needed to use the caching interface $item->set(true); $this->cachePool->save($item); return true; }