ClientAdapter.php
1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
<?php
namespace Cardinity\Http\Guzzle;
use Cardinity\Exception;
use Cardinity\Http\ClientInterface;
use Cardinity\Http\Guzzle\ExceptionMapper;
use Cardinity\Method\MethodInterface;
use GuzzleHttp;
use GuzzleHttp\Exception\ClientException;
/**
* Adapter for GuzzleHttp client
*/
class ClientAdapter implements ClientInterface
{
/** @type GuzzleHttp\ClientInterface */
private $client;
/** @type ExceptionMapper */
private $mapper;
/**
* @param GuzzleHttp\ClientInterface $client
* @param ExceptionMapper $mapper
*/
public function __construct(
GuzzleHttp\ClientInterface $client,
ExceptionMapper $mapper
) {
$this->client = $client;
$this->mapper = $mapper;
}
/**
* Send HTTP request
* @param MethodInterface $method
* @param string $requestMethod POST|GET|PATCH
* @param string $url http URL
* @param array $options query options. Query values goes under 'body' key.
*
* @return array
*/
public function sendRequest(
MethodInterface $method,
$requestMethod,
$url,
array $options = []
) {
try {
$response = $this->client->request($requestMethod, $url, $options);
return json_decode($response->getBody(), true);
} catch (ClientException $e) {
throw $this->mapper->get($e, $method);
} catch (\Exception $e) {
throw new Exception\UnexpectedError('Unexpected error', $e->getCode(), $e);
}
}
}