forked from Codeception/module-phpbrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPhpBrowser.php
283 lines (252 loc) · 7.64 KB
/
PhpBrowser.php
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
<?php
declare(strict_types=1);
namespace Codeception\Module;
use Closure;
use Codeception\Lib\Connector\Guzzle;
use Codeception\Lib\InnerBrowser;
use Codeception\Lib\Interfaces\MultiSession;
use Codeception\Lib\Interfaces\Remote;
use Codeception\TestInterface;
use Codeception\Util\Uri;
use GuzzleHttp\Client as GuzzleClient;
use Symfony\Component\BrowserKit\AbstractBrowser;
/**
* Uses [Guzzle](https://docs.guzzlephp.org/en/stable/) to interact with your application over CURL.
* Module works over CURL and requires **PHP CURL extension** to be enabled.
*
* Use to perform web acceptance tests with non-javascript browser.
*
* If test fails stores last shown page in 'output' dir.
*
* ## Configuration
*
* * url *required* - start url of your app
* * headers - default headers are set before each test.
* * handler (default: curl) - Guzzle handler to use. By default curl is used, also possible to pass `stream`, or any valid class name as [Handler](https://docs.guzzlephp.org/en/latest/handlers-and-middleware.html#handlers).
* * middleware - Guzzle middlewares to add. An array of valid callables is required.
* * curl - curl options
* * cookies - ...
* * auth - ...
* * verify - ...
* * .. those and other [Guzzle Request options](https://docs.guzzlephp.org/en/latest/request-options.html)
*
*
* ### Example (`Acceptance.suite.yml`)
*
* ```yaml
* modules:
* enabled:
* - PhpBrowser:
* url: 'http://localhost' # Internationalized domain names (IDN) need to be passed in punycode
* auth: ['admin', '123345']
* curl:
* CURLOPT_RETURNTRANSFER: true
* cookies:
* cookie-1:
* Name: userName
* Value: john.doe
* cookie-2:
* Name: authToken
* Value: 1abcd2345
* Domain: subdomain.domain.com
* Path: /admin/
* Expires: 1292177455
* Secure: true
* HttpOnly: false
* ```
*
* All SSL certification checks are disabled by default.
* Use Guzzle request options to configure certifications and others.
*
* ## Public API
*
* Those properties and methods are expected to be used in Helper classes:
*
* Properties:
*
* * `guzzle` - contains [Guzzle](https://guzzlephp.org/) client instance: `\GuzzleHttp\Client`
* * `client` - Symfony BrowserKit instance.
*
*/
class PhpBrowser extends InnerBrowser implements Remote, MultiSession
{
/**
* @var string[]
*/
protected array $requiredFields = ['url'];
/**
* @var array<string, mixed>
*/
protected array $config = [
'headers' => [],
'verify' => false,
'expect' => false,
'timeout' => 30,
'curl' => [],
'refresh_max_interval' => 10,
'handler' => 'curl',
'middleware' => null,
// required defaults (not recommended to change)
'allow_redirects' => false,
'http_errors' => false,
'cookies' => true,
];
/**
* @var string[]
*/
protected array $guzzleConfigFields = [
'auth',
'proxy',
'verify',
'cert',
'query',
'ssl_key',
'proxy',
'expect',
'version',
'timeout',
'connect_timeout'
];
/**
* @var Guzzle
*/
public ?AbstractBrowser $client = null;
public ?GuzzleClient $guzzle = null;
public function _initialize()
{
$this->_initializeSession();
}
public function _before(TestInterface $test)
{
if (!$this->client instanceof AbstractBrowser) {
$this->client = new Guzzle();
}
$this->_prepareSession();
}
public function _getUrl()
{
return $this->config['url'];
}
/**
* Alias to `haveHttpHeader`
*/
public function setHeader(string $name, string $value): void
{
$this->haveHttpHeader($name, $value);
}
public function amHttpAuthenticated(string $username, string $password): void
{
if ($this->client instanceof Guzzle) {
$this->client->setAuth($username, $password);
}
}
public function amOnUrl(string $url): void
{
$host = Uri::retrieveHost($url);
$config = $this->config;
$config['url'] = $host;
$this->_reconfigure($config);
$page = substr($url, strlen($host));
if ($page === '') {
$page = '/';
}
$this->debugSection('Host', $host);
$this->amOnPage($page);
}
public function amOnSubdomain(string $subdomain): void
{
$url = $this->config['url'];
$url = preg_replace('#(https?://)(.*\.)(.*\.)#', "$1$3", $url); // removing current subdomain
$url = preg_replace('#(https?://)(.*)#', sprintf('$1%s.$2', $subdomain), $url);
// inserting new
$config = $this->config;
$config['url'] = $url;
$this->_reconfigure($config);
}
protected function onReconfigure()
{
$this->_prepareSession();
}
/**
* Low-level API method.
* If Codeception commands are not enough, use [Guzzle HTTP Client](https://guzzlephp.org/) methods directly
*
* Example:
*
* ``` php
* <?php
* $I->executeInGuzzle(function (\GuzzleHttp\Client $client) {
* $client->get('/get', ['query' => ['foo' => 'bar']]);
* });
* ```
*
* It is not recommended to use this command on a regular basis.
* If Codeception lacks important Guzzle Client methods, implement them and submit patches.
*/
public function executeInGuzzle(Closure $function): mixed
{
return $function($this->guzzle);
}
public function _getResponseCode(): int|string
{
return $this->getResponseStatusCode();
}
public function _initializeSession(): void
{
// independent sessions need independent cookies
$this->client = new Guzzle();
$this->_prepareSession();
}
public function _prepareSession(): void
{
$defaults = array_intersect_key($this->config, array_flip($this->guzzleConfigFields));
$curlOptions = [];
foreach ($this->config['curl'] as $key => $val) {
if (defined($key)) {
$curlOptions[constant($key)] = $val;
}
}
$this->headers = $this->config['headers'];
$this->setCookiesFromOptions();
$defaults['base_uri'] = $this->config['url'];
$defaults['curl'] = $curlOptions;
$handlerStack = Guzzle::createHandler($this->config['handler']);
if (is_array($this->config['middleware'])) {
foreach ($this->config['middleware'] as $middleware) {
$handlerStack->push($middleware);
}
}
$defaults['handler'] = $handlerStack;
$this->guzzle = new GuzzleClient($defaults);
$this->client->setRefreshMaxInterval($this->config['refresh_max_interval']);
$this->client->setClient($this->guzzle);
}
/**
* @return array<string, mixed>
*/
public function _backupSession()
{
return [
'client' => $this->client,
'guzzle' => $this->guzzle,
'crawler' => $this->crawler,
'headers' => $this->headers,
];
}
/**
* @param array<string, mixed> $session
*/
public function _loadSession($session): void
{
foreach ($session as $key => $val) {
$this->$key = $val;
}
}
/**
* @param ?array<string, mixed> $session
*/
public function _closeSession($session = null): void
{
unset($session);
}
}