forked from Codeception/module-yii2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathYii2.php
More file actions
647 lines (573 loc) · 21.3 KB
/
Yii2.php
File metadata and controls
647 lines (573 loc) · 21.3 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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
<?php
declare(strict_types=1);
namespace Codeception\Lib\Connector;
use Codeception\Exception\ConfigurationException;
use Codeception\Exception\ModuleConfigException;
use Codeception\Lib\Connector\Yii2\Logger;
use Codeception\Lib\Connector\Yii2\TestMailer;
use Codeception\Util\Debug;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\BrowserKit\AbstractBrowser as Client;
use Symfony\Component\BrowserKit\Cookie;
use Symfony\Component\BrowserKit\CookieJar;
use Symfony\Component\BrowserKit\History;
use Symfony\Component\BrowserKit\Request as BrowserkitRequest;
use Symfony\Component\BrowserKit\Response;
use Yii;
use yii\base\Event;
use yii\base\ExitException;
use yii\base\Security;
use yii\base\UserException;
use yii\mail\BaseMailer;
use yii\mail\MailEvent;
use yii\mail\MessageInterface;
use yii\web\Application;
use yii\web\IdentityInterface;
use yii\web\Request as YiiRequest;
use yii\web\Response as YiiResponse;
use yii\web\User;
/**
* @extends Client<BrowserkitRequest, Response>
* @internal This class is not part of the public API
*/
final class Yii2 extends Client
{
use Shared\PhpSuperGlobalsConverter;
public const array MAIL_METHODS = [
self::MAIL_CATCH,
self::MAIL_EVENT_AFTER,
self::MAIL_EVENT_BEFORE,
self::MAIL_IGNORE
];
public const string MAIL_CATCH = 'catch';
public const string MAIL_EVENT_AFTER = 'after';
public const string MAIL_EVENT_BEFORE = 'before';
public const string MAIL_IGNORE = 'ignore';
public const array CLEAN_METHODS = [
self::CLEAN_RECREATE,
self::CLEAN_CLEAR,
self::CLEAN_FORCE_RECREATE,
self::CLEAN_MANUAL,
];
/**
* Clean the response object by recreating it.
* This might lose behaviors / event handlers / other changes that are done in the application bootstrap phase.
*/
public const string CLEAN_RECREATE = 'recreate';
/**
* Same as recreate but will not warn when behaviors / event handlers are lost.
*/
public const string CLEAN_FORCE_RECREATE = 'force_recreate';
/**
* Clean the response object by resetting specific properties via its' `clear()` method.
* This will keep behaviors / event handlers, but could inadvertently leave some changes intact.
*
* @see \yii\web\Response::clear()
*/
public const string CLEAN_CLEAR = 'clear';
/**
* Do not clean the response, instead the test writer will be responsible for manually resetting the response in
* between requests during one test
*/
public const string CLEAN_MANUAL = 'manual';
/**
* @var string application config file
*/
public string $configFile;
/**
* @var self::MAIL_CATCH|self::MAIL_IGNORE|self::MAIL_EVENT_AFTER|self::MAIL_EVENT_BEFORE method for handling mails
*/
public string $mailMethod;
/**
* @var string method for cleaning the response object before each request
*/
public string $responseCleanMethod;
/**
* @var string method for cleaning the request object before each request
*/
public string $requestCleanMethod;
/**
* @var string[] List of component names that must be recreated before each request
*/
public array $recreateComponents = [];
/**
* This option is there primarily for backwards compatibility.
* It means you cannot make any modification to application state inside your app, since they will get discarded.
*
* @var bool whether to recreate the whole application before each request
*/
public bool $recreateApplication = false;
/**
* @var bool whether to close the session in between requests inside a single test, if recreateApplication is set to true
*/
public bool $closeSessionOnRecreateApplication = true;
/**
* @var class-string The FQN of the application class to use. In a default Yii setup, should be either `yii\web\Application`
* or `yii\console\Application`
*/
public string|null $applicationClass = null;
/**
* @var list<MessageInterface>
*/
private array $emails = [];
/**
* @internal
*/
protected function getApplication(): \yii\base\Application
{
if (! isset(Yii::$app)) {
$this->startApp();
}
return Yii::$app ?? throw new RuntimeException('Failed to create Yii2 application');
}
private function getWebRequest(): YiiRequest
{
$request = $this->getApplication()->request;
if (! $request instanceof YiiRequest) {
throw new RuntimeException('Request component is not of type ' . YiiRequest::class);
}
return $request;
}
public function resetApplication(bool $closeSession = true): void
{
codecept_debug('Destroying application');
if ($closeSession) {
$this->closeSession();
}
Yii::$app = null;
\yii\web\UploadedFile::reset();
Event::offAll();
Yii::setLogger(null);
// This resolves an issue with database connections not closing properly.
gc_collect_cycles();
}
/**
* Finds and logs in a user
*
* @internal
* @throws ConfigurationException|RuntimeException
*/
public function findAndLoginUser(int|string|IdentityInterface $user): void
{
$app = $this->getApplication();
$userComponent = $app->get('user');
if (! $userComponent instanceof User) {
throw new ConfigurationException('The user component is not configured');
}
$identity = $user instanceof IdentityInterface ? $user : ($userComponent->identityClass)::findIdentity($user);
if ($identity === null) {
throw new RuntimeException('User not found');
}
$userComponent->login($identity);
}
/**
* @internal
* @param string $name The name of the cookie
* @param string $value The value of the cookie
* @return string The value to send to the browser
*/
public function hashCookieData(string $name, string $value): string
{
$request = $this->getWebRequest();
if (! $request->enableCookieValidation) {
return $value;
}
return $this->getApplication()->security->hashData(serialize([$name, $value]), $request->cookieValidationKey);
}
/**
* @internal
* @return non-empty-list<string> List of regex patterns for recognized domain names
*/
public function getInternalDomains(): array
{
$urlManager = $this->getApplication()->urlManager;
$domains = [$this->getDomainRegex($urlManager->hostInfo)];
if ($urlManager->enablePrettyUrl) {
foreach ($urlManager->rules as $rule) {
/**
* @var \yii\web\UrlRule $rule
*/
if ($rule->host !== null) {
$domains[] = $this->getDomainRegex($rule->host);
}
}
}
return array_values(array_unique($domains));
}
/**
* @internal
* @return list<MessageInterface> List of sent emails
*/
public function getEmails(): array
{
return $this->emails;
}
/**
* Deletes all stored emails.
*
* @internal
*/
public function clearEmails(): void
{
$this->emails = [];
}
/**
* Getting domain regex from rule host template
*/
private function getDomainRegex(string $template): string
{
if (preg_match('#https?://(.*)#', $template, $matches)) {
$template = $matches[1];
}
$parameters = [];
if (str_contains($template, '<')) {
$template = preg_replace_callback(
'/<(?:\w+):?([^>]+)?>/u',
function ($matches) use (&$parameters): string {
$key = '__' . count($parameters) . '__';
$parameters[$key] = $matches[1] ?? '\w+';
return $key;
},
$template,
);
}
if ($template === null) {
throw new RuntimeException("Failed to parse domain regex");
}
$template = preg_quote($template);
$template = strtr($template, $parameters);
return '/^' . $template . '$/u';
}
/**
* Gets the name of the CSRF param.
*
* @internal
*/
public function getCsrfParamName(): string
{
return $this->getWebRequest()->csrfParam;
}
public function startApp(?\yii\log\Logger $logger = null): void
{
codecept_debug('Starting application');
$config = include $this->configFile;
if (! isset($config['class'])) {
$config['class'] = $this->applicationClass ?? \yii\web\Application::class;
}
if (isset($config['container'])) {
Yii::configure(Yii::$container, $config['container']);
unset($config['container']);
}
match ($this->mailMethod) {
self::MAIL_CATCH => $config = $this->mockMailer($config),
self::MAIL_EVENT_AFTER => $config['components']['mailer']['on ' . BaseMailer::EVENT_AFTER_SEND] = function (MailEvent $event): void {
if ($event->isSuccessful) {
$this->emails[] = $event->message;
}
},
self::MAIL_EVENT_BEFORE => $config['components']['mailer']['on ' . BaseMailer::EVENT_BEFORE_SEND] = fn (MailEvent $event) => $this->emails[] = $event->message,
self::MAIL_IGNORE => null// Do nothing
};
$app = Yii::createObject($config);
if (! $app instanceof \yii\base\Application) {
throw new ModuleConfigException($this, "Failed to initialize Yii2 app");
}
\Yii::$app = $app;
if ($logger instanceof \yii\log\Logger) {
Yii::setLogger($logger);
} else {
Yii::setLogger(new Logger());
}
}
/**
* @param BrowserkitRequest $request
*/
public function doRequest(object $request): Response
{
$_COOKIE = $request->getCookies();
$_SERVER = $request->getServer();
$_FILES = $this->remapFiles($request->getFiles());
$_REQUEST = $this->remapRequestParameters($request->getParameters());
$_POST = $_GET = [];
if (strtoupper($request->getMethod()) === 'GET') {
$_GET = $_REQUEST;
} else {
$_POST = $_REQUEST;
}
$uri = $request->getUri();
$pathString = parse_url($uri, PHP_URL_PATH);
$queryString = parse_url($uri, PHP_URL_QUERY);
$_SERVER['REQUEST_URI'] = $queryString === null ? $pathString : $pathString . '?' . $queryString;
$_SERVER['REQUEST_METHOD'] = strtoupper($request->getMethod());
$_SERVER['QUERY_STRING'] = (string) $queryString;
parse_str($queryString ?: '', $params);
foreach ($params as $k => $v) {
$_GET[$k] = $v;
}
ob_start();
$this->beforeRequest();
$app = $this->getApplication();
if (! $app instanceof Application) {
throw new ConfigurationException("Application is not a web application");
}
// disabling logging. Logs are slowing test execution down
foreach ($app->log->targets as $target) {
$target->enabled = false;
}
$yiiRequest = $app->getRequest();
if ($request->getContent() !== null) {
$yiiRequest->setRawBody($request->getContent());
$yiiRequest->setBodyParams(null);
} else {
$yiiRequest->setRawBody(null);
$yiiRequest->setBodyParams($_POST);
}
$yiiRequest->setQueryParams($_GET);
try {
/*
* This is basically equivalent to $app->run() without sending the response.
* Sending the response is problematic because it tries to send headers.
*/
$app->trigger($app::EVENT_BEFORE_REQUEST);
$yiiResponse = $app->handleRequest($yiiRequest);
$app->trigger($app::EVENT_AFTER_REQUEST);
$yiiResponse->send();
} catch (\Exception $e) {
if ($e instanceof UserException) {
// Don't discard output and pass exception handling to Yii to be able
// to expect error response codes in tests.
$app->errorHandler->discardExistingOutput = false;
$app->errorHandler->handleException($e);
} elseif (! $e instanceof ExitException) {
// for exceptions not related to Http, we pass them to Codeception
throw $e;
}
$yiiResponse = $app->response;
}
$this->encodeCookies($yiiResponse, $yiiRequest, $app->security);
if ($yiiResponse->isRedirection) {
Debug::debug("[Redirect with headers]" . print_r($yiiResponse->getHeaders()->toArray(), true));
}
$content = ob_get_clean();
if (empty($content) && ! empty($yiiResponse->content) && ! isset($yiiResponse->stream)) {
throw new RuntimeException('No content was sent from Yii application');
} elseif ($content === false) {
throw new RuntimeException('Failed to get output buffer');
}
return new Response($content, $yiiResponse->statusCode, $yiiResponse->getHeaders()->toArray());
}
/**
* Encodes the cookies and adds them to the headers.
*
* @throws \yii\base\InvalidConfigException
*/
protected function encodeCookies(
YiiResponse $response,
YiiRequest $request,
Security $security,
): void {
if ($request->enableCookieValidation) {
$validationKey = $request->cookieValidationKey;
}
foreach ($response->getCookies() as $cookie) {
/**
* @var \yii\web\Cookie $cookie
*/
$value = $cookie->value;
// Expire = 1 means we're removing the cookie
if ($cookie->expire !== 1 && isset($validationKey)) {
$data = version_compare(Yii::getVersion(), '2.0.2', '>')
? [$cookie->name, $cookie->value]
: $cookie->value;
$value = $security->hashData(serialize($data), $validationKey);
}
$expires = is_int($cookie->expire) ? (string) $cookie->expire : null;
$c = new Cookie(
$cookie->name,
$value,
$expires,
$cookie->path,
$cookie->domain,
$cookie->secure,
$cookie->httpOnly,
);
$this->getCookieJar()->set($c);
}
}
/**
* Replace mailer with in memory mailer
*
* @param array<string, mixed> $config Original configuration
* @return array<string, mixed> New configuration
*/
protected function mockMailer(array $config): array
{
// options that make sense for mailer mock
$allowedOptions = [
'htmlLayout',
'textLayout',
'messageConfig',
'messageClass',
'useFileTransport',
'fileTransportPath',
'fileTransportCallback',
'view',
'viewPath',
];
$mailerConfig = [
'class' => TestMailer::class,
'callback' => function (MessageInterface $message): void {
$this->emails[] = $message;
},
];
if (isset($config['components'])) {
if (! is_array($config['components'])) {
throw new ModuleConfigException(
$this,
"Yii2 config does not contain components key is not of type array",
);
}
} else {
$config['components'] = [];
}
if (isset($config['components']['mailer']) && is_array($config['components']['mailer'])) {
foreach ($config['components']['mailer'] as $name => $value) {
if (in_array($name, $allowedOptions, true)) {
$mailerConfig[$name] = $value;
}
}
}
$config['components']['mailer'] = $mailerConfig;
return $config;
}
public function restart(): void
{
parent::restart();
$this->resetApplication();
}
/**
* Return an assoc array with the client context: cookieJar, history.
*
* @internal
* @return array{ cookieJar: CookieJar, history: History }
*/
public function getContext(): array
{
return [
'cookieJar' => $this->cookieJar,
'history' => $this->history,
];
}
/**
* Set the context, see getContext().
*
* @param array{ cookieJar: CookieJar, history: History } $context
*/
public function setContext(array $context): void
{
$this->cookieJar = $context['cookieJar'];
$this->history = $context['history'];
}
/**
* This functions closes the session of the application, if the application exists and has a session.
*
* @internal
*/
public function closeSession(): void
{
$app = $this->getApplication();
if ($app instanceof \yii\web\Application && $app->has('session', true)) {
$app->session->close();
}
}
/**
* Resets the applications' response object.
* The method used depends on the module configuration.
*/
protected function resetResponse(Application $app): void
{
$method = $this->responseCleanMethod;
// First check the current response object.
if (($app->response->hasEventHandlers(YiiResponse::EVENT_BEFORE_SEND)
|| $app->response->hasEventHandlers(YiiResponse::EVENT_AFTER_SEND)
|| $app->response->hasEventHandlers(YiiResponse::EVENT_AFTER_PREPARE)
|| count($app->response->getBehaviors()) > 0)
&& $method === self::CLEAN_RECREATE
) {
Debug::debug(
<<<TEXT
[WARNING] You are attaching event handlers or behaviors to the response object. But the Yii2 module is configured to recreate
the response object, this means any behaviors or events that are not attached in the component config will be lost.
We will fall back to clearing the response. If you are certain you want to recreate it, please configure
responseCleanMethod = 'force_recreate' in the module.
TEXT,
);
$method = self::CLEAN_CLEAR;
}
match ($method) {
self::CLEAN_FORCE_RECREATE, self::CLEAN_RECREATE => $app->set('response', $app->getComponents()['response']),
self::CLEAN_CLEAR => $app->response->clear(),
self::CLEAN_MANUAL => null,
default => throw new InvalidArgumentException("Unknown method: $method"),
};
}
protected function resetRequest(Application $app): void
{
$method = $this->requestCleanMethod;
$request = $app->request;
// First check the current request object.
if (count($request->getBehaviors()) > 0 && $method === self::CLEAN_RECREATE) {
Debug::debug(
<<<TEXT
[WARNING] You are attaching event handlers or behaviors to the request object. But the Yii2 module is configured to recreate
the request object, this means any behaviors or events that are not attached in the component config will be lost.
We will fall back to clearing the request. If you are certain you want to recreate it, please configure
requestCleanMethod = 'force_recreate' in the module.
TEXT,
);
$method = self::CLEAN_CLEAR;
}
match ($method) {
self::CLEAN_FORCE_RECREATE, self::CLEAN_RECREATE => $app->set('request', $app->getComponents()['request']),
self::CLEAN_CLEAR => (function () use ($request): void {
$request->getHeaders()->removeAll();
$request->setBaseUrl(null);
$request->setHostInfo(null);
$request->setPathInfo(null);
$request->setScriptFile(null);
$request->setScriptUrl(null);
$request->setUrl(null);
$request->setPort(0);
$request->setSecurePort(0);
$request->setAcceptableContentTypes(null);
$request->setAcceptableLanguages(null);
})(),
self::CLEAN_MANUAL => null,
default => throw new InvalidArgumentException("Unknown method: $method"),
};
}
/**
* Called before each request, preparation happens here.
*/
protected function beforeRequest(): void
{
if ($this->recreateApplication) {
$this->resetApplication($this->closeSessionOnRecreateApplication);
return;
}
$application = $this->getApplication();
if (! $application instanceof Application) {
throw new ConfigurationException('Application must be an instance of web application when doing requests');
}
$this->resetResponse($application);
$this->resetRequest($application);
$definitions = $application->getComponents(true);
foreach ($this->recreateComponents as $component) {
// Only recreate if it has actually been instantiated.
if ($application->has($component, true)) {
$application->set($component, $definitions[$component]);
}
}
}
}