vendor/gglnx/twig-try-catch/src/Node/TryCatchNode.php line 31

Open in your IDE?
  1. <?php
  2. /**
  3. * Twig Try Catch
  4. *
  5. * @copyright 2022 Dennis Morhardt <info@dennismorhardt.de>
  6. * @copyright 2015-2022 Trilby Media, LLC
  7. * @license MIT License; see LICENSE file for details.
  8. */
  9. namespace Gglnx\TwigTryCatch\Node;
  10. use LogicException;
  11. use Twig\Compiler;
  12. use Twig\Node\Node;
  13. /**
  14. * Node for try/catch construct
  15. *
  16. * @author Dennis Morhardt <info@dennismorhardt.de>
  17. * @package Gglnx\TwigTryCatch\Node
  18. */
  19. class TryCatchNode extends Node
  20. {
  21. /**
  22. * @param Node $try
  23. * @param Node|null $catch
  24. * @param int $lineno
  25. * @param string|null $tag
  26. */
  27. public function __construct(Node $try, Node $catch = null, $lineno = 0, $tag = null)
  28. {
  29. $nodes = ['try' => $try, 'catch' => $catch];
  30. $nodes = array_filter($nodes);
  31. parent::__construct($nodes, [], $lineno, $tag);
  32. }
  33. /**
  34. * Compiles the node to PHP.
  35. *
  36. * @param Compiler $compiler A Twig Compiler instance
  37. * @return void
  38. * @throws LogicException
  39. */
  40. public function compile(Compiler $compiler): void
  41. {
  42. $compiler->addDebugInfo($this);
  43. $compiler->write('try {');
  44. $compiler
  45. ->indent()
  46. ->subcompile($this->getNode('try'))
  47. ->outdent()
  48. ->write('} catch (\Throwable $e) {' . "\n")
  49. ->indent()
  50. ->write('$context[\'e\'] = $e;' . "\n");
  51. if ($this->hasNode('catch')) {
  52. $compiler->subcompile($this->getNode('catch'));
  53. }
  54. $compiler
  55. ->outdent()
  56. ->write("}\n");
  57. }
  58. }