Completed
Push — master ( 11784d...13e877 )
by Guido
05:41
created

TwigService::needsTwig()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
nc 2
nop 3
dl 0
loc 13
rs 9.8333
c 0
b 0
f 0
1
<?php
2
3
namespace Gvera\Services;
4
5
use Gvera\Helpers\config\Config;
6
use Twig\Environment;
7
use Twig\Loader\FilesystemLoader;
8
9
class TwigService
10
{
11
    const VIEWS_PREFIX = __DIR__ . '/../Views/';
12
    private Config $config;
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected T_STRING, expecting T_FUNCTION or T_CONST
Loading history...
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