forked from ProcessMaker/processmaker
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMakeHttpRequests.php
More file actions
238 lines (219 loc) · 7.59 KB
/
MakeHttpRequests.php
File metadata and controls
238 lines (219 loc) · 7.59 KB
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
<?php
namespace ProcessMaker\Traits;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Facades\Log;
use Mustache_Engine;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Illuminate\Support\Arr;
use ProcessMaker\Exception\HttpResponseException;
use Psr\Http\Message\ResponseInterface;
trait MakeHttpRequests
{
private $authTypes = [
'BASIC' => 'basicAuthorization',
'OAUTH2_BEARER' => 'bearerAuthorization',
'OAUTH2_PASSWORD' => 'passwordAuthorization',
];
/**
* Verify certificate ssl
*
* @var bool
*/
protected $verifySsl = true;
/**
* Send a HTTP request based on the datasource, configuration
* and the process request data.
*
* @param array $data
* @param array $config
*
* @return array
*
* @throws GuzzleException
* @throws HttpResponseException
*/
public function request(array $data = [], array $config = [])
{
$mustache = new Mustache_Engine();
$endpoint = $this->endpoints[$config['endpoint']];
$method = $mustache->render($endpoint['method'], $data);
$url = $mustache->render($endpoint['url'], $data);
// If exists a query string in the call, add it to the URL
if (array_key_exists('queryString', $config)) {
$separator = strpos($url, '?') ? '&' : '?';
$url .= $separator . $config['queryString'];
}
$this->verifySsl = array_key_exists('verify_certificate', $this->credentials)
? $this->credentials['verify_certificate']
: true;
// Datasource works with json responses
$headers = ['Accept' => 'application/json'];
if (isset($endpoint['headers']) && is_array($endpoint['headers'])) {
foreach ($endpoint['headers'] as $header) {
$headers[$mustache->render($header['key'], $data)] = $mustache->render($header['value'], $data);
}
}
if (isset($config['dataMapping'])) {
$mappedData = [];
foreach ($config['dataMapping'] as $map) {
$mappedData[$map['key']] = $map['value'];
}
if (empty($endpoint['body'])) {
$endpoint['body'] = json_encode($mappedData);
} else {
$endpointBody = json_decode($endpoint['body'], true);
$endpoint['body'] = json_encode(array_merge($endpointBody, $mappedData));
}
}
$body = $mustache->render($endpoint['body'], $data);
$bodyType = $mustache->render($endpoint['body_type'], $data);
$request = [$method, $url, $headers, $body, $bodyType];
$request = $this->addAuthorizationHeaders(...$request);
try {
return $this->response($this->call(...$request), $data, $config, $mustache);
} catch (ClientException $exception) {
throw new HttpResponseException($exception->getResponse());
}
}
/**
* Add authorization parameters
*
* @param array ...$config
*
* @return array
*/
private function addAuthorizationHeaders(...$config)
{
if (isset($this->authTypes[$this->authtype])) {
$callable = [$this, $this->authTypes[$this->authtype]];
return call_user_func_array($callable, $config);
}
return $config;
}
/**
* Add basic authorization to header
*
* @param string $method
* @param string $url
* @param array $headers
* @param string $body
* @param $bodyType
*
* @return array
*/
private function basicAuthorization($method, $url, $headers, $body, $bodyType)
{
if (isset($this->credentials) && is_array($this->credentials)) {
$headers['Authorization'] = 'Basic ' . base64_encode($this->credentials['username'] . ':' . $this->credentials['password']);
}
return [$method, $url, $headers, $body, $bodyType];
}
/**
* Add bearer authorization to header
*
* @param string $method
* @param string $url
* @param array $headers
* @param string $body
* @param $bodyType
*
* @return array
*/
private function bearerAuthorization($method, $url, $headers, $body, $bodyType)
{
if (isset($this->credentials) && is_array($this->credentials)) {
$headers['Authorization'] = 'Bearer ' . $this->credentials['token'];
}
return [$method, $url, $headers, $body, $bodyType];
}
/**
* Get token with credentials
*
* @param string $method
* @param string $url
* @param array $headers
* @param string $body
* @param $bodyType
*
* @return array
*/
private function passwordAuthorization($method, $url, $headers, $body, $bodyType)
{
if (isset($this->credentials) && is_array($this->credentials)) {
//todo enable mustache
$config = [
'username' => $this->credentials['username'],
'password' => $this->credentials['password'],
'grant_type' => 'password',
'client_id' => $this->credentials['client_id'],
'client_secret' => $this->credentials['client_secret'],
];
$token = $this->response($this->call('POST', $this->credentials['url'], ['Accept' => 'application/json'], json_encode($config), 'form-data'), [], ['dataMapping' => []], new Mustache_Engine());
$headers['Authorization'] = 'Bearer ' . $token['response']['access_token'];
}
return [$method, $url, $headers, $body, $bodyType];
}
/**
* Prepare the response, using the mapping configuration
*
* @param Response $response
* @param array $data
* @param array $config
* @param Mustache_Engine $mustache
*
* @return array
* @throws HttpResponseException
*/
private function response($response, array $data = [], array $config = [], Mustache_Engine $mustache)
{
$status = $response->getStatusCode();
switch (true) {
case $status == 200:
$content = json_decode($response->getBody()->getContents(), true);
break;
case $status > 200 && $status < 300:
$content = [];
break;
default:
throw new HttpResponseException($response);
}
$mapped = [];
!is_array($content) ?: $merged = array_merge($data, $content);
$mapped['status'] = $status;
$mapped['response'] = $content;
if (isset($config['dataMapping'])) {
foreach ($config['dataMapping'] as $map) {
//$value = $mustache->render($map['value'], $merged);
$value = Arr::get($merged, $map['value'], '');
Arr::set($mapped, $map['key'], $value);
}
}
return $mapped;
}
/**
* Call an HTTP request
*
* @param string $method
* @param string $url
* @param array $headers
* @param $body
* @param string $bodyType
*
* @return mixed|ResponseInterface
*
* @throws GuzzleException
*/
private function call($method, $url, array $headers, $body, $bodyType)
{
$client = new Client(['verify' => $this->verifySsl]);
$options = [];
if ($bodyType === 'form-data') {
$options['form_params'] = json_decode($body, true);
}
$request = new Request($method, $url, $headers, $body);
return $client->send($request, $options);
}
}