<?php
namespace App\Package\Toolkit\TwigServiceLoaderSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface,
Symfony\Component\HttpKernel\KernelEvents,
Symfony\Component\HttpKernel\Event\ControllerEvent,
Symfony\Component\DependencyInjection\ContainerInterface,
Twig\Environment;
use App\Package\Toolkit\ApplicationMode\ApplicationMode,
App\Package\Toolkit\Exception\Exception\Exception;
/**
* TwigServiceLoaderSubscriber
*
* Executed on KernelEvents::CONTROLLER
* - adds services to twig globals depending on application mode and
* passed twig services configuration
*
* Twig is taken from container (class \Twig_Environment)
* IMPORTANT: It's not templating, it's raw twig environment
*
* @see include.yml
*
* @author Daniel Balowski <d.balowski@openform.pl> (_creator)
* @copyright Openform
* @since 03.2019
*/
class TwigServiceLoaderSubscriber implements EventSubscriberInterface
{
/**
* @var ContainerInterface
*/
protected $container;
/**
* @var ApplicationMode
*/
protected $applicationMode;
/**
* @var string[]
*/
protected $twigServices;
/**
* @var Environment $twig
*/
protected $twig;
/**
* @param ContainerInterface $container
* @param ApplicationMode $applicationMode
* @param string[] $twigServices
*/
public function __construct(
ContainerInterface $container,
ApplicationMode $applicationMode,
Environment $twig,
array $twigServices
) {
$this->container = $container;
$this->applicationMode = $applicationMode;
$this->twigServices = $twigServices;
$this->twig = $twig;
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents() : array
{
return [
KernelEvents::CONTROLLER => [
[ 'addServicesToTwigGlobals', 255 ],
]
];
}
/**
* Adds services to twig globals
*
* @param ControllerEvent $event
*
* @throws Exception if service does not exist in container
*
* @return void
*/
public function addServicesToTwigGlobals(ControllerEvent $event) : void
{
if (! array_key_exists($this->applicationMode->getCurrentMode(), $this->twigServices)) {
return;
}
$servicesToLoad = [];
foreach($this->twigServices[ $this->applicationMode->getCurrentMode() ] as $services) {
if ($services) {
foreach ($services as $serviceName => $service) {
$servicesToLoad[ $serviceName ] = $service;
}
}
}
foreach($servicesToLoad as $globalName => $service) {
if (! $this->container->has($service)) {
throw new Exception(
' >> Missing service in container: "' . $service . '"'
);
}
$this->twig->addGlobal($globalName, $this->container->get($service));
}
return;
}
}