public function testResponseCanSetCustomStatusCode() { $response = new Response(); $this->assertEquals(200, $response->getStatusCode()); $response->setCustomStatusCode('999'); $this->assertEquals(999, $response->getStatusCode()); }
public function testResponseCanSetStatusCode() { $response = new Response(); $this->assertEquals(200, $response->getStatusCode()); $response->setStatusCode('303'); $this->assertEquals(303, $response->getStatusCode()); }
/** * 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(); }
/** * 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); } }
/** * {@inheritdoc} * @see \InoOicClient\Oic\AbstractResponseHandler::handleResponse() */ public function handleResponse(\Zend\Http\Response $httpResponse) { $responseData = null; $decodeException = null; try { $responseData = $this->getJsonCoder()->decode($httpResponse->getBody()); } catch (\Exception $e) { $decodeException = $e; } if (!$httpResponse->isSuccess()) { if (isset($responseData[Param::ERROR])) { $error = $this->getErrorFactory()->createErrorFromArray($responseData); $this->setError($error); return; } else { throw new HttpErrorStatusException(sprintf("Error code '%d' from server", $httpResponse->getStatusCode())); } } if (null !== $decodeException) { throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $decodeException); } try { $this->response = $this->getResponseFactory()->createResponse($responseData); } catch (\Exception $e) { throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e); } }
/** * @Then the status code should be :code */ public function theStatusCodeShouldBe($code) { if ($this->response->getStatusCode() != $code) { echo $this->response->getBody(); } \PHPUnit_Framework_Assert::assertEquals($code, $this->response->getStatusCode()); }
/** * Parses the HTTP response from a userinfo request. * * @param Http\Response $httpResponse * @throws HttpAuthenticateException * @throws HttpErrorStatusException * @throws InvalidResponseFormatException * @throws Exception\InvalidResponseException */ public function handleResponse(Http\Response $httpResponse) { if (!$httpResponse->isSuccess()) { $statusCode = $httpResponse->getStatusCode(); if (401 === $statusCode && ($authenticateHeader = $httpResponse->getHeaders()->get($this->wwwAuthenticateHeaderName)->current())) { $params = $this->parseAuthenticateHeaderValue($authenticateHeader->getFieldValue()); if (isset($params['error'])) { $this->setError($this->getErrorFactory()->createErrorFromArray($params)); return; } throw new HttpAuthenticateException(sprintf("Missing error information in WWW-Authenticate header: %s", $authenticateHeader->getFieldValue())); } throw new HttpErrorStatusException(sprintf("Error status response from server: %s", $statusCode)); } try { $responseData = $this->getJsonCoder()->decode($httpResponse->getBody()); } catch (\Exception $e) { throw new InvalidResponseFormatException('The HTTP response does not contain valid JSON', null, $e); } try { $this->response = $this->getResponseFactory()->createResponse($responseData); } catch (\Exception $e) { throw new Exception\InvalidResponseException(sprintf("Invalid response: [%s] %s", get_class($e), $e->getMessage()), null, $e); } }
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)); } }
protected function setResponseContent(Response $response, array $data) { if ($response instanceof \Zend\Http\PhpEnvironment\Response) { $response->getHeaders()->addHeaderLine('Content-Type', 'application/json'); $response->setContent(json_encode(array_merge(array('status' => $response->getStatusCode()), $data))); } return $response; }
public function testSet201StatusCodeIfPost() { $request = new HttpRequest(); $request->setMethod(HttpRequest::METHOD_POST); $this->event->setRequest($request); $this->response->setContent('foo'); $this->resourceResponseListener->finishResponse($this->event); $this->assertEquals(201, $this->response->getStatusCode()); }
/** * Checks whether to handle this status code. * * @param HttpResponse $response * @return boolean */ public function checkStatusCode(HttpResponse $response) { // Only 200 responses are cached by default if (empty($this->config['http_codes_black_list'])) { return $response->isOk(); } $statusCode = $response->getStatusCode(); return !in_array($statusCode, (array) $this->config['http_codes_black_list']); }
/** * 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); } }
/** * Construtor * * @param Zend\Http\Client $client * @param Zend\Http\Response $response */ public function __construct(ZendHttpClient $client, ZendHttpResponse $response) { $this->httpClient = $client; $this->httpResponse = $response; try { $this->checkResponseStatus(); if (204 == $this->httpResponse->getStatusCode()) { $this->strategyContent = new EmptyContent($this->httpClient, $this->httpResponse); } else { $contentType = $this->httpResponse->getHeaders()->get('Content-Type')->getFieldValue(); switch (trim($contentType)) { case HalJson::CONTENT_TYPE: $this->strategyContent = new HalJson($this->httpClient, $this->httpResponse); break; default: $errorMessage = sprintf('The apigility server returned a mime type ("%s") that cannot be parsed by apigility client', $mimeType); return new TriggerException($this->httpClient, $this->httpResponse, $errorMessage); } } } catch (RuntimeException $e) { throw $e; } }
/** * Send Http request to retrieve datas * @access protected * @param string $service Service to call * @param string $type Resource type to retrieve (for search service) * @param array $parameters Parameters used for request * @throws \Zend\Http\Exception\RuntimeException * @return \stdClass */ protected function send($service, $type, $parameters) { // reset old parameters $this->getHttpClient()->resetParameters(); // setup Http headers $headers = array(ContentTypeHeader::fromString('Content-Type: ' . HttpClient::ENC_URLENCODED)); // setup HttpClient $this->getHttpClient()->setMethod(HttpRequest::METHOD_GET); $this->getHttpClient()->setParameterGet($parameters); $this->getHttpClient()->setHeaders($headers); // generate URI and set to HttpClient $this->getHttpClient()->setUri($this->generateURI($service, $type)); // get HttpResponse $this->response = $this->getHttpClient()->send(); // is HttpRequest ok ? if (!$this->response->isOk()) { // throw RuntimeException throw new ZendRuntimeException(sprintf('Invalid status code: %d', $this->response->getStatusCode())); } // return decode object return \Zend\Json\Decoder::decode($this->response->getBody()); }
/** * Transforms a Zend\Http\Response into an HttpFoundation one. * * @param ZendResponse $zresponse The Zend\Http\Response * * @return HttpFoundationResponse */ public static function toHttpFoundationResponse(ZendResponse $zresponse) { return HttpFoundationResponse::create($zresponse->getContent(), $zresponse->getStatusCode(), $zresponse->getHeaders()->toArray()); }
/** * @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 401: throw new Exception\InvalidCredentialsException('Authentication error: missing or incorrect Postmark API Key header'); case 422: throw new Exception\ValidationErrorException(sprintf('An error occured on Postmark (error code %s), message: %s', $result['ErrorCode'], $result['Message']), (int) $result['ErrorCode']); case 500: throw new Exception\RuntimeException('Postmark server error, please try again'); default: throw new Exception\RuntimeException('Unknown error during request to Postmark server'); } }
/** * Error structure * { * "requestError": { * "serviceException": { * "messageId": "RESOURCE_NOT_FOUND", * "text": "Application or message with given ID cannot be found." * } * } * } * * @link https://dev.infobip.com/v1/docs/2fa-status-codes-and-error-details Status codes and error details * @param Response $response */ private function decodeError(Response $response) { $data = json_decode($response->getContent()); if (is_object($data)) { $code = $data->requestError->serviceException->messageId; $msg = $data->requestError->serviceException->text; $this->addError(new SendingError('', $this->errorCodes[$code], $msg)); } else { $this->addError(new SendingError('', $response->getStatusCode(), $response->getContent())); } }
/** * @param ResponseInterface $response * @param ItemInterface $key * @param array|null $data * * @throws \RuntimeException * * @return array */ protected function handleSuccessfulResponse(\Zend\Http\Response $response, $key) { switch ((int) $response->getStatusCode()) { case 200: $data = json_decode($response->getBody(), true); $this->addItem($key, $data); return $data; case 304: return $this->cache->addItem($key); case 404: return null; default: throw new \RuntimeException('No support added for HTTP Status Code ' . $response->getStatusCode()); } }
/** * 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; }
protected function createResponse(ZendResponse $response) { return new Response($response->getBody(), $response->getStatusCode(), $response->headers()->toArray()); }
/** * @param HttpResponse $response * @throws Exception\RuntimeException * @return array */ private function parseResponse(HttpResponse $response) { $result = json_decode($response->getBody(), true); if ($response->isSuccess()) { return $result; } // There is a 4xx error if ($response->isClientError()) { if (isset($result['errors']) && is_array($result['errors'])) { $message = implode(', ', $result['errors']); } elseif (isset($result['error'])) { $message = $result['error']; } else { $message = 'Unknown error'; } throw new Exception\RuntimeException(sprintf('An error occured on SendGrid (http code %s), message: %s', $response->getStatusCode(), $message)); } // There is a 5xx error throw new Exception\RuntimeException('SendGrid server error, please try again'); }
/** * Converts a zend response to a symfony response. * * @param \Zend\Http\Response $response * @return \Symfony\Component\HttpFoundation\Response */ protected static function createSymfonyResponse(ZendResponse $response) { $content = $response->getContent(); $status = $response->getStatusCode(); $zendHeaders = $response->getHeaders(); $headers = array(); foreach ($zendHeaders as $header) { $name = $header->getFieldName(); $headers[$name] = $header->getFieldValue(); } return new SymfonyResponse($content, $status, $headers); }
/** * Check for HTTP errors in a response. * * @param \Zend\Http\Response $result The response to check. * * @throws \Exception * @return void */ public function checkForHttpError($result) { if (!$result->isSuccess()) { throw new \Exception('HTTP error ' . $result->getStatusCode()); } }
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()); } }
/** * @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; }
/** * @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; }
/** * Get the last error type * * @return integer */ public function getHttpStatus() { return $this->lastResponse->getStatusCode(); }