TemplateController.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bundle\FrameworkBundle\Controller;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Twig\Environment;
  13. /**
  14. * TemplateController.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. *
  18. * @final
  19. */
  20. class TemplateController
  21. {
  22. private $twig;
  23. public function __construct(Environment $twig = null)
  24. {
  25. $this->twig = $twig;
  26. }
  27. /**
  28. * Renders a template.
  29. *
  30. * @param string $template The template name
  31. * @param int|null $maxAge Max age for client caching
  32. * @param int|null $sharedAge Max age for shared (proxy) caching
  33. * @param bool|null $private Whether or not caching should apply for client caches only
  34. * @param array $context The context (arguments) of the template
  35. */
  36. public function templateAction(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null, array $context = []): Response
  37. {
  38. if (null === $this->twig) {
  39. throw new \LogicException('You can not use the TemplateController if the Twig Bundle is not available.');
  40. }
  41. $response = new Response($this->twig->render($template, $context));
  42. if ($maxAge) {
  43. $response->setMaxAge($maxAge);
  44. }
  45. if (null !== $sharedAge) {
  46. $response->setSharedMaxAge($sharedAge);
  47. }
  48. if ($private) {
  49. $response->setPrivate();
  50. } elseif (false === $private || (null === $private && (null !== $maxAge || null !== $sharedAge))) {
  51. $response->setPublic();
  52. }
  53. return $response;
  54. }
  55. public function __invoke(string $template, int $maxAge = null, int $sharedAge = null, bool $private = null, array $context = []): Response
  56. {
  57. return $this->templateAction($template, $maxAge, $sharedAge, $private, $context);
  58. }
  59. }