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
<?php
namespace Codeception\Lib\Connector;
use Aws\Credentials\Credentials;
use Aws\Signature\SignatureV4;
use Codeception\Util\Uri;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Message\Response;
use GuzzleHttp\Post\PostFile;
use Symfony\Component\BrowserKit\Client;
use Symfony\Component\BrowserKit\Response as BrowserKitResponse;
use GuzzleHttp\Url;
use Symfony\Component\BrowserKit\Request as BrowserKitRequest;
class Guzzle extends Client
{
protected $baseUri;
protected $requestOptions = [
'allow_redirects' => false,
'headers' => [],
];
protected $refreshMaxInterval = 0;
protected $awsCredentials = null;
protected $awsSignature = null;
/** @var \GuzzleHttp\Client */
protected $client;
public function setBaseUri($uri)
{
$this->baseUri = $uri;
}
/**
* Sets the maximum allowable timeout interval for a meta tag refresh to
* automatically redirect a request.
*
* A meta tag detected with an interval equal to or greater than $seconds
* would not result in a redirect. A meta tag without a specified interval
* or one with a value less than $seconds would result in the client
* automatically redirecting to the specified URL
*
* @param int $seconds Number of seconds
*/
public function setRefreshMaxInterval($seconds)
{
$this->refreshMaxInterval = $seconds;
}
public function setClient(\GuzzleHttp\Client $client)
{
$this->client = $client;
}
/**
* Sets the request header to the passed value. The header will be
* sent along with the next request.
*
* Passing an empty value clears the header, which is the equivalent
* of calling deleteHeader.
*
* @param string $name the name of the header
* @param string $value the value of the header
*/
public function setHeader($name, $value)
{
if (strval($value) === '') {
$this->deleteHeader($name);
} else {
$this->requestOptions['headers'][$name] = $value;
}
}
/**
* Deletes the header with the passed name from the list of headers
* that will be sent with the request.
*
* @param string $name the name of the header to delete.
*/
public function deleteHeader($name)
{
unset($this->requestOptions['headers'][$name]);
}
/**
* @param string $username
* @param string $password
* @param string $type Default: 'basic'
*/
public function setAuth($username, $password, $type = 'basic')
{
if (!$username) {
unset($this->requestOptions['auth']);
return;
}
$this->requestOptions['auth'] = [$username, $password, $type];
}
/**
* Taken from Mink\BrowserKitDriver
*
* @param Response $response
*
* @return \Symfony\Component\BrowserKit\Response
*/
protected function createResponse(Response $response)
{
$contentType = $response->getHeader('Content-Type');
if (!$contentType) {
$contentType = 'text/html';
}
if (strpos($contentType, 'charset=') === false) {
$body = $response->getBody(true);
if (preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9]+)/i', $body, $matches)) {
$contentType .= ';charset=' . $matches[1];
}
$response->setHeader('Content-Type', $contentType);
}
$headers = $response->getHeaders();
$status = $response->getStatusCode();
if ($status < 300 || $status >= 400) {
$matches = [];
$matchesMeta = preg_match(
'/\<meta[^\>]+http-equiv="refresh" content="\s*(\d*)\s*;\s*url=(.*?)"/i',
$response->getBody(true),
$matches
);
if (!$matchesMeta) {
// match by header
preg_match(
'/^\s*(\d*)\s*;\s*url=(.*)/i',
(string)$response->getHeader('Refresh'),
$matches
);
}
if ((!empty($matches)) && (empty($matches[1]) || $matches[1] < $this->refreshMaxInterval)) {
$uri = $this->getAbsoluteUri($matches[2]);
$partsUri = parse_url($uri);
$partsCur = parse_url($this->getHistory()->current()->getUri());
foreach ($partsCur as $key => $part) {
if ($key === 'fragment') {
continue;
}
if (!isset($partsUri[$key]) || $partsUri[$key] !== $part) {
$status = 302;
$headers['Location'] = $matchesMeta ? htmlspecialchars_decode($uri) : $uri;
break;
}
}
}
}
return new BrowserKitResponse($response->getBody(), $status, $headers);
}
public function getAbsoluteUri($uri)
{
$baseUri = $this->baseUri;
if (strpos($uri, '://') === false && strpos($uri, '//') !== 0) {
if (strpos($uri, '/') === 0) {
$baseUriPath = parse_url($baseUri, PHP_URL_PATH);
if (!empty($baseUriPath) && strpos($uri, $baseUriPath) === 0) {
$uri = substr($uri, strlen($baseUriPath));
}
return Uri::appendPath((string)$baseUri, $uri);
}
// relative url
if (!$this->getHistory()->isEmpty()) {
return Uri::mergeUrls((string)$this->getHistory()->current()->getUri(), $uri);
}
}
return Uri::mergeUrls($baseUri, $uri);
}
protected function doRequest($request)
{
/** @var $request BrowserKitRequest **/
$requestOptions = [
'body' => $this->extractBody($request),
'cookies' => $this->extractCookies($request),
'headers' => $this->extractHeaders($request)
];
$requestOptions = array_replace_recursive($requestOptions, $this->requestOptions);
$guzzleRequest = $this->client->createRequest(
$request->getMethod(),
$request->getUri(),
$requestOptions
);
foreach ($this->extractFiles($request) as $postFile) {
$guzzleRequest->getBody()->addFile($postFile);
}
// Let BrowserKit handle redirects
try {
if (null !== $this->awsCredentials) {
$response = $this->client->send($this->awsSignature->signRequest($guzzleRequest, $this->awsCredentials));
} else {
$response = $this->client->send($guzzleRequest);
}
} catch (RequestException $e) {
if ($e->hasResponse()) {
$response = $e->getResponse();
} else {
throw $e;
}
}
return $this->createResponse($response);
}
protected function extractHeaders(BrowserKitRequest $request)
{
$headers = [];
$server = $request->getServer();
$contentHeaders = ['Content-Length' => true, 'Content-Md5' => true, 'Content-Type' => true];
foreach ($server as $header => $val) {
$header = html_entity_decode(implode('-', array_map('ucfirst', explode('-', strtolower(str_replace('_', '-', $header))))), ENT_NOQUOTES);
if (strpos($header, 'Http-') === 0) {
$headers[substr($header, 5)] = $val;
} elseif (isset($contentHeaders[$header])) {
$headers[$header] = $val;
}
}
return $headers;
}
protected function extractBody(BrowserKitRequest $request)
{
if (in_array(strtoupper($request->getMethod()), ['GET', 'HEAD'])) {
return null;
}
if ($request->getContent() !== null) {
return $request->getContent();
}
return $request->getParameters();
}
protected function extractFiles(BrowserKitRequest $request)
{
if (!in_array(strtoupper($request->getMethod()), ['POST', 'PUT'])) {
return [];
}
return $this->mapFiles($request->getFiles());
}
protected function mapFiles($requestFiles, $arrayName = '')
{
$files = [];
foreach ($requestFiles as $name => $info) {
if (!empty($arrayName)) {
$name = $arrayName.'['.$name.']';
}
if (is_array($info)) {
if (isset($info['tmp_name'])) {
if ($info['tmp_name']) {
$handle = fopen($info['tmp_name'], 'r');
$filename = isset($info['name']) ? $info['name'] : null;
$files[] = new PostFile($name, $handle, $filename);
}
} else {
$files = array_merge($files, $this->mapFiles($info, $name));
}
} else {
$files[] = new PostFile($name, fopen($info, 'r'));
}
}
return $files;
}
protected function extractCookies(BrowserKitRequest $request)
{
return $this->getCookieJar()->allRawValues($request->getUri());
}
public function setAwsAuth($config)
{
$this->awsCredentials = new Credentials($config['key'], $config['secret']);
$this->awsSignature = new SignatureV4($config['service'], $config['region']);
}
}