HIncludeFragmentRenderer.php 5.5KB

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