-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathLaravel.php
More file actions
461 lines (372 loc) · 13 KB
/
Laravel.php
File metadata and controls
461 lines (372 loc) · 13 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
<?php
declare(strict_types=1);
namespace Codeception\Lib\Connector;
use Closure;
use Codeception\Lib\Connector\Laravel\ExceptionHandlerDecorator as LaravelExceptionHandlerDecorator;
use Codeception\Lib\Connector\Laravel6\ExceptionHandlerDecorator as Laravel6ExceptionHandlerDecorator;
use Codeception\Module\Laravel as LaravelModule;
use Codeception\Stub;
use Exception;
use Illuminate\Contracts\Config\Repository as Config;
use Illuminate\Contracts\Debug\ExceptionHandler;
use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\Events\Dispatcher as Events;
use Illuminate\Contracts\Foundation\Application as AppContract;
use Illuminate\Contracts\Http\Kernel as HttpKernel;
use Illuminate\Database\ConnectionResolverInterface as Db;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Bootstrap\RegisterProviders;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelBrowser as Client;
class Laravel extends Client
{
private array $bindings = [];
private array $contextualBindings = [];
/**
* @var object[]
*/
private array $instances = [];
/**
* @var callable[]
*/
private array $applicationHandlers = [];
private ?AppContract $app = null;
private LaravelModule $module;
private bool $firstRequest = true;
private array $triggeredEvents = [];
private bool $exceptionHandlingDisabled;
private bool $middlewareDisabled;
private bool $eventsDisabled;
private bool $modelEventsDisabled;
private ?object $oldDb = null;
/**
* Constructor.
*
* @param LaravelModule $module
* @throws Exception
*/
public function __construct($module)
{
$this->module = $module;
$this->exceptionHandlingDisabled = $this->module->config['disable_exception_handling'];
$this->middlewareDisabled = $this->module->config['disable_middleware'];
$this->eventsDisabled = $this->module->config['disable_events'];
$this->modelEventsDisabled = $this->module->config['disable_model_events'];
$this->initialize();
$components = parse_url($this->getConfig()->get('app.url', 'http://localhost'));
if (array_key_exists('url', $this->module->config)) {
$components = parse_url($this->module->config['url']);
}
$host = $components['host'] ?? 'localhost';
parent::__construct($this->app, ['HTTP_HOST' => $host]);
// Parent constructor defaults to not following redirects
$this->followRedirects(true);
}
/**
* Execute a request.
*
* @param SymfonyRequest $request
* @throws Exception
*/
protected function doRequest($request): Response
{
if (!$this->firstRequest) {
$this->initialize($request);
}
$this->firstRequest = false;
$this->applyBindings();
$this->applyContextualBindings();
$this->applyInstances();
$this->applyApplicationHandlers();
$request = Request::createFromBase($request);
$response = $this->kernel->handle($request);
$this->getHttpKernel()->terminate($request, $response);
return $response;
}
private function initialize(SymfonyRequest $request = null): void
{
// Store a reference to the database object
// so the database connection can be reused during tests
$this->oldDb = null;
$db = $this->getDb();
if ($db && $db->connection()) {
$this->oldDb = $db;
}
$this->app = $this->loadApplication();
$this->kernel = $this->app;
// Set the request instance for the application,
if (is_null($request)) {
$appConfig = require $this->module->config['project_dir'] . 'config/app.php';
$request = SymfonyRequest::create($appConfig['url']);
}
$this->app->instance('request', Request::createFromBase($request));
// Reset the old database after all the service providers are registered.
if ($this->oldDb) {
$this->getEvents()->listen('bootstrapped: ' . RegisterProviders::class, function (): void {
$this->app->singleton('db', fn(): object => $this->oldDb);
});
}
$this->getHttpKernel()->bootstrap();
$listener = function ($event): void {
$this->triggeredEvents[] = $this->normalizeEvent($event);
};
$this->getEvents()->listen('*', $listener);
// Replace the Laravel exception handler with our decorated exception handler,
// so exceptions can be intercepted for the disable_exception_handling functionality.
if (version_compare(Application::VERSION, '7.0.0', '<')) {
$decorator = new Laravel6ExceptionHandlerDecorator($this->getExceptionHandler());
} else {
$decorator = new LaravelExceptionHandlerDecorator($this->getExceptionHandler());
}
$decorator->exceptionHandlingDisabled($this->exceptionHandlingDisabled);
$this->app->instance(ExceptionHandler::class, $decorator);
if ($this->module->config['disable_middleware'] || $this->middlewareDisabled) {
$this->app->instance('middleware.disable', true);
}
if ($this->module->config['disable_events'] || $this->eventsDisabled) {
$this->mockEventDispatcher();
}
if ($this->module->config['disable_model_events'] || $this->modelEventsDisabled) {
Model::unsetEventDispatcher();
}
$this->module->setApplication($this->app);
}
/**
* Boot the Laravel application object.
*/
private function loadApplication(): AppContract
{
/** @var AppContract $app */
$app = require $this->module->config['bootstrap_file'];
$app->loadEnvironmentFrom($this->module->config['environment_file']);
$app->instance('request', new Request());
return $app;
}
/**
* Replace the Laravel event dispatcher with a mock.
*/
private function mockEventDispatcher(): void
{
// Even if events are disabled we still want to record the triggered events.
// But by mocking the event dispatcher the wildcard listener registered in the initialize method is removed.
// So to record the triggered events we have to catch the calls to the fire method of the event dispatcher mock.
$callback = function ($event): array {
$this->triggeredEvents[] = $this->normalizeEvent($event);
return [];
};
$mock = Stub::makeEmpty(Dispatcher::class, ['dispatch' => $callback]);
$this->app->instance('events', $mock);
}
/**
* Normalize events to class names.
*
* @param object|string $event
* @return string
*/
private function normalizeEvent($event): string
{
if (is_object($event)) {
$event = get_class($event);
}
if (preg_match('#^bootstrapp(ing|ed): #', $event)) {
return $event;
}
// Events can be formatted as 'event.name: parameters'
$segments = explode(':', $event);
return $segments[0];
}
/**
* Apply the registered application handlers.
*/
private function applyApplicationHandlers(): void
{
foreach ($this->applicationHandlers as $handler) {
call_user_func($handler, $this->app);
}
}
/**
* Apply the registered Laravel service container bindings.
*/
private function applyBindings(): void
{
foreach ($this->bindings as $abstract => $binding) {
[$concrete, $shared] = $binding;
$this->app->bind($abstract, $concrete, $shared);
}
}
/**
* Apply the registered Laravel service container contextual bindings.
*/
private function applyContextualBindings(): void
{
foreach ($this->contextualBindings as $concrete => $bindings) {
foreach ($bindings as $abstract => $implementation) {
$this->app->addContextualBinding($concrete, $abstract, $implementation);
}
}
}
/**
* Apply the registered Laravel service container instance bindings.
*/
private function applyInstances(): void
{
foreach ($this->instances as $abstract => $instance) {
$this->app->instance($abstract, $instance);
}
}
/**
* Make sure files are \Illuminate\Http\UploadedFile instances with the private $test property set to true.
* Fixes issue https://github.com/Codeception/Codeception/pull/3417.
*/
protected function filterFiles(array $files): array
{
$files = parent::filterFiles($files);
return $this->convertToTestFiles($files);
}
private function convertToTestFiles(array &$files): array
{
$filtered = [];
foreach ($files as $key => $value) {
if (is_array($value)) {
$filtered[$key] = $this->convertToTestFiles($value);
$files[$key] = $value;
} else {
$filtered[$key] = UploadedFile::createFromBase($value, true);
unset($files[$key]);
}
}
return $filtered;
}
// Public methods called by module
public function clearApplicationHandlers(): void
{
$this->applicationHandlers = [];
}
public function disableEvents(): void
{
$this->eventsDisabled = true;
$this->mockEventDispatcher();
}
public function disableExceptionHandling(): void
{
$this->exceptionHandlingDisabled = true;
$this->getExceptionHandler()->exceptionHandlingDisabled(true);
}
public function disableMiddleware($middleware = null): void
{
if (is_null($middleware)) {
$this->middlewareDisabled = true;
$this->app->instance('middleware.disable', true);
return;
}
foreach ((array) $middleware as $abstract) {
$this->app->instance($abstract, new class
{
public function handle($request, $next)
{
return $next($request);
}
});
}
}
public function disableModelEvents(): void
{
$this->modelEventsDisabled = true;
Model::unsetEventDispatcher();
}
public function enableExceptionHandling(): void
{
$this->exceptionHandlingDisabled = false;
$this->getExceptionHandler()->exceptionHandlingDisabled(false);
}
public function enableMiddleware($middleware = null): void
{
if (is_null($middleware)) {
$this->middlewareDisabled = false;
unset($this->app['middleware.disable']);
return;
}
foreach ((array) $middleware as $abstract) {
unset($this->app[$abstract]);
}
}
/**
* Did an event trigger?
*
* @param object|string $event
*/
public function eventTriggered($event): bool
{
$event = $this->normalizeEvent($event);
foreach ($this->triggeredEvents as $triggeredEvent) {
if ($event == $triggeredEvent || is_subclass_of($event, $triggeredEvent)) {
return true;
}
}
return false;
}
public function haveApplicationHandler(callable $handler): void
{
$this->applicationHandlers[] = $handler;
}
/**
* @param Closure|string|null $concrete
*/
public function haveBinding(string $abstract, $concrete, bool $shared = false): void
{
$this->bindings[$abstract] = [$concrete, $shared];
}
/**
* @param Closure|string $implementation
*/
public function haveContextualBinding(string $concrete, string $abstract, $implementation): void
{
if (! isset($this->contextualBindings[$concrete])) {
$this->contextualBindings[$concrete] = [];
}
$this->contextualBindings[$concrete][$abstract] = $implementation;
}
public function haveInstance(string $abstract, object $instance): void
{
$this->instances[$abstract] = $instance;
}
/**
* @return \Illuminate\Config\Repository
*/
public function getConfig(): ?Config
{
return $this->app['config'] ?? null;
}
/**
* @return \Illuminate\Database\DatabaseManager
*/
public function getDb(): ?Db
{
return $this->app['db'] ?? null;
}
/**
* @return \Illuminate\Events\Dispatcher
*/
public function getEvents(): ?Events
{
return $this->app['events'] ?? null;
}
/**
* @return \Illuminate\Foundation\Exceptions\Handler
*/
public function getExceptionHandler(): ?ExceptionHandler
{
return $this->app[ExceptionHandler::class] ?? null;
}
/**
* @return \Illuminate\Foundation\Http\Kernel
*/
public function getHttpKernel(): ?HttpKernel
{
return $this->app[HttpKernel::class] ?? null;
}
}