leafsphp / router

🏚 router module for leaf PHP
https://leafphp.dev/modules/router/
6 stars 6 forks source link

Optional Route Subpatterns not working as expected #16

Closed tomvb closed 1 month ago

tomvb commented 6 months ago

I'm following the docs for Optional Route Subpatterns here: https://leafphp.dev/docs/routing/sub-patterns.html

I ran into troubles thinking I didn't understand the PCRE-based Route Patterns well enough. But after following the example from the linked docs page and debugging them, it seems the route is not working as expected (or, as the docs say they should work).

Using this example from the docs as my starting point:

app()->get('/blog(/\d+(/\d+(/\d+(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
  // ...
});

I modified it to debug:

  app()->get('/blog(/\d+(/\d+(/\d+(/[a-z0-9_-]+)?)?)?)?', function ($year = null, $month = null, $day = null, $slug = null) {
    print "year: " . $year . "<br>";
    print "month: " . $month . "<br>";
    print "day: " . $day . "<br>";
    print "slug: " . $slug;
  });

The following urls produce these results: /blog/2024/6/2/slug

year: 2024
month: 6
day: 2
slug: slug

/blog/2024/6/2

year: 2024
month: 6
day:
slug:

The first example works, but the second does not return the day value.

Am I doing something wrong or is this a bug?

https://github.com/leafsphp/router/blob/dc3744718289975145bced2aa5c5f3e8ca022f19/src/Router/Core.php#L381

tomvb commented 6 months ago

After messing with the source code some more I found that adding && $matches[$index + 1][0][1] != -1 to line 381 fixes the problem for me.

Full if statement: if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && $matches[$index + 1][0][1] != -1 && is_array($matches[$index + 1][0])) {

mychidarko commented 1 month ago

@tomvb your solution works perfectly. Do you mind opening a PR so you could get the contribution credit

tomvb commented 1 month ago

I've created a PR here: https://github.com/leafsphp/router/pull/20

First PR ever, hope I did it correctly :)