Skip to content

Instantly share code, notes, and snippets.

@goroba
Last active August 7, 2019 11:31
Show Gist options
  • Select an option

  • Save goroba/512df8233d27ef17682053e665e43cba to your computer and use it in GitHub Desktop.

Select an option

Save goroba/512df8233d27ef17682053e665e43cba to your computer and use it in GitHub Desktop.
Replace request ip with X-REAL-IP header value, used by Docker to pass real outer IP to containers in Symfony Application (if you or your DevOps don't wonna to bother with `fastcgi_param REMOTE_ADDR $http_x_real_ip;` stuff).
<?php
namespace App\EventSubscriber;
use App\Manager\SettingManager;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class RequestListener implements EventSubscriberInterface
{
/**
* @var Request
*/
private $request;
/**
* @required
*
* @param RequestStack $requestStack
*/
public function setDependencies(RequestStack $requestStack)
{
$this->request = $requestStack->getCurrentRequest();
}
/**
* @return array
*/
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [
['onKernelRequest']
],
];
}
/**
* @param GetResponseEvent $event
*/
public function onKernelRequest(GetResponseEvent $event)
{
if ($this->request->headers->has('x-real-ip')) {
$this->request->server->set('REMOTE_ADDR', $this->request->headers->get('x-real-ip'));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment