1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Polidog\Esa; |
4
|
|
|
|
5
|
|
|
use GuzzleHttp\ClientInterface as HttpClientInterface; |
6
|
|
|
use GuzzleHttp\HandlerStack; |
7
|
|
|
use GuzzleHttp\Middleware; |
8
|
|
|
use GuzzleHttp\Psr7\Response; |
9
|
|
|
use Psr\Http\Message\RequestInterface; |
10
|
|
|
|
11
|
|
|
final class Client |
12
|
|
|
{ |
13
|
|
|
private $accessToken; |
14
|
|
|
|
15
|
|
|
private $currentTeam; |
16
|
|
|
|
17
|
|
|
private $httpClient; |
18
|
|
|
|
19
|
|
|
private $apiMethods; |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var array |
23
|
|
|
*/ |
24
|
|
|
private $httpOptions = [ |
25
|
|
|
'base_uri' => 'https://api.esa.io/v1/', |
26
|
|
|
'timeout' => 60, |
27
|
|
|
'allow_redirect' => false, |
28
|
|
|
'headers' => [ |
29
|
|
|
'User-Agent' => 'esa-php-api v1', |
30
|
|
|
'Accept' => 'application/json', |
31
|
|
|
], |
32
|
|
|
]; |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* @param $accessToken |
36
|
|
|
* @param $currentTeam |
37
|
|
|
* @param HttpClientInterface $httpClient |
38
|
|
|
* @param array $httpOptions |
39
|
|
|
*/ |
40
|
|
|
public function __construct($accessToken, $currentTeam, HttpClientInterface $httpClient = null, $httpOptions = []) |
41
|
|
|
{ |
42
|
|
|
$this->accessToken = $accessToken; |
43
|
|
|
$this->currentTeam = $currentTeam; |
44
|
|
|
$this->httpOptions = array_merge($this->httpOptions, $httpOptions); |
45
|
|
|
$this->httpOptions['handler'] = $this->createAuthStack(); |
46
|
|
|
|
47
|
|
|
if (empty($httpClient)) { |
48
|
|
|
$httpClient = new \GuzzleHttp\Client($this->httpOptions); |
49
|
|
|
} |
50
|
|
|
$this->httpClient = $httpClient; |
51
|
|
|
$this->apiMethods = new ApiMethods($httpClient, $currentTeam); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function __call($name, $args) |
55
|
|
|
{ |
56
|
|
|
/** @var Response $response */ |
57
|
|
|
$response = call_user_func_array([$this->apiMethods, $name], $args); |
58
|
|
|
if ($response->getStatusCode() == 200) { |
59
|
|
|
return json_decode($response->getBody()->getContents(), true); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|
63
|
|
|
private function createAuthStack() |
64
|
|
|
{ |
65
|
|
|
$stack = HandlerStack::create(); |
66
|
|
|
$stack->push(Middleware::mapRequest(function (RequestInterface $request) { |
67
|
|
|
return $request->withHeader('Authorization', 'Bearer '.$this->accessToken); |
68
|
|
|
})); |
69
|
|
|
|
70
|
|
|
return $stack; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|