Skip to content

Conversation

@davidmyersdev
Copy link

In this PR, I am proposing a new filter() method to be added to Klein. This method is to be used for middleware that wouldn't normally add to the number of matched routes. This method utilizes the Route class's built in $count_match param that wasn't being publicly exposed.

Use case:

I currently have catch-all routes set up to enable Auth in my application at different levels of access. These catch-all routes conditionally add to the number of $matched based on where the user is trying to access. Because of this, I cannot add a 404 listener when a user tries to access a page that doesn't exist. Instead of throwing a 404, Klein sees that my catch-all Auth route has been matched, and therefore doesn't see the route as nonexistent. With the new filter() method, this would no longer be an issue.

Example:

<?php
// resource route-group
$router->with('/[:resource]/?', function () use ($router)
{
    // catch-all filter to make sure user has access to the requested resource
    $router->filter('/[**:trailing]?', function ($request, $response, $service)
    {
        // make sure user has access to resource
        if (Auth::user()->hasAccessTo($request->resource))
        {
            // do something regarding auth here
        }
    });
});

// http error handler (e.g. 404)
$router->onHttpError(function ($code, $router)
{
    switch ($code)
    {
        case 404:
            $router->response()->body('404. Looks like we can't find the resource you are after!');
            break;
        default:
            $router->response()->body('Oops. There was a '.$code.' error.');
            break;
    }
});

With the provided fix, navigating to /resource/some-fake-url will return a 404 error. Without the provided fix, a blank response will be sent, and a 404 error will not occur.

If you'd like more info about this very common use case, please let me know. Thanks for your time!

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

Successfully merging this pull request may close these issues.

1 participant