TwigNodeMarkdown.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. <?php
  2. /**
  3. * @package Grav\Common\Twig
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Twig\Node;
  9. use Twig\Compiler;
  10. use Twig\Node\Node;
  11. use Twig\Node\NodeOutputInterface;
  12. class TwigNodeMarkdown extends Node implements NodeOutputInterface
  13. {
  14. /**
  15. * TwigNodeMarkdown constructor.
  16. * @param Node $body
  17. * @param int $lineno
  18. * @param string $tag
  19. */
  20. public function __construct(Node $body, $lineno, $tag = 'markdown')
  21. {
  22. parent::__construct(['body' => $body], [], $lineno, $tag);
  23. }
  24. /**
  25. * Compiles the node to PHP.
  26. *
  27. * @param Compiler $compiler A Twig_Compiler instance
  28. */
  29. public function compile(Compiler $compiler)
  30. {
  31. $compiler
  32. ->addDebugInfo($this)
  33. ->write('ob_start();' . PHP_EOL)
  34. ->subcompile($this->getNode('body'))
  35. ->write('$content = ob_get_clean();' . PHP_EOL)
  36. ->write('preg_match("/^\s*/", $content, $matches);' . PHP_EOL)
  37. ->write('$lines = explode("\n", $content);' . PHP_EOL)
  38. ->write('$content = preg_replace(\'/^\' . $matches[0]. \'/\', "", $lines);' . PHP_EOL)
  39. ->write('$content = join("\n", $content);' . PHP_EOL)
  40. ->write('echo $this->env->getExtension(\'Grav\Common\Twig\TwigExtension\')->markdownFunction($context, $content);' . PHP_EOL);
  41. }
  42. }