Completed
Push — master ( d8fbea...c06e4f )
by Arman
28s queued 12s
created

TwigRenderer::render()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 25
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 5
eloc 14
c 1
b 0
f 0
nc 7
nop 3
dl 0
loc 25
rs 9.4888
1
<?php
2
3
/**
4
 * Quantum PHP Framework
5
 *
6
 * An open source software development framework for PHP
7
 *
8
 * @package Quantum
9
 * @author Arman Ag. <[email protected]>
10
 * @copyright Copyright (c) 2018 Softberg LLC (https://softberg.org)
11
 * @link http://quantum.softberg.org/
12
 * @since 2.6.0
13
 */
14
15
namespace Quantum\Renderer;
16
17
use Quantum\Libraries\Storage\FileSystem;
18
use Quantum\Exceptions\ViewException;
19
use Twig\Loader\FilesystemLoader;
20
use Twig\TwigFunction;
21
use Quantum\Di\Di;
22
23
class TwigRenderer implements TemplateRenderer
24
{
25
26
    /**
27
     * Renders the template
28
     * @param string $view
29
     * @param array $params
30
     * @param array $configs
31
     * @return string
32
     * @throws \Quantum\Exceptions\DiException
33
     * @throws \Quantum\Exceptions\ViewException
34
     * @throws \ReflectionException
35
     * @throws \Twig\Error\LoaderError
36
     * @throws \Twig\Error\RuntimeError
37
     * @throws \Twig\Error\SyntaxError
38
     */
39
    public function render(string $view, array $params = [], array $configs = []): string
40
    {
41
        $fs = Di::get(FileSystem::class);
42
43
        if ($fs->exists(modules_dir() . DS . current_module() . DS . 'Views' . DS . $view . '.php')) {
44
            $loader = new FilesystemLoader(modules_dir() . DS . current_module() . DS . 'Views');
45
        } else if ($fs->exists(base_dir() . DS . 'base' . DS . 'views' . DS . $view . '.php')) {
46
            $loader = new FilesystemLoader(base_dir() . DS . 'base' . DS . 'views');
47
        } else {
48
            throw ViewException::fileNotFound($view);
49
        }
50
        
51
        $twig = new \Twig\Environment($loader, $configs);
52
53
        $definedFunctions = get_defined_functions();
54
55
        $allDefinedFunctions = array_merge($definedFunctions['internal'], $definedFunctions['user']);
56
57
        foreach ($allDefinedFunctions as $function) {
58
            if (function_exists($function)) {
59
                $twig->addFunction(new TwigFunction($function, $function));
60
            }
61
        }
62
63
        return $twig->render($view . '.php', $params);
64
    }
65
66
}