yiisoft / router

Router is a request matcher and URL generator
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
59 stars 24 forks source link

Mark cors preflight requests #245

Open olegbaturin opened 1 month ago

olegbaturin commented 1 month ago

Mark request as cors preflight here https://github.com/yiisoft/router/blob/98969eb86377333fbf01a2eb2ef4382e928b197b/src/RouteCollection.php#L186

Maybe $request->withAttribute('preflight', true);

samdark commented 1 month ago

Would you please elaborate?

olegbaturin commented 1 month ago

I want to make a CorsMiddleware with logic:

public function process() {
   $response = $handler->handle($request);

   if (cors preflight) {
       do cors things with $response
   }
}

I see that $request is immutable, so maybe it's possible to mark the Response?

olegbaturin commented 1 month ago

Another solution is to pass the CorsState object to $resuest and then modify it in the cors action.

final class CorsState {
    private bool $preflight = false;

    public function getPreflight()
    {
        return $this->preflight;
    }

    public function setPreflight()
    {
        $this->preflight = true;
    }
}

In the CorsMiddleware

public function process() {
   $corsState = new CorsState();
   $request = $request->withAttribute('preflight', $corsState);
   $response = $handler->handle($request);

   if ($corsState->getPreflight()) {
       do cors things with $response
   }
}

In the cors action:

if ($request->hasAttribute('preflight')) {
    $request->getAttribute('preflight')->setPreflight();
}
return $responseFactory->createResponse(204);