Repository navigation
Expand file tree
/
Copy pathKernelBrowser.php
More file actions
321 lines (262 loc) · 10.4 KB
/
Copy pathKernelBrowser.php
File metadata and controls
321 lines (262 loc) · 10.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
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle;
use Symfony\Bundle\FrameworkBundle\Test\TestBrowserToken;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\BrowserKit\History;
use Symfony\Component\BrowserKit\Request as DomRequest;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\HttpKernel\HttpKernelBrowser;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Component\HttpKernel\Profiler\Profile as HttpProfile;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Simulates a browser and makes requests to a Kernel object.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class KernelBrowser extends HttpKernelBrowser
{
private bool $hasPerformedRequest = false;
private bool $profiler = false;
private bool $reboot = true;
private ?\Closure $containerConfigurator = null;
/**
* @var array<string, TestBrowserToken>
*/
private array $tokens = [];
public function __construct(KernelInterface $kernel, array $server = [], ?History $history = null, ?CookieJar $cookieJar = null)
{
parent::__construct($kernel, $server, $history, $cookieJar);
}
public function getContainer(): ContainerInterface
{
$container = $this->kernel->getContainer();
return $container->has('test.service_container') ? $container->get('test.service_container') : $container;
}
public function getKernel(): KernelInterface
{
return $this->kernel;
}
/**
* Gets the profile associated with the current Response.
*/
public function getProfile(): HttpProfile|false|null
{
if (!isset($this->response) || !$this->getContainer()->has('profiler')) {
return false;
}
return $this->getContainer()->get('profiler')->loadProfileFromResponse($this->response);
}
public function getSession(): ?SessionInterface
{
$container = $this->getContainer();
if (!$container->has('session.factory')) {
return null;
}
$session = $container->get('session.factory')->createSession();
$cookieJar = $this->getCookieJar();
$cookie = $cookieJar->get($session->getName());
if ($cookie instanceof Cookie) {
$session->setId($cookie->getValue());
}
$session->start();
if (!$cookie instanceof Cookie) {
$domains = array_unique(array_map(static fn (Cookie $cookie) => $cookie->getName() === $session->getName() ? $cookie->getDomain() : '', $cookieJar->all())) ?: [''];
foreach ($domains as $domain) {
$cookieJar->set(new Cookie($session->getName(), $session->getId(), domain: $domain));
}
}
return $session;
}
/**
* Enables the profiler for the very next request.
*
* If the profiler is not enabled, the call to this method does nothing.
*/
public function enableProfiler(): void
{
if ($this->getContainer()->has('profiler')) {
$this->profiler = true;
}
}
/**
* Disables kernel reboot between requests.
*
* By default, the Client reboots the Kernel for each request. This method
* allows to keep the same kernel across requests.
*/
public function disableReboot(): void
{
$this->reboot = false;
}
/**
* Enables kernel reboot between requests.
*/
public function enableReboot(): void
{
$this->reboot = true;
}
/**
* Registers a callable to configure the container for the lifetime of this client.
*
* It is applied right away and then again after each kernel reboot, before the
* container has been used to handle a request.
*
* @internal
*/
public function setContainerConfigurator(\Closure $configurator): void
{
if ($this->insulated) {
throw new \LogicException('Cannot configure the container when requests are insulated, as closures cannot be passed to the insulated process.');
}
$this->containerConfigurator = $configurator;
$configurator($this->getContainer());
}
public function insulate(bool $insulated = true): void
{
if ($insulated && $this->containerConfigurator) {
throw new \LogicException('Cannot insulate requests when a container configurator is registered, as closures cannot be passed to the insulated process.');
}
parent::insulate($insulated);
}
public function restart(): void
{
parent::restart();
$this->tokens = [];
}
/**
* @param UserInterface $user
* @param array<string, mixed> $tokenAttributes
*
* @return $this
*/
public function loginUser(object $user, string $firewallContext = 'main', array $tokenAttributes = []): static
{
if (!interface_exists(UserInterface::class)) {
throw new \LogicException(\sprintf('"%s" requires symfony/security-core to be installed. Try running "composer require symfony/security-core".', __METHOD__));
}
if (!$user instanceof UserInterface) {
throw new \LogicException(\sprintf('The first argument of "%s" must be instance of "%s", "%s" provided.', __METHOD__, UserInterface::class, get_debug_type($user)));
}
$token = new TestBrowserToken($user->getRoles(), $user, $firewallContext);
$token->setAttributes($tokenAttributes);
// stateless firewalls don't read the session, so the token is also sent with each request
$this->tokens[$firewallContext] = $token;
$container = $this->getContainer();
$container->get('security.untracked_token_storage')->setToken($token);
if (!$session = $this->getSession()) {
return $this;
}
try {
$session->set('_security_'.$firewallContext, serialize($token));
} catch (\Throwable $e) {
$hint = method_exists($user, '__serialize')
? 'Review the "__serialize()" implementation to exclude any fields that cannot or should not be persisted there'
: 'Implement "__serialize()"/"__unserialize()" to control what is serialized into the session, and exclude any fields that should not be persisted there';
throw new \LogicException(\sprintf('Cannot store the security token in the session: the user object of class "%s" (or one of its referenced objects) is not serializable. %s (e.g. Doctrine relations). See https://symfony.com/doc/current/security.html#understanding-how-users-are-refreshed-from-the-session for details.', $user::class, $hint), 0, $e);
}
$session->save();
return $this;
}
protected function filterRequest(DomRequest $request): Request
{
$httpRequest = parent::filterRequest($request);
if ($this->tokens) {
$httpRequest->attributes->set('_security_test_tokens', $this->tokens);
}
return $httpRequest;
}
/**
* @param Request $request
*/
protected function doRequest(object $request): Response
{
// avoid shutting down the Kernel if no request has been performed yet
// WebTestCase::createClient() boots the Kernel but do not handle a request
if ($this->hasPerformedRequest && $this->reboot) {
$this->kernel->boot();
$this->kernel->shutdown();
if ($this->containerConfigurator) {
$this->kernel->boot();
($this->containerConfigurator)($this->getContainer());
}
} else {
$this->hasPerformedRequest = true;
}
if ($this->profiler) {
$this->profiler = false;
$this->kernel->boot();
$this->getContainer()->get('profiler')->enable();
}
return parent::doRequest($request);
}
/**
* @param Request $request
*/
protected function doRequestInProcess(object $request): Response
{
$response = parent::doRequestInProcess($request);
$this->profiler = false;
return $response;
}
/**
* Returns the script to execute when the request must be insulated.
*
* It assumes that the autoloader is named 'autoload.php' and that it is
* stored in the same directory as the kernel (this is the case for the
* Symfony Standard Edition). If this is not your case, create your own
* client and override this method.
*
* @param Request $request
*/
protected function getScript(object $request): string
{
$kernel = var_export(serialize($this->kernel), true);
$request = var_export(serialize($request), true);
$errorReporting = error_reporting();
$requires = '';
foreach (get_declared_classes() as $class) {
if (str_starts_with($class, 'ComposerAutoloaderInit')) {
$r = new \ReflectionClass($class);
$file = \dirname($r->getFileName(), 2).'/autoload.php';
if (is_file($file)) {
$requires .= 'require_once '.var_export($file, true).";\n";
}
}
}
if (!$requires) {
throw new \RuntimeException('Composer autoloader not found.');
}
$requires .= 'require_once '.var_export((new \ReflectionObject($this->kernel))->getFileName(), true).";\n";
$profilerCode = '';
if ($this->profiler) {
$profilerCode = <<<'EOF'
$container = $kernel->getContainer();
$container = $container->has('test.service_container') ? $container->get('test.service_container') : $container;
$container->get('profiler')->enable();
EOF;
}
$code = <<<EOF
<?php
error_reporting($errorReporting);
$requires
\$kernel = unserialize($kernel);
\$kernel->boot();
$profilerCode
\$request = unserialize($request);
EOF;
return $code.$this->getHandleScript();
}
}