/** * resolves user id to user data. * * @param int $id id to resolve * * @return User */ public function resolveUserFunction($id) { if ($this->cache->contains($id)) { return $this->cache->fetch($id); } $user = $this->userRepository->findUserById($id); if ($user === null) { return; } $this->cache->save($id, $user); return $user; }
/** * @Route("/entry-point/{mac}", defaults={"mac" = null}) * @Method({"GET", "POST"}) * @Template() */ public function indexAction(Request $request, $mac) { // Attempting to do anything here as a logged in user will fail. Set the current user token to null to log user out. $this->get('security.token_storage')->setToken(null); if (!$mac) { if (!$request->getSession()->get('auth-data')) { // No MAC code, nothing in the session, so we can't help - return to front page. return $this->redirectToRoute('barbon_hostedapi_app_index_index'); } } else { $cacheKey = sprintf('mac-%s', $mac); // If MAC isn't found in the cache, it's already been processed - redirect back to this route without the MAC, and try again. if (!$this->cache->contains($cacheKey)) { return $this->redirectToRoute('barbon_hostedapi_landlord_authentication_entrypoint_index'); } // store data to session and empty the cache $authData = unserialize($this->cache->fetch($cacheKey)); $request->getSession()->set('auth-data', $authData); $this->cache->delete($cacheKey); } // Decide which tab should start as visible, so that is a registration attempt is in progress it re-shows that tab. $selectedTab = $request->query->get('action') ?: 'register'; if ($request->isMethod(Request::METHOD_POST)) { if ($request->request->has('direct_landlord')) { $selectedTab = 'register'; } } return array('selectedTab' => $selectedTab); }
/** * @param int $start * @param int $maxResults * @return Category[]|null * @throws RepositoryException */ public function findAll($start = 0, $maxResults = 100) { $cacheKey = self::CACHE_NAMESPACE . sha1($start . $maxResults); if ($this->isCacheEnabled()) { if ($this->cache->contains($cacheKey)) { return $this->cache->fetch($cacheKey); } } $compiledUrl = $this->baseUrl . "?start_element={$start}&num_elements={$maxResults}"; $response = $this->client->request('GET', $compiledUrl); $repositoryResponse = RepositoryResponse::fromResponse($response); if (!$repositoryResponse->isSuccessful()) { throw RepositoryException::failed($repositoryResponse); } $stream = $response->getBody(); $responseContent = json_decode($stream->getContents(), true); $stream->rewind(); $result = []; if (!$responseContent['response']['content_categories']) { $responseContent['response']['content_categories'] = []; } foreach ($responseContent['response']['content_categories'] as $segmentArray) { $result[] = Category::fromArray($segmentArray); } if ($this->isCacheEnabled()) { $this->cache->save($cacheKey, $result, self::CACHE_EXPIRATION); } return $result; }
public function getTimestamp($key) { if (!$this->cache->contains($key . ':timestamp')) { return (double) 0; } return floatval($this->cache->fetch($key . ':timestamp')); }
/** * 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 $key * * @throws \LogicException * * @return bool|mixed */ public function getFromCache($key) { // If the results are already cached if ($this->cache->contains($key)) { return unserialize($this->cache->fetch($key)); } return false; }
/** * {@inheritDoc} */ protected function internalRemoveItem(&$normalizedKey) { $key = $this->getOptions()->getNamespace() . $normalizedKey; if (!$this->cache->contains($key)) { return false; } return $this->cache->delete($key); }
/** * Returns websocket context for given connection. * * @param ConnectionInterface $conn * * @return ConnectionContextInterface */ protected function getContext(ConnectionInterface $conn) { $id = ConnectionContext::getIdFromConnection($conn); if (!$this->contexts->contains($id)) { $this->saveContext($this->createContext($conn)); } return $this->contexts->fetch($id); }
/** * @param string $txid * @param int $vout * @return Utxo */ public function fetch($txid, $vout) { $index = $this->getInternalIndex($txid, $vout); if (!$this->cache->contains($index)) { throw new \RuntimeException('Utxo not found in this cache'); } return $this->cache->fetch($index); }
/** * {@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 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; }
/** * @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 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; }
/** * {@inheritdoc} */ public function getRolePermissions(Role $role) { $cacheId = sprintf('roles/%s', $role->getRoleName()); $permissions = $this->cache->fetch($cacheId); if (!$this->cache->contains($cacheId)) { $permissions = $this->driver->getRolePermissions($role); $this->cache->save($cacheId, $permissions); } return $permissions; }
public function renderLatestBlogPosts() { $cacheId = $this->blogOptions->getCacheKey(); $posts = $this->cache->contains($cacheId) ? $this->cache->fetch($cacheId) : []; $elements = []; foreach ($posts as $post) { $elements[] = sprintf('<li><a target="_blank" href="%s">%s</a></li>', $post['link'], $post['title']); } return sprintf('<ul class="fh5co-links blog-posts">%s</ul>', implode('', $elements)); }
/** * 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; }
/** * {@inheritdoc} */ public function getStructures($webspaceKey) { if (!$this->cache->contains($webspaceKey)) { return $this->loadStructures($webspaceKey); } $keys = $this->cache->fetch($webspaceKey); return array_map(function ($key) { return $this->structureManager->getStructure($key); }, $keys); }
/** * @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; }
/** * Performs a request to the QBank API. * * @param string $endpoint The API endpoint URL to request. * @param array $parameters The parameters to send. * @param string $method The HTTP verb to use. * @param CachePolicy $cachePolicy The custom caching policy to use. * @param bool $delayed If the request should be delayed until destruction. * * @return array The response result. * * @throws RequestException * @throws ResponseException */ protected function call($endpoint, array $parameters = [], $method = self::METHOD_GET, CachePolicy $cachePolicy = null, $delayed = false) { $cachePolicy = $cachePolicy !== null ? $cachePolicy : $this->cachePolicy; if ($delayed) { $this->delayedRequests[] = $this->client->createRequest(strtoupper($method), $endpoint, $parameters); $this->logger->debug('Request to QBank added to delayed queue. ' . strtoupper($method) . ' ' . $endpoint, ['endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method]); return []; } if ($cachePolicy->isEnabled() && ($method == self::METHOD_GET || $method == self::METHOD_POST && preg_match('/v\\d+\\/search/', $endpoint)) && $this->cache->contains(md5($endpoint . json_encode($parameters)))) { /** @var string $response */ $response = $this->cache->fetch(md5($endpoint . json_encode($parameters))); $this->logger->info('Using cached response. ' . strtoupper($method) . ' ' . $endpoint, ['endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method, 'response' => substr(print_r($response, true), 0, 4096)]); return $response; } try { $start = microtime(true); /** @var ResponseInterface $response */ $response = $this->client->{$method}($endpoint, $parameters); $this->logger->debug('Request to QBank sent. ' . strtoupper($method) . ' ' . $endpoint, ['endpoint' => $endpoint, 'parameters' => $parameters, 'time' => number_format(round((microtime(true) - $start) * 1000), 0, '.', ' ') . ' ms', 'method' => $method, 'response' => substr($response->getBody(), 0, 4096)]); $data = null; if (in_array('application/json', array_map('trim', explode(';', $response->getHeader('Content-type'))))) { try { $data = $response->json(); } catch (\RuntimeException $re) { $this->logger->error('Error while receiving response from QBank. ' . strtoupper($method) . ' ' . $endpoint, ['message' => 'Response not in json format.', 'endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method, 'response' => substr($response->getBody(), 0, 4096)]); throw new ResponseException('Error while receiving response from QBank: Response not in json format.'); } } else { return $response->getBody()->__toString(); } if ($cachePolicy->isEnabled() && $cachePolicy->getCacheType() == CachePolicy::EVERYTHING && ($method == self::METHOD_GET || $method == self::METHOD_POST && preg_match('/v\\d+\\/search/', $endpoint))) { $this->cache->save(md5($endpoint . json_encode($parameters)), $data, $cachePolicy->getLifetime()); } return $data; } catch (\GuzzleHttp\Exception\RequestException $re) { $this->logger->error('Error while sending request to QBank. ' . strtoupper($method) . ' ' . $endpoint, ['exception' => $re, 'message' => $re->getMessage(), 'endpoint' => $endpoint, 'parameters' => $parameters, 'method' => $method, 'response' => $re->hasResponse() ? substr($re->getResponse()->getBody(), 0, 4096) : '']); $message = null; $details = null; if ($re->hasResponse() && strpos($re->getResponse()->getHeader('content-type'), 'application/json') === 0) { $content = $re->getResponse()->json(); if (!empty($content['error'])) { $details = $content['error']; } if (isset($content['error']['message'])) { $message = ' [info]' . $content['error']['message']; } if (isset($content['error']['errors']) && is_array($content['error']['errors'])) { foreach ($content['error']['errors'] as $key => $error) { $message .= "\n\t{$key}: {$error}"; } } } throw new RequestException('Error while sending request to QBank: ' . $re->getMessage() . $message, $re->hasResponse() ? $re->getResponse()->getStatusCode() : 0, $re, $details); } }
/** * resolves user id to user data. * * @param int $userId id to resolve * * @return Contact */ public function resolveUserFunction($userId) { if (!$this->cache->contains($userId)) { $user = $this->userRepository->findUserById($userId); if ($user === null) { return; } $this->cache->save($userId, $user->getContact()); } return $this->cache->fetch($userId); }
public function testWithNoCacheResponseIsCached() { $response = new Response(); $next = function ($req, $resp) { return $resp; }; $this->router->match($this->request)->willReturn(RouteResult::fromRouteMatch('home', $next, ['cacheable' => true])); $this->assertFalse($this->cache->contains('/foo')); $this->middleware->__invoke($this->request, $response, $next); $this->assertTrue($this->cache->contains('/foo')); }
/** * @param $dir * @return array */ public function discoverControllers($dir) { if ($this->useCache && $this->cache->contains(self::CONTROLLER_CACHE_INDEX)) { $controllerFiles = $this->cache->fetch('annot.controllerFiles'); } else { $controllerFiles = $this->app['annot.controllerFinder']($this->app, $dir); if ($this->useCache) { $this->cache->save(self::CONTROLLER_CACHE_INDEX, $controllerFiles); } } return $controllerFiles; }
/** * Fetches information about the given URL. * * @param string $url The URL to crawl * @return array|false Returns the gathered information as array or FALSE if none of the crawlers was able to crawl the URL. */ public function fetch($url) { if ($this->cache && $this->cache->contains($url)) { return $this->cache->fetch($url); } else { $result = $this->doFetch($url); if ($this->cache && $result) { $this->cache->save($url, $result); } return $result; } }
/** * resolves user id to user data. * * @param int $id id to resolve * * @return Contact */ public function resolveContactFunction($id) { if ($this->cache->contains($id)) { return $this->cache->fetch($id); } $contact = $this->contactRepository->find($id); if ($contact === null) { return; } $this->cache->save($id, $contact); return $contact; }
/** * @param string $className * * @return ClassMetadataInterface */ public function getMetadataForClass($className) { if (null === $this->cacheDriver) { return $this->mappingDriver->loadMetadataForClass($className); } if ($this->cacheDriver->contains($className)) { return $this->cacheDriver->fetch($className); } $metadata = $this->mappingDriver->loadMetadataForClass($className); $this->cacheDriver->save($className, $metadata); return $metadata; }
/** * {@inheritdoc} */ public function locateTemplate(TemplateReferenceInterface $template, ThemeInterface $theme) { $cacheKey = $this->getCacheKey($template, $theme); if ($this->cache->contains($cacheKey)) { $location = $this->cache->fetch($cacheKey); if (null === $location) { throw new ResourceNotFoundException($template->getPath(), $theme); } return $location; } return $this->decoratedTemplateLocator->locateTemplate($template, $theme); }
/** * {@inheritdoc} */ public function configureOptions(OptionsResolver $resolver) { $cacheKey = 'timezones'; if ($this->cache) { if ($this->cache->contains($cacheKey)) { self::$timezones = $this->cache->fetch($cacheKey); } else { $this->cache->save($cacheKey, self::getTimezones()); } } $resolver->setDefaults(array('choices' => self::$timezones)); }
/** * {@inheritdoc} */ public function hasPermission(RoleInterface $role, $permissionCode) { if ($this->cache->contains($this->getCacheKey($role))) { return in_array($permissionCode, $this->cache->fetch($this->getCacheKey($role))); } $permissions = $this->map->getPermissions($role); $permissionsCache = []; foreach ($permissions as $permission) { $permissionsCache[] = $permission->getCode(); } $this->cache->save($this->getCacheKey($role), $permissionsCache, $this->ttl); return in_array($permissionCode, $permissionsCache); }
/** * Retrieve some xml from the device. * * @param string $url The url to retrieve * * @return XmlParser */ public function getXml($url) { $uri = "http://{$this->ip}:1400{$url}"; if ($this->cache->contains($uri)) { $this->logger->info("getting xml from cache: {$uri}"); $xml = $this->cache->fetch($uri); } else { $this->logger->notice("requesting xml from: {$uri}"); $xml = (string) (new Client())->get($uri)->getBody(); $this->cache->save($uri, $xml, Cache::DAY); } return new XmlParser($xml); }