Search code examples
phpsymfonysymfony4

Symfony 4 Redirect without a custom controller


so the problem which I'm facing is, that I'm not able to use wildcards inside of my redirects configured in the routing.yml

homepage:
  path: /test/{wildcard}
  controller: Symfony\Bundle\FrameworkBundle\Controller\RedirectController::urlRedirectAction
  defaults:
    path: /{wildcard}
    permanent: true

In the default path I need to get the wildcard path. So e.g test/wildcard should redirect to /wildcard. But what Symfony is doing is, that it's redirecting to /{wildcard}. So how can I get the wildcard parameter?


Solution

  • So in order to give an answer to my question. The solution is the following: You need to create a custom RedirectController, which is able to handle wildcards within a route.

    This is what the the controller can look like:

    <?php
    
    
    namespace Custom\RedirectBundle\Controller;
    
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpFoundation\Request;
    
    class RedirectController
    {
    
        public function urlRedirectAction(
            Request $request,
            bool $permanent = false,
            string $route = '',
            array $dynamicRoutePath =
            []
        ): RedirectResponse {
            $statusCode = $permanent ? 301 : 302;
            if ('' !== $route) {
                $url = "/".$route;
                if (!empty($dynamicRoutePath)) {
                    $url = $this->getPath($request, $dynamicRoutePath, $url);
                }
    
                return new RedirectResponse($url, $statusCode);
            }
            $route = $this->getPath($request, $dynamicRoutePath);
    
            return new RedirectResponse($route, $statusCode);
        }
    
        private function getPath(Request $request, array $path, string $url = ''): string
        {
            foreach ($path as $pathParameter) {
                $pathconfig = $request->get($pathParameter);
                $url        = $url."/".$pathconfig;
            }
    
            return $url;
        }
    
    }
    
    

    Configuration in routing.yml:

    magazin_category_slug:
      path: /magazin/{category}/{slug}
      controller: CustomRedirectBundle:Redirect:urlRedirect
      defaults:
        permanent: true
        route: newBaseRoute
        dynamicRoutePath:
          - category