/** * Helper method responsible for constructing and returning {@see BadResponseError} exceptions. * * @param RequestInterface $request The faulty request * @param ResponseInterface $response The error-filled response * * @return BadResponseError */ public function httpError(RequestInterface $request, ResponseInterface $response) { $message = $this->header('HTTP Error'); $message .= sprintf("The remote server returned a \"%d %s\" error for the following transaction:\n\n", $response->getStatusCode(), $response->getReasonPhrase()); $message .= $this->header('Request'); $message .= trim(str($request)) . PHP_EOL . PHP_EOL; $message .= $this->header('Response'); $message .= trim(str($response)) . PHP_EOL . PHP_EOL; $message .= $this->header('Further information'); // @codeCoverageIgnoreStart switch ($response->getStatusCode()) { case 400: $message .= "Please ensure that your input values are valid and well-formed. "; break; case 401: $message .= "Please ensure that your authentication credentials are valid. "; break; case 404: $message .= "Please ensure that the resource you're trying to access actually exists. "; break; case 500: $message .= "Please try this operation again once you know the remote server is operational. "; break; } // @codeCoverageIgnoreEnd $message .= "Visit http://docs.php-opencloud.com/en/latest/http-codes for more information about debugging " . "HTTP status codes, or file a support issue on https://github.com/php-opencloud/openstack/issues."; $e = new BadResponseError($message); $e->setRequest($request); $e->setResponse($response); return $e; }
public function formatProvider() { $request = new Request('PUT', '/', ['x-test' => 'abc'], Psr7\stream_for('foo')); $response = new Response(200, ['X-Baz' => 'Bar'], Psr7\stream_for('baz')); $err = new RequestException('Test', $request, $response); return [['{request}', [$request], Psr7\str($request)], ['{response}', [$request, $response], Psr7\str($response)], ['{request} {response}', [$request, $response], Psr7\str($request) . ' ' . Psr7\str($response)], ['{request} {response}', [$request], Psr7\str($request) . ' '], ['{req_headers}', [$request], "PUT / HTTP/1.1\r\nx-test: abc"], ['{res_headers}', [$request, $response], "HTTP/1.1 200 OK\r\nX-Baz: Bar"], ['{res_headers}', [$request], 'NULL'], ['{req_body}', [$request], 'foo'], ['{res_body}', [$request, $response], 'baz'], ['{res_body}', [$request], 'NULL'], ['{method}', [$request], $request->getMethod()], ['{url}', [$request], $request->getUri()], ['{target}', [$request], $request->getRequestTarget()], ['{req_version}', [$request], $request->getProtocolVersion()], ['{res_version}', [$request, $response], $response->getProtocolVersion()], ['{res_version}', [$request], 'NULL'], ['{host}', [$request], $request->getHeaderLine('Host')], ['{hostname}', [$request, $response], gethostname()], ['{hostname}{hostname}', [$request, $response], gethostname() . gethostname()], ['{code}', [$request, $response], $response->getStatusCode()], ['{code}', [$request], 'NULL'], ['{phrase}', [$request, $response], $response->getReasonPhrase()], ['{phrase}', [$request], 'NULL'], ['{error}', [$request, $response, $err], 'Test'], ['{error}', [$request], 'NULL'], ['{req_header_x-test}', [$request], 'abc'], ['{req_header_x-not}', [$request], ''], ['{res_header_X-Baz}', [$request, $response], 'Bar'], ['{res_header_x-not}', [$request, $response], ''], ['{res_header_X-Baz}', [$request], 'NULL']]; }
public function test_it_builds_http_errors() { $request = new Request('POST', '/servers'); $response = new Response(400, [], stream_for('Invalid parameters')); $requestStr = trim(str($request)); $responseStr = trim(str($response)); $errorMessage = <<<EOT HTTP Error ~~~~~~~~~~ The remote server returned a "400 Bad Request" error for the following transaction: Request ~~~~~~~ {$requestStr} Response ~~~~~~~~ {$responseStr} Further information ~~~~~~~~~~~~~~~~~~~ Please ensure that your input values are valid and well-formed. Visit http://docs.php-opencloud.com/en/latest/http-codes for more information about debugging HTTP status codes, or file a support issue on https://github.com/php-opencloud/openstack/issues. EOT; $e = new BadResponseError($errorMessage); $e->setRequest($request); $e->setResponse($response); $this->assertEquals($e, $this->builder->httpError($request, $response)); }
/** * @param $httpVerb * @param $callName * @param array $arguments * @return \Psr\Http\Message\StreamInterface * @throws \Exception */ public static function request($httpVerb, $callName, array $arguments) { // Validations if (!self::_validateRequestVerb($httpVerb)) { throw new \Exception("You must pass a proper verb: get, head, post, put, delete or options"); } // Setup $api_key = config('laramandrill.api_key'); $verify = config('laramandrill.verify'); $output = config('laramandrill.output'); $api_base_url = config('laramandrill.api_base_url'); // determine endpoint $client = new Client([]); $endpoint = $api_base_url . $callName . '.' . $output; // build payload $arguments['key'] = $api_key; $httpVerb = strtoupper($httpVerb); $options = ['headers' => ['User-Agent' => 'laramandrill/1.0', 'Content-Type' => 'application/json'], 'body' => json_encode($arguments), 'verify' => $verify]; try { $response = $client->request($httpVerb, $endpoint, $options); return $response->getBody(); } catch (RequestException $e) { echo str($e->getRequest()); if ($e->hasResponse()) { echo str($e->getResponse()); } } throw new \Exception('Unknown issue with mandrill request/response'); }
/** * {@inheritdoc} */ public function save(RequestInterface $request, ResponseInterface $response) { foreach ($this->responseHeadersBlacklist as $header) { $response = $response->withoutHeader($header); } file_put_contents($this->getPath($request), Psr7\str($response)); $response->getBody()->seek(0); }
public function __sleep() { /* * Because the Crawler isn't serialized correctly, we exclude it from serialization * It will be available again after wakeup through lazy loading with getCrawler() */ // we store the response manually, because otherwise it will not get serialized. $this->body = Psr7\str($this->response); return array('uri', 'body'); }
/** * Write a mock response file * * @param Response $response * @param string $filename * * @code * $response = $subscription->getService()->getLastResponse(); * MockResponse::write($response, 'subscription.success'); */ public static function write(Response $response, $filename) { $responseString = Psr7\str($response); // remove identifying information $responseString = preg_replace("/^Set-Cookie: (.*)\$/im", "Set-Cookie: removed", $responseString); $responseString = preg_replace("/^X-Request-Id: (.*)\$/im", "X-Request-Id: removed", $responseString); // write the mock response $handle = fopen(dirname(__DIR__) . '/mock/' . $filename, 'w+'); fwrite($handle, $responseString); fclose($handle); }
/** * Helper method responsible for constructing and returning {@see BadResponseError} exceptions. * * @param RequestInterface $request The faulty request * @param ResponseInterface $response The error-filled response * * @return BadResponseError */ public function httpError(RequestInterface $request, ResponseInterface $response) { $message = $this->header('HTTP Error'); $message .= sprintf("The remote server returned a \"%d %s\" error for the following transaction:\n\n", $response->getStatusCode(), $response->getReasonPhrase()); $message .= $this->header('Request'); $message .= trim(str($request)) . PHP_EOL . PHP_EOL; $message .= $this->header('Response'); $message .= trim(str($response)) . PHP_EOL . PHP_EOL; $message .= $this->header('Further information'); $message .= $this->getStatusCodeMessage($response->getStatusCode()); $message .= "Visit http://docs.php-opencloud.com/en/latest/http-codes for more information about debugging " . "HTTP status codes, or file a support issue on https://github.com/php-opencloud/openstack/issues."; $e = new BadResponseError($message); $e->setRequest($request); $e->setResponse($response); return $e; }
public function testConvertsResponsesToStrings() { $response = new Psr7\Response(200, ['Baz' => 'bar', 'Qux' => ' ipsum'], 'hello', '1.0', 'FOO'); $this->assertEquals("HTTP/1.0 200 FOO\r\nBaz: bar\r\nQux: ipsum\r\n\r\nhello", Psr7\str($response)); }
/** * @param string $method * @param string $url * @param array $parameters * * @return bool|mixed|\Psr\Http\Message\ResponseInterface */ public function makeRequest($method = 'GET', $url = '', array $parameters = []) { try { $isGet = strtolower($method) === 'get' ? true : false; $parameters = !empty($parameters) ? $parameters : $this->getRequestParameters($isGet); return $this->response = $this->client->request($method, !empty($url) ? $url : $this->url, $parameters); } catch (RequestException $e) { $this->printErrorMessage(Psr7\str($e->getRequest())); if ($e->hasResponse()) { $this->response = $e->getResponse(); $this->printErrorMessage(Psr7\str($e->getResponse())); } } return false; }
/** * {@inheritdoc} */ public function save(RequestInterface $request, ResponseInterface $response) { file_put_contents($this->getPath($request), Psr7\str($response)); $response->getBody()->seek(0); }
public function authorize($authorizationCode) { $postArgs = array('code' => $authorizationCode, 'grant_type' => 'authorization_code', 'client_id' => $this->config->client_id, 'client_secret' => $this->config->client_secret, 'scope' => $this->getScopes(), 'state' => $this->getState(), 'redirect_uri' => $this->getRedirectUri()); try { $response = $this->client->post(static::OAUTH_TOKEN_URI, ['http_errors' => false, 'headers' => ['Content-Type' => 'application/json'], 'json' => $postArgs]); $responseBody = $response->getBody()->getContents(); if ($response->getStatusCode() == 200) { $this->setToken(json_decode($responseBody)); $this->token->created_at = time(); $this->token->expires_at = $this->token->expires_in + time(); $this->token->revoked = false; $this->storeToken(); } else { throw MailiumOauthClientException::remoteErrorDetected($response->getStatusCode(), $responseBody); } } catch (RequestException $e) { echo Psr7\str($e->getRequest()); if ($e->hasResponse()) { echo Psr7\str($e->getResponse()); } } }