Respect / Rest

Thin controller for RESTful applications
http://respect.github.io/Rest
Other
604 stars 102 forks source link

Class routes: interpret optional parameters #37

Closed augustohp closed 12 years ago

augustohp commented 12 years ago

When you register a route, you can have optional parameters, like /users/*, if you declare in the function that the parameter is optional, than if none is given the route matches and is dispatched. This doesn't happen with classes used as routes. #sadpanda

alganet commented 12 years ago

Could you create a test for this in a separate branch?

pablolmiranda commented 12 years ago

For the both cases the route didn't match. I greated the both tests on my fork and both tests fail:

function test_optional_parameter_in_class_routes(){
        $r = new Router();
        $r->any('/optional/*', 'MyOptionalParamRoute');
        $response = $r->dispatch('get', '/optional')->response();
        $this->assertEquals('John Doe', (string) $response);
    }

    function test_optional_parameter_in_function_routes(){
        $r = new Router();
        $r->any('/optional/*', function($user=null){
            return $user ?: 'John Doe';
        });
        $response = $r->dispatch('get', '/optional')->response();
        $this->assertEquals('John Doe', (string) $response);
    }
alganet commented 12 years ago

This is actually a known issue. I've discussed this with @augustohp a couple of weeks ago. If you declare more than one parameter (like /optional/*/*), the second and subsequent ones can be optional, but the first can't.

I'm not sure if we should drop optional parameters at all (it is easy to achieve the same result declaring more routes) or fix this. The fix may be complex 'cause this part of the implementation is very sensitive (regex translation). Documentation also needs to be improved.

I'm gonna work on this today or tomorrow depending on my time windows.

augustohp commented 12 years ago

@pablolmiranda: In the mean time, there still a way to work with this.

Register two routes to the same class/closure, like this:

This works since we already use that in some enviroments. Let us know if this works for you. ;)

alganet commented 12 years ago

I believe this is fixed for now! @pablolmiranda I've pulled your test cases from your repo and commited them. It should be working for any route with any number of optional parameters (as long as they're at the end of the route).

I'm closing the issue, if the problem persists please let me know.