vendor/netgen/site-bundle/bundle/Templating/Twig/BaseDebugTemplate.php line 30

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace Netgen\Bundle\SiteBundle\Templating\Twig;
  4. use Symfony\Component\Filesystem\Filesystem;
  5. use Twig\Template;
  6. use function dirname;
  7. use function getcwd;
  8. use function implode;
  9. use function mb_stripos;
  10. use function mb_substr;
  11. use function preg_replace;
  12. use function str_contains;
  13. use function str_ends_with;
  14. use function trim;
  15. /**
  16. * Meant to be used as a Twig base template class.
  17. *
  18. * Wraps the yield method to:
  19. * - Inject debug info into template to be able to see in the markup which one is used
  20. */
  21. abstract class BaseDebugTemplate extends Template
  22. {
  23. private Filesystem $fileSystem;
  24. public function yield(array $context, array $blocks = []): iterable
  25. {
  26. $this->fileSystem = $this->fileSystem ?? new Filesystem();
  27. // Get parent result to be able to insert template name as HTML comments if applicable.
  28. // Layout template name will only appear at the end, to avoid potential quirks with old browsers
  29. // when comments appear before doctype declaration.
  30. $templateResult = implode('', [...parent::yield($context, $blocks)]);
  31. $templateName = trim($this->fileSystem->makePathRelative($this->getSourceContext()->getPath(), dirname((string) getcwd())), '/');
  32. $isHtmlTemplate = str_ends_with($templateName, 'html.twig');
  33. $templateName = $isHtmlTemplate ? $templateName . ' (' . $this->getSourceContext()->getName() . ')' : $templateName;
  34. // Display start template comment, if applicable.
  35. if ($isHtmlTemplate) {
  36. if (str_contains(trim($templateResult), '<!doctype')) {
  37. $templateResult = (string) preg_replace(
  38. '#(<!doctype[^>]+>)#im',
  39. "$1\n<!-- START " . $templateName . ' -->',
  40. $templateResult,
  41. );
  42. } else {
  43. yield "\n<!-- START " . $templateName . " -->\n";
  44. }
  45. }
  46. // Display stop template comment after result, if applicable.
  47. if ($isHtmlTemplate) {
  48. if (str_contains($templateResult, '</body>')) {
  49. $bodyPos = (int) mb_stripos($templateResult, '</body>');
  50. // Add layout template name before </body>, to avoid display quirks in some browsers.
  51. yield mb_substr($templateResult, 0, $bodyPos)
  52. . "\n<!-- STOP " . $templateName . " -->\n"
  53. . mb_substr($templateResult, $bodyPos);
  54. } else {
  55. yield $templateResult;
  56. yield "\n<!-- STOP " . $templateName . " -->\n";
  57. }
  58. } else {
  59. yield $templateResult;
  60. }
  61. }
  62. }