src/EventSubscriber/Maintenance/MaintenanceSubscriber.php line 26

Open in your IDE?
  1. <?php
  2. namespace App\EventSubscriber\Maintenance;
  3. use Symfony\Component\HttpKernel\Event\RequestEvent;
  4. use Psr\Log\LoggerInterface;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Twig\Environment;
  7. class MaintenanceSubscriber
  8. {
  9. private $logger;
  10. private $twig;
  11. private $underMaintenance;
  12. public function __construct(LoggerInterface $logger, Environment $twig, $underMaintenance)
  13. {
  14. $this->logger = $logger;
  15. $this->twig = $twig;
  16. $this->underMaintenance = $underMaintenance;
  17. }
  18. public function onKernelRequest(RequestEvent $event)
  19. {
  20. // Check for UNDER_MAINTENANCE env var, if it is empty or false, then we can exit
  21. if (!$this->underMaintenance || $this->strEquals($this->underMaintenance, 'false')) {
  22. return;
  23. }
  24. // Check for if UNDER_MAINTENANCE is not set to true
  25. if (!$this->strEquals($this->underMaintenance, 'true')) {
  26. // Exit if we have an invalidate date
  27. if (!$this->validateDate($this->underMaintenance)) {
  28. return;
  29. }
  30. $underMaintenanceEndDate = strtotime($this->underMaintenance);
  31. $now = new \DateTime();
  32. // Exit if maintenance end date has passed
  33. if ($now > $underMaintenanceEndDate) {
  34. return;
  35. }
  36. }
  37. // Final sanity check for if UNDER_MAINTENACE is true or a valid date
  38. if ($this->strEquals($this->underMaintenance, 'true') || $this->validateDate(($this->underMaintenance))) {
  39. // render page
  40. $event->setResponse(new Response(
  41. $this->twig->render('views/maintenance.html.twig'),
  42. Response::HTTP_SERVICE_UNAVAILABLE,
  43. ));
  44. $event->stopPropagation();
  45. }
  46. // Do nothing
  47. }
  48. private function strEquals($string, $value)
  49. {
  50. return strtoupper($string) === strtoupper($value);
  51. }
  52. private function validateDate($date, $format = 'Y-m-d H:i:s')
  53. {
  54. $d = \DateTime::createFromFormat($format, $date);
  55. return $d && $d->format($format) == $date;
  56. }
  57. }