public function getAllProjects() { $key = "{$this->cachePrefix}-all-projects"; if ($this->cache && ($projects = $this->cache->fetch($key))) { return $projects; } $first = json_decode($this->client->get('projects.json', ['query' => ['limit' => 100]])->getBody(), true); $projects = $first['projects']; if ($first['total_count'] > 100) { $requests = []; for ($i = 100; $i < $first['total_count']; $i += 100) { $requests[] = $this->client->getAsync('projects.json', ['query' => ['limit' => 100, 'offset' => $i]]); } /** @var Response[] $responses */ $responses = Promise\unwrap($requests); $responseProjects = array_map(function (Response $response) { return json_decode($response->getBody(), true)['projects']; }, $responses); $responseProjects[] = $projects; $projects = call_user_func_array('array_merge', $responseProjects); } usort($projects, function ($projectA, $projectB) { return strcasecmp($projectA['name'], $projectB['name']); }); $this->cache && $this->cache->save($key, $projects); return $projects; }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param callable $next * @return ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next) { $key = $this->generateKey($request); $data = $this->cache->fetch($key); if (false !== $data) { list($body, $code, $headers) = unserialize($this->cache->fetch($key)); $response->getBody()->write($body); $response = $response->withStatus($code); foreach (unserialize($headers) as $name => $value) { $response = $response->withHeader($name, $value); } return $response; } // prepare headers $ttl = $this->config['ttl']; $response = $next ? $next($request, $response) : $response; $response = $response->withHeader('Cache-Control', sprintf('public,max-age=%d,s-maxage=%d', $ttl, $ttl))->withHeader('ETag', $key); // save cache - status code, headers, body $body = $response->getBody()->__toString(); $code = $response->getStatusCode(); $headers = serialize($response->getHeaders()); $data = serialize([$body, $code, $headers]); $this->cache->save($key, $data, $this->config['ttl']); return $response; }
/** * @param $token * @param AuthUser $user * @return AccessToken */ public function insertAccessToken($token, AuthUser $user) { $accessToken = new AccessToken(); $accessToken->setCreatedAt(new \DateTime())->setId($token)->setUsername($user->getUsername()); $this->cache->save($token, $accessToken, 604800); return $accessToken; }
/** * Get the list of videos from YouTube * * @param string $channelId * @throws \Mcfedr\YouTube\LiveStreamsBundle\Exception\MissingChannelIdException * @return array */ public function getStreams($channelId = null) { if (!$channelId) { $channelId = $this->channelId; } if (!$channelId) { throw new MissingChannelIdException("You must specify the channel id"); } if ($this->cache) { $data = $this->cache->fetch($this->getCacheKey($channelId)); if ($data !== false) { return $data; } } $searchResponse = $this->client->get('search', ['query' => ['part' => 'id', 'channelId' => $channelId, 'eventType' => 'live', 'type' => 'video', 'maxResults' => 50]]); $searchData = json_decode($searchResponse->getBody()->getContents(), true); $videosResponse = $this->client->get('videos', ['query' => ['part' => 'id,snippet,liveStreamingDetails', 'id' => implode(',', array_map(function ($video) { return $video['id']['videoId']; }, $searchData['items']))]]); $videosData = json_decode($videosResponse->getBody()->getContents(), true); $streams = array_map(function ($video) { return ['name' => $video['snippet']['title'], 'thumb' => $video['snippet']['thumbnails']['high']['url'], 'videoId' => $video['id']]; }, array_values(array_filter($videosData['items'], function ($video) { return !isset($video['liveStreamingDetails']['actualEndTime']); }))); if ($this->cache && $this->cacheTimeout > 0) { $this->cache->save($this->getCacheKey($channelId), $streams, $this->cacheTimeout); } return $streams; }
/** * @param float $latitude * @param float $longitude * @return WeatherForecastForDay */ public function getForDay($latitude, $longitude, $timestamp) { if (!$this->isValidTimestamp($timestamp)) { throw new \Exception('Invalid timestamp: ' . $timestamp); } if (!$this->isValidLatitude($latitude)) { throw new \Exception('Invalid latitude: ' . $latitude); } if (!$this->isValidLongitude($longitude)) { throw new \Exception('Invalid longitude: ' . $longitude); } $latitude = $this->normalizeGeoCoordinate($latitude); $longitude = $this->normalizeGeoCoordinate($longitude); $timestamp = $this->normalizeTimestamp($timestamp); $cacheKey = md5($latitude . $longitude . $timestamp); if (false === ($apiData = $this->cache->fetch($cacheKey))) { try { $apiData = $this->provider->getForDay($latitude, $longitude, $timestamp); $this->cache->save($cacheKey, $apiData, 3600 * 6); //TTL 6h } catch (\Exception $e) { return null; } } return new WeatherForecastForDay($apiData); }
/** * {@inheritdoc} */ public function getMetadataFor($value) { $class = $this->getClass($value); if (empty($class)) { throw InvalidArgumentException::create(InvalidArgumentException::VALUE_IS_NOT_AN_OBJECT, $value); } if (isset($this->loadedClasses[$class])) { return $this->loadedClasses[$class]; } if (null !== $this->cache && ($this->loadedClasses[$class] = $this->cache->fetch($class))) { return $this->loadedClasses[$class]; } if (!class_exists($class) && !interface_exists($class)) { throw InvalidArgumentException::create(InvalidArgumentException::CLASS_DOES_NOT_EXIST, $class); } $reflectionClass = new \ReflectionClass($class); $classMetadata = $this->createMetadata($reflectionClass); if (!$this->loader->loadClassMetadata($classMetadata)) { return $classMetadata; } $this->mergeSuperclasses($classMetadata); $this->validate($classMetadata); if ($this->eventDispatcher) { $this->eventDispatcher->dispatch(ClassMetadataLoadedEvent::LOADED_EVENT, new ClassMetadataLoadedEvent($classMetadata)); } if (null !== $this->cache) { $this->cache->save($class, $classMetadata); } return $this->loadedClasses[$class] = $classMetadata; }
/** * Get metadata for a certain class - loads once and caches * @param string $className * @throws \Drest\DrestException * @return ClassMetaData $metaData */ public function getMetadataForClass($className) { if (isset($this->loadedMetadata[$className])) { return $this->loadedMetadata[$className]; } // check the cache if ($this->cache !== null) { $classMetadata = $this->cache->fetch($this->cache_prefix . $className); if ($classMetadata instanceof ClassMetaData) { if ($classMetadata->expired()) { $this->cache->delete($this->cache_prefix . $className); } else { $this->loadedMetadata[$className] = $classMetadata; return $classMetadata; } } } $classMetadata = $this->driver->loadMetadataForClass($className); if ($classMetadata !== null) { $this->loadedMetadata[$className] = $classMetadata; if ($this->cache !== null) { $this->cache->save($this->cache_prefix . $className, $classMetadata); } return $classMetadata; } if (is_null($this->loadedMetadata[$className])) { throw DrestException::unableToLoadMetaDataFromDriver(); } return $this->loadedMetadata[$className]; }
/** * {@inheritdoc} */ public function getMetadataFor($value) { $class = $this->getClass($value); if (isset($this->loadedClasses[$class])) { return $this->loadedClasses[$class]; } if ($this->cache && ($this->loadedClasses[$class] = $this->cache->fetch($class))) { return $this->loadedClasses[$class]; } $classMetadata = new ClassMetadata($class); $this->loader->loadClassMetadata($classMetadata); $reflectionClass = $classMetadata->getReflectionClass(); // Include metadata from the parent class if ($parent = $reflectionClass->getParentClass()) { $classMetadata->merge($this->getMetadataFor($parent->name)); } // Include metadata from all implemented interfaces foreach ($reflectionClass->getInterfaces() as $interface) { $classMetadata->merge($this->getMetadataFor($interface->name)); } if ($this->cache) { $this->cache->save($class, $classMetadata); } return $this->loadedClasses[$class] = $classMetadata; }
/** * @param BlockHeaderInterface $block * @return bool */ public function save(BlockHeaderInterface $block) { $key = $this->cacheIndexBlk($block); $this->blocks->save($key, $block); $this->size++; return $this; }
protected function saveCached(\Money\CurrencyPair $pair) { if ($this->cache) { $cacheKey = $this->getCacheKey($pair->getCounterCurrency(), $pair->getBaseCurrency()); $this->cache->save($cacheKey, $pair, self::CACHE_LIFETIME); } }
public function getArguments(Request $request, $controller) { if (!is_array($controller)) { throw new \InvalidArgumentException('Can not resolve arguments ' . 'for the controller type: "' . ($controller instanceof \Closure ? 'closure' : gettype($controller)) . '" for URI "' . $request->getPathInfo() . '"'); } $id = get_class($controller[0]) . '::' . $controller[1] . '#method-parameters'; if (($parameters = $this->cacheProvider->fetch($id)) === false) { $parameters = $this->getParameters($controller[0], $controller[1]); $this->cacheProvider->save($id, $parameters); } $attributes = $request->attributes->all(); $arguments = array(); foreach ($parameters as $name => $options) { if (array_key_exists($name, $attributes)) { $arguments[] = $attributes[$name]; continue; } if (array_key_exists('defaultValue', $options)) { $arguments[] = $options['defaultValue']; continue; } throw new \RuntimeException('Controller ' . get_class($controller[0]) . '::' . $controller[1] . ' requires that you provide a value ' . 'for the "$' . $name . '" argument (because there is no default value or ' . 'because there is a non optional argument after this one).'); } return $arguments; }
/** * {@inheritdoc} */ public function getMetadataFor($value) { $class = $this->getClass($value); if (!$class) { throw new InvalidArgumentException(sprintf('Cannot create metadata for non-objects. Got: "%s"', gettype($value))); } if (isset($this->loadedClasses[$class])) { return $this->loadedClasses[$class]; } if ($this->cache && ($this->loadedClasses[$class] = $this->cache->fetch($class))) { return $this->loadedClasses[$class]; } if (!class_exists($class) && !interface_exists($class)) { throw new InvalidArgumentException(sprintf('The class or interface "%s" does not exist.', $class)); } $classMetadata = new ClassMetadata($class); $this->loader->loadClassMetadata($classMetadata); $reflectionClass = $classMetadata->getReflectionClass(); // Include metadata from the parent class if ($parent = $reflectionClass->getParentClass()) { $classMetadata->merge($this->getMetadataFor($parent->name)); } // Include metadata from all implemented interfaces foreach ($reflectionClass->getInterfaces() as $interface) { $classMetadata->merge($this->getMetadataFor($interface->name)); } if ($this->cache) { $this->cache->save($class, $classMetadata); } return $this->loadedClasses[$class] = $classMetadata; }
/** * get config webhook for current webinstance * * @param $version * * @return mixed */ public function getCacheContext($version) { if (!($config = $this->cache->fetch($this->getCacheKey()))) { $config = $this->createConfig($version); $this->cache->save($this->getCacheKey(), $config, 86400); } return $config; }
/** * Get the contents of an URI and cache it for CACHE_LIFETIME seconds. * * @param string $uri * @return string */ public function getContents($uri) { if (!$this->cache->contains($uri)) { $this->cache->save($uri, $contents = $this->download($uri), static::CACHE_LIFETIME); return $contents; } return $this->cache->fetch($uri); }
/** * @param RequestInterface $request * @param ResponseInterface $response * @return bool true if success */ public function cache(RequestInterface $request, ResponseInterface $response) { try { return $this->storage->save($this->getCacheKey($request), $this->getCacheObject($response)); } catch (\Exception $ignored) { return false; } }
/** * @param \databox[] $databoxes */ private function saveCache(array $databoxes) { $rows = array(); foreach ($databoxes as $databox) { $rows[$databox->get_sbas_id()] = $databox->getRawData(); } $this->cache->save($this->cacheKey, $rows); }
/** * @param TransactionInterface $tx */ private function saveOutputs(TransactionInterface $tx) { $txid = $tx->getTransactionId(); $vout = 0; foreach ($tx->getOutputs()->getOutputs() as $output) { $this->contents->save($this->cacheIndex($txid, $vout), new Utxo($txid, $vout++, $output)); } $this->size += $vout; }
public function remember($key, \closure $callable, $lifeTime = 0) { if ($this->cache->contains($key)) { return $this->cache->fetch($key); } $data = $callable(); $this->cache->save($key, $data, $lifeTime); return $data; }
/** * @param string $ip * @return Location */ public function getIpData($ip) { if ($this->storage->contains($ip)) { return $this->storage->fetch($ip); } $result = $this->provider->fetchDataForIp($ip); $this->storage->save($ip, $result); return $result; }
/** * {@inheritDoc} */ public function interpret($rule) { if ($this->cache->contains($rule)) { return unserialize($this->cache->fetch($rule)); } $ast = $this->interpreter->interpret($rule); $this->cache->save($rule, serialize($ast), $this->lifeTime); return $ast; }
/** * @param int $id */ public function addGroupToQueue($id) { $groupIds = []; if ($this->cache->contains(self::QUEUE_CACHE_ID)) { $groupIds = $this->cache->fetch(self::QUEUE_CACHE_ID); } $groupIds[$id] = $id; $this->cache->save(self::QUEUE_CACHE_ID, $groupIds); }
/** * {@inheritdoc} */ public function tagContentDigest(array $tags, $identifier) { foreach ($tags as $tag) { $identifiers = $this->getCacheIds([$tag]); $identifiers[] = $identifier; $encodedIdentifiers = json_encode(array_unique($identifiers), true); $this->cache->save($tag, $encodedIdentifiers); } }
/** * Try to get cached statistic data, fetch from backed and save otherwise * * @return array|mixed */ public function get() { $data = $this->cache->fetch(static::CACHE_KEY); if (false === $data) { $data = $this->fetch(); $this->cache->save(static::CACHE_KEY, $data, static::CACHE_TTL); } return $data; }
/** * {@inheritdoc} */ public function findMatching($route, $host) { if ($this->cache->contains($this->getCacheKey())) { return $this->cache->fetch($this->getCacheKey()); } $rules = $this->ruleProvider->getRules(); $this->cache->save($this->getCacheKey(), $rules, $this->ttl); return $rules; }
public function createRate($key, $limit, $period) { $info = array(); $info['limit'] = $limit; $info['calls'] = 1; $info['reset'] = time() + $period; $this->client->save($key, $info, $period); return $this->getRateInfo($key); }
/** * {@inheritDoc} */ public function query() { $content = $this->cache->fetch($this->getClassName()); if (!$content) { $content = $this->loader->load($this->metadata, $this->parser); $this->cache->save($this->getClassName(), $content); } return Query::from($content); }
public function getStatistics($user, $repository) { $key = self::CACHE_NAMESPACE . $user . '/' . $repository; $statistics = $this->cache->fetch($key); if ($statistics === false) { $statistics = $this->wrapped->getStatistics($user, $repository); $this->cache->save($key, $statistics); } return $statistics; }
public function save(RequestInterface $request, ResponseInterface $response) { $ttl = (int) $request->getConfig()->get('cache.ttl'); $key = $this->getCacheKey($request); // Persist the response body if needed if ($response->getBody() && $response->getBody()->getSize() > 0) { $this->cache->save($key, array('code' => $response->getStatusCode(), 'headers' => $response->getHeaders(), 'body' => (string) $response->getBody()), $ttl); $request->getConfig()->set('cache.key', $key); } }
/** * Returns thumbnail data for the given transaction. * * Handles the cache layer around the creation as well. * * @param Transaction $transaction * * @return string */ protected function getThumbnail(Transaction $transaction) { $cacheKey = $transaction->getHash(); if ($this->cache->contains($cacheKey)) { return $this->cache->fetch($cacheKey); } $imageData = $this->creator->create($transaction); $this->cache->save($cacheKey, $imageData, $this->cacheTime); return $imageData; }
/** * @param $postalCode * @param null $number * @return array * @throws \RuntimeException */ public function find($postalCode, $number = null) { $cacheKey = md5($postalCode . '_' . $number); if ($this->cache->contains($cacheKey)) { return unserialize($this->cache->fetch($cacheKey)); } $result = $this->service->find($postalCode, $number); $this->cache->save($cacheKey, serialize($result)); return $result; }