-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathphpGuzzle.js
More file actions
377 lines (348 loc) · 11.4 KB
/
Copy pathphpGuzzle.js
File metadata and controls
377 lines (348 loc) · 11.4 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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
const getOptions = require('./options').getOptions,
sanitizeString = require('./util/sanitize').sanitizeString,
sanitizeOptions = require('./util/sanitize').sanitizeOptions,
parseBody = require('./util/parseBody').parseBody,
guzzleTimeout = 'timeout',
guzzleAllowRedirects = 'allow_redirects',
_ = require('./lodash');
/**
* Gets the defined indentation from options
*
* @param {object} options - process options
* @returns {String} - indentation characters
*/
function getIndentation (options) {
if (options && options.indentType && options.indentCount) {
let charIndentation = options.indentType === 'Tab' ? '\t' : ' ';
return charIndentation.repeat(options.indentCount);
}
return ' ';
}
/**
* Gets the defined body trim from options
*
* @param {object} options - process options
* @returns {boolea} - wheter to trim the request body
*/
function getBodyTrim (options) {
if (options && options.trimRequestBody) {
return options.trimRequestBody;
}
return false;
}
/**
* Takes in an array and group the ones with same key
*
* @param {Array} headerArray - postman SDK-headers
* @returns {String} - request headers in the desired format
*/
function groupHeadersSameKey (headerArray) {
let res = [],
group = headerArray.reduce((header, a) => {
header[a.key] = [...header[a.key] || [], a];
return header;
}, {});
Object.keys(group).forEach((item) => {
let values = [];
group[item].forEach((child) => {
values.push(child.value);
});
res.push({key: item, value: values.join(', ') });
});
return res;
}
/**
* Transforms an array of headers into the desired form of the language
*
* @param {Array} mapToSnippetArray - array of key values
* @param {String} indentation - used for indenting snippet's structure
* @param {boolean} sanitize - whether to sanitize the key and values
* @returns {String} - array in the form of [ key => value ]
*/
function getSnippetArray (mapToSnippetArray, indentation, sanitize) {
mapToSnippetArray = groupHeadersSameKey(mapToSnippetArray);
let mappedArray = mapToSnippetArray.map((entry) => {
return `${indentation}'${sanitize ? sanitizeString(entry.key, true) : entry.key}' => ` +
`${sanitize ? '\'' + sanitizeString(entry.value) + '\'' : entry.value}`;
});
return `[\n${mappedArray.join(',\n')}\n]`;
}
/**
* Transforms an array of headers into the desired form of the language
*
* @param {Array} headers - postman SDK-headers
* @param {String} indentation - used for indenting snippet's structure
* @returns {String} - request headers in the desired format
*/
function getSnippetHeaders (headers, indentation) {
if (headers.length > 0) {
headers = headers.filter((header) => { return !header.disabled; });
return `$headers = ${getSnippetArray(headers, indentation, true)};\n`;
}
return '';
}
/**
* Used to get the headers and put them in the desired form of the language
*
* @param {Object} request - postman SDK-request object
* @returns {String} - request headers in the desired format
*/
function getRequestHeaders (request) {
return request.headers.members;
}
/**
* Returns the request's url in string format
*
* @param {Object} request - postman SDK-request object
* @returns {String} - request url in string representation
*/
function getRequestURL (request) {
return request.url.toString();
}
/**
* Returns the request's url in string format
*
* @param {Object} request - postman SDK-request object
* @returns {String} - request url in string representation
*/
function getRequestMethod (request) {
return request.method;
}
/**
* Validates if the input is a function
*
* @module convert
*
* @param {*} validateFunction - postman SDK-request object
* @returns {boolean} true if is a function otherwise false
*/
function validateIsFunction (validateFunction) {
return typeof validateFunction === 'function';
}
/**
* Returns the snippet header
*
* @module convert
* @param {string} includeBoilerplate - wheter to include the boilerplate
* @returns {string} the snippet headers (uses)
*/
function getSnippetBoilerplate (includeBoilerplate) {
if (includeBoilerplate) {
return '<?php\n' +
'$composerHome = substr(shell_exec(\'composer config home -g\'), 0, -1).\'/vendor/autoload.php\';\n' +
'require $composerHome; // your path to autoload.php \n' +
'use Psr\\Http\\Message\\ResponseInterface;\n' +
'use GuzzleHttp\\Exception\\RequestException;\n' +
'use GuzzleHttp\\Client;\n' +
'use GuzzleHttp\\Psr7\\Utils;\n' +
'use GuzzleHttp\\Psr7\\Request;\n';
}
return '<?php\n';
}
/**
* Returns the snippet footer sync
*
* @param {string} includeRequestOptions - wheter to include the request options
* @module convert
* @returns {string} the snippet headers (uses)
*/
function getSnippetFooterSync (includeRequestOptions) {
if (!includeRequestOptions) {
return '$res = $client->send($request);\n' +
'echo $res->getBody();\n';
}
return '$res = $client->send($request, $options);\n' +
'echo $res->getBody();';
}
/**
* Returns the snippet footer async
*
* @module convert
* @param {string} includeRequestOptions - wheter to include the request options
* @returns {string} the snippet headers (uses)
*/
function getSnippetFooterAsync (includeRequestOptions) {
if (!includeRequestOptions) {
return '$res = $client->sendAsync($request)->wait();\n' +
'echo $res->getBody();\n';
}
return '$res = $client->sendAsync($request, $options)->wait();\n' +
'echo $res->getBody();';
}
/**
* Returns the snippet footer
*
* @module convert
* @param {object} options - process options
* @param {boolean} includeRequestOptions - wheter to include the request options
* @returns {string} the snippet headers (uses)
*/
function getSnippetFooter (options, includeRequestOptions) {
if (options && options.asyncType && options.asyncType === 'sync') {
return getSnippetFooterSync(includeRequestOptions);
}
return getSnippetFooterAsync(includeRequestOptions);
}
/**
* Generates the snippet for creating the request object
* if has body is true then the body will be added
*
* @module convert
*
* @param {string} method - request's method in string representation
* @param {string} url - request's url in string representation
* @param {boolean} hasBody - wheter the request has body or not
* @param {string} snippetHeaders - the generated snippet headers
* @returns {String} - returns generated PHP-Guzzle snippet for request creation
*/
function getSnippetRequestObject (method, url, hasBody, snippetHeaders) {
if (hasBody && snippetHeaders !== '') {
return `$request = new Request('${method}', '${url}', $headers, $body);\n`;
}
if (!hasBody && snippetHeaders !== '') {
return `$request = new Request('${method}', '${url}', $headers);\n`;
}
if (hasBody && snippetHeaders === '') {
return `$request = new Request('${method}', '${url}', [], $body);\n`;
}
return `$request = new Request('${method}', '${url}');\n`;
}
/**
* Generates the snippet for the client's creation
*
* @param {object} options - process options
* @returns {String} - the snippet to create the client
*/
function getSnippetClient (options) {
if (options) {
let connectionTimeout = options.requestTimeout,
followRedirect = options.followRedirect,
clientOptions = [];
if (connectionTimeout && connectionTimeout !== 0) {
clientOptions.push({ key: guzzleTimeout, value: connectionTimeout });
}
if (followRedirect === false) {
clientOptions.push({ key: guzzleAllowRedirects, value: followRedirect });
}
if (clientOptions.length > 0) {
let snippetArrayOptions = getSnippetArray(clientOptions, getIndentation(options), false) + '\n';
return `$client = new Client(${snippetArrayOptions});\n`;
}
}
return '$client = new Client();\n';
}
/**
* Add the content type header if needed
*
* @module convert
*
* @param {Object} request - postman SDK-request object
*/
function addContentTypeHeader (request) {
if (request.body && request.body.mode === 'graphql' && !request.headers.has('Content-Type')) {
request.addHeader({
key: 'Content-Type',
value: 'application/json'
});
}
}
/**
* Identifies if the request should have a body
*
* @module convert
*
* @param {Object} request - postman SDK-request object
* @param {string} snippetBody - generated body snippet
* @returns {String} - returns generated PHP-Guzzle snippet via callback
*/
function includeBody (request, snippetBody) {
if (_.isEmpty(request.body) || snippetBody === '' || snippetBody.startsWith('$options')) {
return false;
}
return true;
}
/**
* Identifies if the params should go as option
*
* @module convert
*
* @param {string} snippetBody - generated body snippet
* @returns {String} - returns generated PHP-Guzzle snippet via callback
*/
function includeRequestOptions (snippetBody) {
return snippetBody.startsWith('$options');
}
/**
* Gets the defined indentation from options
*
* @param {object} options - process options
* @returns {String} - indentation characters
*/
function getIncludeBoilerplate (options) {
if (options && options.includeBoilerplate !== undefined && options.includeBoilerplate !== null) {
return options.includeBoilerplate;
}
return false;
}
/**
* Used to convert the postman sdk-request object in PHP-Guzzle request snippet
*
* @module convert
*
* @param {Object} request - postman SDK-request object
* @param {object} options - process options
* @param {Function} callback - function with parameters (error, snippet)
* @returns {String} - returns generated PHP-Guzzle snippet via callback
*/
function convert (request, options, callback) {
if (!validateIsFunction(callback)) {
throw new Error('Php-Guzzle~convert: Callback is not a function');
}
let snippet = '',
snippetbody,
requestBuilderSnippet,
includeParamsAsOption,
hasBody;
options = sanitizeOptions(options, getOptions());
addContentTypeHeader(request);
const method = getRequestMethod(request),
indentation = getIndentation(options),
includeBoilerplate = getIncludeBoilerplate(options),
url = getRequestURL(request),
snippetHeaders = getSnippetHeaders(getRequestHeaders(request), indentation),
snippetHeader = getSnippetBoilerplate(includeBoilerplate),
snippetClient = getSnippetClient(options);
snippetbody = parseBody(request.body, indentation, getBodyTrim(options), request.headers.get('Content-Type'));
hasBody = includeBody(request, snippetbody);
includeParamsAsOption = includeRequestOptions(snippetbody);
requestBuilderSnippet = getSnippetRequestObject(method, url, hasBody, snippetHeaders);
snippet += snippetHeader;
snippet += snippetClient;
snippet += snippetHeaders;
snippet += snippetbody;
snippet += requestBuilderSnippet;
snippet += getSnippetFooter(options, includeParamsAsOption);
return callback(null, snippet);
}
module.exports = {
/**
* Used in order to get options for generation of PHP-Guzzle code snippet
*
* @module getOptions
*
* @returns {Array} Options specific to generation of PHP-Guzzlep code snippet
*/
getOptions,
convert,
getHeaders: getRequestHeaders,
getSnippetHeaders,
getSnippetBoilerplate,
getURL: getRequestURL,
getMethod: getRequestMethod,
getIndentation,
getSnippetClient,
getSnippetFooter,
getSnippetRequestObject,
groupHeadersSameKey,
getIncludeBoilerplate
};