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; }
/** * Sets or removes value from cache * * @param string $name * @param string $value * @return void */ public function setValue($name, $value = null) { if ($value === null) { $this->container->removeItem($name); } else { $this->container->setItem($name, $value); } }
/** * @param mixed $key * @param mixed $data * @return bool */ public function set($key, $data) { if (!$this->isKey($key)) { $key = $this->createKey($key); } $data = serialize($data); return $this->cache->setItem($key, $data); }
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; }
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 setDelayedItem($key, Closure $closure) { $this->storage->setItem($this->getDelayedKey($key), self::UNDER_CONSTRUCTION_VALUE); $setReturn = $this->storage->setItem($key, $closure()); $this->storage->removeItem($this->getDelayedKey($key)); return $setReturn; }
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; }
/** * @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; }
/** * 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; }
/** * 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 instanceof CacheItem) { throw new InvalidArgumentException('$item must be an instance of ' . CacheItem::class); } $this->validateKey($item->getKey()); try { $options = false; $expiration = $item->getExpiration(); // @todo I can't see any way to set the TTL on an individual item except by temporarily overwriting the // option on the storage adapter. Not sure if all storage adapters will support this... if ($expiration instanceof DateTime) { $options = $this->storage->getOptions(); $new = clone $options; $interval = $expiration->diff(new DateTime(), true); $new->setTtl($interval->format('%s')); $this->storage->setOptions($new); } $saved = $this->storage->setItem($item->getKey(), $item->get()); if ($options) { $this->storage->setOptions($options); } } 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 $saved; }
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')); }
/** * @return string */ public function sendAction() { $queueSize = $this->options->getQueueSize(); $throttleSize = $this->mailThrottle->getThrottleSize(); if ($queueSize < 1 || 0 === $throttleSize) { $this->logger->err('Can not send anything.'); return ''; } $currentQueueSize = $throttleSize > 0 ? min($queueSize, $throttleSize) : $queueSize; $readyQueue = $this->queueItemRepository->getReadyQueue($currentQueueSize); $this->processQueueToSend($readyQueue); if ($this->hasCacheStorage()) { $this->cacheStorage->setItem(\DmMailer\View\DataProvider\Kpi::CS_LAST_MESSAGE_SENDING, $this->getTime()); } return ''; }
/** * 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; }
/** * 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; }
/** * 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; }
/** * @group 4629 * @return void */ public function testCallCanReturnCachedNullValues() { $callback = new FailableCallback(); $key = $this->_pattern->generateKey($callback, array()); $this->_storage->setItem($key, array(null)); $value = $this->_pattern->call($callback); $this->assertNull($value); }
/** * * @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; }
/** * Helper function for storing cached data. * Data is cached for up to $this->cacheLifetime seconds so that it would be * faster to process e.g. requests where multiple calls to the backend are made. * * @param string $key Cache entry key * @param mixed $entry Entry to be cached * * @return void */ protected function putCachedData($key, $entry) { // Don't write to cache if we don't have a cache! if (null === $this->cache) { return; } $item = ['time' => time(), 'entry' => $entry]; $this->cache->setItem($this->formatCacheKey($key), $item); }
/** * @param string $name name of lock * @param bool $blocking * @return bool */ protected function getLock($name, $blocking) { if ($this->isLocked($name)) { return false; } $options = $this->cache->getOptions(); $oldTTL = 0; if (!empty($options->getTtl())) { $oldTTL = $options->getTtl(); } $options->setTtl($this->expiration); if (!$this->cache->setItem($name, serialize($this->getLockInformation()))) { $options->setTtl($oldTTL); return false; } $this->locks[$name] = $name; return true; }
/** * 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; }
/** * @test */ public function canSetDelayedItemReturnsAdapter() { $this->storage->setItem($this->delayedKey, 'under_construction')->shouldBeCalled(); $this->storage->removeItem($this->delayedKey)->shouldBeCalled(); $this->storage->setItem('foo', 'bar')->willReturn(true); $return = $this->cache->setDelayedItem('foo', function () { return 'bar'; }); $this->assertSame(true, $return); }
/** * Save the page contents to the cache storage. * * @param MvcEvent $e Mvc Event * * @return void */ public function save(MvcEvent $e) { if (!$this->shouldCacheRequest($e)) { return; } $id = $this->createId($e->getRequest()); $item = serialize($e->getResponse()); $this->cacheStorage->setItem($id, $item); $this->getEventManager()->trigger(new CacheEvent(CacheEvent::EVENT_SAVE, $this)); }
/** * 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; }
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); }
public function testSetItemAndSetItemsCallSaveWithTtl() { $ttl = rand(); $provider = $this->getMock('Doctrine\\Common\\Cache\\ArrayCache'); $provider->expects($this->exactly(4))->method('save')->with($this->anything(), $this->anything(), $ttl); $this->storage = new DoctrineCacheStorage($this->options, $provider); $this->options->setTtl($ttl); $this->storage->setItem('key', 'value'); $items = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'); $this->storage->setItems($items); }
/** * Store an entry in our cache (if any) * * @param string $key key used to store the entry in the cache (should match /^[a-z0-9_+-]*$/Di) * @param mixed $value entry to store in the cache */ protected static function storeInCache($key, &$value) { try { self::validateCache(); } catch (\Exception $exception) { // Fake an exception from setItem, so the cache's own EventManager can determine what to do with it $result = false; return self::triggerCacheException('setItem', array('key' => &$key, 'value' => &$value), $result, $exception); } return self::$cache->setItem($key, $value); }
/** * @return string */ public function closeSentAction() { $messagesBeingSent = $this->messageRepository->getMessagesBeingSent(true); if ($this->isVerbose()) { $this->logger->info('Messages checked: ' . count($messagesBeingSent)); } $closed = 0; foreach ($messagesBeingSent as $message) { if ($this->closeSentMessage($message)) { $closed++; } } if ($this->isVerbose()) { $this->logger->info('Messages closed: ' . $closed); } if ($this->hasCacheStorage()) { $this->cacheStorage->setItem(\DmMailer\View\DataProvider\Kpi::CS_LAST_MESSAGE_CLOSING, time()); } return ''; }
/** * Swap object data to disk * Actually swaps data or only unloads it from memory, * if object is not changed since last swap * * @param \Zend\Memory\Container\Movable $container * @param int $id */ private function _swap(Container\Movable $container, $id) { if ($container->isLocked()) { return; } if (!$container->isSwapped()) { $this->cache->setItem($this->managerId . $id, $container->getRef()); } $this->memorySize -= $this->sizes[$id]; $container->markAsSwapped(); $container->unloadValue(); }
public function setDelayedItem($key, Closure $closure) { try { $delayedKey = $this->getDelayedKey($key); $this->storage->setItem($this->getDelayedKey($key), self::UNDER_CONSTRUCTION_VALUE); $setReturn = $this->storage->setItem($key, $closure()); $this->storage->removeItem($delayedKey); return $setReturn; } catch (\Exception $exception) { $this->storage->removeItem($delayedKey); throw $exception; } }
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()); } }