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
<?php
namespace Codeception\Lib\Connector;
use Codeception\Lib\Connector\Laravel5\ExceptionHandlerDecorator;
use Codeception\Lib\Connector\Shared\LaravelCommon;
use Codeception\Stub;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Symfony\Component\HttpFoundation\Request as SymfonyRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Client;
class Laravel5 extends Client
{
use LaravelCommon;
/**
* @var Application
*/
private $app;
/**
* @var \Codeception\Module\Laravel5
*/
private $module;
/**
* @var bool
*/
private $firstRequest = true;
/**
* @var array
*/
private $triggeredEvents = [];
/**
* @var bool
*/
private $exceptionHandlingDisabled;
/**
* @var bool
*/
private $middlewareDisabled;
/**
* @var bool
*/
private $eventsDisabled;
/**
* @var bool
*/
private $modelEventsDisabled;
/**
* @var object
*/
private $oldDb;
/**
* Constructor.
*
* @param \Codeception\Module\Laravel5 $module
*/
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->app['config']->get('app.url', 'http://localhost'));
if (array_key_exists('url', $this->module->config)) {
$components = parse_url($this->module->config['url']);
}
$host = isset($components['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
* @return Response
*/
protected function doRequest($request)
{
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->app->make('Illuminate\Contracts\Http\Kernel')->terminate($request, $response);
return $response;
}
/**
* 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.
*
* @param array $files
* @return array
*/
protected function filterFiles(array $files)
{
$files = parent::filterFiles($files);
if (! class_exists('Illuminate\Http\UploadedFile')) {
// The \Illuminate\Http\UploadedFile class was introduced in Laravel 5.2.15,
// so don't change the $files array if it does not exist.
return $files;
}
return $this->convertToTestFiles($files);
}
/**
* @param array $files
* @return array
*/
private function convertToTestFiles(array $files)
{
$filtered = [];
foreach ($files as $key => $value) {
if (is_array($value)) {
$filtered[$key] = $this->convertToTestFiles($value);
} else {
$filtered[$key] = UploadedFile::createFromBase($value, true);
}
}
return $filtered;
}
/**
* Initialize the Laravel framework.
*
* @param SymfonyRequest $request
*/
private function initialize($request = null)
{
// Store a reference to the database object
// so the database connection can be reused during tests
$this->oldDb = null;
if (isset($this->app['db']) && $this->app['db']->connection()) {
$this->oldDb = $this->app['db'];
}
$this->app = $this->kernel = $this->loadApplication();
// 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->app['events']->listen('bootstrapped: Illuminate\Foundation\Bootstrap\RegisterProviders', function () {
$this->app->singleton('db', function () {
return $this->oldDb;
});
});
}
$this->app->make('Illuminate\Contracts\Http\Kernel')->bootstrap();
// Record all triggered events by adding a wildcard event listener
// Since Laravel 5.4 wildcard event handlers receive the event name as the first argument,
// but for earlier Laravel versions the firing() method of the event dispatcher should be used
// to determine the event name.
if (method_exists($this->app['events'], 'firing')) {
$listener = function () {
$this->triggeredEvents[] = $this->normalizeEvent($this->app['events']->firing());
};
} else {
$listener = function ($event) {
$this->triggeredEvents[] = $this->normalizeEvent($event);
};
}
$this->app['events']->listen('*', $listener);
// Replace the Laravel exception handler with our decorated exception handler,
// so exceptions can be intercepted for the disable_exception_handling functionality.
$decorator = new ExceptionHandlerDecorator($this->app['Illuminate\Contracts\Debug\ExceptionHandler']);
$decorator->exceptionHandlingDisabled($this->exceptionHandlingDisabled);
$this->app->instance('Illuminate\Contracts\Debug\ExceptionHandler', $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.
* @return Application
* @throws ModuleConfig
*/
private function loadApplication()
{
$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()
{
// 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) {
$this->triggeredEvents[] = $this->normalizeEvent($event);
return [];
};
// In Laravel 5.4 the Illuminate\Contracts\Events\Dispatcher interface was changed,
// the 'fire' method was renamed to 'dispatch'. This code determines the correct method to mock.
$method = method_exists($this->app['events'], 'dispatch') ? 'dispatch' : 'fire';
$mock = Stub::makeEmpty('Illuminate\Contracts\Events\Dispatcher', [
$method => $callback
]);
$this->app->instance('events', $mock);
}
/**
* Normalize events to class names.
*
* @param $event
* @return string
*/
private function normalizeEvent($event)
{
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];
}
//======================================================================
// Public methods called by module
//======================================================================
/**
* Did an event trigger?
*
* @param $event
* @return bool
*/
public function eventTriggered($event)
{
$event = $this->normalizeEvent($event);
foreach ($this->triggeredEvents as $triggeredEvent) {
if ($event == $triggeredEvent || is_subclass_of($event, $triggeredEvent)) {
return true;
}
}
return false;
}
/**
* Disable Laravel exception handling.
*/
public function disableExceptionHandling()
{
$this->exceptionHandlingDisabled = true;
$this->app['Illuminate\Contracts\Debug\ExceptionHandler']->exceptionHandlingDisabled(true);
}
/**
* Enable Laravel exception handling.
*/
public function enableExceptionHandling()
{
$this->exceptionHandlingDisabled = false;
$this->app['Illuminate\Contracts\Debug\ExceptionHandler']->exceptionHandlingDisabled(false);
}
/**
* Disable events.
*/
public function disableEvents()
{
$this->eventsDisabled = true;
$this->mockEventDispatcher();
}
/**
* Disable model events.
*/
public function disableModelEvents()
{
$this->modelEventsDisabled = true;
Model::unsetEventDispatcher();
}
/*
* Disable middleware.
*/
public function disableMiddleware()
{
$this->middlewareDisabled = true;
$this->app->instance('middleware.disable', true);
}
}