TwigNodeTryCatch.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * @package Grav\Common\Twig
  4. *
  5. * @copyright Copyright (c) 2015 - 2021 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Twig\Node;
  9. use LogicException;
  10. use Twig\Compiler;
  11. use Twig\Node\Node;
  12. /**
  13. * Class TwigNodeTryCatch
  14. * @package Grav\Common\Twig\Node
  15. */
  16. class TwigNodeTryCatch extends Node
  17. {
  18. /**
  19. * TwigNodeTryCatch constructor.
  20. * @param Node $try
  21. * @param Node|null $catch
  22. * @param int $lineno
  23. * @param string|null $tag
  24. */
  25. public function __construct(Node $try, Node $catch = null, $lineno = 0, $tag = null)
  26. {
  27. $nodes = ['try' => $try, 'catch' => $catch];
  28. $nodes = array_filter($nodes);
  29. parent::__construct($nodes, [], $lineno, $tag);
  30. }
  31. /**
  32. * Compiles the node to PHP.
  33. *
  34. * @param Compiler $compiler A Twig Compiler instance
  35. * @return void
  36. * @throws LogicException
  37. */
  38. public function compile(Compiler $compiler): void
  39. {
  40. $compiler->addDebugInfo($this);
  41. $compiler->write('try {');
  42. $compiler
  43. ->indent()
  44. ->subcompile($this->getNode('try'))
  45. ->outdent()
  46. ->write('} catch (\Exception $e) {' . "\n")
  47. ->indent()
  48. ->write('if (isset($context[\'grav\'][\'debugger\'])) $context[\'grav\'][\'debugger\']->addException($e);' . "\n")
  49. ->write('$context[\'e\'] = $e;' . "\n");
  50. if ($this->hasNode('catch')) {
  51. $compiler->subcompile($this->getNode('catch'));
  52. }
  53. $compiler
  54. ->outdent()
  55. ->write("}\n");
  56. }
  57. }