vendor/gglnx/twig-try-catch/src/TokenParser/TryCatchTokenParser.php line 40

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\TokenParser;
  10. use Gglnx\TwigTryCatch\Node\TryCatchNode;
  11. use Twig\Token;
  12. use Twig\TokenParser\AbstractTokenParser;
  13. /**
  14. * Adds parser for try/catch syntax.
  15. *
  16. * <pre>
  17. * {% try %}
  18. * <li>{{ user.get('name') }}</li>
  19. * {% catch %}
  20. * {{ e.message }}
  21. * {% endcatch %}
  22. * </pre>
  23. *
  24. * @author Dennis Morhardt <info@dennismorhardt.de>
  25. * @package Gglnx\TwigTryCatch\TokenParser
  26. */
  27. class TryCatchTokenParser extends AbstractTokenParser
  28. {
  29. /**
  30. * Parses a token and returns a node.
  31. *
  32. * @param Token $token
  33. * @return TryCatchNode
  34. * @throws SyntaxError
  35. */
  36. public function parse(Token $token)
  37. {
  38. $lineno = $token->getLine();
  39. $stream = $this->parser->getStream();
  40. $stream->expect(Token::BLOCK_END_TYPE);
  41. $try = $this->parser->subparse([$this, 'decideCatch']);
  42. $stream->next();
  43. $stream->expect(Token::BLOCK_END_TYPE);
  44. $catch = $this->parser->subparse([$this, 'decideEnd']);
  45. $stream->next();
  46. $stream->expect(Token::BLOCK_END_TYPE);
  47. return new TryCatchNode($try, $catch, $lineno, $this->getTag());
  48. }
  49. /**
  50. * @param Token $token
  51. * @return bool
  52. */
  53. public function decideCatch(Token $token): bool
  54. {
  55. return $token->test(['catch']);
  56. }
  57. /**
  58. * @param Token $token
  59. * @return bool
  60. */
  61. public function decideEnd(Token $token): bool
  62. {
  63. return $token->test(['endtry']) || $token->test(['endcatch']);
  64. }
  65. /**
  66. * Gets the tag name associated with this token parser.
  67. *
  68. * @return string The tag name
  69. */
  70. public function getTag(): string
  71. {
  72. return 'try';
  73. }
  74. }