vendor/corley/maintenance-bundle/Corley/MaintenanceBundle/Listener/SoftLockListener.php line 42

Open in your IDE?
  1. <?php
  2. namespace Corley\MaintenanceBundle\Listener;
  3. use Symfony\Component\HttpFoundation\Response;
  4. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. class SoftLockListener
  7. {
  8.     private $requestStack;
  9.     private $maintenancePage;
  10.     private $lock;
  11.     private $whitePaths;
  12.     private $whiteIps;
  13.     public function __construct($maintenancePage$maintenanceLock, array $whitePaths, array $whiteIps)
  14.     {
  15.         $this->maintenancePage $maintenancePage;
  16.         $this->lock file_exists($maintenanceLock);
  17.         $this->whiteIps $whiteIps;
  18.         array_walk($whitePaths, function(&$elem) {
  19.             $elem "/" str_replace("/""\\/"$elem) . "/";
  20.         });
  21.         $this->whitePaths array_replace(array("/^\/_/"), $whitePaths);
  22.     }
  23.     public function setRequestStack($requestStack)
  24.     {
  25.         $this->requestStack $requestStack;
  26.     }
  27.     /**
  28.      * @param GetResponseEvent|RequestEvent $event
  29.      *
  30.      * Note: To enable support for all currently supported versions of Symfony we can't
  31.      * typehint the event since the event class changed between SF 4.4 and 5.0. As Nicolas
  32.      * explained it the class isn't deprecated in 4.4 because the replacement relies on it.
  33.      */
  34.     public function onKernelRequest($event)
  35.     {
  36.         if ($this->isUnderMaintenance()) {
  37.             $response = new Response();
  38.             $response->setStatusCode(503);
  39.             $response->setContent(file_get_contents($this->maintenancePage));
  40.             $event->setResponse($response);
  41.             $event->stopPropagation();
  42.         }
  43.     }
  44.     private function isUnderMaintenance()
  45.     {
  46.         $path $this->requestStack->getCurrentRequest()->getPathInfo();
  47.         return ($this->lock && $this->isIpNotAuthorized() && $this->isPathUnderMaintenance($path));
  48.     }
  49.     private function isIpNotAuthorized()
  50.     {
  51.         $currentIp $this->requestStack->getCurrentRequest()->getClientIp();
  52.         foreach ($this->whiteIps as $allowedIp) {
  53.             if ($currentIp == $allowedIp) {
  54.                 return false;
  55.             }
  56.         }
  57.         return true;
  58.     }
  59.     private function isPathUnderMaintenance($path)
  60.     {
  61.         foreach ($this->whitePaths as $pattern) {
  62.             if (preg_match($pattern$path)) {
  63.                 return false;
  64.             }
  65.         }
  66.         return true;
  67.     }
  68. }