Twig::addGlobal()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
dl 0
loc 4
ccs 0
cts 4
cp 0
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 2
crap 2
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
        if (array_key_exists('runtime', $this->config)) {
31
            foreach ($this->config['runtime'] as $key => $value) {
32
                $this->twig->addGlobal($key, $value);
33
            }
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