Sin descripción

HIncludeFragmentRenderer.php 5.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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\Component\HttpKernel\Fragment;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use Symfony\Component\HttpFoundation\Response;
  13. use Symfony\Component\HttpKernel\Controller\ControllerReference;
  14. use Symfony\Component\HttpKernel\UriSigner;
  15. use Symfony\Component\Templating\EngineInterface;
  16. use Twig\Environment;
  17. use Twig\Error\LoaderError;
  18. use Twig\Loader\ExistsLoaderInterface;
  19. use Twig\Loader\SourceContextLoaderInterface;
  20. /**
  21. * Implements the Hinclude rendering strategy.
  22. *
  23. * @author Fabien Potencier <fabien@symfony.com>
  24. */
  25. class HIncludeFragmentRenderer extends RoutableFragmentRenderer
  26. {
  27. private $globalDefaultTemplate;
  28. private $signer;
  29. private $templating;
  30. private $charset;
  31. /**
  32. * @param EngineInterface|Environment $templating An EngineInterface or a Twig instance
  33. * @param string $globalDefaultTemplate The global default content (it can be a template name or the content)
  34. */
  35. public function __construct($templating = null, UriSigner $signer = null, string $globalDefaultTemplate = null, string $charset = 'utf-8')
  36. {
  37. $this->setTemplating($templating);
  38. $this->globalDefaultTemplate = $globalDefaultTemplate;
  39. $this->signer = $signer;
  40. $this->charset = $charset;
  41. }
  42. /**
  43. * Sets the templating engine to use to render the default content.
  44. *
  45. * @param EngineInterface|Environment|null $templating An EngineInterface or an Environment instance
  46. *
  47. * @throws \InvalidArgumentException
  48. *
  49. * @internal
  50. */
  51. public function setTemplating($templating)
  52. {
  53. if (null !== $templating && !$templating instanceof EngineInterface && !$templating instanceof Environment) {
  54. throw new \InvalidArgumentException('The hinclude rendering strategy needs an instance of Twig\Environment or Symfony\Component\Templating\EngineInterface.');
  55. }
  56. if ($templating instanceof EngineInterface) {
  57. @trigger_error(sprintf('Using a "%s" instance for "%s" is deprecated since version 4.3; use a \Twig\Environment instance instead.', EngineInterface::class, __CLASS__), \E_USER_DEPRECATED);
  58. }
  59. $this->templating = $templating;
  60. }
  61. /**
  62. * Checks if a templating engine has been set.
  63. *
  64. * @return bool true if the templating engine has been set, false otherwise
  65. */
  66. public function hasTemplating()
  67. {
  68. return null !== $this->templating;
  69. }
  70. /**
  71. * {@inheritdoc}
  72. *
  73. * Additional available options:
  74. *
  75. * * default: The default content (it can be a template name or the content)
  76. * * id: An optional hx:include tag id attribute
  77. * * attributes: An optional array of hx:include tag attributes
  78. */
  79. public function render($uri, Request $request, array $options = [])
  80. {
  81. if ($uri instanceof ControllerReference) {
  82. if (null === $this->signer) {
  83. throw new \LogicException('You must use a proper URI when using the Hinclude rendering strategy or set a URL signer.');
  84. }
  85. // we need to sign the absolute URI, but want to return the path only.
  86. $uri = substr($this->signer->sign($this->generateFragmentUri($uri, $request, true)), \strlen($request->getSchemeAndHttpHost()));
  87. }
  88. // We need to replace ampersands in the URI with the encoded form in order to return valid html/xml content.
  89. $uri = str_replace('&', '&amp;', $uri);
  90. $template = $options['default'] ?? $this->globalDefaultTemplate;
  91. if (null !== $this->templating && $template && $this->templateExists($template)) {
  92. $content = $this->templating->render($template);
  93. } else {
  94. $content = $template;
  95. }
  96. $attributes = isset($options['attributes']) && \is_array($options['attributes']) ? $options['attributes'] : [];
  97. if (isset($options['id']) && $options['id']) {
  98. $attributes['id'] = $options['id'];
  99. }
  100. $renderedAttributes = '';
  101. if (\count($attributes) > 0) {
  102. $flags = \ENT_QUOTES | \ENT_SUBSTITUTE;
  103. foreach ($attributes as $attribute => $value) {
  104. $renderedAttributes .= sprintf(
  105. ' %s="%s"',
  106. htmlspecialchars($attribute, $flags, $this->charset, false),
  107. htmlspecialchars($value, $flags, $this->charset, false)
  108. );
  109. }
  110. }
  111. return new Response(sprintf('<hx:include src="%s"%s>%s</hx:include>', $uri, $renderedAttributes, $content));
  112. }
  113. private function templateExists(string $template): bool
  114. {
  115. if ($this->templating instanceof EngineInterface) {
  116. try {
  117. return $this->templating->exists($template);
  118. } catch (\Exception $e) {
  119. return false;
  120. }
  121. }
  122. $loader = $this->templating->getLoader();
  123. if (1 === Environment::MAJOR_VERSION && !$loader instanceof ExistsLoaderInterface) {
  124. try {
  125. if ($loader instanceof SourceContextLoaderInterface) {
  126. $loader->getSourceContext($template);
  127. } else {
  128. $loader->getSource($template);
  129. }
  130. return true;
  131. } catch (LoaderError $e) {
  132. }
  133. return false;
  134. }
  135. return $loader->exists($template);
  136. }
  137. /**
  138. * {@inheritdoc}
  139. */
  140. public function getName()
  141. {
  142. return 'hinclude';
  143. }
  144. }