Question

In some symfony2 project I have next definition of routes:

MyBundle_Default:
    resource: "routing/default.yml"
    prefix: /{slug}-{resource_id}
    requirements:
        slug: "[a-z\-]+"
        resource_id: "\d+"

But this requirements don't work. For example, if I have "-" in slug (e.g. "test-route") url like /test-route-9 do not work.

Is this a bug?

Was it helpful?

Solution 4

Looks like it was indeed a bug. At least in Symfony 3.4.36, all works as expected.

OTHER TIPS

Mainly, I think your problem comes from the dash character. Let me explain. Say the url entered is /test-route-9. With your requirements, the slug matched would be test-route- because your regex states that is characters between a-z or the dash - that can be matched.

Regex will match every thing it can, so it will "eat" the dash character. By "eating" it, the rest would be only 9 which would not be correct because the routing expects another dash before matching the resource_id portion. Hence, this url wouldn't match as you expect.

Simple fix is to separate components with a / instead of dash, or change the character separating your slug to differentiate it from the url component separator.

Fix by changing separator in url:

prefix: /{slug}/{resource_id}
requirements:
    slug: "[a-z\-]+"
    resource_id: "\d+"

Or:

prefix: /{slug}_{resource_id}
requirements:
    slug: "[a-z\-]+"
    resource_id: "\d+"

Fix by changing separator for the slug directly:

prefix: /{slug}-{resource_id}
requirements:
    slug: "[a-z_]+"
    resource_id: "\d+"

I'm pretty sure the problem comes from this. Did not test anything, but worth a try just to be sure the problem lies with the dash character separator.

It's a typo, you put the requirement on hotel_id but define in the url resource_id!

Try with

slug: "[a-z\-]+(?<!-)"

This will make sure that the regex does NOT match the last dash, which is the problem as mentioned in Matts answer.

I hope it works for you :)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top