webcron/lib/Framework/Twig.php

61 lines
1.7 KiB
PHP
Raw Normal View History

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-04-08 13:19:33 +02:00
use Twig\Environment;
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;
public function __construct(Kernel $kernel)
{
$loader = new FilesystemLoader([$kernel->getTemplateDir()]);
$this->environment = new Environment($loader);
$this->kernel = $kernel;
$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);
}
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
});
2021-05-26 13:09:13 +02:00
$this->environment->addExtension(new EntryFilesTwigExtension(new EntrypointLookup('./public/build/entrypoints.json')));
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
}
}