Exemplo n.º 1
0
 private function processResponse(Response $response)
 {
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Status Code %s', $response->getStatusCode()));
         $this->logger->debug(var_export($response->getContent(), true));
     }
     if (500 <= $response->getStatusCode()) {
         throw new ApiServerException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (400 <= $response->getStatusCode()) {
         try {
             $error = $this->parser->parse($response->getContent());
             $error = $error instanceof Model\Error ? $error : new Model\Error();
         } catch (ApiParserException $e) {
             throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders(), null, $e);
         }
         throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders(), $error);
     }
     if (204 === $response->getStatusCode()) {
         return true;
     }
     $content = trim($response->getContent());
     if (empty($content)) {
         return true;
     }
     $object = $this->parser->parse($content);
     $object->setApi($this);
     return $object;
 }
Exemplo n.º 2
0
 public function testAddHeadersResetsStatusLine()
 {
     $response = new Response();
     $this->assertNull($response->getStatusCode());
     $response->addHeaders(array('HTTP/1.0 200 OK'));
     $this->assertEquals(200, $response->getStatusCode());
 }
Exemplo n.º 3
0
 /**
  * Check if request was successfully
  *
  * @param \Buzz\Message\Response $response
  * @return bool
  * @throws \RuntimeException
  */
 protected function isValidRequest(Response $response)
 {
     if ((int) $response->getStatusCode() == 401) {
         throw new \RuntimeException('Invalid Request');
     } elseif ((int) $response->getStatusCode() == 200) {
         return true;
     } elseif ((int) $response->getStatusCode() == 201) {
         return true;
     } elseif ((int) $response->getStatusCode() == 404) {
         throw new \RuntimeException('Page not found!');
     }
     throw new \RuntimeException('Unknown status type:' . $response->getStatusCode());
 }
Exemplo n.º 4
0
 /**
  * @param Request $request
  * @param Response $response
  * 
  * @return HttpException
  */
 public static function factory(Request $request, Response $response)
 {
     if ($response->isClientError()) {
         $label = 'Client error response';
     } elseif ($response->isServerError()) {
         $label = 'Server error response';
     } else {
         $label = 'Unsuccessful response';
     }
     $message = implode(PHP_EOL, array($label, '[status code] ' . $response->getStatusCode(), '[reason phrase] ' . $response->getReasonPhrase(), '[url] ' . $request->getUrl()));
     $e = new static($message, $response->getStatusCode());
     $e->setResponse($response);
     $e->setRequest($request);
     return $e;
 }
Exemplo n.º 5
0
 /**
  * Parse a response.
  *
  * @return \Tev\Bs\Contracts\ResponseInterface
  *
  * @throws \Exception
  * @throws \Tev\Bs\Exception\ErrorResponseException
  */
 public function getResponse()
 {
     $content = json_decode($this->response->getContent());
     if ($content === null) {
         throw new Exception('Failed to get response from server');
     }
     if (isset($content->error) && $content->error) {
         $excp = new ErrorResponseException($content->message, $this->response->getStatusCode());
         $excp->setResponse(new Response($content, $this->endpoint));
         throw $excp;
     }
     if (isset($content->per_page)) {
         return new PaginatedResponse($content, $this->endpoint);
     }
     return new Response($content, $this->endpoint);
 }
Exemplo n.º 6
0
 /**
  * Verifies the last request.
  * If the last request was not successful, it will be throw an exception.
  *
  * @param \Buzz\Message\Response $response The response object from the last reques
  * @param string $url The url which was requested
  * @return \Buzz\Message\Response
  * @throws \Exception
  */
 protected function verifyResult(\Buzz\Message\Response $response, $url)
 {
     if ($response->getStatusCode() !== 200) {
         throw new \Exception('Request to "' . $url . '" failed', 1364061673);
     }
     return $response;
 }
Exemplo n.º 7
0
 /**
  * @param Response $curlResponse
  *
  * @throws HttpStatusParserException
  */
 public function parse(Response $curlResponse)
 {
     $statusCode = $curlResponse->getStatusCode();
     if ($this->shouldThrowException($statusCode)) {
         throw new HttpStatusParserException($curlResponse->getContent(), $statusCode);
     }
 }
 /**
  * @param Buzz\Message\Response                        $response
  * @param AntiMattr\Twitter\Marketplace\Model\Merchant $merchant
  *
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\BadRequestException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\InternalErrorException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\NotFoundException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\UnauthorizedException
  */
 public function bind(Response $response, $merchant)
 {
     $status = $response->getStatusCode();
     if (400 == $status) {
         throw new BadRequestException();
     }
     if (401 == $status) {
         throw new UnauthorizedException();
     }
     if (404 == $status) {
         throw new NotFoundException();
     }
     if (500 == $status) {
         throw new InternalErrorException();
     }
     $content = $this->getContent($response);
     if (isset($content->support) && isset($content->support->email)) {
         $merchant->setSupportEmail($content->support->email);
     }
     if (isset($content->name)) {
         $merchant->setName($content->name);
     }
     if (isset($content->email)) {
         $merchant->setEmail($content->email);
     }
     if (isset($content->state)) {
         $merchant->setState(strtoupper($content->state));
     }
     if (isset($content->domains) && is_array($content->domains)) {
         $collection = new ArrayCollection($content->domains);
         $merchant->setDomains($collection);
     }
     if (isset($content->id)) {
         $merchant->setId($content->id);
     }
     if (isset($content->external_id)) {
         $merchant->setExternalId($content->external_id);
     }
     if (isset($content->address)) {
         $data = $content->address;
         $address = $merchant->getAddress();
         if (isset($data->city)) {
             $address->setLocality($data->city);
         }
         if (isset($data->state)) {
             $address->setRegion($data->state);
         }
         if (isset($data->street1)) {
             $address->setStreetAddressLine1($data->street1);
         }
         if (isset($data->country)) {
             $address->setCountry($data->country);
         }
         if (isset($data->postal_code)) {
             $address->setPostalCode($data->postal_code);
         }
     }
 }
 /**
  * @param string|null $message
  */
 public function __construct(RequestInterface $request, Response $response, $message = null)
 {
     $this->request = $request;
     $this->response = $response;
     if ($message === null) {
         $curlError = $response->getHeader('X-Curl-Error-Result');
         $message = sprintf('HTTP %s request to "%s%s" failed: %d - "%s".', $request->getMethod(), $request->getHost(), $request->getResource(), $curlError ?: $response->getStatusCode(), $curlError ? curl_strerror($curlError) : $response->getReasonPhrase());
     }
     parent::__construct($message);
 }
 /**
  * @param Response $response
  * @return ProxyMediaInterface
  *
  * @throws MediaStorageClientManagerNotFoundException
  * @throws MediaStorageClientProxyMediaManagerException
  */
 public function createFromResponse(Response $response)
 {
     if ($response && $response->isOk()) {
         $content = json_decode($response->getContent(), true);
         if ($content && !json_last_error() && is_array($content)) {
             $content = new ArrayCollection($content);
         } else {
             throw new MediaStorageClientProxyMediaManagerException('Client not response new value');
         }
     } elseif ($response->getStatusCode() == 404) {
         throw new MediaStorageClientManagerNotFoundException(sprintf('Unable to find the object'));
     } else {
         throw new MediaStorageClientProxyMediaManagerException('Client response code: ' . $response->getStatusCode());
     }
     $proxyMedia = $this->create();
     $proxyMedia->setReferenceFull($content->get('reference_full'));
     $proxyMedia->setName($content->get('name'));
     $proxyMedia->setProviderMetadata($content->toArray());
     return $proxyMedia;
 }
Exemplo n.º 11
0
 protected function assertHttpResponseCodeEquals(HttpResponse $response, $expected)
 {
     $responseCode = $response->getStatusCode();
     if ($responseCode != $expected) {
         $errorMessageString = '';
         if (strpos($response->getHeader('Content-Type'), 'application/vnd.ez.api.ErrorMessage+xml') !== false) {
             $body = \simplexml_load_string($response->getContent());
             $errorMessageString = $this->getHttpResponseCodeErrorMessage($body);
         } elseif (strpos($response->getHeader('Content-Type'), 'application/vnd.ez.api.ErrorMessage+json') !== false) {
             $body = json_decode($response->getContent());
             $errorMessageString = $this->getHttpResponseCodeErrorMessage($body->ErrorMessage);
         }
         self::assertEquals($expected, $responseCode, $errorMessageString);
     }
 }
Exemplo n.º 12
0
 /**
  * Converts a buzz response to a pinterest response.
  *
  * @param Request      $request      The request.
  * @param BuzzResponse $buzzResponse The buzz response.
  *
  * @return Response The response.
  */
 private static function convertResponse(Request $request, BuzzResponse $buzzResponse)
 {
     $statusCode = $buzzResponse->getStatusCode();
     $rawBody = (string) $buzzResponse->getContent();
     $rawHeaders = $buzzResponse->getHeaders();
     $headers = array();
     foreach ($rawHeaders as $header) {
         if (stristr($header, 'HTTP/1.')) {
             continue;
         }
         list($key, $value) = explode(': ', $header);
         $headers[$key] = $value;
     }
     return new Response($request, $statusCode, $rawBody, $headers);
 }
Exemplo n.º 13
0
 protected function assertHttpResponseCodeEquals(HttpResponse $response, $expected)
 {
     $responseCode = $response->getStatusCode();
     if ($responseCode != $expected) {
         $errorMessageString = '';
         if ($response->getHeader('Content-Type') == 'application/vnd.ez.api.ErrorMessage+xml') {
             $body = \simplexml_load_string($response->getContent());
             $errorMessageString = $body->errorDescription;
         } elseif ($response->getHeader('Content-Type') == 'application/vnd.ez.api.ErrorMessage+json') {
             $body = json_decode($response->getContent());
             $errorMessageString = "Error message: {$body->ErrorMessage->errorDescription}";
         }
         self::assertEquals($expected, $responseCode, $errorMessageString);
     }
 }
 /**
  * @param Buzz\Message\Response                     $response
  * @param AntiMattr\Twitter\Marketplace\Model\Order $order
  *
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\BadRequestException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\InternalErrorException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\NotFoundException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\UnauthorizedException
  */
 public function bind(Response $response, $order)
 {
     $status = $response->getStatusCode();
     if (400 == $status) {
         throw new BadRequestException();
     }
     if (401 == $status) {
         throw new UnauthorizedException();
     }
     if (404 == $status) {
         throw new NotFoundException();
     }
     if (500 == $status) {
         throw new InternalErrorException();
     }
 }
 /**
  * @param Response $response
  * @return mixed
  * @throws BadAuthentificationException
  */
 public function handleResponse(Response $response)
 {
     $data = json_decode($response->getContent(), true);
     if ($response->getStatusCode() != 200) {
         if (!$data) {
             $e = new BadAuthentificationException("Authentification request has failed : {$response}");
             $e->setOAuthErrorName("undefined");
             $e->setOAuthErrorDescription("Can't handle API response.");
             throw $e;
         }
         $e = new BadAuthentificationException(sprintf("OAuth exception. %s : %s", $data['error'], $data['error_description']));
         $e->setOAuthErrorName($data['error']);
         $e->setOAuthErrorDescription($data['error_description']);
         throw $e;
     }
     return $data;
 }
 /**
  * @param Response $response
  * @param object   $tracking
  *
  * @throws DuplicateException
  * @throws NotFoundException
  * @throws InvalidCourierException
  * @throws InvalidNumberException
  * @throws BadRequestException
  * @throws UnauthorizedException
  */
 protected function handleError(Response $response, $tracking)
 {
     $statusCode = $response->getStatusCode();
     if ('400' == $statusCode && '4003' == $this->getErrorCode($response)) {
         $message = $this->getErrorMessage($response, 'Tracking already exists.');
         $exception = new DuplicateException($message);
         $content = $this->getContent($response);
         if (isset($content->data)) {
             $exception->setData($content->data);
         }
         throw $exception;
     } elseif ('400' == $statusCode && '4004' == $this->getErrorCode($response)) {
         $message = $this->getErrorMessage($response, 'Tracking does not exist.');
         $exception = new NotFoundException($message);
         $content = $this->getContent($response);
         if (isset($content->data)) {
             $exception->setData($content->data);
         }
         throw $exception;
     } elseif ('400' == $statusCode && '4005' == $this->getErrorCode($response)) {
         $message = $this->getErrorMessage($response, 'The value of `tracking_number` is invalid.');
         $exception = new InvalidNumberException($message);
         $content = $this->getContent($response);
         if (isset($content->data)) {
             $exception->setData($content->data);
         }
         throw $exception;
     } elseif ('400' == $statusCode && '4012' == $this->getErrorCode($response)) {
         $message = $this->getErrorMessage($response, 'Cannot detect courier. Activate courier at https://www.aftership.com/settings/courier');
         $exception = new InvalidCourierException($message);
         $content = $this->getContent($response);
         if (isset($content->data)) {
             $exception->setData($content->data);
         }
         throw $exception;
     } elseif ('400' == $statusCode) {
         $message = $this->getErrorMessage($response, 'Bad Request.');
         throw new BadRequestException($message);
     } elseif ('401' == $statusCode) {
         $message = $this->getErrorMessage($response, 'Invalid API key.');
         throw new UnauthorizedException($message);
     }
 }
 /**
  * @param Buzz\Message\Response $response
  * @param Doctrine\Common\Collections\Collection $collection
  *
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\BadRequestException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\InternalErrorException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\NotFoundException
  * @throws AntiMattr\Twitter\Marketplace\Exception\Http\UnauthorizedException
  */
 public function bind(Response $response, $collection)
 {
     $status = $response->getStatusCode();
     if (400 == $status) {
         $errors = $this->getErrors($response);
         $message = sprintf("Exception: Failed urls %s", implode(",", $errors));
         throw new BadRequestException($message);
     }
     if (401 == $status) {
         throw new UnauthorizedException();
     }
     if (404 == $status) {
         throw new NotFoundException();
     }
     if (500 == $status) {
         throw new InternalErrorException();
     }
     if (200 == $status && ($errors = $this->getErrors($response))) {
         $message = sprintf("Exception: Failed urls %s", implode(",", $errors));
         throw new BadRequestException($message);
     }
 }
Exemplo n.º 18
0
 private function processResponse(Response $response)
 {
     if (null !== $this->logger) {
         $this->logger->info(sprintf('Status Code %s', $response->getStatusCode()));
         $this->logger->debug(var_export($response->getContent(), true));
     }
     if (500 <= $response->getStatusCode()) {
         throw new ApiServerException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (400 <= $response->getStatusCode()) {
         throw new ApiClientException($response->getStatusCode(), $response->getContent(), $response->getReasonPhrase(), $response->getHeaders());
     }
     if (204 === $response->getStatusCode()) {
         return true;
     }
     if (null !== $response->getContent()) {
         $object = $this->parser->parse($response->getContent());
         $object->setApi($this);
         return $object;
     }
 }
Exemplo n.º 19
0
 /**
  * Converts a Buzz response into a PSR response.
  *
  * @param BuzzResponse $response
  *
  * @return ResponseInterface
  */
 private function createResponse(BuzzResponse $response)
 {
     $body = $response->getContent();
     return $this->responseFactory->createResponse($response->getStatusCode(), null, $this->getBuzzHeaders($response), $body, number_format($response->getProtocolVersion(), 1));
 }
Exemplo n.º 20
0
 public function __construct($method, Response $response)
 {
     $this->method = $method;
     $this->response = $response;
     parent::__construct('The server responded with a ' . $response->getStatusCode() . ' status code in method ' . $method . ': ' . $response->getContent());
 }
 /**
  * @param Response   $response
  * @param Collection $collection
  *
  * @throws BadRequestException
  */
 protected function handleError(Response $response, Collection $collection)
 {
     $statusCode = $response->getStatusCode();
     if ('200' != $statusCode) {
         $message = $this->getErrorMessage($response, 'Bad Request.');
         throw new BadRequestException($message);
     }
 }
Exemplo n.º 22
0
 /**
  * @param Response $response
  *
  * @return \Exception
  */
 protected function handleResponse(Response $response)
 {
     if ($this->exception) {
         return $this->exception->create($response->getContent(), $response->getStatusCode());
     }
     $content = json_decode($response->getContent());
     return new \RuntimeException(sprintf('[%d] %s (%s)', $response->getStatusCode(), $content->message, $content->id));
 }
 /**
  * Checks if we had a successfull response with Json content in it
  *
  * @param Response $response
  * @return bool
  */
 protected function isJsonResponse(Response $response)
 {
     return $response->getStatusCode() == 200 && $response->getHeader('content-type') == 'application/json';
 }
Exemplo n.º 24
0
 /**
  * @Then /^the response status code should be (\d+)$/
  * @param  int        $httpStatus
  * @return void
  * @throws \Exception
  */
 public function theResponseStatusCodeShouldBe($httpStatus)
 {
     if ((string) $this->response->getStatusCode() !== $httpStatus) {
         throw new \Exception(sprintf('HTTP code does not match %s (actual: %s)', $httpStatus, $this->response->getStatusCode()));
     }
 }
Exemplo n.º 25
0
 /**
  * @param \Buzz\Message\Response $response
  *
  * @throws HttpException if status not OK
  * @throws HttpException if content not json
  *
  * @return \stdClass|\stdClass[]|null
  */
 protected function getResult(Response $response)
 {
     if (false == $response->isSuccessful()) {
         throw new HttpException($response->getStatusCode(), sprintf("The api call finished with status %s but it was expected 200. Response content:\n\n%s", $response->getStatusCode(), $response->getContent()));
     }
     $content = $response->getContent();
     $result = null;
     if (false == empty($content)) {
         $result = json_decode($response->getContent());
         if (null === $result) {
             throw new LogicException(sprintf("The response status is successful but the content is not a valid json object:\n\n%s", $response->getContent()));
         }
     }
     return $result;
 }
Exemplo n.º 26
0
 protected function getSessionIdFromResponse(Response $response)
 {
     $statusCode = $response->getStatusCode();
     if ($statusCode === 200) {
         $content = json_decode($response->getContent(), true);
         if ($content['status'] !== 0) {
             throw new LibraryException(sprintf('Expected status 0, got "%s".', $content['status']));
         }
         return $content['sessionId'];
     }
     if ($statusCode !== 302) {
         echo $response->getContent();
         throw new LibraryException(sprintf('The response should be a redirection, response code from server was "%s"', $statusCode));
     }
     $location = $response->getHeader('Location');
     if (!preg_match('#/session/([0-9a-f\\-]+)?#', $location, $vars)) {
         throw new LibraryException(sprintf('The Location should end with /session/<session-id> (location returned: %s)', $location));
     }
     return $vars[1];
 }
 /**
  * Handles and parses the response
  * Returns a value indicating success/fail
  *
  * @param  \Buzz\Message\Response $response
  * @return bool
  */
 protected function parseResponse(\Buzz\Message\Response $response)
 {
     if (null !== $response->getStatusCode() && $response->getStatusCode() != 200) {
         return false;
     }
     $doc = new \DOMDocument();
     $doc->loadXML($response->getContent());
     $elems = $doc->getElementsByTagName("response-result");
     if (!$elems->length) {
         $this->logger->error('Response is empty');
         return false;
     }
     $responseElement = $elems->item(0);
     if ($responseElement->getAttribute("code") != "1001") {
         $this->logger->error($responseElement->getAttribute("code") . ' : ' . $responseElement->getAttribute("desc"));
     }
     return $responseElement->getAttribute("code") == "1001";
 }
Exemplo n.º 28
0
 /**
  * @param  Response $response
  * @param  string                $method
  * @param  array                 $arguments
  * @return \stdClass
  * @throws \RuntimeException
  */
 protected function validateResponse($response, $method, $arguments)
 {
     if (!in_array($response->getStatusCode(), array(200, 401, 409))) {
         throw new \RuntimeException('Unexpected response received from Transmission');
     }
     if ($response->getStatusCode() == 401) {
         throw new \RuntimeException('Access to Transmission requires authentication');
     }
     if ($response->getStatusCode() == 409) {
         $this->setToken($response->getHeader(self::TOKEN_HEADER));
         return $this->call($method, $arguments);
     }
     return json_decode($response->getContent());
 }
Exemplo n.º 29
0
 /**
  * @param Response $response
  *
  * @throws HttpException
  */
 protected function handleError(Response $response)
 {
     $body = (string) $response->getContent();
     $code = (int) $response->getStatusCode();
     $content = json_decode($response->getContent());
     throw new HttpException(isset($content->message) ? $content->message : 'Request not processed.', $code);
 }
Exemplo n.º 30
0
 /**
  * @param RequestInterface $request
  * @param Response         $response
  */
 private function logResponse(RequestInterface $request, Response $response)
 {
     $this->logger->debug(sprintf('Request to %s%s with content "%s" was send and response with content "%s" and status %d received', $request->getHost(), $request->getResource(), $request->getContent(), $response->getContent(), $response->getStatusCode()));
 }