/** * @param mixed$key * @return bool */ public function has($key) { if (!$this->isKey($key)) { $key = $this->createKey($key); } return $this->cache->hasItem($key); }
public function provide($container) { $instance = $this->instanceManager->getInstanceFromRequest(); $pages = []; try { $container = $this->navigationManager->findContainerByNameAndInstance($container, $instance); } catch (ContainerNotFoundException $e) { return []; } $key = hash('sha256', serialize($container)); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } foreach ($container->getPages() as $page) { $addPage = $this->buildPage($page); $hasUri = isset($addPage['uri']); $hasMvc = isset($addPage['action']) || isset($addPage['controller']) || isset($addPage['route']); $hasProvider = isset($addPage['provider']); if ($hasUri || $hasMvc || $hasProvider) { $pages[] = $addPage; } } $this->storage->setItem($key, $pages); return $pages; }
/** * @param null|array $arguments Must be serializable. * @return mixed */ public function getValue($arguments = null) { $cacheKey = Cache::makeCacheKey($this->name, $arguments); if (!$this->storage->hasItem($cacheKey)) { $this->warm($arguments); } return unserialize($this->storage->getItem($cacheKey)); }
/** * Set key with value * If item already exists, it is replaced * * @access public * @param string $key * @param string $value */ public function setItem($key, $value) { if ($this->cacheAdapter->hasItem($key)) { $methodName = "replaceItem"; } else { $methodName = "setItem"; } $this->cacheAdapter->{$methodName}($key, $value); }
protected function getResult() { if ($this->cache->hasItem('result')) { return $this->cache->getItem('result'); } // The bellow code do not work with zend // $this->cache->setItem('result', $this->calculation); // $result = $this->cache->getItem('result'); $calculation = $this->calculation; $result = $calculation(); $this->cache->setItem('result', $result); return $result; }
/** * Check if a page is saved in the cache and return contents. * Return null when no item is found. * * @param MvcEvent $e Mvc Event * * @return mixed */ public function load(MvcEvent $e) { $id = $this->createId($e->getRequest()); if (!$this->cacheStorage->hasItem($id)) { return null; } $event = new CacheEvent(CacheEvent::EVENT_LOAD, $this); $event->setCacheKey($id); $this->getEventManager()->trigger($event); if ($event->getAbort()) { return null; } return $this->cacheStorage->getItem($id); }
public function getUnrevisedRevisions(TaxonomyTermInterface $term) { $key = hash('sha256', serialize($term)); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $entities = $this->getEntities($term); $collection = new ArrayCollection(); $this->iterEntities($entities, $collection, 'isRevised'); $iterator = $collection->getIterator(); $iterator->ksort(); $collection = new ArrayCollection(iterator_to_array($iterator)); $this->storage->setItem($key, $collection); return $collection; }
public function render($limit = 25) { $user = $this->userManager->getUserFromAuthenticator(); $key = hash('sha256', serialize($user)); $output = ''; if ($this->storage->hasItem($key)) { //return $this->storage->getItem($key); } if ($user) { $notifications = $this->notificationManager->findNotificationsBySubscriber($user, $limit); $output = $this->renderer->render($this->template, ['notifications' => $notifications]); $this->storage->setItem($key, $output); } return $output; }
public function testTaggable() { if (!$this->_storage instanceof TaggableInterface) { $this->markTestSkipped("Storage doesn't implement TaggableInterface"); } // store 3 items and register the current default namespace $this->assertSame([], $this->_storage->setItems(['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'])); $this->assertTrue($this->_storage->setTags('key1', ['tag1a', 'tag1b'])); $this->assertTrue($this->_storage->setTags('key2', ['tag2a', 'tag2b'])); $this->assertTrue($this->_storage->setTags('key3', ['tag3a', 'tag3b'])); $this->assertFalse($this->_storage->setTags('missing', ['tag'])); // return tags $tags = $this->_storage->getTags('key1'); $this->assertInternalType('array', $tags); sort($tags); $this->assertSame(['tag1a', 'tag1b'], $tags); // this should remove nothing $this->assertTrue($this->_storage->clearByTags(['tag1a', 'tag2a'])); $this->assertTrue($this->_storage->hasItem('key1')); $this->assertTrue($this->_storage->hasItem('key2')); $this->assertTrue($this->_storage->hasItem('key3')); // this should remove key1 and key2 $this->assertTrue($this->_storage->clearByTags(['tag1a', 'tag2b'], true)); $this->assertFalse($this->_storage->hasItem('key1')); $this->assertFalse($this->_storage->hasItem('key2')); $this->assertTrue($this->_storage->hasItem('key3')); // this should remove key3 $this->assertTrue($this->_storage->clearByTags(['tag3a', 'tag3b'], true)); $this->assertFalse($this->_storage->hasItem('key1')); $this->assertFalse($this->_storage->hasItem('key2')); $this->assertFalse($this->_storage->hasItem('key3')); }
public function testTagable() { if (!$this->_storage instanceof TaggableInterface) { $this->markTestSkipped("Storage doesn't implement TaggableInterface"); } $this->assertSame(array(), $this->_storage->setItems(array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'))); $this->assertTrue($this->_storage->setTags('key1', array('tag1a', 'tag1b'))); $this->assertTrue($this->_storage->setTags('key2', array('tag2a', 'tag2b'))); $this->assertTrue($this->_storage->setTags('key3', array('tag3a', 'tag3b'))); $this->assertFalse($this->_storage->setTags('missing', array('tag'))); // return tags $tags = $this->_storage->getTags('key1'); $this->assertInternalType('array', $tags); sort($tags); $this->assertSame(array('tag1a', 'tag1b'), $tags); // this should remove nothing $this->assertTrue($this->_storage->clearByTags(array('tag1a', 'tag2a'))); $this->assertTrue($this->_storage->hasItem('key1')); $this->assertTrue($this->_storage->hasItem('key2')); $this->assertTrue($this->_storage->hasItem('key3')); // this should remove key1 and key2 $this->assertTrue($this->_storage->clearByTags(array('tag1a', 'tag2b'), true)); $this->assertFalse($this->_storage->hasItem('key1')); $this->assertFalse($this->_storage->hasItem('key2')); $this->assertTrue($this->_storage->hasItem('key3')); // this should remove key3 $this->assertTrue($this->_storage->clearByTags(array('tag3a', 'tag3b'), true)); $this->assertFalse($this->_storage->hasItem('key1')); $this->assertFalse($this->_storage->hasItem('key2')); $this->assertFalse($this->_storage->hasItem('key3')); }
public function findSourceByAlias($alias, $useCache = false) { if (!is_string($alias)) { throw new Exception\InvalidArgumentException(sprintf('Expected alias to be string but got "%s"', gettype($alias))); } $key = 'source:by:alias:' . $alias; if ($useCache && $this->storage->hasItem($key)) { // The item is null so it didn't get found. $item = $this->storage->getItem($key); if ($item === self::CACHE_NONEXISTENT) { throw new Exception\AliasNotFoundException(sprintf('Alias `%s` not found.', $alias)); } return $item; } /* @var $entity Entity\AliasInterface */ $criteria = ['alias' => $alias]; $order = ['timestamp' => 'DESC']; $results = $this->getAliasRepository()->findBy($criteria, $order); $entity = current($results); if (!is_object($entity)) { $this->storage->setItem($key, self::CACHE_NONEXISTENT); throw new Exception\AliasNotFoundException(sprintf('Alias `%s` not found.', $alias)); } $source = $entity->getSource(); if ($useCache) { $this->storage->setItem($key, $source); } return $source; }
/** * Get a plugin by instance Id * * @param integer $pluginInstanceId Plugin Instance Id * * @return array|mixed * @throws \Rcm\Exception\PluginInstanceNotFoundException * @deprecated */ public function getPluginByInstanceId($pluginInstanceId) { $cacheId = 'rcmPluginInstance_' . $pluginInstanceId; if ($this->cache->hasItem($cacheId)) { $return = $this->cache->getItem($cacheId); $return['fromCache'] = true; return $return; } $pluginInstance = $this->getInstanceEntity($pluginInstanceId); if (empty($pluginInstance)) { throw new PluginInstanceNotFoundException('Plugin for instance id ' . $pluginInstanceId . ' not found.'); } $instanceConfig = $this->getInstanceConfigFromEntity($pluginInstance); $return = $this->getPluginViewData($pluginInstance->getPlugin(), $pluginInstanceId, $instanceConfig); if ($pluginInstance->isSiteWide()) { $return['siteWide'] = true; $displayName = $pluginInstance->getDisplayName(); if (!empty($displayName)) { $return['displayName'] = $displayName; } } $return['md5'] = $pluginInstance->getMd5(); if ($return['canCache']) { $this->cache->setItem($cacheId, $return); } return $return; }
public function testReplaceItemsReturnsFailedKeys() { $this->assertTrue($this->_storage->setItem('key1', 'value1')); $failedKeys = $this->_storage->replaceItems(array('key1' => 'XYZ', 'key2' => 'value2')); $this->assertSame(array('key2'), $failedKeys); $this->assertSame('XYZ', $this->_storage->getItem('key1')); $this->assertFalse($this->_storage->hasItem('key2')); }
/** * * @param string $filename * @param \Soluble\Media\BoxDimension $box * @param string $format * @param int $quality * @throws \Soluble\Media\Converter\Exception * @throws \Exception */ public function getThumbnail($filename, BoxDimension $box, $format = null, $quality = null) { $width = $box->getWidth(); $height = $box->getHeight(); if ($quality === null) { $quality = $this->default_quality; } $cache_key = md5("{$filename}/{$width}/{$height}/{$quality}/{$format}"); if ($this->cacheEnabled && $this->cacheStorage->hasItem($cache_key)) { $cacheMd = $this->cacheStorage->getMetadata($cache_key); if ($cacheMd['mtime'] < filemtime($filename)) { // invalid cache $binaryContent = $this->generateThumbnail($filename, $box, $format, $quality); $this->cacheStorage->setItem($cache_key, $binaryContent); } else { $binaryContent = $this->cacheStorage->getItem($cache_key); } } else { $binaryContent = $this->generateThumbnail($filename, $box, $format, $quality); $this->cacheStorage->setItem($cache_key, $binaryContent); } switch ($format) { case 'jpg': $content_type = 'image/jpeg'; break; case 'png': $content_type = 'image/png'; break; case 'gif': $content_type = 'image/gif'; break; default: throw new \Exception("Unsupported format '{$format}'"); } header("Content-type: {$content_type}", true); header("Accept-Ranges: bytes", true); header("Cache-control: max-age=2592000, public", true); header("Content-Disposition: inline; filename=\"{$filename}\";", true); header('Last-Modified: ' . gmdate('D, d M Y H:i:s', filemtime($filename)) . ' GMT', true); header('Expires: ' . gmdate('D, d M Y H:i:s', strtotime('+1 years')) . ' GMT', true); //header('Content-Disposition: attachment; filename="downloaded.pdf"'); header('Pragma: cache', true); echo $binaryContent; die; }
/** * @param array $options * @return array */ public function provide(array $options) { $this->options = ArrayUtils::merge($this->defaultOptions, $options); $key = hash('sha256', serialize($this->options)); $this->options['types'] = ArrayUtils::merge($this->options['types'], $this->options['hidden']); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $term = $this->getTerm(); if ($this->getObjectManager()->isOpen()) { $this->getObjectManager()->refresh($term); } $terms = $term->findChildrenByTaxonomyNames($this->options['types']); $pages = $this->iterTerms($terms, $this->options['max_depth']); $this->term = null; $this->storage->setItem($key, $pages); return $pages; }
/** * @test */ public function getCachedItemGetsCachedItemWhenCacheIsReady() { $this->storage->hasItem('foo')->willReturn(true); $this->storage->getItem('foo')->willReturn('bar'); $return = $this->cache->getCachedItem('foo', function () { return 'baz'; }); $this->assertEquals('bar', $return); }
/** * Read from a string and create an array * * @param string $string String * * @return array|bool */ public function fromString($string) { $key = $this->generateKey($string); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $config = $this->reader->fromString($string); $this->storage->setItem($key, $config); return $config; }
/** * Returns the ClassMetadata descriptor for a class. * * The class name must be the fully-qualified class name without a leading backslash * (as it is returned by get_class($obj)). * * @param string $className * @return ClassMetadata */ public function getClassMetadata($className) { if (!$this->cache->hasItem('Eoko\\ODM\\DocumentManager\\Cache\\' . $className)) { $classMetadata = new ClassMetadata($className, $this->metadataDriver); $this->cache->setItem('Eoko\\ODM\\DocumentManager\\Cache\\' . $className, $classMetadata); } else { $classMetadata = $this->cache->getItem('Eoko\\ODM\\DocumentManager\\Cache\\' . $className); } return $classMetadata; }
/** * @param \Zend\Cache\Storage\StorageInterface $cache */ public function it_should_save_parsed_annotations_in_cache($cache) { // TODO: fix me! // $cache->hasItem will return ProphecyObject which will always return true in the if. // Therefore the conditions will be incorrect. return; $cache->hasItem('cache-key')->willReturn(false); $this->mockConfiguration($cache); $this->getFormSpecification('stdClass'); $cache->setItem('cache-key', Argument::type('ArrayObject'))->shouldHaveBeenCalled(); }
public function normalize($object) { if (!is_object($object)) { throw new Exception\InvalidArgumentException(sprintf('Expected object but got %s.', gettype($object))); } $key = hash('sha256', serialize($object)); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } foreach ($this->adapters as $class => $adapterClass) { if ($object instanceof $class) { /* @var $adapterClass Adapter\AdapterInterface */ $adapter = $this->pluginManager->get($adapterClass); $normalized = $adapter->normalize($object); $this->storage->setItem($key, $normalized); return $normalized; } } throw new Exception\NoSuitableAdapterFoundException($object); }
/** * Confirms if the cache contains specified cache item. * * Note: This method MAY avoid retrieving the cached value for performance reasons. * This could result in a race condition with CacheItemInterface::get(). To avoid * such situation use CacheItemInterface::isHit() instead. * * @param string $key * The key for which to check existence. * * @throws InvalidArgumentException * If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException * MUST be thrown. * * @return bool * True if item exists in the cache, false otherwise. */ public function hasItem($key) { $this->validateKey($key); try { $hasItem = $this->storage->hasItem($key); } catch (Exception\InvalidArgumentException $e) { throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e); } catch (Exception\ExceptionInterface $e) { throw new CacheException($e->getMessage(), $e->getCode(), $e); } return $hasItem; }
public function call(Call $apiCall) { $uri = $this->makeUri($apiCall); if ($this->cacheStorage) { $cacheId = 'pimcore_rest_api_' . md5($uri); if ($this->cacheStorage->hasItem($cacheId)) { return $this->cacheStorage->getItem($cacheId); } } $this->httpClient->setUri($uri); try { $response = $this->httpClient->send(); $this->failIfRequestFailed($response); $json = $this->getDecodedJsonOrFail($response); $responseObject = $this->mapJsonToResponseObject($apiCall, $json); if ($this->cacheStorage) { $this->cacheStorage->setItem($cacheId, $responseObject); } return $responseObject; } catch (\Exception $ex) { throw new Exception($ex->getMessage()); } }
/** * @param $wikiText * @return string|null */ public function preview($wikiText) { $data = ''; $key = 'preview_' . sha1($wikiText); if (!$this->cache) { $data = $this->getPreview($wikiText); } elseif ($this->cache->hasItem($key)) { $data = $this->cache->getItem($key); } else { $data = $this->getPreview($wikiText); $this->cache->setItem($key, $data); } return $data; }
/** * @see \Markdown\Service\RenderServiceInterface::render() */ public function render($input) { $key = hash('sha512', $input); if ($this->storage->hasItem($key)) { return $this->storage->getItem($key); } $rendered = null; $this->dnode->connect($this->options->getHost(), $this->options->getPort(), function ($remote, $connection) use($input, &$rendered) { $remote->render($input, function ($output, $exception = null, $error = null) use(&$rendered, $connection) { if ($exception !== null) { $connection->end(); throw new Exception\RuntimeException(sprintf('Bridge threw exception "%s" with message "%s".', $exception, $error)); } $rendered = $output; $connection->end(); }); }); $this->loop->run(); if ($rendered === null) { throw new Exception\RuntimeException(sprintf('Broken pipe')); } $this->storage->setItem($key, $rendered); return $rendered; }
/** * Triggered on sendAction.pre. * * @param EventInterface $event Triggered event * * @throws \Zend\Cache\Exception\ExceptionInterface * * @return void|\PAMI\Message\Response\ResponseMessage */ public function onSendPre(EventInterface $event) { /* @var OutgoingMessage $action */ $action = $event->getParam('action'); /* @var Client $client */ $client = $event->getTarget(); if (!$this->isActionCacheable($action)) { return; } $cacheId = $this->generateCacheId($action, $client->getHost()); if ($this->cache->hasItem($cacheId)) { // If cached item is an instance of \PAMI\Message\Response\ResponseMessage, the execution will be stopped return $this->cache->getItem($cacheId); } }
/** * Load an entry belonging to the given key from our cache (if any) * * @param string $key key to look for in the cache (should match /^[a-z0-9_+-]*$/Di) * @param int $mtime unix timestamp to compare the cache entry with (the entry will be ignored if older than $mtime) * @return mixed entry from cache or false if its key isn't found in cache or the entry is too old */ protected static function loadFromCache($key, $mtime = 0) { try { self::validateCache(); } catch (\Exception $exception) { // Fake an exception from getItem, so the cache's own EventManager can determine what to do with it $result = false; return self::triggerCacheException('getItem', array('key' => &$key), $result, $exception); } if (!self::$cache->hasItem($key)) { return false; } $meta = self::$cache->getMetadata($key); if (!array_key_exists('mtime', $meta) || $meta['mtime'] < $mtime) { return false; } return self::$cache->getItem($key); }
/** * Getter for virtual properties * * @param string $item * @param array $arguments * @return \EasyRdf\Graph|\EasyRdf\Sparql\Result|mixed|null * @throws \Exception */ public function get($item, array $arguments = []) { if (!$this->has($item)) { $tpl = "Property '%s' does not exist"; $msg = sprintf($tpl, $item); throw new \Exception($msg); } $data = null; $key = sprintf('item_%s__args_%s', $item, sha1(implode('-', $arguments))); if (null == $this->cache) { $data = $this->query($item, $arguments); } elseif (!$this->cache->hasItem($key)) { $data = $this->query($item, $arguments); $this->cache->setItem($key, serialize($data)); } else { $data = unserialize($this->cache->getItem($key)); } return $data; }
/** * Triggered after controller and view calls * * @param FilterResponseEvent $event */ public function onKernelResponse(FilterResponseEvent $event) { $request = $event->getRequest(); $response = $event->getResponse(); if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST && $request->isMethodSafe()) { $key = $this->getKeyFromRequest($request); $response->setLastModified(new \DateTime()); // If no cache request header exists - do nothing if ($request->isNoCache() || !$response->isSuccessful()) { return; //TODO redirects cache } // If response does not exists - put it to cache if (!$this->storage->hasItem($key)) { $response->setTtl($this->storage->getOptions()->getTtl()); $data = ['content' => $response->getContent(), 'status' => $response->getStatusCode(), 'headers' => $response->headers->all()]; $this->storage->addItem($key, $data); if ($this->storage instanceof TaggableInterface) { $this->storage->setTags($key, $tags); } } } }
/** * @param string $url * @param array $options * * @return array */ protected function makeRequest($url, array $options = []) { if ($this->client === null) { $this->client = new HttpClient(); $adapter = new \Zend\Http\Client\Adapter\Curl(); $adapter->setCurlOption(CURLOPT_SSL_VERIFYPEER, false); $this->client->setAdapter($adapter); } $key = $this->getRequestKey($url, $options); if ($this->cache->hasItem($key) === true) { return $this->cache->getItem($key); // $options = array_replace_recursive($options, [ // 'headers' => [ // 'If-Modified-Since' => $this->cache->getMetadata($key)['mtime'], // ], // ]); } $options = array_replace_recursive($options, ['headers' => ['Accept' => 'application/json', 'User-Agent' => $this->getUserAgent()], 'query' => ['apikey' => $this->apiKey, 'locale' => $this->region->getLocale()]]); $request = new Request(); $request->setUri($url); foreach ($options['query'] as $param => $value) { $request->getQuery()->{$param} = $value; } $request->getHeaders()->addHeaders($options['headers']); $request->setMethod(Request::METHOD_GET); try { $response = $this->client->dispatch($request); } catch (ClientException $exception) { if ($exception->getCode() === 404) { return null; } throw new BattleNetException($exception->getResponse()->json()['detail'], $exception->getCode()); } //return json_decode($response->getBody(), true); return $this->handleSuccessfulResponse($response, $key); }
/** * Check if lock is locked * * @param string $name name of lock * @return bool */ public function isLocked($name) { return $this->cache->hasItem($name); }