Skip to content
This repository was archived by the owner on Feb 16, 2023. It is now read-only.

Commit a8ccedc

Browse files
authored
Run RequestHandled on boot (#469)
* Run RequestHandled on boot * Load cors in callback
1 parent 5781ffc commit a8ccedc

File tree

2 files changed

+22
-6
lines changed

2 files changed

+22
-6
lines changed

src/CorsServiceProvider.php

+8
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use Illuminate\Foundation\Application as LaravelApplication;
77
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
88
use Laravel\Lumen\Application as LumenApplication;
9+
use Illuminate\Foundation\Http\Events\RequestHandled;
910

1011
class CorsServiceProvider extends BaseServiceProvider
1112
{
@@ -34,6 +35,13 @@ public function boot()
3435
} elseif ($this->app instanceof LumenApplication) {
3536
$this->app->configure('cors');
3637
}
38+
39+
// Add the headers on the Request Handled event as fallback in case of exceptions
40+
if (class_exists(RequestHandled::class) && $this->app->bound('events')) {
41+
$this->app->make('events')->listen(RequestHandled::class, function (RequestHandled $event) {
42+
$this->app->make(HandleCors::class)->onRequestHandled($event);
43+
});
44+
}
3745
}
3846

3947
/**

src/HandleCors.php

+14-6
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
use Closure;
66
use Asm89\Stack\CorsService;
7+
use Illuminate\Contracts\Http\Kernel;
78
use Illuminate\Foundation\Http\Events\RequestHandled;
89
use Illuminate\Http\Request;
910
use Illuminate\Contracts\Container\Container;
@@ -46,12 +47,6 @@ public function handle($request, Closure $next)
4647
return $response;
4748
}
4849

49-
// Add the headers on the Request Handled event as fallback in case of exceptions
50-
if (class_exists(RequestHandled::class) && $this->container->bound('events')) {
51-
$this->container->make('events')->listen(RequestHandled::class, function (RequestHandled $event) {
52-
$this->addHeaders($event->request, $event->response);
53-
});
54-
}
5550

5651
// Handle the request
5752
$response = $next($request);
@@ -80,6 +75,19 @@ protected function addHeaders(Request $request, Response $response): Response
8075
return $response;
8176
}
8277

78+
/**
79+
* Add the headers to the Response, if they don't exist yet.
80+
*
81+
* @param RequestHandled $event
82+
*/
83+
public function onRequestHandled(RequestHandled $event)
84+
{
85+
if ($this->shouldRun($event->request) && $this->container->make(Kernel::class)->hasMiddleware(static::class)) {
86+
$this->addHeaders($event->request, $event->response);
87+
}
88+
}
89+
90+
8391
/**
8492
* Determine if the request has a URI that should pass through the CORS flow.
8593
*

0 commit comments

Comments
 (0)