oidc-1.0.0-alpha2/src/JsonHttp/JsonHttpClient.php
src/JsonHttp/JsonHttpClient.php
<?php
namespace Drupal\oidc\JsonHttp;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\GuzzleException;
use Psr\Http\Message\ResponseInterface;
/**
* Provides a JSON HTTP client.
*/
class JsonHttpClient implements JsonHttpClientInterface {
/**
* The HTTP client.
*
* @var \GuzzleHttp\ClientInterface
*/
protected $httpClient;
/**
* Class constructor.
*
* @param \GuzzleHttp\ClientInterface $http_client
* The HTTP client.
*/
public function __construct(ClientInterface $http_client) {
$this->httpClient = $http_client;
}
/**
* {@inheritdoc}
*/
public function get(JsonHttpGetRequestInterface $request) {
return $this->request('GET', $request->getUrl(), $this->buildOptionsArray($request));
}
/**
* {@inheritdoc}
*/
public function post(JsonHttpPostRequestInterface $request) {
$options = $this->buildOptionsArray($request);
if ($form_params = $request->getFormParams()) {
$options['form_params'] = $form_params;
}
return $this->request('POST', $request->getUrl(), $options);
}
/**
* Build the HTTP-client compatible options array.
*
* @param \Drupal\oidc\JsonHttp\JsonHttpRequestInterface $request
* The JSON HTTP request.
*
* @return array
* The options an array.
*/
protected function buildOptionsArray(JsonHttpRequestInterface $request) {
$options = [
'allow_redirects' => FALSE,
'headers' => [
'Accept' => 'application/json',
],
'on_headers' => function (ResponseInterface $response) {
$status_code = $response->getStatusCode();
if ($status_code !== 200) {
throw new \RuntimeException('A response with status code ' . $status_code . ' was not expected');
}
},
];
if ($headers = $request->getHeaders()) {
$options['headers'] += $headers;
}
if ($basic_auth = $request->getBasicAuth()) {
$options['auth'] = $basic_auth;
}
return $options;
}
/**
* Perform an HTTP request.
*
* @param string $method
* The HTTP method.
* @param string $url
* The URL.
* @param array $options
* The request options.
*
* @return array
* The decoded response.
*
* @throws \RuntimeException
*/
protected function request($method, $url, array $options) {
try {
$response = $this->httpClient->request($method, $url, $options);
}
catch (GuzzleException $ex) {
throw new \RuntimeException('Failed to perform a ' . $method . ' request to ' . $url);
}
// Decode the response.
$response = @json_decode($response->getBody()->getContents(), TRUE);
if (!is_array($response)) {
throw new \RuntimeException('Decoding JSON response of the ' . $method . ' to ' . $url . ' failed');
}
return $response;
}
}
