Created
August 8, 2012 18:23
-
-
Save kriswallsmith/3297290 to your computer and use it in GitHub Desktop.
implements QSA on Symfony2 redirects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use JMS\DiExtraBundle\Annotation as DI; | |
use Symfony\Component\HttpKernel\Event\FilterResponseEvent; | |
/** @DI\Service */ | |
class QSAListener | |
{ | |
private $blacklist; | |
/** @DI\InjectParams({"blacklist"=@DI\Inject("%qsa.blacklist%")}) */ | |
public function __construct(array $blacklist = array()) | |
{ | |
$this->blacklist = $blacklist; | |
} | |
/** @DI\Observe("kernel.response") */ | |
public function onKernelResponse(FilterResponseEvent $event) | |
{ | |
$request = $event->getRequest(); | |
$response = $event->getResponse(); | |
if (!$response->isRedirection() || !$request->isMethodSafe() || !$request->query->all()) { | |
return; | |
} | |
$query = array(); | |
foreach (array_diff($request->query->keys(), $this->blacklist) as $key) { | |
$query[$key] = $request->query->get($key); | |
} | |
// attach the query string | |
$location = $response->headers->get('Location'); | |
$location .= false === strpos($location, '?') ? '?' : '&'; | |
$location .= http_build_query($query); | |
// modify the response content | |
$response->setContent(str_replace( | |
htmlspecialchars($response->headers->get('Location'), ENT_QUOTES, 'UTF-8'), | |
htmlspecialchars($location, ENT_QUOTES, 'UTF-8'), | |
$response->getContent() | |
)); | |
// modify the location header | |
$response->headers->set('Location', $location); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks @phuedx!