<?php
namespace App\Subscriber;
use App\Entity\Parameter;
use App\Service\ParameterContainer;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
class ParameterSubscriber implements EventSubscriberInterface
{
protected $parameters = null;
protected $twig;
protected $parameterContainer;
protected $entityManager;
public function __construct(
\Twig_Environment $twig,
ParameterContainer $parameterContainer,
EntityManagerInterface $entityManager
) {
$this->twig = $twig;
$this->parameterContainer = $parameterContainer;
$this->entityManager = $entityManager;
}
public function onKernelRequest(RequestEvent $event)
{
$globalParameters = $this->getParameters();
$this->storeParameter(ParameterContainer::SETTINGS_KEY, $globalParameters);
}
protected function getParameters(): array
{
if (is_null($this->parameters)) {
$parameters = $this->entityManager->getRepository(Parameter::class)->findAll();
$globalParameters = array();
/** @var Parameter $setting */
foreach ($parameters as $parameter) {
$globalParameters[$parameter->getName()] = $parameter->getValue();
}
$this->parameters = $globalParameters;
}
return $this->parameters;
}
protected function storeParameter($key, $value)
{
$this->parameterContainer->setParameter($key, $value);
$this->twig->addGlobal($key, $value);
}
public static function getSubscribedEvents()
{
return [
KernelEvents::REQUEST => [['onKernelRequest', 20]],
];
}
}