1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the Valkyrja Framework package. |
7
|
|
|
* |
8
|
|
|
* (c) Melech Mizrachi <[email protected]> |
9
|
|
|
* |
10
|
|
|
* For the full copyright and license information, please view the LICENSE |
11
|
|
|
* file that was distributed with this source code. |
12
|
|
|
*/ |
13
|
|
|
|
14
|
|
|
namespace Valkyrja\View; |
15
|
|
|
|
16
|
|
|
use Twig\Environment; |
17
|
|
|
use Twig\Error\LoaderError; |
18
|
|
|
use Twig\Error\RuntimeError; |
19
|
|
|
use Twig\Error\SyntaxError; |
20
|
|
|
use Valkyrja\View\Contract\Renderer as Contract; |
21
|
|
|
use Valkyrja\View\Template\Contract\Template; |
22
|
|
|
use Valkyrja\View\Template\Template as DefaultTemplate; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Class TwigRenderer. |
26
|
|
|
* |
27
|
|
|
* @author Melech Mizrachi |
28
|
|
|
*/ |
29
|
|
|
class TwigRenderer implements Contract |
30
|
|
|
{ |
31
|
|
|
/** |
32
|
|
|
* TwigRenderer constructor. |
33
|
|
|
* |
34
|
|
|
* @param Environment $twig The Twig environment |
35
|
|
|
*/ |
36
|
|
|
public function __construct( |
37
|
|
|
protected Environment $twig |
38
|
|
|
) { |
39
|
|
|
} |
40
|
|
|
|
41
|
|
|
/** |
42
|
|
|
* @inheritDoc |
43
|
|
|
*/ |
44
|
|
|
public function startRender(): void |
45
|
|
|
{ |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
/** |
49
|
|
|
* @inheritDoc |
50
|
|
|
*/ |
51
|
|
|
public function endRender(): string |
52
|
|
|
{ |
53
|
|
|
return ''; |
54
|
|
|
} |
55
|
|
|
|
56
|
|
|
/** |
57
|
|
|
* @inheritDoc |
58
|
|
|
* |
59
|
|
|
* @throws LoaderError When the template cannot be found |
60
|
|
|
* @throws SyntaxError When an error occurred during compilation |
61
|
|
|
* @throws RuntimeError When an error occurred during rendering |
62
|
|
|
*/ |
63
|
|
|
public function render(string $name, array $variables = []): string |
64
|
|
|
{ |
65
|
|
|
return $this->renderFile($name, $variables); |
66
|
|
|
} |
67
|
|
|
|
68
|
|
|
/** |
69
|
|
|
* @inheritDoc |
70
|
|
|
*/ |
71
|
|
|
public function createTemplate(string $name, array $variables = []): Template |
72
|
|
|
{ |
73
|
|
|
return new DefaultTemplate( |
74
|
|
|
renderer: $this, |
75
|
|
|
name: $name, |
76
|
|
|
variables: $variables |
77
|
|
|
); |
78
|
|
|
} |
79
|
|
|
|
80
|
|
|
/** |
81
|
|
|
* @inheritDoc |
82
|
|
|
* |
83
|
|
|
* @throws LoaderError When the template cannot be found |
84
|
|
|
* @throws SyntaxError When an error occurred during compilation |
85
|
|
|
* @throws RuntimeError When an error occurred during rendering |
86
|
|
|
*/ |
87
|
|
|
public function renderFile(string $name, array $variables = []): string |
88
|
|
|
{ |
89
|
|
|
return $this->twig->render($name, $variables); |
90
|
|
|
} |
91
|
|
|
} |
92
|
|
|
|