1: <?php
2: 3: 4: 5: 6: 7: 8: 9:
10:
11: namespace Autarky\TwigTemplating;
12:
13: use Symfony\Component\EventDispatcher\EventDispatcherInterface;
14:
15: use Autarky\Events\EventDispatcherAwareInterface;
16:
17: 18: 19:
20: class TemplatingEngine implements EventDispatcherAwareInterface
21: {
22: 23: 24: 25: 26:
27: protected $twig;
28:
29: 30: 31: 32: 33:
34: protected $eventDispatcher;
35:
36: 37: 38:
39: public function __construct(TwigEnvironment $twig)
40: {
41: $this->twig = $twig;
42: }
43:
44: 45: 46: 47: 48:
49: public function setEventDispatcher(EventDispatcherInterface $eventDispatcher)
50: {
51: $this->eventDispatcher = $eventDispatcher;
52: $this->twig->setEventDispatcher($eventDispatcher);
53: }
54:
55: 56: 57: 58: 59: 60: 61: 62:
63: public function render($name, array $context = array())
64: {
65: return $this->twig->loadTemplate($name)
66: ->render($context);
67: }
68:
69: 70: 71: 72: 73: 74: 75: 76: 77:
78: public function creating($name, $handler, $priority = 0)
79: {
80: $this->addEventListener('creating', $name, $handler, $priority);
81: }
82:
83: 84: 85: 86: 87: 88: 89: 90: 91:
92: public function rendering($name, $handler, $priority = 0)
93: {
94: $this->addEventListener('rendering', $name, $handler, $priority);
95: }
96:
97: protected function addEventListener($event, $name, $handler, $priority = 0)
98: {
99: if ($this->eventDispatcher === null) {
100: throw new \RuntimeException('Cannot register templating event listeners without first setting the EventDispatcher on the TemplateManager.');
101: }
102:
103: $this->eventDispatcher->addListener("template.$event: $name", $handler, $priority);
104: }
105:
106: 107: 108: 109: 110: 111: 112: 113:
114: public function addGlobal($name, $value)
115: {
116: $this->twig->addGlobal($name, $value);
117: }
118:
119: 120: 121: 122: 123: 124: 125: 126:
127: public function addNamespace($namespace, $location)
128: {
129: $loader = $this->twig->getLoader();
130:
131: $loader->addPath($location, $namespace);
132:
133: foreach ($loader->getPaths() as $path) {
134: if (is_dir($dir = $path.'/'.$namespace)) {
135: $loader->prependPath($dir, $namespace);
136: }
137: }
138: }
139: }
140: