|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Glorand\Drip\Api; |
|
4
|
|
|
|
|
5
|
|
|
use Glorand\Drip\Api\Response\ApiResponse; |
|
6
|
|
|
use GuzzleHttp\Client; |
|
7
|
|
|
use GuzzleHttp\Exception\GuzzleException; |
|
8
|
|
|
use GuzzleHttp\Psr7\Response; |
|
9
|
|
|
|
|
10
|
|
|
abstract class Api |
|
11
|
|
|
{ |
|
12
|
|
|
const GET = 'get'; |
|
13
|
|
|
const POST = 'post'; |
|
14
|
|
|
const PUT = 'put'; |
|
15
|
|
|
const DELETE = 'delete'; |
|
16
|
|
|
|
|
17
|
|
|
/** |
|
18
|
|
|
* @var Client |
|
19
|
|
|
*/ |
|
20
|
|
|
protected $client; |
|
21
|
|
|
/** @var string */ |
|
22
|
|
|
protected $accountId; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* Api constructor. |
|
26
|
|
|
* |
|
27
|
|
|
* @param \GuzzleHttp\Client $client |
|
28
|
|
|
* @param string $accountId |
|
29
|
|
|
*/ |
|
30
|
9 |
|
public function __construct(Client $client, string $accountId) |
|
31
|
|
|
{ |
|
32
|
9 |
|
$this->client = $client; |
|
33
|
9 |
|
$this->accountId = $accountId; |
|
34
|
9 |
|
} |
|
35
|
|
|
|
|
36
|
9 |
|
protected function prepareUrl(string $url): string |
|
37
|
|
|
{ |
|
38
|
9 |
|
if (false !== strpos($url, ':account_id:')) { |
|
39
|
7 |
|
$url = str_replace(':account_id:', $this->accountId, $url); |
|
40
|
|
|
} |
|
41
|
|
|
|
|
42
|
9 |
|
return trim($url, '/'); |
|
43
|
|
|
} |
|
44
|
|
|
|
|
45
|
4 |
|
protected function sendGet($url, array $params = []): ApiResponse |
|
46
|
|
|
{ |
|
47
|
|
|
$options = [ |
|
48
|
4 |
|
'query' => $params, |
|
49
|
|
|
]; |
|
50
|
|
|
|
|
51
|
4 |
|
return $this->makeRequest(self::GET, $this->prepareUrl($url), $options); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
5 |
|
protected function sendPost($url, array $params = []): ApiResponse |
|
55
|
|
|
{ |
|
56
|
|
|
$options = [ |
|
57
|
5 |
|
'body' => json_encode($params), |
|
58
|
|
|
]; |
|
59
|
|
|
|
|
60
|
5 |
|
return $this->makeRequest(self::POST, $this->prepareUrl($url), $options); |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
/** |
|
64
|
|
|
* @param string $method |
|
65
|
|
|
* @param string $url |
|
66
|
|
|
* @param array $options |
|
67
|
|
|
* |
|
68
|
|
|
* @return ApiResponse |
|
69
|
|
|
*/ |
|
70
|
9 |
|
private function makeRequest(string $method, string $url, array $options = []): ApiResponse |
|
71
|
|
|
{ |
|
72
|
|
|
try { |
|
73
|
9 |
|
$response = $this->client->request($method, $url, $options); |
|
74
|
7 |
|
} catch (GuzzleException $e) { |
|
75
|
7 |
|
$response = new Response($e->getCode(), [], $e->getMessage()); |
|
76
|
|
|
} |
|
77
|
|
|
|
|
78
|
9 |
|
return new ApiResponse($url, $options, $response); |
|
79
|
|
|
} |
|
80
|
|
|
} |
|
81
|
|
|
|