1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Audiens\AdForm; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Client as GuzzleClient; |
6
|
|
|
use Psr\Http\Message\ResponseInterface; |
7
|
|
|
|
8
|
|
|
class HttpClient |
9
|
|
|
{ |
10
|
|
|
/** @var Authentication */ |
11
|
|
|
protected $authentication; |
12
|
|
|
|
13
|
|
|
/** @var GuzzleClient */ |
14
|
|
|
protected $guzzle; |
15
|
|
|
|
16
|
|
|
/** @var string */ |
17
|
|
|
protected $accessToken = null; |
18
|
|
|
|
19
|
|
|
public function __construct($authentication, array $config = []) |
20
|
|
|
{ |
21
|
|
|
$this->authentication = $authentication; |
22
|
|
|
|
23
|
|
|
$this->guzzle = new GuzzleClient( |
24
|
|
|
[ |
25
|
|
|
'debug' => $config['debug'] ?? false, |
26
|
|
|
'base_uri' => Client::BASE_URL, |
27
|
|
|
'headers' => [ |
28
|
|
|
'User-Agent' => 'Audiens', |
29
|
|
|
'Accept' => 'application/json', |
30
|
|
|
'Content-type' => 'application/json', |
31
|
|
|
], |
32
|
|
|
] |
33
|
|
|
); |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function get(string $uri, array $options = []): ResponseInterface |
37
|
|
|
{ |
38
|
|
|
return $this->request('GET', $uri, $options); |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
public function post(string $uri, array $options = []): ResponseInterface |
42
|
|
|
{ |
43
|
|
|
return $this->request('POST', $uri, $options); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
public function put(string $uri, array $options = []): ResponseInterface |
47
|
|
|
{ |
48
|
|
|
return $this->request('PUT', $uri, $options); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
public function delete(string $uri, array $options = []): ResponseInterface |
52
|
|
|
{ |
53
|
|
|
return $this->request('DELETE', $uri, $options); |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* Performs the actual request on the Guzzle instance |
58
|
|
|
* also injects the Oauth2 Access Token for each request |
59
|
|
|
*/ |
60
|
|
|
public function request(string $method, string $uri, array $options = []): ResponseInterface |
61
|
|
|
{ |
62
|
|
|
$options['headers']['Authorization'] = 'Bearer '.$this->authentication->getAccessToken(); // Inject Oauth2 Access Token on each request if it expires try to re-authenticate |
63
|
|
|
|
64
|
|
|
return $this->guzzle->request($method, $uri, $options); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|