/** * {@inheritdoc} */ public function save() { $item = $this->pool->getItem($this->key); $item->set($this->getForStorage()); $item->expiresAfter($this->expire); $this->pool->save($item); }
/** * @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); }
/** * {@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; }); }
public function save($name, $contents) { $resolvedTemplate = $this->parseTemplateNamespace($name); $key = $resolvedTemplate['namespace'] . '::' . $resolvedTemplate['template']; $cacheItem = $this->cacheItemPool->getItem($key); $cacheItem->set($contents); return $this->cacheItemPool->save($cacheItem); }
public function set($key, $value, $ttl = 0) { $item = $this->pool->getItem($key); $item->set($value); if ($ttl > 0) { $item->expiresAfter($ttl); } $this->pool->save($item); }
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; }
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(); }
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; }); }
/** {@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; }
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; }
/** * 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); } }
/** * @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; }
/** * Persists a cache item immediately. * * @param CacheItemInterface $item * The cache item to save. * * @return bool * True if the item was successfully persisted. False if there was an error. */ public function save(CacheItemInterface $item) { if (!$item->isHit()) { return false; } return $this->local->save($item) && $this->remote->save($item); }
/** * After the routing, make sure to store the result in cache. * * @param GetResponseEvent $event */ public function onAfterRouting(GetResponseEvent $event) { $request = $event->getRequest(); if (!$request->attributes->has('_controller')) { // routing has not taken place return; } if ($request->attributes->has('_cache_hit')) { $request->attributes->remove('_cache_hit'); // object is in cache already return; } // Save to the cache $item = $this->getCacheItem($request); $item->set($request->attributes->all()); $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; }
/** * 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(CacheItemInterface $item) { if (!$item instanceof Item) { throw new InvalidArgumentException('MatthiasMullie\\Scrapbook\\Taggable\\Pool can only save MatthiasMullie\\Scrapbook\\Taggable\\Item objects'); } // unwrap Taggable\Item & save it to original Pool return $this->pool->save($item->getOriginal()); }
/** * {@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); }
/** * {@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; }); }
/** * Cache a value to the specified key * * @param string|\Psr\Cache\CacheItemInterface $value Value name * @param mixed $data Value * @param AbstractModule $mod Calling module */ public function saveI($value, $data, AbstractModule $mod = null) { $this->checkInit(); $item = $value; if (!$value instanceof CacheItemInterface) { $item = new \Stash\Item(); $item->setKey($this->getKeyName($value, $mod)); } $item->set($data); $this->cache->save($item); }
/** * Fetches all the settings * * @return array */ private function getSettings() { $item = $this->cache->getItem('settings'); if ($item->isHit()) { return $item->get(); } $settings = $this->getAllSettingsFromDatabase(); $item->set($settings); $this->cache->save($item); return $settings; }
/** * @param string $className * @param RequestParser $parser * * @return \Mcustiel\SimpleRequest\RequestParser|mixed */ private function generateRequestParserObject($className, RequestParser $parser) { $cacheKey = str_replace('\\', '', $className . get_class($parser)); $cacheItem = $this->cache->getItem($cacheKey); $return = $cacheItem->get(); if ($return === null) { $return = $this->parserGenerator->populateRequestParser($className, $parser, $this); $cacheItem->set($return); $this->cache->save($cacheItem); } return $return; }
/** * {@inheritdoc} */ public function save(CacheItemInterface $item) { $parts = $this->explodeKey($item->getKey()); $parentKey = ''; foreach ($parts as $part) { $parentKey .= $part; $parent = $this->cache->getItem($parentKey); $parent->set(null); $this->cache->save($parent); } return $this->cache->save($item); }
/** * Fetches all the needed data and caches it in our statistics array * * @param int $startDate * @param int $endDate * @return array */ private function getData($startDate, $endDate) { $dateRange = $startDate . '-' . $endDate; $item = $this->cache->getItem('analytics-' . $dateRange); if ($item->isHit()) { return $item->get(); } $data = array('metrics' => $this->getMetrics($startDate, $endDate), 'visitGraphData' => $this->collectVisitGraphData($startDate, $endDate), 'pageViews' => $this->collectMostVisitedPagesData($startDate, $endDate), 'sourceGraphData' => $this->collectSourceGraphData($startDate, $endDate)); $item->set($data); $this->cache->save($item); return $data; }
/** * @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; }