-
Notifications
You must be signed in to change notification settings - Fork 41
/
AbstractService.php
119 lines (104 loc) · 2.73 KB
/
AbstractService.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<?php
namespace Shopify\Service;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Shopify\ApiInterface;
use Shopify\Object\PaginationLink;
abstract class AbstractService
{
/**
* Instantiated Guzzle Client for requests
* @var Client
*/
private $client;
/**
* The last API response from Shopify
* @var Response|null
*/
private $lastResponse;
const REQUEST_METHOD_GET = 'GET';
const REQUEST_METHOD_POST = 'POST';
const REQUEST_METHOD_PUT = 'PUT';
const REQUEST_METHOD_DELETE = 'DELETE';
public static function factory(ApiInterface $api)
{
return new static($api);
}
public function __construct(ApiInterface $api)
{
$this->client = $api->getHttpHandler();
}
/**
* Get the client instance
*
* @return Client
*/
public function getClient()
{
return $this->client;
}
/**
* @param $endpoint
* @param string $method
* @param array $params
* @return mixed
*/
public function request($endpoint, $method = self::REQUEST_METHOD_GET, array $params = [])
{
return $this->send(new Request($method, $endpoint), $params);
}
/**
* @param $endpoint
* @param string $method
* @return Request
*/
public function createRequest($endpoint, $method = self::REQUEST_METHOD_GET)
{
return new Request($method, $endpoint);
}
/**
* Get the last response from Shopify
* @return Response
*/
public function getLastResponse()
{
return $this->lastResponse;
}
public function send(Request $request, array $params = array())
{
$args = array();
if ($request->getMethod() === 'GET') {
$args['query'] = $params;
} else {
$args['json'] = $params;
}
$this->lastResponse = $this->client->send($request, $args);
return json_decode(
$this->lastResponse->getBody()->getContents(),
true
);
}
public function createObject($className, $data)
{
$obj = new $className();
$obj->setData($data);
return $obj;
}
public function createCollection($className, $data)
{
return array_map(
function ($object) use ($className) {
return $this->createObject($className, $object);
}, $data
);
}
/** [fetch pagination link from Shopify Link headers]
* supported only in api version 2019-07 of the API and above
* @return PaginationLink
*/
public function getPaginationLink(): PaginationLink
{
return new PaginationLink($this->getLastResponse()->getHeaderLine('Link'));
}
}