Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Match any route to OPTIONS request method #84

Open
akrz opened this issue May 10, 2018 · 3 comments
Open

Match any route to OPTIONS request method #84

akrz opened this issue May 10, 2018 · 3 comments

Comments

@akrz
Copy link

akrz commented May 10, 2018

Is it possible to make a route that matches all routes for a given request method? I need this to match any route to an OPTIONS request method. Something like this:

$router->options('*', function (){
    return new Response();
});
@nmsobri
Copy link

nmsobri commented Nov 13, 2018

@akrz did you find a solution to this?

@akrz
Copy link
Author

akrz commented Nov 13, 2018

Sort of, I do a catch of HttpMethodNotAllowedException and check that the HTTP method is OPTIONS.
i.e.:

try {
    // dispatch route...
} catch (HttpMethodNotAllowedException $e) {
    if ($requestMethod === 'OPTIONS') {
        $this->handleOptionsRequests($e->getMessage()); // I send an empty response with appropriate headers here
    }

    throw new HttpMethodNotAllowedException($e->getMessage());
}

@nitz
Copy link

nitz commented Mar 12, 2020

Apologies to the people I'm replying to here, as this thread is almost a year and a half old, I just wanted to share what I found that worked, in case someone else finds this useful.

So I created a route that takes just a single parameter of 0 or more of any characters, and then just ignored that value.

However, the '0' portion of that (including with the ? which should make it optional), an OPTIONS / request would still 404. So, "I'll just add a / route, right?"

Well, yes but you have to be careful:

$router->options('/{x:.*}?', function($x = null) { return httpOptions(); });
$router->options('/', function() { return httpOptions(); }); // this throws...

If you add it like that, you'll get a Phroute\\Phroute\\Exception\\BadRouteException that says: Static route '' is shadowed by previously defined variable route '(.*)' for method 'OPTIONS' in /path/to/app/vendor/phroute/phroute/src/Phroute/RouteCollector.php:157

So it even realizes that the regex route should catch it (despite it not)

All is not lost though; This works just fine:

$router->options('/', function() { return httpOptions(); });
$router->options('/{x:.*}?', function($x = null) { return httpOptions(); });

Handles OPTIONS /, OPTIONS /foo, OPTIONS /b/a/r, and so on. Definitely appears to be a bug here of some sort.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants