1 <?php
2
3 namespace wataridori\ChatworkSDK;
4
5 use wataridori\ChatworkSDK\Exception\RequestFailException;
6
7 class ChatworkRequest
8 {
9 const REQUEST_METHOD_GET = 'GET';
10 const REQUEST_METHOD_POST = 'POST';
11 const REQUEST_METHOD_PUT = 'PUT';
12 const REQUEST_METHOD_DELETE = 'DELETE';
13 const REQUEST_HEADER = 'X-ChatWorkToken';
14 const CHATWORK_API_LINK = 'https://api.chatwork.com/';
15
16 17 18 19 20
21 protected $apiVersion = 'v2';
22
23 24 25 26 27
28 protected $method;
29
30 31 32 33 34
35 protected $endPoint;
36
37 38 39 40 41
42 protected $params = [];
43
44 45 46 47 48
49 protected $apiKey;
50
51 52 53 54 55 56
57 public function __construct($apiKey, $method = self::REQUEST_METHOD_GET)
58 {
59 $this->apiKey = $apiKey;
60 $this->method = $method;
61 }
62
63 64 65 66 67
68 public function setEndPoint($endPoint)
69 {
70 $this->endPoint = $endPoint;
71 }
72
73 74 75 76 77
78 public function setParams($params)
79 {
80 $this->params = $params;
81 }
82
83 84 85 86 87
88 public function setMethod($method)
89 {
90 $this->method = $method;
91 }
92
93 94 95 96 97
98 public function getHeader()
99 {
100 return self::REQUEST_HEADER . ": {$this->apiKey}";
101 }
102
103 104 105 106 107
108 protected function buildUrl()
109 {
110 return self::CHATWORK_API_LINK . "{$this->apiVersion}/{$this->endPoint}";
111 }
112
113 114 115 116 117 118 119
120 public function send()
121 {
122 $curl = curl_init();
123 $url = $this->buildUrl();
124 curl_setopt($curl, CURLOPT_HTTPHEADER, [$this->getHeader()]);
125
126 switch ($this->method) {
127 case self::REQUEST_METHOD_GET:
128 curl_setopt($curl, CURLOPT_HTTPGET, 1);
129 if ($this->params) {
130 $url .= '?' . http_build_query($this->params, '', '&');
131 }
132 break;
133 case self::REQUEST_METHOD_POST:
134 curl_setopt($curl, CURLOPT_POST, 1);
135 if ($this->params) {
136 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($this->params, '', '&'));
137 }
138 break;
139 case self::REQUEST_METHOD_PUT:
140 curl_setopt($curl, CURLOPT_PUT, 1);
141 if ($this->params) {
142 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($this->params, '', '&'));
143 }
144 break;
145 case self::REQUEST_METHOD_DELETE:
146 curl_setopt($curl, CURLOPT_CUSTOMREQUEST, self::REQUEST_METHOD_DELETE);
147 if ($this->params) {
148 $url .= '?' . http_build_query($this->params, '', '&');
149 }
150 break;
151 }
152 curl_setopt($curl, CURLOPT_URL, $url);
153 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
154 if (!ChatworkSDK::getSslVerificationMode()) {
155 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
156 }
157 $response = json_decode(curl_exec($curl), 1);
158 $info = curl_getinfo($curl);
159 curl_close($curl);
160 if ($info['http_code'] >= 400) {
161 $error = $response['errors'];
162 throw new RequestFailException();
163 }
164
165 return [
166 'http_code' => $info['http_code'],
167 'response' => $response,
168 ];
169 }
170 }
171