Symfony URL Manipulation: Difference between revisions
Jump to navigation
Jump to search
(Created page with "Some times it's very needy to Manipulate URL base on different condition. This example presents how to manipulate URL <syntaxhighlight lang="php"> namespace Chorke\Bundle\Weba...") |
No edit summary |
||
Line 63: | Line 63: | ||
private function getContextPath(Request $request) | private function getContextPath(Request $request) | ||
{ | { | ||
$server = $this->getServerPath($request); | |||
$base = $request->getBasePath(); | $base = $request->getBasePath(); | ||
$contextPath = "{$server}{$base}"; | $contextPath = "{$server}{$base}"; | ||
return $contextPath; | return $contextPath; |
Revision as of 11:43, 7 January 2018
Some times it's very needy to Manipulate URL base on different condition. This example presents how to manipulate URL
namespace Chorke\Bundle\WebappBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* @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,
'javapull' => $this->getAbsolutePath('java_pull'),
'zendpull' => $this->getAbsolutePath('zend_pull')
);
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);
}
private function getAbsolutePath($route, $parameters=array())
{
$absolutePath = $this->generateUrl(
$route, $parameters, UrlGeneratorInterface::ABSOLUTE_URL
);
return $absolutePath;
}
private function getContextPath(Request $request)
{
$server = $this->getServerPath($request);
$base = $request->getBasePath();
$contextPath = "{$server}{$base}";
return $contextPath;
}
private function getServerPath(Request $request)
{
$scheme = $request->getScheme();
$host = $request->getHost();
$port = $request->getPort();
$isDefaultHttp = ($scheme == 'http' ) && ($port == 80);
$isDefaultHttps = ($scheme == 'https') && ($port == 443);
$port = ($isDefaultHttp||$isDefaultHttps) ? '' : ":{$port}";
$serverPath = "{$scheme}://{$host}{$port}";
return $serverPath;
}
}