/**
  * {@inheritdoc}
  */
 public function load()
 {
     $contents = $this->storage->getItem($this->key);
     if ($contents !== null) {
         $this->setFromStorage($contents);
     }
 }
示例#2
0
 /**
  * {@inheritdoc}
  *
  * @see \Cerberus\CerberusInterface::getStatus()
  */
 public function getStatus($serviceName = null)
 {
     $this->setNamespace($serviceName);
     $success = false;
     $failures = (int) $this->storage->getItem('failures', $success);
     if (!$success) {
         $failures = 0;
         $this->storage->setItem('failures', $failures);
     }
     // Still has failures left
     if ($failures < $this->maxFailures) {
         return CerberusInterface::CLOSED;
     }
     $success = false;
     $lastAttempt = $this->storage->getItem('last_attempt', $success);
     // This is the first attempt after a failure, open the circuit
     if (!$success) {
         $lastAttempt = time();
         $this->storage->setItem('last_attempt', $lastAttempt);
         return CerberusInterface::OPEN;
     }
     // Reached maxFailues but has passed the timeout limit, so we can try again
     // We update the lastAttempt so only one call passes through
     if (time() - $lastAttempt >= $this->timeout) {
         $lastAttempt = time();
         $this->storage->setItem('last_attempt', $lastAttempt);
         return CerberusInterface::HALF_OPEN;
     }
     return CerberusInterface::OPEN;
 }
示例#3
0
 /**
  * @param mixed $key
  * @return mixed
  */
 public function get($key)
 {
     if (!$this->isKey($key)) {
         $key = $this->createKey($key);
     }
     return unserialize($this->cache->getItem($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;
 }
示例#5
0
 /**
  * @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));
 }
示例#6
0
 /**
  * @since 1.1
  *
  * {@inheritDoc}
  */
 public function fetch($id)
 {
     if ($this->contains($id)) {
         $this->cacheHits++;
         return $this->cache->getItem($id);
     }
     $this->cacheMisses++;
     return false;
 }
 /**
  * Returns a Cache Item representing the specified key.
  *
  * This method must always return a CacheItemInterface object, even in case of
  * a cache miss. It MUST NOT return null.
  *
  * @param string $key
  *   The key for which to return the corresponding Cache Item.
  *
  * @throws InvalidArgumentException
  *   If the $key string is not a legal value a \Psr\Cache\InvalidArgumentException
  *   MUST be thrown.
  *
  * @return CacheItemInterface
  *   The corresponding Cache Item.
  */
 public function getItem($key)
 {
     $this->validateKey($key);
     try {
         $cacheItem = $this->storage->getItem($key, $success);
     } 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 new CacheItem($key, $success ? $cacheItem : null, $success);
 }
示例#8
0
 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;
 }
示例#9
0
 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;
 }
示例#10
0
 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;
 }
示例#11
0
 /**
  * Returns the items for a given page.
  *
  * @param integer $pageNumber
  * @return mixed
  */
 public function getItemsByPage($pageNumber)
 {
     $pageNumber = $this->normalizePageNumber($pageNumber);
     if ($this->cacheEnabled()) {
         $data = self::$cache->getItem($this->_getCacheId($pageNumber));
         if ($data) {
             return $data;
         }
     }
     $offset = ($pageNumber - 1) * $this->getItemCountPerPage();
     $items = $this->adapter->getItems($offset, $this->getItemCountPerPage());
     $filter = $this->getFilter();
     if ($filter !== null) {
         $items = $filter->filter($items);
     }
     if (!$items instanceof Traversable) {
         $items = new ArrayIterator($items);
     }
     if ($this->cacheEnabled()) {
         $cacheId = $this->_getCacheId($pageNumber);
         self::$cache->setItem($cacheId, $items);
         self::$cache->setTags($cacheId, array($this->_getCacheInternalId()));
     }
     return $items;
 }
示例#12
0
 public function testDecrementItemsReturnsEmptyArrayIfNonWritable()
 {
     $this->_storage->setItem('key', 10);
     $this->_options->setWritable(false);
     $this->assertSame(array(), $this->_storage->decrementItems(array('key' => 5)));
     $this->assertEquals(10, $this->_storage->getItem('key'));
 }
示例#13
0
 /**
  * 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;
 }
示例#14
0
 /**
  * @param $cacheKey
  * @param Closure $closure
  * @param null $lifetime
  * @return mixed
  */
 public function getItem($cacheKey, Closure $closure, $lifetime = null)
 {
     // we have to check if we enable the caching in config
     if (!$this->isCachingEnable()) {
         return $closure();
     }
     $data = $this->cachingService->getItem($cacheKey);
     if (!$data) {
         $data = $closure();
         if ($lifetime > 0) {
             $this->cachingService->setOptions($this->cachingService->getOptions()->setTtl($lifetime));
         }
         $this->cachingService->setItem($cacheKey, $data);
     }
     return $data;
 }
示例#15
0
 /**
  * Call widget
  *
  * @param string $position
  * @param integer $pageId
  * @param integer $userRole
  * @param array $widgetInfo
  * @param boolean $useLayout
  * @throws \Page\Exception\PageException
  * @return string|boolean
  */
 protected function callWidget($position, $pageId, $userRole, array $widgetInfo, $useLayout = true)
 {
     // don't call any widgets
     if (true === self::$widgetRedirected) {
         return false;
     }
     // check a widget visibility
     if ($userRole != AclBaseModel::DEFAULT_ROLE_ADMIN) {
         if (!empty($widgetInfo['hidden']) && in_array($userRole, $widgetInfo['hidden'])) {
             return false;
         }
     }
     // call the widget
     $widget = $this->getView()->{$widgetInfo['widget_name']}();
     // check the widget
     if (!$widget instanceof IPageWidget) {
         throw new PageException(sprintf($widgetInfo['widget_name'] . ' must be an object implementing IPageWidget'));
     }
     // init the widget
     $widget->setPageId($pageId)->setWidgetPosition($position)->setWidgetConnectionId($widgetInfo['widget_connection_id']);
     $widgetCacheName = null;
     if ((int) $widgetInfo['widget_cache_ttl']) {
         // generate a cache name
         $widgetCacheName = CacheUtility::getCacheName($widgetInfo['widget_name'], [$widgetInfo['widget_connection_id']]);
         // check the widget data in a cache
         if (null !== ($cachedWidgetData = $this->dynamicCache->getItem($widgetCacheName))) {
             // check a local widget lifetime
             if ($cachedWidgetData['widget_expire'] >= time()) {
                 // include widget's css and js files
                 if (false !== $cachedWidgetData['widget_content'] && !$this->request->isXmlHttpRequest()) {
                     $widget->includeJsCssFiles();
                 }
                 return $cachedWidgetData['widget_content'];
             }
             // clear cache
             $this->dynamicCache->removeItem($widgetCacheName);
         }
     }
     if (false !== ($widgetContent = $widget->getContent())) {
         self::$widgetRedirected = $widget->isWidgetRedirected();
         // include widget's css and js files
         if (!$this->request->isXmlHttpRequest()) {
             $widget->includeJsCssFiles();
         }
         // add the widget's layout
         if ($useLayout) {
             if (!empty($widgetInfo['widget_layout'])) {
                 $widgetContent = $this->getView()->partial($this->layoutPath . $widgetInfo['widget_layout'], ['title' => $this->getView()->pageWidgetTitle($widgetInfo), 'content' => $widgetContent]);
             } else {
                 $widgetContent = $this->getView()->partial($this->layoutPath . 'default', ['title' => $this->getView()->pageWidgetTitle($widgetInfo), 'content' => $widgetContent]);
             }
         }
     }
     // cache the widget data
     if ($widgetCacheName) {
         $this->dynamicCache->setItem($widgetCacheName, ['widget_content' => $widgetContent, 'widget_expire' => time() + $widgetInfo['widget_cache_ttl']]);
     }
     return $widgetContent;
 }
示例#16
0
 /**
  * @param \Zend\Cache\Storage\StorageInterface $cache
  */
 public function it_should_load_form_from_cache($cache)
 {
     $cache->hasItem('cache-key')->willReturn(true);
     $cache->getItem('cache-key')->willReturn(array());
     $this->mockConfiguration($cache);
     $result = $cache->getItem('cache-key');
     $this->getFormSpecification('stdClass')->shouldBe($result);
 }
示例#17
0
 /**
  * Retrieve the filesystem path to a view script
  *
  * @param  string $name
  * @param  null|Renderer $renderer
  * @throws \Zend\View\Exception\DomainException
  * @return string
  */
 public function resolve($name, Renderer $renderer = null)
 {
     if (!self::$currentLayoutId) {
         $activeLayouts = LayoutService::getCurrentLayouts();
         self::$currentLayoutId = end($activeLayouts)['name'];
     }
     // generate a cache name
     $cacheName = CacheUtility::getCacheName(self::CACHE_TEMPLATE_PATH, [$name, $renderer, self::$currentLayoutId]);
     // check data in cache
     if (null === ($templatePath = $this->dynamicCacheInstance->getItem($cacheName))) {
         if (false !== ($templatePath = parent::resolve($name, $renderer))) {
             // save data in cache
             $this->dynamicCacheInstance->setItem($cacheName, $templatePath);
         }
     }
     return $templatePath;
 }
 /**
  *
  * @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;
 }
示例#20
0
 /**
  * @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);
 }
示例#21
0
 /**
  * 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;
 }
示例#22
0
 /**
  * Triggered before controller call
  *
  * @param GetResponseEvent $event
  */
 public function onKernelRequest(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     if ($event->getRequestType() === HttpKernelInterface::MASTER_REQUEST && $request->isMethodSafe()) {
         $key = $this->getKeyFromRequest($request);
         // If no cache request header exists - clear cache
         if ($request->isNoCache()) {
             $this->storage->removeItem($key);
         }
         // If response exists in cache - restore it and set back to event
         if ($this->storage->hasItem($key)) {
             $data = $this->storage->getItem($key);
             $response = new Response($data['content'], $data['status'], $data['headers']);
             $response->prepare($request);
             $response->isNotModified($request);
             $event->setResponse($response);
         }
     }
 }
 /**
  * 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;
 }
示例#24
0
 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);
 }
示例#25
0
 /**
  * @return array
  */
 private function getLastMessageSendingData()
 {
     $kpiData = $this->cacheStorage->getItem(static::CS_LAST_MESSAGE_SENDING);
     $kpiType = self::DANGER;
     if (!empty($kpiData)) {
         $kpiData = (int) $kpiData;
         $time = time();
         $timeout = $this->options->getPeriodInMinutes() * 60;
         $kpiType = $time - $timeout > $kpiData ? self::DANGER : self::SUCCESS;
     }
     return [self::LAST_MESSAGE_SENDING => [self::VALUE => $kpiData, self::TYPE => $kpiType]];
 }
示例#26
0
 public function getCachedItem($key, Closure $closure)
 {
     if ($this->storage->hasItem($key)) {
         return $this->storage->getItem($key);
     }
     if ($this->itemIsUnderConstruction($key)) {
         $this->waitForItem($key);
         return $this->storage->getItem($key);
     }
     $this->setDelayedItem($key, $closure);
     return $this->getItem($key);
 }
示例#27
0
 /**
  * Get current key, value or metadata.
  *
  * @return mixed
  */
 public function current()
 {
     if ($this->mode == IteratorInterface::CURRENT_AS_SELF) {
         return $this;
     }
     $key = $this->key();
     if ($this->mode == IteratorInterface::CURRENT_AS_METADATA) {
         return $this->storage->getMetadata($key);
     } elseif ($this->mode == IteratorInterface::CURRENT_AS_VALUE) {
         return $this->storage->getItem($key);
     }
     return $key;
 }
示例#28
0
 /**
  * Load value from swap file.
  *
  * @internal
  * @param \Zend\Memory\Container\Movable $container
  * @param int $id
  */
 public function load(Container\Movable $container, $id)
 {
     $value = $this->cache->getItem($this->managerId . $id);
     // Try to swap other objects if necessary
     // (do not include specified object into check)
     $this->memorySize += strlen($value);
     $this->_swapCheck();
     // Add loaded object to the end of loaded objects list
     $container->setValue($value);
     if ($this->sizes[$id] > $this->minSize) {
         // Add object to the end of "unload candidates list"
         $this->unloadCandidates[$id] = $container;
     }
 }
示例#29
0
 /**
  * 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);
 }
示例#30
0
 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());
     }
 }