1
|
|
|
<?php |
2
|
|
|
declare(strict_types = 1); |
3
|
|
|
|
4
|
|
|
namespace Selami\View\Twig; |
5
|
|
|
|
6
|
|
|
use Selami\View\ViewInterface; |
7
|
|
|
use Psr\Container\ContainerInterface; |
8
|
|
|
use \Twig\Environment as TwigEnvironment; |
9
|
|
|
|
10
|
|
|
class Twig implements ViewInterface |
11
|
|
|
{ |
12
|
|
|
private $twig; |
13
|
|
|
private $config; |
14
|
|
|
public function __construct(TwigEnvironment $twig, array $config) |
15
|
|
|
{ |
16
|
|
|
$this->config = $config; |
17
|
|
|
$this->twig = $twig; |
18
|
|
|
$this->addGlobals(); |
19
|
|
|
new TwigExtensions($this->twig, $this->config); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public static function viewFactory(ContainerInterface $container, array $config) : ViewInterface |
23
|
|
|
{ |
24
|
|
|
$twig = $container->get(TwigEnvironment::class); |
25
|
|
|
return new static($twig, $config); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
private function addGlobals() : void |
29
|
|
|
{ |
30
|
|
|
$this->twig->addGlobal('RuntimeConfig', $this->config); // Runtime Config values |
31
|
|
|
$this->twig->addGlobal('QueryParameters', $this->config['query_parameters']??[]); // Query Parameters ($_REQUEST) |
|
|
|
|
32
|
|
|
$this->twig->addGlobal('Sessions', $this->config['session']??[]); // Query Parameters ($_SESSION) |
|
|
|
|
33
|
|
|
$this->twig->addGlobal('Cookies', $this->config['cookies']??[]); // Query Parameters ($_COOKIES) |
|
|
|
|
34
|
|
|
|
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
public function addGlobal(string $name, $value) : void |
38
|
|
|
{ |
39
|
|
|
$this->twig->addGlobal($name, $value); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
public function render(string $templateFile, array $parameters = []) : string |
43
|
|
|
{ |
44
|
|
|
$output = $this->twig->render($templateFile, $parameters); |
45
|
|
|
preg_match('/{{(\s*)Widget\_/mi', $output, $matches); |
46
|
|
|
if (isset($matches[1])) { |
47
|
|
|
$template = $this->twig->createTemplate($output); |
48
|
|
|
$output = $template->render([]); |
49
|
|
|
} |
50
|
|
|
return $output; |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.
The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.
This check looks for comments that seem to be mostly valid code and reports them.