ViewRenderer   A
last analyzed

Complexity

Total Complexity 4

Size/Duplication

Total Lines 30
Duplicated Lines 0 %

Test Coverage

Coverage 100%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 16
c 1
b 0
f 0
dl 0
loc 30
ccs 19
cts 19
cp 1
rs 10
wmc 4

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 2 1
A render() 0 24 3
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\TemplateRendererInterface;
10
use Yiisoft\View\ViewInterface;
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
 * `ViewRenderer` allows using Twig with a View service.
22
 */
23
final class ViewRenderer implements TemplateRendererInterface
24
{
25 3
    public function __construct(private Environment $environment)
26
    {
27 3
    }
28
29 2
    public function render(ViewInterface $view, string $template, array $parameters): string
30
    {
31 2
        $environment = $this->environment;
32 2
        $renderer = function () use ($view, $template, $parameters, $environment): void {
33 2
            $template = str_replace('\\', '/', $template);
34 2
            $basePath = str_replace('\\', '/', $view->getBasePath());
35 2
            $file = str_replace($basePath, '', $template);
36
37 2
            echo $environment->render($file, array_merge($parameters, ['this' => $view]));
38 2
        };
39
40 2
        $obInitialLevel = ob_get_level();
41 2
        ob_start();
42 2
        ob_implicit_flush(false);
43
44
        try {
45
            /** @psalm-suppress PossiblyInvalidFunctionCall,PossiblyNullFunctionCall */
46 2
            $renderer->bindTo($view)();
47 1
            return ob_get_clean();
48 1
        } catch (Throwable $e) {
49 1
            while (ob_get_level() > $obInitialLevel) {
50 1
                ob_end_clean();
51
            }
52 1
            throw $e;
53
        }
54
    }
55
}
56