/** * Build the API response from the given HTTP response * * @param Response $httpResponse */ public function __construct(Response $httpResponse) { $this->setHttpResponse($httpResponse); // Looking for HTTP error $statusCode = $this->httpResponse->getStatusCode(); if (!($statusCode > 199 && $statusCode < 300)) { $this->isError = true; $this->setErrorMessage($this->httpResponse->getReasonPhrase()); } $contentType = $httpResponse->getHeaders()->get('content-type')->getFieldValue(); if (strpos($contentType, 'application/vnd.zend.serverapi+xml') === 0) { // Looking for XML error libxml_use_internal_errors(true); $xml = simplexml_load_string($httpResponse->getBody()); if (!$xml) { $errorMessage = ''; foreach (libxml_get_errors() as $error) { $errorMessage .= $error->message . "\n"; } $this->isError = true; $this->setErrorMessage($errorMessage); return; } // Lookign for API error if ($xml->errorData) { $this->isError = true; $this->setErrorMessage((string) $xml->errorData->errorMessage); $this->setApiErrorCode((string) $xml->errorData->errorCode); return; } $this->setXml($xml); } }
/** * Sets the default response values (server raw response, return code, return message and request name) * * @param ActionResponseInterface $actionResponse */ protected function setDefaultResponseValues(ActionResponseInterface $actionResponse) { $this->serverRawResponse = $actionResponse->getResponse(); $this->returnCode = $this->serverRawResponse->getStatusCode(); $this->returnMessage = $this->serverRawResponse->getReasonPhrase(); $this->requestName = $actionResponse->getRequestName(); }
protected function dispatchRequestAndDecodeResponse($url, $method, $data = null) { $request = new Request(); $this->lastResponse = null; $request->getHeaders()->addHeaders(array('Content-Type' => 'application/x-www-form-urlencoded; charset=UTF-8', 'Accept' => 'application/json', 'User-Agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:37.0) Gecko/20100101 Firefox/37.0')); if (!empty($this->host)) { $request->getHeaders()->addHeaders(array('Host' => $this->host)); } if (!empty($this->key)) { $request->getHeaders()->addHeaders(array('Authorization' => 'Bearer ' . $this->key)); } $request->setUri($url); $request->setMethod($method); if (is_null($data)) { $data = array(); } if (isset($this->key)) { $data["auth"] = $this->key; } if ($method == "POST" || $method == "PUT") { $request->setPost(new Parameters($data)); if (isset($this->key)) { $request->setQuery(new Parameters(array('auth' => $this->key))); } } else { $request->setQuery(new Parameters($data)); } $this->lastResponse = $this->httpClient->send($request); if ($this->lastResponse->isSuccess()) { return json_decode($this->lastResponse->getBody(), true); } else { return array('error' => true, 'headers' => array("code" => $this->lastResponse->getStatusCode(), "reasons" => $this->lastResponse->getReasonPhrase()), 'body' => json_decode($this->lastResponse->getBody(), true)); } }
/** * @param HttpResponse $response * * @return $this */ public function setFromResponseObj(HttpResponse $response) { if ($response->isSuccess()) { $this->setStatus($response->isSuccess()); } else { $this->setError($response->getReasonPhrase()); } return $this; }
/** * Exception factory. * * Returns a RequestErrorException or RemoteErrorException depending on * the response's status code. * * @param Response $response Server response * * @return RequestErrorException|RemoteErrorException */ public static function createFromResponse(Response $response) { $status = $response->getStatusCode(); $phrase = $response->getReasonPhrase(); if ($status >= 500) { return new RemoteErrorException($status . ' ' . $phrase, $status, $response); } else { return new RequestErrorException($status . ' ' . $phrase, $status, $response); } }
/** * Construtor. * * @param Zend\Http\Client $client * @param Zend\Http\Response $response */ public function __construct(ZendHttpClient $client, ZendHttpResponse $response, $depth = 0) { $this->httpClient = $client; $this->httpResponse = $response; if (!$this->httpResponse->isSuccess()) { $error = json_decode($this->httpResponse->getBody()); if (empty($error)) { $error = new \stdClass(); $error->status = $this->httpResponse->getStatusCode(); $error->title = $this->httpResponse->getReasonPhrase(); $error->detail = ''; } if (!isset($error->status)) { $error->status = 500; } if (!isset($error->detail)) { $error->detail = 'An error occurred.'; } throw new RuntimeException(json_encode($error, null, 100), $error->status); } if (!$this->httpResponse->getHeaders()->has('Content-Type')) { throw new RuntimeException("Missing 'Content-Type' header.", 500); } $contentType = $this->httpResponse->getHeaders()->get('Content-Type')->getFieldValue(); $pos = strpos($contentType, ';'); if ($pos !== false) { $contentType = substr($contentType, 0, $pos); } if (empty($this->httpResponse->getBody())) { $this->content = null; } elseif ($contentType == 'application/hal+json' || $contentType == 'application/json') { $this->content = new Resource(Hal::fromJson($this->httpResponse->getBody(), $depth)); } elseif ($contentType == 'application/hal+xml' || $contentType == 'application/xml') { $this->content = new Resource(Hal::fromXml($this->httpResponse->getBody(), $depth)); } else { throw new RuntimeException("Unable to handle content type '{$contentType}' for response: '{$this->httpResponse->getBody()}'.", 500); } }
/** * @param Response $response * * @throws Exception\ClientException * * @return mixed */ protected function decodeBody(Response $response) { if ($response->isServerError()) { throw new Exception\ClientException(sprintf("'%s' provider encountered a '%s' error while querying '%s'", $this->getIdentifier(), $response->getReasonPhrase(), $this->uri)); } $body = Json::decode($response->getBody()); if ($response->isClientError()) { throw new Exception\ClientException($body->error->message, $response->getStatusCode()); } return $body; }
/** * @param int $status * @param array $body */ private function rawResponse($status, $body) { $zfResponse = new ZfResponse(); $zfResponse->setStatusCode($status); $reasonPhrase = $zfResponse->getReasonPhrase(); \header('HTTP/1.0 ' . $status . ' ' . $reasonPhrase); \header('Content-Type: application/json'); die(json_encode($body)); }
/** * @param array $bodyDecodeResponse * @param Response $response * @return Exception\ApiProblem\DomainException|Exception\InvalidResponseException */ protected function getInvalidResponseException(array $bodyDecodeResponse, Response $response) { $contentType = $response->getHeaders()->get('Content-Type'); if ($contentType instanceof ContentType && $contentType->match('application/problem+*')) { $apiProblemDefaults = ['type' => $response->getReasonPhrase(), 'title' => '', 'status' => $response->getStatusCode(), 'detail' => '', 'instance' => '']; $bodyDecodeResponse += $apiProblemDefaults; //Setup remote exception $remoteExceptionStack = isset($bodyDecodeResponse['exception_stack']) && is_array($bodyDecodeResponse['exception_stack']) ? $bodyDecodeResponse['exception_stack'] : []; array_unshift($remoteExceptionStack, ['message' => $bodyDecodeResponse['detail'], 'code' => $bodyDecodeResponse['status'], 'trace' => isset($bodyDecodeResponse['trace']) ? $bodyDecodeResponse['trace'] : null]); //Setup exception $exception = new Exception\ApiProblem\DomainException($bodyDecodeResponse['detail'], $bodyDecodeResponse['status'], Exception\RemoteException::factory($remoteExceptionStack)); $exception->setType($bodyDecodeResponse['type']); $exception->setTitle($bodyDecodeResponse['title']); foreach ($apiProblemDefaults as $key => $value) { unset($bodyDecodeResponse[$key]); } $exception->setAdditionalDetails($bodyDecodeResponse); } else { $exception = new Exception\InvalidResponseException($response->getReasonPhrase(), $response->getStatusCode()); $exception->setResponse($response); } return $exception; }
/** * Prepare a solarium response from the given request and client * response * * @throws HttpException * @param Request $request * @param \Zend\Http\Response $response * @return Response */ protected function prepareResponse($request, $response) { if ($response->isClientError()) { throw new HttpException($response->getReasonPhrase(), $response->getStatusCode()); } if ($request->getMethod() == Request::METHOD_HEAD) { $data = ''; } else { $data = $response->getBody(); } // this is used because in ZF2 status line isn't in the headers anymore $headers = array($response->renderStatusLine()); return new Response($data, $headers); }
/** * @param HttpResponse $response * @throws Exception\InvalidCredentialsException * @throws Exception\ValidationErrorException * @throws Exception\RuntimeException * @return array */ private function parseResponse(HttpResponse $response) { $result = json_decode($response->getBody(), true); if ($response->isSuccess()) { return $result; } switch ($response->getStatusCode()) { case 400: throw new Exception\ValidationErrorException(sprintf('An error occured on Mailgun, reason: %s', $response->getReasonPhrase())); case 401: throw new Exception\InvalidCredentialsException('Authentication error: missing or incorrect Mailgun authorization'); case 402: throw new Exception\RuntimeException(sprintf('An error occured on Mailgun, reason: %s', $response->getReasonPhrase())); case 500: case 502: case 503: case 504: throw new Exception\RuntimeException('Mailgun server error, please try again'); default: throw new Exception\RuntimeException('Unknown error during request to Mailgun server'); } }
protected function processResponse(Response $response) { if (!$response->isSuccess()) { $data = json_decode($response->getBody(), self::JSON_DECODE_TYPE_ARRAY, self::JSON_DECODE_DEPTH); if (is_array($data) && array_key_exists('status', $data) && is_array($data['status']) && array_key_exists('code', $data['status']) && array_key_exists('message', $data['status'])) { throw new RuntimeException($data['status']['message'], $data['status']['code'], new RuntimeException($response, -1, new RuntimeException($this->getClient()->getLastRawRequest()))); } throw new RuntimeException($response->getReasonPhrase(), $response->getStatusCode(), new RuntimeException($response, -1, new RuntimeException($this->getClient()->getLastRawRequest()))); } $data = json_decode($response->getBody(), self::JSON_DECODE_TYPE_ARRAY, self::JSON_DECODE_DEPTH); if (!is_array($data)) { throw new RuntimeException($response->getReasonPhrase(), $response->getStatusCode(), new RuntimeException($response, -1, new RuntimeException($this->getClient()->getLastRawRequest()))); } if (is_array($data) && array_key_exists('status', $data) && is_array($data['status']) && array_key_exists('code', $data['status']) && array_key_exists('message', $data['status']) && $data['status']['code'] < 0) { throw new RuntimeException($data['status']['message'], $data['status']['code'], new RuntimeException($response, -1, new RuntimeException($this->getClient()->getLastRawRequest()))); } return $data; }
private function handleException(Response $resp) { // TODO: test coverage if ($resp->isClientError()) { if ($resp->getStatusCode() === 403) { throw new AuthenticationException($this->apiKey, $this->apiSecret, null); } else { throw new DomainException('The OpenTok API request failed: ' . $resp->getReasonPhrase(), null); } } elseif ($resp->isServerError()) { throw new UnexpectedValueException('The OpenTok API server responded with an error: ' . $resp->getReasonPhrase(), null); } else { throw new Exception('An unexpected error occurred:' . $resp->getReasonPhrase()); } }