1
|
|
|
<?php |
2
|
|
|
namespace Redbox\Twitch\Transport; |
3
|
|
|
use Redbox\Twitch\Client; |
4
|
|
|
use Redbox\Twitch\Exception; |
5
|
|
|
use Redbox\Twitch\Transport\Adapter; |
6
|
|
|
use Redbox\Twitch\Transport\Adapter\Curl as DefaultAdapter; |
7
|
|
|
|
8
|
|
|
class Http implements TransportInterface |
9
|
|
|
{ |
10
|
|
|
/** |
11
|
|
|
* @var Client |
12
|
|
|
*/ |
13
|
|
|
protected $client; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* @var Adapter\AdapterInterface |
17
|
|
|
*/ |
18
|
|
|
protected $adapter; |
19
|
|
|
|
20
|
|
|
public function __construct(Client $client) |
21
|
|
|
{ |
22
|
|
|
$this->client = $client; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/* -- Setters */ |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Set the Transport adapter we will use to communicate |
29
|
|
|
* to Twitch. |
30
|
|
|
* |
31
|
|
|
* @param Adapter\AdapterInterface $adapter |
32
|
|
|
*/ |
33
|
|
|
public function setAdapter($adapter) |
34
|
|
|
{ |
35
|
|
|
/** |
36
|
|
|
* Not a adapter throws a BadFunctionCallException or true |
37
|
|
|
* if usable. |
38
|
|
|
*/ |
39
|
|
|
if ($adapter->verifySupport() === true) { |
40
|
|
|
$this->adapter = $adapter; |
41
|
|
|
} |
42
|
|
|
} |
43
|
|
|
|
44
|
|
|
/** |
45
|
|
|
* Returns the Adapter set to communicate to Twitch. |
46
|
|
|
* If none is set we will try to work with Curl. |
47
|
|
|
* |
48
|
|
|
* @return Adapter\AdapterInterface |
49
|
|
|
*/ |
50
|
|
|
public function getAdapter() |
51
|
|
|
{ |
52
|
|
|
if (!$this->adapter) { |
53
|
|
|
$this->setAdapter(new DefaultAdapter); |
54
|
|
|
} |
55
|
|
|
return $this->adapter; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/* -- Getters -- */ |
59
|
|
|
|
60
|
|
|
|
61
|
|
|
public function sendRequest(HttpRequest $request) |
62
|
|
|
{ |
63
|
|
|
if (!$this->client) { |
64
|
|
|
throw new Exception\TwitchException('Client was not set'); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
$apiurl = rtrim($this->client->getApiUrl(), '/'); |
68
|
|
|
$url = sprintf('%s/%s', $apiurl, $request->getUrl()); |
69
|
|
|
$url = rtrim($url, '/'); |
70
|
|
|
|
71
|
|
|
|
72
|
|
|
$this->getAdapter()->open(); |
73
|
|
|
|
74
|
|
|
$data = $this->getAdapter()->send($url, $request->getRequestMethod(), $request->getRequestHeaders(), $request->getPostBody()); |
75
|
|
|
$status_code = $this->getAdapter()->getHttpStatusCode(); |
76
|
|
|
|
77
|
|
|
$data = json_decode($data); |
78
|
|
|
|
79
|
|
|
$this->getAdapter()->close(); |
80
|
|
|
|
81
|
|
|
// TODO we need to return more info |
82
|
|
|
if ($status_code !== 200) { |
83
|
|
|
throw new Exception\TwitchException( |
84
|
|
|
$data->error, |
85
|
|
|
$data->status |
86
|
|
|
); |
87
|
|
|
} |
88
|
|
|
return $data; |
89
|
|
|
} |
90
|
|
|
} |