phpsymfonyroutespointer-aliasing

Unable to overwrite pathInfo in a Symfony 2 Request


I'm trying to deal with aliases (friendly-urls) and probably I'm not doing it right. What I want to do is to transform urls like '/blog/my-post-about-something' into '/posts/23'.

I have written a listener for the kernel.request event that makes some operations and modifies the original request

class RequestListener
{

    public function onKernelRequest(KernelEvent $event)
    {
        $request = $event->getRequest();
        $converted_path = $this->getPathIfAny($request);
        if ($converted_path) {
            $request->server->set('REQUEST_URI', $converted_path);
        }
    }

    public function getPathIfAny(Request $request)
    {
        return $somePathOrNull;
    }
}

All the logic works properly and updates the original request. The problem is, even if I change the 'REQUEST_URI', the property $pathInfo remains unaltered and pointing to the previous path, so I keep getting 404 errors.

Is there any way to override the uri completely, or should I try to solve the problem in a different manner?

Here is the listener definition

my_cmf.request_listener:
    class: My\CMFBundle\Event\RequestListener
    tags:
      - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest , priority: -10}

Related link to this issue: https://github.com/symfony/symfony/issues/10478


Solution

  • I have a similar issue with my project. I was able to update the path info, but still struggling to get it passed to subsequent events

    Try this:

    $event->getRequest()->server->set('REQUEST_URI', '/en/guestbook');
    $event->getRequest()->initialize($event->getRequest()->query->all(), $event->getRequest()->request->all(), $event->getRequest()->attributes->all(), $event->getRequest()->cookies->all(), $event->getRequest()->files->all(), $event->getRequest()->server->all(), $event->getRequest()->getContent());
    
    var_dump($event->getRequest()->getPathInfo());
    

    The initialize method resets the whole class.