Skip to content

Instantly share code, notes, and snippets.

@kelunik

kelunik/Twig.php Secret

Created September 13, 2016 14:37
Show Gist options
  • Save kelunik/250f1bb415af7926ac6873aa53ef40ca to your computer and use it in GitHub Desktop.
Save kelunik/250f1bb415af7926ac6873aa53ef40ca to your computer and use it in GitHub Desktop.
<?php
namespace Kelunik\DaaS\Rendering;
use Twig_Environment as TwigEnvironment;
use Psr\Log\LoggerInterface as PsrLogger;
use Twig_TemplateInterface as TwigTemplate;
class Twig {
private $twigEnvironment;
private $templates;
private $logger;
public function __construct(TwigEnvironment $twigEnvironment, PsrLogger $logger) {
$this->twigEnvironment = $twigEnvironment;
$this->logger = $logger;
}
public function render(string $name, TwigContext $context) {
assert($this->debug("Rendering '{$name}' with '" . json_encode($context->toArray()) . "'"));
$template = $this->load($name);
return $template->render($context->toArray());
}
private function load(string $name): TwigTemplate {
if (!isset($this->templates[$name])) {
$this->templates[$name] = $this->twigEnvironment->loadTemplate($name);
}
return $this->templates[$name];
}
private function debug(string $message, array $context = []) {
$this->logger->debug($message, $context);
// return true to always pass assertions
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment