-
Notifications
You must be signed in to change notification settings - Fork 40
/
Copy pathAbstractService.php
75 lines (63 loc) · 1.83 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
<?php
namespace Shopify\Service;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Shopify\ApiInterface;
use Shopify\Object\AbstractObject;
use Shopify\Inflector;
abstract class AbstractService
{
private $api;
private $mapper;
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->api = $api;
}
public function getApi()
{
return $this->api;
}
public function request($endpoint, $method = self::REQUEST_METHOD_GET, array $params = array())
{
$request = $this->createRequest($endpoint, $method);
return $this->send($request, $params);
}
public function createRequest($endpoint, $method = self::REQUEST_METHOD_GET)
{
return new Request($method, $endpoint);
}
public function send(Request $request, array $params = array())
{
$handler = $this->getApi()->getHttpHandler();
$args = array();
if ($request->getMethod() === 'GET') {
$args['query'] = $params;
} else {
$args['json'] = $params;
}
$this->lastResponse = $handler->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
);
}
}