/** * Returns sizes array for photo identified by Flickr photo id * * @param int $photoId * @return array Array of photo size information */ public function getSizes($photoId) { $sizes = $this->adapter->getItem($photoId); if (is_null($sizes)) { $sizes = $this->flickr->getSizes($photoId); $this->adapter->addItem($photoId, $sizes); } return $sizes; }
/** * Set options. * * @param array|\Traversable|SessionOptions $options * @return Memory * @see getOptions() */ public function setOptions($options) { if (!$options instanceof SessionOptions) { $options = new SessionOptions($options); } return parent::setOptions($options); }
/** * All a user to add and update a feed in the application * * @return ViewModel */ public function manageAction() { $formManager = $this->serviceLocator->get('FormElementManager'); $form = $formManager->get('BabyMonitor\\Forms\\ManageRecordForm'); $feedId = (int) $this->params()->fromRoute('id'); if ($this->getRequest()->isGet()) { if (!empty($feedId)) { if ($feed = $this->_feedTable->fetchById($feedId)) { $form->setData($feed->getArrayCopy()); } else { $this->flashMessenger()->addInfoMessage('Unable to find that feed. Perhaps a new one?'); return $this->redirect()->toRoute(self::DEFAULT_ROUTE, array('action' => 'manage')); } } } if ($this->getRequest()->isPost()) { $form->setData($this->getRequest()->getPost()); if ($form->isValid()) { $feed = new FeedModel(); $feed->exchangeArray($form->getData()); $this->_feedTable->save($feed); if (!is_null($this->_cache)) { $this->_cache->removeItem(self::KEY_ALL_RESULTS); } $this->getEventManager()->trigger('Feed.Modify', $this, array('feedData' => $feed)); return $this->redirect()->toRoute(self::DEFAULT_ROUTE, array()); } } return new ViewModel(array('form' => $form, 'cancelTitle' => $feedId ? "Don't update the record" : "Don't create the record", 'messages' => array('info' => $this->flashMessenger()->hasInfoMessages()))); }
/** * Set options. * * @param array|Traversable|WinCacheOptions $options * @return WinCache * @see getOptions() */ public function setOptions($options) { if (!$options instanceof WinCacheOptions) { $options = new WinCacheOptions($options); } return parent::setOptions($options); }
/** * Set options. * * @param array|\Traversable|MemoryOptions $options * @return Memory * @see getOptions() */ public function setOptions($options) { if (!$options instanceof MemoryOptions) { $options = new MemoryOptions($options); } return parent::setOptions($options); }
/** * Set options. * * @param array|Traversable|ApcOptions $options * @return Apc * @see getOptions() */ public function setOptions($options) { if (!$options instanceof ApcOptions) { $options = new ApcOptions($options); } return parent::setOptions($options); }
/** * @param $entity * * @return mixed * @throws \InvalidArgumentException If the ResultSetPrototype is not Hydrating * @throws \InvalidArgumentException If a BaseEntity object is not provided */ public function persist($entity) { if (!$this->getResultSetPrototype() instanceof HydratingResultSet) { throw new \InvalidArgumentException('Result Set Prototype is not configured correctly'); } if (!$entity instanceof BaseEntity) { throw new \InvalidArgumentException('Can only persist object entities'); } $hydrator = $this->getResultSetPrototype()->getHydrator(); $data = $hydrator->extract($entity); $sql = $this->getSql(); $identifierName = $this->getIdentifierName(); $identifier = null; if (array_key_exists($identifierName, $data)) { $identifier = $data[$identifierName]; unset($data[$identifierName]); } array_walk($data, function (&$value) { if ($value instanceof \DateTime) { $value = $value->format('Y-m-d H:i:s'); } }); if (!empty($identifier)) { // UPDATE $data['lastModified'] = date('Y-m-d H:i:s'); $where = array(); $where[$identifierName] = $identifier; $statement = $sql->prepareStatementForSqlObject($sql->update()->set($data)->where($where)); $result = $statement->execute(); unset($statement, $result); // cleanup } else { // INSERT $data['createdDatetime'] = date('Y-m-d H:i:s'); $data['status'] = '1'; $data['lastModified'] = date('Y-m-d H:i:s'); $insert = $sql->insert(); $insert->values($data); $statement = $sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $identifier = $result->getGeneratedValue(); unset($statement, $result); // cleanup $where = array(); $where[$identifierName] = $identifier; } // refresh data $statement = $sql->prepareStatementForSqlObject($this->sql->select()->where($where)); $result = $statement->execute(); $rowData = $result->current(); unset($statement, $result); // cleanup $hydrator->hydrate($rowData, $entity); if ($this->cacheAdapter instanceof CacheAdapter) { $this->cacheAdapter->setItem($this->getCacheKeyHash($entity->getId()), $entity); } return $entity; }
/** * @inheritdoc */ public function build() { if ($this->built) { return; } $key = 'assets-manager'; if ($this->cacheAdapter->hasItem($key)) { $data = $this->cacheAdapter->getItem($key); $assetManager = unserialize($data); if ($assetManager instanceof AssetManager) { $this->setAssetManager($assetManager); return; } } parent::build(); $this->cacheAdapter->setItem($key, serialize($this->getAssetManager())); $this->built = true; }
/** * Flush the whole storage * * @return bool */ public function flush() { if (!$this->cache instanceof FlushableInterface) { return false; } try { return $this->cache->flush(); } catch (ZendException\ExceptionInterface $ex) { return false; } }
/** * Remove an item from the cache * @param string $key * @return boolean */ public function clearItem($key) { //check if caching is enabled $arr_config = $this->getServiceLocator()->get("config"); if ($arr_config["front_end_application_config"]["cache_enabled"] == FALSE) { return FALSE; } //end if //adjust key $key = $this->setIdentifier($key); $this->storageFactory->removeItem($key); }
/** * Constructor * * @param array|Traversable|WinCacheOptions $options * @throws Exception * @return void */ public function __construct($options = null) { if (!extension_loaded('wincache')) { throw new Exception\ExtensionNotLoadedException("WinCache extension is not loaded"); } $enabled = ini_get('wincache.ucenabled'); if (PHP_SAPI == 'cli') { $enabled = $enabled && (bool) ini_get('wincache.enablecli'); } if (!$enabled) { throw new Exception\ExtensionNotLoadedException("WinCache is disabled - see 'wincache.ucenabled' and 'wincache.enablecli'"); } parent::__construct($options); }
/** * Cache Response for future requests * * @param MvcEvent $e * @return \Zend\Stdlib\ResponseInterface */ public function onFinish(MvcEvent $e) { $request = $e->getRequest(); if (!$request instanceof HttpRequest) { return; } if (!$request->isGet()) { return; } $response = $e->getResponse(); if ($response instanceof HttpResponse && !$response->isOk()) { return; } // Do not continue if weren't able to compose a key if (empty($this->cache_key)) { return; } if (!$this->cacheAdapter->hasItem($this->cache_key)) { $resourceIdentifier = $e->getRouteMatch()->getParam('resource'); $resource = call_user_func($this->getResourceLocatorService(), $resourceIdentifier); if (!$resource instanceof Resource || !$resource->isCacheable()) { return; } // Generate Response cache headers based on Resource CacheOptions $cacheOptions = $resource->getCacheOptions(); $cacheControl = new CacheControl(); $cacheControl->addDirective($cacheOptions->getAccess()); $cacheControl->addDirective('max-age', $cacheOptions->getMaxAge()); $cacheControl->addDirective('expires', $cacheOptions->getExpires()); $cacheControl->addDirective('must-revalidate'); $dateTime = new \DateTime(); $dateTime->modify('+ ' . $cacheOptions->getExpires() . 'seconds'); $expires = new Expires(); $expires->setDate($dateTime); $lastModified = new LastModified(); $lastModified->setDate(new \DateTime()); // Add Headers to Response Header $response->getHeaders()->addHeader($cacheControl); $response->getHeaders()->addHeader($expires); $response->getHeaders()->addHeaderLine('Pragma: ' . $cacheOptions->getAccess()); $response->getHeaders()->addHeader(Etag::fromString('Etag: ' . md5($response->getBody()))); $response->getHeaders()->addHeader($lastModified); // Set cache adapter's TTL using Resource cache expires value $this->cacheAdapter->getOptions()->setTtl($cacheOptions->getExpires()); $this->cacheAdapter->setItem($this->cache_key, $response); //return $response; } }
/** * Constructor * * @param null|array|Traversable|MemcachedOptions $options * @throws Exception * @return void */ public function __construct($options = null) { if (static::$extMemcachedMajorVersion === null) { $v = (string) phpversion('memcached'); static::$extMemcachedMajorVersion = $v !== '' ? (int) $v[0] : 0; } if (static::$extMemcachedMajorVersion < 1) { throw new Exception\ExtensionNotLoadedException('Need ext/memcached version >= 1.0.0'); } $this->memcached = new MemcachedResource(); parent::__construct($options); // It's ok to add server as soon as possible because // ext/memcached auto-connects to the server on first use // TODO: Handle multiple servers $options = $this->getOptions(); $this->memcached->addServer($options->getServer(), $options->getPort()); }
/** * Constructor * * @param null|array|Traversable|ApcOptions $options * @throws Exception * @return void */ public function __construct($options = null) { if (version_compare('3.1.6', phpversion('apc')) > 0) { throw new Exception\ExtensionNotLoadedException("Missing ext/apc >= 3.1.6"); } $enabled = ini_get('apc.enabled'); if (PHP_SAPI == 'cli') { $enabled = $enabled && (bool) ini_get('apc.enable_cli'); } if (!$enabled) { throw new Exception\ExtensionNotLoadedException("ext/apc is disabled - see 'apc.enabled' and 'apc.enable_cli'"); } // init select map if (static::$selectMap === null) { static::$selectMap = array('value' => \APC_ITER_VALUE, 'mtime' => \APC_ITER_MTIME, 'ctime' => \APC_ITER_CTIME, 'atime' => \APC_ITER_ATIME, 'rtime' => \APC_ITER_DTIME, 'ttl' => \APC_ITER_TTL, 'num_hits' => \APC_ITER_NUM_HITS, 'ref_count' => \APC_ITER_REFCOUNT, 'mem_size' => \APC_ITER_MEM_SIZE, 'internal_key' => \APC_ITER_KEY); } parent::__construct($options); }
/** * @param string $request Request uri * @throws \RuntimeException * @return \Zend\Http\PhpEnvironment\Response */ public function dispatch($request) { if (!$this->getResolver()) { throw new \RuntimeException("No resolver setted"); } $asset = $this->resolver->resolve($request); $content = null; $responseCode = 404; $headers = Headers::fromString("Content-Type: text/plain"); if ($asset) { $headers = $this->getHeaders($asset->getFile(), $asset->getMime()); if ($this->browserCached($asset->getFile())) { $responseCode = 304; $headers->addHeader(Connection::fromString("Connection: close")); } else { $responseCode = 200; $cacheKey = "assets-cache-" . md5($request); if ($this->cache) { $content = $this->cache->getItem($cacheKey); } if (!$content) { $content = $asset->getContent(); $assetName = end(explode('\\', get_class($asset))); if (array_key_exists($assetName, $this->filters)) { foreach ($this->filters[$assetName] as $filter) { $content = $filter->filter($content); } } if ($this->cache) { $this->cache->addItem($cacheKey, $content); } } } } else { $content = "Asset not found!"; } $response = new Response(); $response->setStatusCode($responseCode); $response->setContent($content); $response->setHeaders($headers); return $response; }
protected function checkPreEventCanChangeArguments($method, array $args, array $expectedArgs) { $internalMethod = 'internal' . ucfirst($method); $eventName = $method . '.pre'; // init mock $this->_storage = $this->getMockForAbstractAdapter(array($internalMethod)); $this->_storage->getEventManager()->attach($eventName, function ($event) use($expectedArgs) { $params = $event->getParams(); foreach ($expectedArgs as $k => $v) { $params[$k] = $v; } }); // set expected arguments of internal method call $tmp = $this->_storage->expects($this->once())->method($internalMethod); $equals = array(); foreach ($expectedArgs as $v) { $equals[] = $this->equalTo($v); } call_user_func_array(array($tmp, 'with'), $equals); // run call_user_func_array(array($this->_storage, $method), $args); }
/** * Compile to file. If destination is not specified return CSS. * * @param string $source * @param string|null $destination * @param array|string|null $include Include path(s) to use * @throws \Exception on compilation error * @return string Compiled CSS */ public function compile($source, $destination = null, $include = null) { $include = array_merge($this->includes, (array) $include); $useCache = null == $destination && null !== $this->cache; if ($useCache) { if ($this->cache->hasItem($source)) { return $this->cache->getItem($source); } } $arguments = implode(' ', array_map('escapeshellarg', $this->arguments)); $arguments .= ' ' . $this->getCommandArguments($source, $destination, $include); $command = "{$this->compiler} {$arguments}" . ' 2>&1'; $result = exec($command, $output, $exitCode); if ($exitCode != 0) { throw new \Exception(sprintf('Error compiling CSS "%s": %s', $source, implode(PHP_EOL, $output))); } $css = implode(PHP_EOL, $output); if ($useCache) { $this->cache->setItem($source, $css); } return $css; }
/** * {@inheritDoc} * @param Cache $cache */ public function __construct($options, Cache $cache) { parent::__construct($options); $this->cache = $cache; }
/** * Remove multiple items. * * @param array $keys * @return array Array of not removed keys * @throws Exception\ExceptionInterface * * @triggers removeItems.pre(PreEvent) * @triggers removeItems.post(PostEvent) * @triggers removeItems.exception(ExceptionEvent) */ public function removeItems(array $keys) { $options = $this->getOptions(); if ($options->getWritable() && $options->getClearStatCache()) { clearstatcache(); } return parent::removeItems($keys); }
/** * Internal method to set an item only if token matches * * @param mixed $token * @param string $normalizedKey * @param mixed $value * @return bool * @see getItem() * @see setItem() */ protected function internalCheckAndSetItem(&$token, &$normalizedKey, &$value) { if (is_int($token) && is_int($value)) { return apcu_cas($normalizedKey, $token, $value); } return parent::internalCheckAndSetItem($token, $normalizedKey, $value); }
/** * Internal method to remove multiple items. * * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ protected function internalRemoveItems(array &$normalizedKeys) { // support for removing multiple items at once has been added in ext/memcached-2.0.0 if (static::$extMemcachedMajorVersion < 2) { return parent::internalRemoveItems($normalizedKeys); } $rsCodes = $this->memcached->deleteMulti($normalizedKeys); $missingKeys = array(); foreach ($rsCodes as $key => $rsCode) { if ($rsCode !== true && $rsCode != MemcachedResource::RES_SUCCESS) { if ($rsCode != MemcachedResource::RES_NOTFOUND) { throw $this->getExceptionByResultCode($rsCode); } $missingKeys[] = $key; } } return $missingKeys; }
/** * @param $token * @return void */ private function setTokenToCache($token) { $this->cache->setItem($this->getCacheKey(), $token); }
/** * Set options. * * @param array|\Traversable|CouchbaseOptions $options * * @return \CouchbaseCluster * * @see getOptions() */ public function setOptions($options) { if (!$options instanceof CouchbaseOptions) { $options = new CouchbaseOptions($options); } return parent::setOptions($options); }
/** * Obtain the authentication to use with the EDS API from cache if it exists. If * not, then generate a new one. * * @param bool $isInvalid whether or not the the current token is invalid * * @return string */ protected function getAuthenticationToken($isInvalid = false) { $token = null; if ($this->ipAuth) { return $token; } if ($isInvalid) { $this->cache->setItem('edsAuthenticationToken', null); } $authTokenData = $this->cache->getItem('edsAuthenticationToken'); if (isset($authTokenData)) { $currentToken = isset($authTokenData['token']) ? $authTokenData['token'] : ''; $expirationTime = isset($authTokenData['expiration']) ? $authTokenData['expiration'] : 0; $this->debugPrint('Cached Authentication data: ' . "{$currentToken}, expiration time: {$expirationTime}"); // Check to see if the token expiration time is greater than the current // time. If the token is expired or within 5 minutes of expiring, // generate a new one. if (!empty($currentToken) && time() <= $expirationTime - 60 * 5) { return $currentToken; } } $username = $this->userName; $password = $this->password; $orgId = $this->orgId; if (!empty($username) && !empty($password)) { $this->debugPrint('Calling Authenticate with username: '******'AuthToken']; $timeout = $results['AuthTimeout'] + time(); $authTokenData = ['token' => $token, 'expiration' => $timeout]; $this->cache->setItem('edsAuthenticationToken', $authTokenData); } return $token; }
/** * @param string $cacheName Name of the cache being used. Defaults to cache. */ public function __construct($cacheName = 'cache') { parent::__construct(); $this->cacheName = $cacheName; }
/** * Internal method to remove multiple items. * * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ protected function internalRemoveItems(array &$normalizedKeys) { // support for removing multiple items at once has been added in ext/memcached-2.0.0 if (static::$extMemcachedMajorVersion < 2) { return parent::internalRemoveItems($normalizedKeys); } $memc = $this->getMemcachedResource(); foreach ($normalizedKeys as &$normalizedKey) { $normalizedKey = $this->namespacePrefix . $normalizedKey; } $rsCodes = $memc->deleteMulti($normalizedKeys); $missingKeys = array(); foreach ($rsCodes as $key => $rsCode) { if ($rsCode !== true && $rsCode != MemcachedResource::RES_SUCCESS) { if ($rsCode != MemcachedResource::RES_NOTFOUND) { throw $this->getExceptionByResultCode($rsCode); } $missingKeys[] = $key; } } // remove namespace prefix if ($missingKeys && $this->namespacePrefix !== '') { $nsPrefixLength = strlen($this->namespacePrefix); foreach ($missingKeys as &$missingKey) { $missingKey = substr($missingKey, $nsPrefixLength); } } return $missingKeys; }
/** * Internal method to remove multiple items. * * @param array $normalizedKeys * @return array Array of not removed keys * @throws Exception\ExceptionInterface */ protected function internalRemoveItems(array &$normalizedKeys) { $memc = $this->getMemcachedResource(); // support for removing multiple items at once has been added in ext/memcached-2.0.0 // and HHVM doesn't support this feature yet if (!method_exists($memc, 'deleteMulti')) { return parent::internalRemoveItems($normalizedKeys); } foreach ($normalizedKeys as &$normalizedKey) { $normalizedKey = $this->namespacePrefix . $normalizedKey; } $missingKeys = []; foreach ($memc->deleteMulti($normalizedKeys) as $normalizedKey => $rsCode) { if ($rsCode !== true && $rsCode != MemcachedResource::RES_SUCCESS) { if ($rsCode != MemcachedResource::RES_NOTFOUND) { throw $this->getExceptionByResultCode($rsCode); } $missingKeys[] = $normalizedKey; } } // remove namespace prefix if ($missingKeys && $this->namespacePrefix !== '') { $nsPrefixLength = strlen($this->namespacePrefix); foreach ($missingKeys as &$missingKey) { $missingKey = substr($missingKey, $nsPrefixLength); } } return $missingKeys; }
/** * Set options. * * @param array|Traversable|RedisArrayOptions $options * @return RedisArray * @see getOptions() */ public function setOptions($options) { if (!$options instanceof RedisArrayOptions) { $options = new RedisArrayOptions($options); } return parent::setOptions($options); }
/** * {@inheritDoc} */ public function setOptions($options) { return parent::setOptions($options instanceof MongoDbOptions ? $options : new MongoDbOptions($options)); }
/** * Set Cache Adapter * * @param \Zend\Cache\Storage\Adapter\AbstractAdapter $cacheAdapter */ public function setCacheAdapter($cacheAdapter) { $this->cacheAdapter = $cacheAdapter; $this->cacheAdapter->getOptions()->setTtl($this->getCacheOptions()->getExpires()); }