Skip to content

Instantly share code, notes, and snippets.

@Ph3nol
Forked from kriswallsmith/QSAListener.php
Created August 8, 2012 18:36
Show Gist options
  • Save Ph3nol/3297393 to your computer and use it in GitHub Desktop.
Save Ph3nol/3297393 to your computer and use it in GitHub Desktop.
implements QSA on Symfony2 redirects
<?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