1 | <?php |
||
9 | class TwigService |
||
10 | { |
||
11 | const VIEWS_PREFIX = __DIR__ . '/../Views/'; |
||
12 | private Config $config; |
||
|
|||
13 | private bool $loadTwig; |
||
14 | private Environment $twig; |
||
15 | |||
16 | /** |
||
17 | * TwigService constructor. |
||
18 | * @param Config $config |
||
19 | */ |
||
20 | public function __construct(Config $config) |
||
21 | { |
||
22 | $this->config = $config; |
||
23 | } |
||
24 | |||
25 | /** |
||
26 | * @param $controllerName |
||
27 | * @param $controllerMethod |
||
28 | * @param null $path |
||
29 | * @return bool |
||
30 | */ |
||
31 | public function needsTwig($controllerName, $controllerMethod, $path = null): bool |
||
32 | { |
||
33 | $path = $path ?? self::VIEWS_PREFIX; |
||
34 | if (null === $this->loadTwig) { |
||
35 | $this->loadTwig = file_exists( |
||
36 | $path . |
||
37 | $controllerName . |
||
38 | DIRECTORY_SEPARATOR . |
||
39 | $controllerMethod . '.html.twig' |
||
40 | ); |
||
41 | } |
||
42 | return $this->loadTwig; |
||
43 | } |
||
44 | |||
45 | /** |
||
46 | * @param string|null $path |
||
47 | * @return Environment |
||
48 | */ |
||
49 | public function loadTwig(string $path = null): Environment |
||
50 | { |
||
51 | $path = $path ?? self::VIEWS_PREFIX; |
||
52 | $devMode = boolval($this->config->getConfigItem('devmode')); |
||
53 | $cache = $devMode ? false : __DIR__ . '/../../var/cache/views/'; |
||
54 | $loader = new FilesystemLoader($path); |
||
55 | $this->twig = new Environment($loader, ['cache' => $cache, 'debug' => $devMode]); |
||
56 | return $this->twig; |
||
57 | } |
||
58 | |||
59 | public function render($name, $method, $viewParams) |
||
60 | { |
||
61 | return $this->twig->render( |
||
62 | DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR . $method . '.html.twig', |
||
63 | $viewParams |
||
64 | ); |
||
65 | } |
||
66 | |||
67 | public function reset() |
||
68 | { |
||
69 | $this->twig = null; |
||
70 | $this->loadTwig = null; |
||
71 | } |
||
72 | } |
||
73 |