Skip to content
This repository has been archived by the owner on Oct 11, 2024. It is now read-only.

Optional Route Subpatterns not working as expected #16

Closed
tomvb opened this issue May 8, 2024 · 3 comments
Closed

Optional Route Subpatterns not working as expected #16

tomvb opened this issue May 8, 2024 · 3 comments

Comments

@tomvb
Copy link
Contributor

tomvb commented May 8, 2024

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?

if (isset($matches[$index + 1]) && isset($matches[$index + 1][0]) && is_array($matches[$index + 1][0])) {

@tomvb
Copy link
Contributor Author

tomvb commented May 8, 2024

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
Copy link
Member

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

tomvb added a commit to tomvb/router-subpattern-fix that referenced this issue Sep 26, 2024
@tomvb
Copy link
Contributor Author

tomvb commented Sep 26, 2024

I've created a PR here: #20

First PR ever, hope I did it correctly :)

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
Status: Done
Development

No branches or pull requests

2 participants