-
Notifications
You must be signed in to change notification settings - Fork 148
/
Client.php
102 lines (90 loc) · 2.3 KB
/
Client.php
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
<?php
namespace PagarMe\Sdk;
use GuzzleHttp\Client as GuzzleClient;
class Client
{
/**
* @var string
*/
private $apiKey;
/**
* @var GuzzleClient
*/
private $client;
/**
* @param \GuzzleHttp\Client $client
* @param string $apiKey
* @param int|null $timeout
*/
public function __construct(GuzzleClient $client, $apiKey, $timeout = null)
{
$this->client = $client;
$this->apiKey = $apiKey;
if ($timeout != null) {
$this->setDefaultTimeout($timeout);
}
}
/**
* @param int $timeout
*/
public function setDefaultTimeout($timeout)
{
$this->client->setDefaultOption('timeout', $timeout);
}
/**
* @return int
*/
public function getDefaultTimeout()
{
return $this->client->getDefaultOption('timeout');
}
/**
* @param RequestInterface $apiRequest
* @return \stdClass
* @throws ClientException
*/
public function send(RequestInterface $apiRequest)
{
$request = $this->client->createRequest(
$apiRequest->getMethod(),
$apiRequest->getPath(),
$this->buildBody($apiRequest)
);
try {
$response = $this->client->send($request);
return json_decode($response->getBody()->getContents());
} catch (\GuzzleHttp\Exception\ClientException $exception) {
$response = $exception->getResponse()->getBody()->getContents();
$code = $exception->getResponse()->getStatusCode();
throw new ClientException($response, $code);
} catch (\GuzzleHttp\Exception\RequestException $exception) {
throw new ClientException(
$exception->getMessage(),
$exception->getCode()
);
}
}
/**
* @param RequestInterface $apiRequest
* @return array
*/
private function buildBody(RequestInterface $request)
{
return [
'json' => array_merge(
$request->getPayload(),
[
'api_key' => $this->apiKey
]
)
];
}
/**
* @return string
* @codeCoverageIgnore
*/
public function getApiKey()
{
return $this->apiKey;
}
}