/** * @param mixed $key * @return bool */ public function remove($key) { if (!$this->isKey($key)) { $key = $this->createKey($key); } return $this->cache->removeItem($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; }
/** * 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 null|array $arguments Must be serializable. * @return void */ public function warm($arguments = null) { $callable = $this->callable; if (is_array($arguments)) { $value = call_user_func_array($callable, $arguments); } else { $value = $callable(); } $cacheKey = Cache::makeCacheKey($this->name, $arguments); $this->storage->addItem($cacheKey, serialize($value)); }
/** * @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(); }
/** * Set array of items * If items already exists, they are replaced * * @access public * @param array $items */ public function setItems($items) { $existingItemsKeys = array_flip($this->cacheAdapter->hasItems(array_keys($items))); $existingItems = array_intersect_key($items, $existingItemsKeys); $nonExistingItems = array_diff_key($items, $existingItemsKeys); if (count($existingItems) > 0) { $this->cacheAdapter->replaceItems($existingItems); } if (count($nonExistingItems) > 0) { $this->cacheAdapter->setItems($nonExistingItems); } }
/** * @param Event $e * @param string $class * @param string $event * @return void */ public function invalidate(Event $e, $class, $event) { $term = $e->getParam('term'); $result = false; if ($term instanceof TaxonomyTermInterface) { $result = $this->cacheService->clearByTags(['route_taxonomy/term/get', 'param_term_' . $term->getId()]); $this->cacheService->clearByTags(['navigation/render']); $this->clearParents($term); } if ($this->storage instanceof FlushableInterface && !$result) { $this->storage->flush(); } }
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; }
/** * @param Event $e * @param string $class * @param string $event * @return void */ public function invalidate(Event $e, $class, $event) { $repository = $e->getParam('repository'); $result = false; if ($repository instanceof EntityInterface) { $result = $this->cacheService->clearByTags(['route_entity/page', 'param_entity_' . $repository->getId()]); $this->clearTaxonomyTerms($repository->getTaxonomyTerms()); } elseif ($repository instanceof PageRepositoryInterface) { $result = $this->cacheService->clearByTags(['route_page/view', 'param_page_' . $repository->getId()]); } if ($this->storage instanceof FlushableInterface && !$result) { $this->storage->flush(); } }
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 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 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')); }
/** * 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; }
/** * 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; }
/** * {@inheritDoc} */ protected function doGetStats() { /* @var $storage TotalSpaceCapableInterface */ /* @var $storage AvailableSpaceCapableInterface */ $storage = $this->storage; return array(Cache::STATS_HITS => $this->storage->getMetadata(Cache::STATS_HITS), Cache::STATS_MISSES => $this->storage->getMetadata(Cache::STATS_MISSES), Cache::STATS_UPTIME => $this->storage->getMetadata(Cache::STATS_UPTIME), Cache::STATS_MEMORY_USAGE => $storage instanceof TotalSpaceCapableInterface ? $storage->getTotalSpace() : null, Cache::STATS_MEMORY_AVAILIABLE => $storage instanceof AvailableSpaceCapableInterface ? $storage->getAvailableSpace() : null); }
/** * Triggers an option event if this options instance has a connection to * an adapter implements EventsCapableInterface. * * @param string $optionName * @param mixed $optionValue * @return void */ protected function triggerOptionEvent($optionName, $optionValue) { if ($this->adapter instanceof EventsCapableInterface) { $event = new Event('option', $this->adapter, new ArrayObject([$optionName => $optionValue])); $this->adapter->getEventManager()->triggerEvent($event); } }
/** * @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 ''; }
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; }
/** * 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; }
/** * Sets the zend-cache storage namespace. * * @param string $serviceName */ private function setNamespace($serviceName = null) { if ($serviceName === null) { $this->storage->getOptions()->setNamespace($this->defaultNamespace); } else { $this->storage->getOptions()->setNamespace($serviceName); } }
/** * Helper function for removing cached data. * * @param string $key Cache entry key * * @return void */ protected function removeCachedData($key) { // Don't write to cache if we don't have a cache! if (null === $this->cache) { return; } $this->cache->removeItem($this->formatCacheKey($key)); }
/** * @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); }
/** * 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; }
/** * 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); }
/** * @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); }
/** * 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; }
/** * 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; }
/** * 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)); }