<?php
namespace App\Service;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Yaml\Yaml;
class MaintenanceListener
{
// todo: make configurable
const PORTAL_MAINTENANCE_MODE = false;
/** @var \Symfony\Component\DependencyInjection\ContainerInterface */
protected $container;
/** @var \Twig_Environment */
protected $twig;
/** @var bool */
protected $isActive = false;
/** @var string */
protected $title;
/** @var string */
protected $message;
/** @var TokenStorageInterface */
protected $tokenStorage;
const PROTECTED_ROUTES = [
'anfrage',
'client_details',
'tan_verification',
'payment_details',
'execute_payment_paypal',
'execute_payment_sofort',
'cancel_payment',
'payment_success',
];
public function __construct(ContainerInterface $container, \Twig_Environment $twig, TokenStorageInterface $tokenStorage)
{
$this->container = $container;
$this->twig = $twig;
$appSettings = Yaml::parseFile(__DIR__ . '/../../config/app_settings.yaml');
if ( ! empty($appSettings) && isset($appSettings['maintenance'])) {
$maintenanceSettings = $appSettings['maintenance'];
$this->isActive = $maintenanceSettings['is_active'] ?: false;
$this->title = $maintenanceSettings['title'];
$this->message = $maintenanceSettings['message']['custom'] ?: $maintenanceSettings['message']['default'];
}
$this->tokenStorage = $tokenStorage;
}
public function onKernelRequest(GetResponseEvent $event)
{
// If maintenance is active
if ($this->isActive || static::PORTAL_MAINTENANCE_MODE) {
$token = $this->tokenStorage->getToken();
if ($token !== null) {
/** @var \Symfony\Component\Security\Core\User\UserInterface $currentUser */
$currentUser = $this->tokenStorage->getToken()->getUser();
if ( ! is_string($currentUser) && ! in_array('ROLE_ADMIN', $currentUser->getRoles())) {
// logout user if not admin
$this->container->get('security.token_storage')->setToken(null);
$this->container->get('session')->invalidate();
}
}
$route = $event->getRequest()->get('_route');
if (($this->isActive && in_array($route, static::PROTECTED_ROUTES))
|| strpos($route, 'portal') === 0
|| strpos($route, 'customer') === 0
) {
// We load our maintenance template
$template = $this->twig->render('maintenance.html.twig', [
'title' => $this->title,
'message' => $this->message,
]);
// We send our response with a 503 response code (service unavailable)
$event->setResponse(new Response($template, 503));
$event->stopPropagation();
}
}
}
}