public function notifyWhenResponseIsComplete()
 {
     parent::$stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
         print 'Response!' . PHP_EOL;
         return $response;
     }));
 }
Пример #2
0
 public function __construct()
 {
     static::init();
     $Stack = new HandlerStack();
     $Stack->setHandler(new CurlHandler());
     /**
      * Здесь ставим ловушку, чтобы с помощью редиректов
      *   определить адрес сервера, который сможет отсылать сообщения
      */
     $Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) {
         $code = $Response->getStatusCode();
         if ($code >= 301 && $code <= 303 || $code == 307 || $code == 308) {
             $location = $Response->getHeader('Location');
             preg_match('/https?://([^-]*-)client-s/', $location, $matches);
             if (array_key_exists(1, $matches)) {
                 $this->cloud = $matches[1];
             }
         }
         return $Response;
     }));
     /**
      * Ловушка для отлова хедера Set-RegistrationToken
      * Тоже нужен для отправки сообщений
      */
     $Stack->push(Middleware::mapResponse(function (ResponseInterface $Response) {
         $header = $Response->getHeader("Set-RegistrationToken");
         if (count($header) > 0) {
             $this->regToken = trim(explode(';', $header[0])[0]);
         }
         return $Response;
     }));
     //$cookieJar = new FileCookieJar('cookie.txt', true);
     $this->client = new Client(['handler' => $Stack, 'cookies' => true]);
 }
Пример #3
0
 /**
  * @param string $clientId
  * @param string $clientSecret
  */
 public function __construct($clientId, $clientSecret)
 {
     $stack = HandlerStack::create();
     $stack->push(Middleware::mapResponse(function (Response $response) {
         $jsonStream = new JsonStream($response->getBody());
         return $response->withBody($jsonStream);
     }));
     $guzzle = new Guzzle(['base_uri' => 'https://api.shutterstock.com/v2/', 'auth' => [$clientId, $clientSecret], 'handler' => $stack]);
     $this->guzzle = $guzzle;
 }
Пример #4
0
 /**
  * @return callable
  */
 public function getCallable()
 {
     return Middleware::mapResponse(function (ResponseInterface $response) {
         if ($response->hasHeader(AbstractHttpClient::HEADER_HOST_ZED)) {
             $message = sprintf('Transfer response [%s]', $response->getStatusCode());
             $this->getLogger()->info($message, ['guzzle-body' => $response->getBody()->getContents()]);
         }
         return $response;
     });
 }
 public function testConstructSetsJsonMiddleware()
 {
     $stack = HandlerStack::create();
     $stack->push(Middleware::mapResponse(function (Response $response) {
         $jsonStream = new JsonStream($response->getBody());
         return $response->withBody($jsonStream);
     }));
     $guzzle = new Guzzle(['base_uri' => 'https://api.shutterstock.com/v2/', 'auth' => ['client_id', 'client_secret'], 'handler' => $stack]);
     $client = $this->getClient();
     $this->assertAttributeEquals($guzzle, 'guzzle', $client);
 }
Пример #6
0
 private function errorHandler()
 {
     $handler = \GuzzleHttp\HandlerStack::create();
     $handler->push(\GuzzleHttp\Middleware::mapResponse(function ($response) {
         if ($response->getStatusCode() >= 400) {
             $data = json_decode($response->getBody());
             throw new Exception(sprintf('%s %s – %s', $response->getStatusCode(), $data->error, $data->detail));
         }
         return $response;
     }));
     return $handler;
 }
Пример #7
0
 /**
  * @return HandlerStack
  */
 protected function getGuzzleHandler()
 {
     $handler = HandlerStack::create();
     $handler->push(Middleware::mapResponse(function (ResponseInterface $response) {
         $this->lastResponse = $response;
         return $response;
     }));
     $handler->push(Middleware::mapRequest(function (RequestInterface $request) {
         $this->lastRequest = $request;
         return $request;
     }));
     return $handler;
 }
 public function testMapsResponse()
 {
     $h = new MockHandler([new Response(200)]);
     $stack = new HandlerStack($h);
     $stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
         return $response->withHeader('Bar', 'foo');
     }));
     $comp = $stack->resolve();
     $p = $comp(new Request('PUT', 'http://www.google.com'), []);
     $p->wait();
     $this->assertEquals('foo', $p->wait()->getHeaderLine('Bar'));
 }
Пример #9
0
 /**
  * @codeCoverageIgnore
  */
 public static function mapResponse(callable $fn) : callable
 {
     return GuzzleMiddleware::mapResponse($fn);
 }
Пример #10
0
 private function buildClientAndRequest()
 {
     $this->logger->info("Getting Request Client");
     $stack = new HandlerStack();
     $stack->setHandler(new CurlHandler());
     $stack->push(Middleware::mapRequest(function (RequestInterface $request) {
         return $this->addRequestHeaders($request);
     }));
     $stack->push(Middleware::mapResponse(function (ResponseInterface $response) {
         $this->logger->info('Response status code: ' . $response->getStatusCode());
         $this->validateResponse($response);
         return $response;
     }));
     $this->client = new Client(['handler' => $stack, 'base_uri' => $this->baseAddress, 'verify' => false]);
     $this->logger->info("Request URI : " . $this->mozuUrl->getUrl());
     $this->request = new Psr7\Request($this->mozuUrl->getVerb(), $this->mozuUrl->getUrl(), array(), $this->requestBody);
 }
Пример #11
0
 /**
  * Test invalid rights
  */
 public function testInvalidRight()
 {
     $this->setExpectedException('\\GuzzleHttp\\Exception\\ClientException');
     $handlerStack = $this->client->getConfig('handler');
     $handlerStack->push(Middleware::mapResponse(function (Response $response) {
         $body = $response->getBody();
         $body->write('{\\"message\\":\\"Invalid credentials\\"}');
         return $response->withStatus(403)->withHeader('Content-Type', 'application/json; charset=utf-8')->withHeader('Content-Length', 37)->withBody($body);
     }));
     $api = new Api($this->application_key, $this->application_secret, $this->endpoint, $this->consumer_key, $this->client);
     $invoker = self::getPrivateMethod('rawCall');
     $invoker->invokeArgs($api, ['GET', '/me']);
 }
Пример #12
0
 /**
  *
  * @param \Kazoo\SDK $sdk
  */
 public function __construct(SDK $sdk)
 {
     $this->setSDK($sdk);
     $sdk = $this->getSDK();
     $options = $sdk->getOptions();
     $handler = HandlerStack::create();
     $handler->push(Middleware::mapRequest(function (Request $request) {
         $sdk = $this->getSDK();
         $token = $sdk->getAuthToken()->getToken();
         return $request->withHeader('X-Auth-Token', $token);
     }));
     $handler->push(Middleware::mapResponse(function (GuzzleResponse $guzzleResponse) {
         $response = new Response($guzzleResponse);
         $code = $response->getStatusCode();
         switch ($code) {
             case 400:
                 throw new Validation($response);
             case 401:
                 // invalid creds
                 throw new Unauthenticated($response);
             case 402:
                 // not enough credit
                 throw new Billing($response);
             case 403:
                 // forbidden
                 throw new Unauthorized($response);
             case 404:
                 // not found
                 throw new NotFound($response);
             case 405:
                 // invalid method
                 throw new InvalidMethod($response);
             case 409:
                 // conflicting documents
                 throw new Conflict($response);
             case 429:
                 // too many requests
                 throw new RateLimit($response);
             default:
                 if ($code >= 400 && $code < 500) {
                     throw new ApiException($response);
                 } else {
                     if ($code > 500) {
                         throw new HttpException($response);
                     }
                 }
         }
         return $guzzleResponse;
     }));
     $options['handler'] = $handler;
     $this->setClient(new GuzzleClient($options));
 }