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

Commit

Permalink
Run RequestHandled on boot (#469)
Browse files Browse the repository at this point in the history
* Run RequestHandled on boot

* Load cors in callback
  • Loading branch information
barryvdh authored Apr 26, 2021
1 parent 5781ffc commit a8ccedc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 6 deletions.
8 changes: 8 additions & 0 deletions src/CorsServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
use Illuminate\Foundation\Application as LaravelApplication;
use Illuminate\Support\ServiceProvider as BaseServiceProvider;
use Laravel\Lumen\Application as LumenApplication;
use Illuminate\Foundation\Http\Events\RequestHandled;

class CorsServiceProvider extends BaseServiceProvider
{
Expand Down Expand Up @@ -34,6 +35,13 @@ public function boot()
} elseif ($this->app instanceof LumenApplication) {
$this->app->configure('cors');
}

// Add the headers on the Request Handled event as fallback in case of exceptions
if (class_exists(RequestHandled::class) && $this->app->bound('events')) {
$this->app->make('events')->listen(RequestHandled::class, function (RequestHandled $event) {
$this->app->make(HandleCors::class)->onRequestHandled($event);
});
}
}

/**
Expand Down
20 changes: 14 additions & 6 deletions src/HandleCors.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use Closure;
use Asm89\Stack\CorsService;
use Illuminate\Contracts\Http\Kernel;
use Illuminate\Foundation\Http\Events\RequestHandled;
use Illuminate\Http\Request;
use Illuminate\Contracts\Container\Container;
Expand Down Expand Up @@ -46,12 +47,6 @@ public function handle($request, Closure $next)
return $response;
}

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

// Handle the request
$response = $next($request);
Expand Down Expand Up @@ -80,6 +75,19 @@ protected function addHeaders(Request $request, Response $response): Response
return $response;
}

/**
* Add the headers to the Response, if they don't exist yet.
*
* @param RequestHandled $event
*/
public function onRequestHandled(RequestHandled $event)
{
if ($this->shouldRun($event->request) && $this->container->make(Kernel::class)->hasMiddleware(static::class)) {
$this->addHeaders($event->request, $event->response);
}
}


/**
* Determine if the request has a URI that should pass through the CORS flow.
*
Expand Down

0 comments on commit a8ccedc

Please sign in to comment.