Passed
Pull Request — master (#61)
by Rustam
12:31
created

TemplateRenderer   A

Complexity

Total Complexity 4

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 0
Metric Value
wmc 4
eloc 15
dl 0
loc 27
ccs 18
cts 18
cp 1
rs 10
c 0
b 0
f 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
A render() 0 21 3
A __construct() 0 2 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\View\Twig;
6
7
use Throwable;
8
use Twig\Environment;
9
use Yiisoft\View\Template;
10
use Yiisoft\View\TemplateRendererInterface;
11
12
use function array_merge;
13
use function ob_end_clean;
14
use function ob_get_clean;
15
use function ob_get_level;
16
use function ob_implicit_flush;
17
use function ob_start;
18
use function str_replace;
19
20
/**
21
 * TemplateRenderer allows using Twig with a View service.
22
 */
23
final class TemplateRenderer implements TemplateRendererInterface
24
{
25 2
    public function __construct(private Environment $environment)
26
    {
27 2
    }
28
29 2
    public function render(Template $template): string
30
    {
31 2
        $view = $template->getView();
32 2
        $templateFile = str_replace(
33 2
            [$view->getBasePath(), $template->getViewContext()?->getViewPath() ?? ''],
34 2
            '',
35 2
            $template->getTemplate()
36 2
        );
37
38 2
        $obInitialLevel = ob_get_level();
39 2
        ob_start();
40 2
        ob_implicit_flush(false);
41
42
        try {
43 2
            $this->environment->display($templateFile, array_merge($template->getParameters(), ['this' => $view]));
44 1
            return ob_get_clean();
45 1
        } catch (Throwable $e) {
46 1
            while (ob_get_level() > $obInitialLevel) {
47 1
                ob_end_clean();
48
            }
49 1
            throw $e;
50
        }
51
    }
52
}
53