-
-
Notifications
You must be signed in to change notification settings - Fork 122
/
Copy pathTemplateController.php
78 lines (66 loc) · 2.55 KB
/
TemplateController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\HttpFoundation\Response;
use Twig\Environment;
/**
* TemplateController.
*
* @author Fabien Potencier <[email protected]>
*
* @final
*/
class TemplateController
{
public function __construct(
private ?Environment $twig = null,
) {
}
/**
* Renders a template.
*
* @param string $template The template name
* @param int|null $maxAge Max age for client caching
* @param int|null $sharedAge Max age for shared (proxy) caching
* @param bool|null $private Whether or not caching should apply for client caches only
* @param array $context The context (arguments) of the template
* @param int $statusCode The HTTP status code to return with the response (200 "OK" by default)
* @param array $headers The HTTP headers to add to the response
*/
public function templateAction(string $template, ?int $maxAge = null, ?int $sharedAge = null, ?bool $private = null, array $context = [], int $statusCode = 200, array $headers = []): Response
{
if (null === $this->twig) {
throw new \LogicException('You cannot use the TemplateController if the Twig Bundle is not available. Try running "composer require symfony/twig-bundle".');
}
$response = new Response($this->twig->render($template, $context), $statusCode);
if ($maxAge) {
$response->setMaxAge($maxAge);
}
if (null !== $sharedAge) {
$response->setSharedMaxAge($sharedAge);
}
if ($private) {
$response->setPrivate();
} elseif (false === $private || (null === $private && (null !== $maxAge || null !== $sharedAge))) {
$response->setPublic();
}
foreach ($headers as $key => $value) {
$response->headers->set($key, $value);
}
return $response;
}
/**
* @param int $statusCode The HTTP status code (200 "OK" by default)
*/
public function __invoke(string $template, ?int $maxAge = null, ?int $sharedAge = null, ?bool $private = null, array $context = [], int $statusCode = 200, array $headers = []): Response
{
return $this->templateAction($template, $maxAge, $sharedAge, $private, $context, $statusCode, $headers);
}
}