Skip to content

Instantly share code, notes, and snippets.

@h4cc
Created May 29, 2013 12:11
Show Gist options
  • Save h4cc/5669832 to your computer and use it in GitHub Desktop.
Save h4cc/5669832 to your computer and use it in GitHub Desktop.
Symfony2 Listener, that will check if a redirect to our page has a route defined.
<?php
/**
* Symfony2 Listener, that will check if a redirect to our page has a route defined.
*
* @author Julius Beckmann
* @date 27.05.13
*/
namespace h4cc\PennerZoneBundle;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use \Symfony\Bundle\FrameworkBundle\Routing\Router;
use \Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
class ResponseListener
{
private $router;
public function __construct(Router $router) {
$this->router = $router;
}
public function onKernelResponse(FilterResponseEvent $event)
{
$response = $event->getResponse();
if($response instanceof RedirectResponse) {
if(!$this->isRedirectToOtherDomain($response)) {
try {
$this->matchResponseWithRouter($response);
}catch(ResourceNotFoundException $e) {
// Router does not know that url
$this->redirectToSafePage($response);
}
}
}
}
/**
* @param $response
* @throws ResourceNotFoundException
*/
protected function matchResponseWithRouter($response) {
$url = $response->getTargetUrl();
$this->router->match($url);
}
protected function isRedirectToOtherDomain($response) {
//TODO: Implement
return false;
}
protected function redirectToSafePage($response) {
$response->setTargetUrl('/');
}
}
<service id="acme_demo.filter_response_listener" class="Acme\DemoBundle\ResponseListener">
<tag name="kernel.event_listener" event="kernel.response" method="onKernelResponse" />
<argument type="service" id="router" />
</service>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment