getTemplateDir()]); $this->environment = new Environment($loader); if(!$_ENV['DEBUG']) { $cache = new FilesystemCache($kernel->getCacheDir() . '/twig'); $this->environment->setCache($cache); } $this->kernel = $kernel; $this->addExtensions(); $this->addFunctions(); $this->addFilters(); } public function render(string $template, array $vars = []): string { return $this->environment->render($template, $vars); } public function addExtensions() { $this->environment->addExtension(new IntlExtension()); $this->environment->addExtension(new EntryFilesTwigExtension(new EntrypointLookup('./public/build/entrypoints.json'))); } public function addFunctions() { $path = new TwigFunction('path', function(string $route, array $params = []) { return $this->kernel->getRouter()->getUrlForRoute($route, $params); }); $randombits = new TwigFunction('randombits', function($length) { $characters = '01'; $charactersLength = strlen($characters); $randomString = ''; for ($i = 0; $i < $length; $i++) { $randomString .= $characters[rand(0, $charactersLength - 1)]; } return $randomString; }); $this->environment->addFunction($path); $this->environment->addFunction($randombits); } 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"; }); $markdown = new TwigFilter('markdown', function(string $markdown) { $parsedown = new \Parsedown(); return $parsedown->text($markdown); }); $this->environment->addFilter($secondsToInterval); $this->environment->addFilter($markdown); } }