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

TemplateRenderer::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
dl 0
loc 2
ccs 1
cts 1
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 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