[Symfony] Get the routing informations of the referer

Published on 2018-10-31 • Modified on 2018-11-03

Sometimes it is useful to get the referrer routing informations when you have a page that have multiple access points. Knowing the context can therefore help you to customize the user output depending on the referrer route or its parameters.


<?php declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;

/**
 * I am using a PHP trait in order to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Sf 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Sf <= 4.1)
 * Services are injected in the controller constructor.
 */
trait Snippet7Trait
{
    public function snippet7(Request $r): void
    {
        if (!$this->router instanceof RouterInterface) {
            throw new \RuntimeException("Houston, We've Got a Problem. 💥");
        }

        $referer = $r->headers->get('referer'); // get the referer, it can be empty!
        if (!\is_string($referer) || !$referer) {
            var_dump('Referer is invalid or empty.');

            return;
        }

        $refererPathInfo = Request::create($referer)->getPathInfo();

        // Remove the scriptname if using a dev controller like app_dev.php (Symfony 3.x only)
        $refererPathInfo = str_replace($r->getScriptName(), '', $refererPathInfo);

        // try to match the path with the application routing
        $routeInfos = $this->router->match($refererPathInfo);

        // get the Symfony route name
        $refererRoute = $routeInfos['_route'] ?? '';

        // get the parameters, remove useless ones and add a parameter to test
        unset($routeInfos['_route'], $routeInfos['_controller']);
        $routeInfos['foo'] = 'bar';

        // No route found (external URL for example)
        if (!$refererRoute) {
            var_dump(sprintf('No route found for the "%s" referer.', $referer));

            return;
        }

        // Ok, now we can generate a new URL for this referer with new parameters
        try {
            $newUrl = $this->router->generate($refererRoute, $routeInfos); // new URL with foo bar
        } catch (\Exception $e) {
            $newUrl = 'Error when generating the new URL from the referer.';
        }

        var_dump($referer);
        var_dump($newUrl);

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow