Symfony URL Redirection

From Chorke Wiki
Revision as of 11:36, 7 January 2018 by Shahed (talk | contribs)
Jump to navigation Jump to search

Some time is very needy to redirect URL base on different conditional behaviour. This example presents how to check locale and redirect to locale

namespace Chorke\Bundle\WebappBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

/**
 * @Route("/home")
 */
class HomeController extends Controller
{
    private $lingos;
    private $locals;
    
    public function __construct()
    {
        $lingos = "ar|bn|en|fr|tk|zz";
        $this->lingos = str_replace("|zz", "", $lingos);
        $this->locals = explode('|', $this->lingos);
    }

    /**
     * @Route("/{_locale}",
     *  name="home_index", defaults={"_locale"="zz"},
     *  requirements={"_locale"="ar|bn|en|fr|tk|zz"})
     */
    public function indexAction($_locale)
    {
        if(!$this->hasLocal($_locale))
        {
            return $this->redirectToLocal('home_index');
        }
        $parameters = array('locale' => $_locale);
        return $this->render('WebappBundle:Home:index.html.twig', $parameters);
    }

    private function hasLocal($locale)
    {
        return in_array($locale, $this->locals);
    }

    private function redirectToLocal($route)
    {
        $parameters = array('_locale' => 'en');
        return $this->redirectToRoute($route, $parameters, Response::HTTP_TEMPORARY_REDIRECT);
    }

}