1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17:
18:
19: namespace LINE\LINEBot\HTTPClient;
20:
21: use LINE\LINEBot\Constant\Meta;
22: use LINE\LINEBot\Exception\CurlExecutionException;
23: use LINE\LINEBot\HTTPClient;
24: use LINE\LINEBot\Response;
25:
26: 27: 28: 29: 30: 31: 32:
33: class CurlHTTPClient implements HTTPClient
34: {
35:
36: private $authHeaders;
37:
38: private $userAgentHeader = ['User-Agent: LINE-BotSDK-PHP/' . Meta::VERSION];
39:
40: 41: 42: 43: 44:
45: public function __construct($channelToken)
46: {
47: $this->authHeaders = [
48: "Authorization: Bearer $channelToken",
49: ];
50: }
51:
52: 53: 54: 55: 56: 57:
58: public function get($url)
59: {
60: return $this->sendRequest('GET', $url, [], []);
61: }
62:
63: 64: 65: 66: 67: 68: 69:
70: public function post($url, array $data)
71: {
72: return $this->sendRequest('POST', $url, ['Content-Type: application/json; charset=utf-8'], $data);
73: }
74:
75: 76: 77: 78: 79: 80: 81: 82:
83: private function sendRequest($method, $url, array $additionalHeader, array $reqBody)
84: {
85: $curl = new Curl($url);
86:
87: $headers = array_merge($this->authHeaders, $this->userAgentHeader, $additionalHeader);
88:
89: $options = [
90: CURLOPT_CUSTOMREQUEST => $method,
91: CURLOPT_HTTPHEADER => $headers,
92: CURLOPT_HEADER => false,
93: CURLOPT_RETURNTRANSFER => true,
94: CURLOPT_BINARYTRANSFER => true,
95: CURLOPT_HEADER => true,
96: ];
97:
98: if ($method === 'POST') {
99: if (empty($reqBody)) {
100:
101: $options[CURLOPT_HTTPHEADER][] = 'Content-Length: 0';
102: } else {
103: $options[CURLOPT_POSTFIELDS] = json_encode($reqBody);
104: }
105: }
106:
107: $curl->setoptArray($options);
108:
109: $result = $curl->exec();
110:
111: if ($curl->errno()) {
112: throw new CurlExecutionException($curl->error());
113: }
114:
115: $info = $curl->getinfo();
116: $httpStatus = $info['http_code'];
117:
118: $responseHeaderSize = $info['header_size'];
119:
120: $responseHeaderStr = substr($result, 0, $responseHeaderSize);
121: $responseHeaders = [];
122: foreach (explode("\r\n", $responseHeaderStr) as $responseHeader) {
123: $kv = explode(':', $responseHeader, 2);
124: if (count($kv) === 2) {
125: $responseHeaders[$kv[0]] = trim($kv[1]);
126: }
127: }
128:
129: $body = substr($result, $responseHeaderSize);
130:
131: return new Response($httpStatus, $body, $responseHeaders);
132: }
133: }
134: