public function onComplete(CompleteEvent $event)
 {
     if (in_array($event->getRequest()->getPath(), $this->paths)) {
         $response = $event->getResponse();
         $response->setHeaders(['Cache-Control' => sprintf('max-age=%d', $this->maxAge)]);
     }
 }
Example #2
0
 /**
  * Invoked for every HTTP error.
  *
  * @param CompleteEvent $event
  *
  * @throws BadResponseError
  */
 public function onComplete(CompleteEvent $event)
 {
     $response = $event->getResponse();
     if ($response->getStatusCode() >= 400) {
         throw $this->httpError($event->getRequest(), $response);
     }
 }
 /**
  * Throw a RequestException if the response is not marked as successful.
  *
  * @param \GuzzleHttp\Event\CompleteEvent $event
  *
  * @throws \GuzzleHttp\Exception\RequestException
  *
  * @return void
  */
 public function onComplete(CompleteEvent $event)
 {
     $json = $event->getResponse()->json();
     if (array_get($json, 'result') !== 'success' || array_key_exists('response', $json) === false) {
         throw RequestException::create($event->getRequest(), $event->getResponse());
     }
 }
Example #4
0
 public function onComplete(CompleteEvent $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     if (!$this->cache->contains($request->__toString())) {
         $this->cache->save($request->__toString(), $response, 1000);
     }
 }
 public function onComplete(CompleteEvent $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     if ($request->getConfig()->get('cache_lookup') === 'MISS' && $this->canCacheRequest($request) && $this->canCacheResponse($response)) {
         $this->storage->save($request, $response);
     }
 }
Example #6
0
 /**
  * Throw a RequestException on an HTTP protocol error
  *
  * @param CompleteEvent $event Emitted event
  * @throws RequestException
  */
 public function onComplete(CompleteEvent $event)
 {
     $code = (string) $event->getResponse()->getStatusCode();
     // Throw an exception for an unsuccessful response
     if ($code[0] === '4' || $code[0] === '5') {
         throw RequestException::create($event->getRequest(), $event->getResponse());
     }
 }
 function it_logs_in_after_responses_that_required_login_and_retries_the_request(SiteConfig $siteConfig, Factory $authenticatorFactory, CompleteEvent $completeEvent, Authenticator $authenticator, ClientInterface $guzzle)
 {
     $siteConfig->requiresLogin()->willReturn(true);
     $authenticatorFactory->buildFromSiteConfig($siteConfig)->willReturn($authenticator);
     $authenticator->isLoginRequired(Argument::type('string'))->willReturn(true);
     $authenticator->login($guzzle)->shouldBeCalled();
     $completeEvent->retry()->shouldBeCalled();
     $this->loginIfRequested($completeEvent);
 }
 public function onComplete(CompleteEvent $event)
 {
     $request = $event->getRequest();
     if (!file_exists($this->getPath($request))) {
         mkdir($this->getPath($request), 0777, true);
     }
     $response = $event->getResponse();
     file_put_contents($this->getFullFilePath($request), (string) $response);
 }
Example #9
0
 /**
  * When a request completes, this method is executed. Because this class
  * checks for HTTP errors and handles them, this method checks the HTTP
  * status code and invokes {@see RequestException} if necessary.
  *
  * @param CompleteEvent $event
  * @throws \OpenStack\Common\Transport\Exception\RequestException
  */
 public function onComplete(CompleteEvent $event)
 {
     $status = (int) $event->getResponse()->getStatusCode();
     // Has an error occurred (4xx or 5xx status)?
     if ($status >= 400 && $status <= 505) {
         $request = new RequestAdapter($event->getRequest());
         $response = new ResponseAdapter($event->getResponse());
         throw RequestException::create($request, $response);
     }
 }
 public function testHasValues()
 {
     $c = new Client();
     $r = new Request('GET', '/');
     $res = new Response(200);
     $t = new Transaction($c, $r);
     $e = new CompleteEvent($t);
     $e->intercept($res);
     $this->assertTrue($e->isPropagationStopped());
     $this->assertSame($res, $e->getResponse());
 }
 public function onComplete(CompleteEvent $event)
 {
     $response = $event->getResponse();
     if (!($expected = $this->getExpected($response))) {
         return;
     }
     $request = $event->getRequest();
     $response->setBody(new ReadIntegrityStream($response->getBody(), $this->hash, $expected, function ($result, $expected) use($request, $response) {
         throw new MessageIntegrityException(sprintf('Message integrity check failure. Expected ' . '"%s" but got "%s"', $expected, $result), $request, $response);
     }));
 }
 private function matchesHash(CompleteEvent $event, $hash, StreamInterface $body)
 {
     $body->seek(0);
     while (!$body->eof()) {
         $this->hash->update($body->read(16384));
     }
     $result = $this->hash->complete();
     if ($hash !== $result) {
         throw new MessageIntegrityException(sprintf('Message integrity check failure. Expected "%s" but' . ' got "%s"', $hash, $result), $event->getRequest(), $event->getResponse());
     }
 }
 public function stripXmlNamespaces(CompleteEvent $event)
 {
     /**
      * Parsing XML with namespaces doesn't seem to work for Guzzle,
      * so using regex to remove them.
      */
     $xml = $event->getResponse()->getBody()->getContents();
     $xml = Utils::stripNamespacesFromXml($xml);
     /**
      * Intercept response and replace body with cleaned up XML
      */
     $stream = Stream::factory($xml);
     $response = $event->getResponse();
     $response->setBody($stream);
     $event->intercept($response);
 }
 public function cacheQuery(CompleteEvent $event, $name)
 {
     if (!$this->cache) {
         return;
     }
     $request = $event->getRequest();
     $content = (string) $event->getResponse()->getBody();
     //if content is empty, do not proceed with caching
     if (count($content) < 1 or $content == '' or $content == NULL) {
         return;
     }
     if ($request->getMethod() == 'GET' and $event->getResponse()->getStatusCode() == 200) {
         if (!$this->store->has($this->_cache_name)) {
             \Log::info('storing response in cache');
             $this->store->put($this->_cache_name, $content, $this->cache_ttl);
         }
     }
 }
 public function loginIfRequested(CompleteEvent $event)
 {
     if (($config = $this->buildSiteConfig($event->getRequest())) === false) {
         return;
     }
     if (!$config->requiresLogin()) {
         return;
     }
     $authenticator = $this->authenticatorFactory->buildFromSiteConfig($config);
     if ($authenticator->isLoginRequired($event->getResponse()->getBody())) {
         $client = $event->getClient();
         $emitter = $client->getEmitter();
         $emitter->detach($this);
         $authenticator->login($client);
         $emitter->attach($this);
         $event->retry();
     }
 }
Example #16
0
 public function cacheQuery(CompleteEvent $event, $name)
 {
     $request = $event->getRequest();
     $content = Base::parse($event->getResponse());
     //if content is empty, do not proceed with caching
     if (count($content) < 1 or $content == '' or $content == NULL) {
         return;
     }
     if ($request->getMethod() == 'GET' and $event->getResponse()->getStatusCode() == 200) {
         $url = Base::getBaseUrl($request->getUrl());
         if (!preg_match('/token|oauth/', $url)) {
             $ttl = $this->params['cache_ttl'];
             if (!$this->store->has($this->_cache_name)) {
                 \Log::info('storing response in cache');
                 $this->store->put($this->_cache_name, $content, $ttl);
             }
         }
     }
 }
Example #17
0
 /**
  * Called when a request receives a redirect response
  *
  * @param CompleteEvent $event Event emitted
  * @throws TooManyRedirectsException
  */
 public function onComplete(CompleteEvent $event)
 {
     $response = $event->getResponse();
     if (substr($response->getStatusCode(), 0, 1) != '3' || !$response->hasHeader('Location')) {
         return;
     }
     $redirectCount = 0;
     $redirectRequest = $event->getRequest();
     $redirectResponse = $response;
     $max = $redirectRequest->getConfig()->getPath('redirect/max') ?: 5;
     do {
         if (++$redirectCount > $max) {
             throw new TooManyRedirectsException("Will not follow more than {$redirectCount} redirects", $redirectRequest);
         }
         $redirectRequest = $this->createRedirectRequest($redirectRequest, $redirectResponse);
         $redirectResponse = $event->getClient()->send($redirectRequest);
     } while (substr($redirectResponse->getStatusCode(), 0, 1) == '3' && $redirectResponse->hasHeader('Location'));
     if ($redirectResponse !== $response) {
         $event->intercept($redirectResponse);
     }
 }
Example #18
0
 /**
  * Called when a request receives a redirect response
  *
  * @param CompleteEvent $event Event emitted
  * @throws TooManyRedirectsException
  */
 public function onComplete(CompleteEvent $event)
 {
     $response = $event->getResponse();
     if (substr($response->getStatusCode(), 0, 1) != '3' || !$response->hasHeader('Location')) {
         return;
     }
     $request = $event->getRequest();
     $config = $request->getConfig();
     // Increment the redirect and initialize the redirect state.
     if ($redirectCount = $config['redirect_count']) {
         $config['redirect_count'] = ++$redirectCount;
     } else {
         $config['redirect_scheme'] = $request->getScheme();
         $config['redirect_count'] = $redirectCount = 1;
     }
     $max = $config->getPath('redirect/max') ?: 5;
     if ($redirectCount > $max) {
         throw new TooManyRedirectsException("Will not follow more than {$redirectCount} redirects", $request);
     }
     $this->modifyRedirectRequest($request, $response);
     $event->retry();
 }
 private function handle304Response(RequestInterface $request, ResponseInterface $response, ResponseInterface $validated, CompleteEvent $event)
 {
     // Make sure that this response has the same ETag
     if ($validated->getHeader('ETag') !== $response->getHeader('ETag')) {
         // Revalidation failed, so remove from cache and retry.
         $this->storage->delete($request);
         $event->intercept($event->getClient()->send($request));
         return;
     }
     // Replace cached headers with any of these headers from the
     // origin server that might be more up to date
     $modified = false;
     foreach (self::$replaceHeaders as $name) {
         if ($validated->hasHeader($name) && $validated->getHeader($name) != $response->getHeader($name)) {
             $modified = true;
             $response->setHeader($name, $validated->getHeader($name));
         }
     }
     // Store the updated response in cache
     if ($modified) {
         $this->storage->cache($request, $response);
     }
 }
 /**
  * When the request is completed, it's cached.
  *
  * @param CompleteEvent $event Guzzle 4/5 event.
  *
  * @return void
  */
 public function onComplete(CompleteEvent $event)
 {
     $response = $event->getResponse();
     if (!Utils::canCacheResponse($response)) {
         return;
     }
     $request = $this->request;
     $keys = [$request->getMethod() . ' ' . $request->getUrl(), $request->getMethod() . ' ' . $response->getEffectiveUrl()];
     $ttl = $this->getTtl($response);
     foreach ($keys as $key) {
         $this->cache->save($key, $response, $ttl);
     }
 }
Example #21
0
 public function onComplete(CompleteEvent $event)
 {
     $this->add($event->getRequest(), $event->getResponse());
 }
 /**
  * @param CompleteEvent $event
  *
  * @throws \RuntimeException|ExceptionInterface
  */
 protected function handleResponse(CompleteEvent $event)
 {
     $this->response = $event->getResponse();
     if ($this->response->getStatusCode() >= 200 && $this->response->getStatusCode() <= 299) {
         return;
     }
     $body = $this->response->getBody();
     $code = $this->response->getStatusCode();
     if ($this->exception) {
         throw $this->exception->create($body, $code);
     }
     $content = $this->response->json();
     throw new \RuntimeException(sprintf('[%d] %s (%s)', $code, $content->message, $content->id), $code);
 }
 /**
  * Checks if the request and response can be cached, and if so, store it.
  *
  * @param CompleteEvent $event
  */
 public function onComplete(CompleteEvent $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     // Cache the response if it can be cached and isn't already
     if ($request->getConfig()->get('cache_lookup') === 'MISS' && call_user_func($this->canCache, $request) && Utils::canCacheResponse($response)) {
         // Store the date when the response was cached
         $response->setHeader('X-Guzzle-Cache-Date', gmdate('D, d M Y H:i:s T', time()));
         $this->storage->cache($request, $response);
     }
     $this->addResponseHeaders($request, $response);
 }
 /**
  * Checks if the request and response can be cached, and if so, store it
  */
 public function onComplete(CompleteEvent $event)
 {
     $request = $event->getRequest();
     $response = $event->getResponse();
     // Cache the response if it can be cached and isn't already
     if ($request->getConfig()->get('cache_lookup') === 'MISS' && call_user_func($this->canCache, $request) && Utils::canCacheResponse($response)) {
         $this->storage->cache($request, $response);
     }
     $this->addResponseHeaders($request, $response);
 }
 /**
  * @param CompleteEvent $event
  */
 public function onComplete(CompleteEvent $event)
 {
     $response = $event->getResponse();
     $response->setReasonPhrase($this->getErrorMessage($response));
     parent::onComplete($event);
 }
Example #26
0
 public function onComplete(CompleteEvent $event)
 {
     $this->cookieJar->extractCookies($event->getRequest(), $event->getResponse());
 }
 /**
  * @param CompleteEvent $e
  */
 public function onComplete(CompleteEvent $e)
 {
     $response = $e->getResponse();
     $this->log->debug(sprintf('Response code %s: %s', $response->getStatusCode(), $response->getReasonPhrase()));
 }
 /**
  * Method to handle complete events.
  *
  * @param CompleteEvent $event
  */
 public function onComplete(CompleteEvent $event)
 {
     // Stop measurement.
     $this->stopMeasure($event->getRequest(), $event->getResponse());
 }
 /**
  * 
  * @param CompleteEvent $event
  */
 public function onComplete(CompleteEvent $event)
 {
     $this->logger->log(substr($event->getResponse()->getStatusCode(), 0, 1) == '2' ? LogLevel::INFO : LogLevel::WARNING, $this->formatter->format($event->getRequest(), $event->getResponse()), ['request' => $event->getRequest(), 'response' => $event->getResponse()]);
     $this->rewindResponse($event->getResponse());
 }
Example #30
0
 /**
  * Callback called after a response has been received
  *
  * @param CompleteEvent $event
  */
 public function onResponse(CompleteEvent $event)
 {
     $this->lastResponse = $event->getResponse();
 }