2021-04-08 13:19:33 +02:00
|
|
|
<?php
|
|
|
|
|
|
|
|
|
|
|
|
namespace JeroenED\Framework;
|
|
|
|
|
|
|
|
|
2021-05-26 13:09:13 +02:00
|
|
|
use Mehrkanal\EncoreTwigExtension\Extensions\EntryFilesTwigExtension;
|
|
|
|
use Symfony\WebpackEncoreBundle\Asset\EntrypointLookup;
|
2021-08-02 13:28:14 +02:00
|
|
|
use Twig\Cache\FilesystemCache;
|
2021-04-08 13:19:33 +02:00
|
|
|
use Twig\Environment;
|
2021-05-28 14:24:33 +02:00
|
|
|
use Twig\Extra\Intl\IntlExtension;
|
2021-04-08 13:19:33 +02:00
|
|
|
use Twig\Loader\FilesystemLoader;
|
2021-04-08 13:28:13 +02:00
|
|
|
use Twig\TwigFilter;
|
2021-04-08 13:19:33 +02:00
|
|
|
use Twig\TwigFunction;
|
|
|
|
|
|
|
|
class Twig
|
|
|
|
{
|
|
|
|
private Environment $environment;
|
|
|
|
private Kernel $kernel;
|
2021-08-02 13:28:14 +02:00
|
|
|
|
2021-04-08 13:19:33 +02:00
|
|
|
public function __construct(Kernel $kernel)
|
|
|
|
{
|
|
|
|
$loader = new FilesystemLoader([$kernel->getTemplateDir()]);
|
|
|
|
$this->environment = new Environment($loader);
|
2021-08-02 17:07:41 +02:00
|
|
|
|
|
|
|
if(!$_ENV['DEBUG']) {
|
|
|
|
$cache = new FilesystemCache($kernel->getCacheDir() . '/twig');
|
|
|
|
$this->environment->setCache($cache);
|
|
|
|
}
|
|
|
|
|
2021-04-08 13:19:33 +02:00
|
|
|
$this->kernel = $kernel;
|
2021-05-28 14:24:33 +02:00
|
|
|
$this->addExtensions();
|
2021-04-08 13:19:33 +02:00
|
|
|
$this->addFunctions();
|
2021-04-08 13:28:13 +02:00
|
|
|
$this->addFilters();
|
2021-04-08 13:19:33 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
public function render(string $template, array $vars = []): string
|
|
|
|
{
|
|
|
|
return $this->environment->render($template, $vars);
|
|
|
|
}
|
|
|
|
|
2021-05-28 14:24:33 +02:00
|
|
|
public function addExtensions()
|
|
|
|
{
|
|
|
|
$this->environment->addExtension(new IntlExtension());
|
|
|
|
$this->environment->addExtension(new EntryFilesTwigExtension(new EntrypointLookup('./public/build/entrypoints.json')));
|
|
|
|
}
|
2021-04-08 13:19:33 +02:00
|
|
|
public function addFunctions()
|
|
|
|
{
|
2021-04-08 16:34:25 +02:00
|
|
|
$path = new TwigFunction('path', function(string $route, array $params = []) {
|
2021-04-08 14:54:30 +02:00
|
|
|
return $this->kernel->getRouter()->getUrlForRoute($route, $params);
|
2021-04-08 13:19:33 +02:00
|
|
|
});
|
|
|
|
$this->environment->addFunction($path);
|
2021-04-08 13:28:13 +02:00
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
public function addFilters() {
|
|
|
|
$secondsToInterval = new TwigFilter('interval', function(int $time) {
|
|
|
|
$days = floor($time / (60 * 60 * 24));
|
|
|
|
$time -= $days * (60 * 60 * 24);
|
|
|
|
|
|
|
|
$hours = floor($time / (60 * 60));
|
|
|
|
$time -= $hours * (60 * 60);
|
|
|
|
|
|
|
|
$minutes = floor($time / 60);
|
|
|
|
$time -= $minutes * 60;
|
|
|
|
|
|
|
|
$seconds = floor($time);
|
|
|
|
$time -= $seconds;
|
|
|
|
|
|
|
|
return "{$days}d {$hours}h {$minutes}m {$seconds}s";
|
|
|
|
});
|
|
|
|
$this->environment->addFilter($secondsToInterval);
|
2021-04-08 13:19:33 +02:00
|
|
|
}
|
|
|
|
}
|