1
|
|
|
<?php |
2
|
|
|
namespace Javis\JsonApi; |
3
|
|
|
|
4
|
|
|
|
5
|
|
|
use GuzzleHttp\Psr7; |
6
|
|
|
|
7
|
|
|
/** |
8
|
|
|
* Stores a instance of HTTP Client object with all the configuration |
9
|
|
|
* required to access the API. This instance can be use to do multiple calls to |
10
|
|
|
* different endopoints of the API |
11
|
|
|
*/ |
12
|
|
|
class Client |
13
|
|
|
{ |
14
|
|
|
protected $client; |
15
|
|
|
protected $base_uri; |
16
|
|
|
protected $options; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param \GuzzleHttp\Client $http_client |
20
|
|
|
*/ |
21
|
|
|
public function __construct($base_uri, array $options = [], \GuzzleHttp\Client $http_client = null) |
22
|
|
|
{ |
23
|
|
|
$this->base_uri = /** @scrutinizer ignore-call */ Psr7\uri_for($base_uri); |
24
|
|
|
|
25
|
|
|
$this->options = $options; |
26
|
|
|
|
27
|
|
|
$this->client = (!empty($http_client)) ? $http_client : new \GuzzleHttp\Client($this->getOptions()); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* Returns an instance of a Json Api Query to do a call to an API endpoint |
32
|
|
|
* @param string $endpoint relative uri to the endpoint |
33
|
|
|
* @return Query |
34
|
|
|
*/ |
35
|
|
|
public function endpoint($endpoint) |
36
|
|
|
{ |
37
|
|
|
$endpoint = /** @scrutinizer ignore-call */ Psr7\uri_for($endpoint); |
38
|
|
|
|
39
|
|
|
if ($endpoint->isAbsolute($endpoint)) { |
40
|
|
|
throw new \Exception("Endpoint must be a relative path"); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
return new Query($this, $endpoint); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
/** |
47
|
|
|
* Get the Guzzle HTTP Options to use with the requests |
48
|
|
|
* @return array |
49
|
|
|
*/ |
50
|
|
|
protected function getOptions() |
51
|
|
|
{ |
52
|
|
|
return array_merge_recursive([ |
53
|
|
|
'base_uri' => $this->base_uri, |
54
|
|
|
'http_errors' => true, |
55
|
|
|
'headers' => ['Accept' => 'application/json'] |
56
|
|
|
], $this->options); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* [request description] |
61
|
|
|
* @param string $method [description] |
62
|
|
|
* @param string $endpoint [description] |
63
|
|
|
* @param array $options [description] |
64
|
|
|
* @return Response [description] |
65
|
|
|
*/ |
66
|
|
|
public function request($method, $endpoint, array $options) |
67
|
|
|
{ |
68
|
|
|
$response = $this->client->request($method, $endpoint, $options); |
69
|
|
|
|
70
|
|
|
return new Response($response); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
|
74
|
|
|
} |
75
|
|
|
|