Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check url before redirect symfony2

if ($u = $this->generateUrl('_'.$specific.'_thanks'))
  return $this->redirect($u);
else
  return $this->redirect($this->generateUrl('_thanks'));

I wan't to redirect to the _specific_thanks url when it exist. So How to check if a url exist?

When I did that, I had this error:

Route "_specific_thanks" does not exist.

like image 757
Harold Avatar asked Jan 03 '13 09:01

Harold


3 Answers

I don't think there's a direct way to check if a route exists. But you can look for route existence through the router service.

$router = $this->container->get('router');

You can then get a route collection and call get() for a given route, which returns null if it doesn't exist.

$router->getRouteCollection()->get('_'. $specific. '_thanks');
like image 191
Ahmed Siouani Avatar answered Oct 21 '22 21:10

Ahmed Siouani


Using getRouteCollection() on runtime is not the correct solution. Executing this method will require the cache to be rebuilt. This means that routing cache will be rebuilt on each request, making your app much slower than needed.

If you want to check whether a route exists or not, use the try ... catch construct:

use Symfony\Component\Routing\Exception\RouteNotFoundException;

try {
    dump($router->generate('some_route'));
} catch (RouteNotFoundException $e) {
    dump('Oh noes, route "some_route" doesn't exists!');
}
like image 40
Wouter J Avatar answered Oct 21 '22 20:10

Wouter J


Try something like this, check the route exists in the array of all routes:

    $router = $this->get('router');

    if (array_key_exists('_'.$specific.'_thanks',$router->getRouteCollection->all())){
        return $this->redirect($this->generateUrl('_'.$specific.'_thanks'))
    } else {
        return $this->redirect($this->generateUrl('_thanks'));
    }
like image 26
Luke Avatar answered Oct 21 '22 22:10

Luke