TwigTokenParserTryCatch.php 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. <?php
  2. /**
  3. * @package Grav.Common.Twig
  4. *
  5. * @copyright Copyright (C) 2015 - 2018 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Twig\TokenParser;
  9. use Grav\Common\Twig\Node\TwigNodeTryCatch;
  10. /**
  11. * Handles try/catch in template file.
  12. *
  13. * <pre>
  14. * {% try %}
  15. * <li>{{ user.get('name') }}</li>
  16. * {% catch %}
  17. * {{ e.message }}
  18. * {% endcatch %}
  19. * </pre>
  20. */
  21. class TwigTokenParserTryCatch extends \Twig_TokenParser
  22. {
  23. /**
  24. * Parses a token and returns a node.
  25. *
  26. * @param \Twig_Token $token A Twig_Token instance
  27. *
  28. * @return \Twig_Node A Twig_Node instance
  29. */
  30. public function parse(\Twig_Token $token)
  31. {
  32. $lineno = $token->getLine();
  33. $stream = $this->parser->getStream();
  34. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  35. $try = $this->parser->subparse([$this, 'decideCatch']);
  36. $stream->next();
  37. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  38. $catch = $this->parser->subparse([$this, 'decideEnd']);
  39. $stream->next();
  40. $stream->expect(\Twig_Token::BLOCK_END_TYPE);
  41. return new TwigNodeTryCatch($try, $catch, $lineno, $this->getTag());
  42. }
  43. public function decideCatch(\Twig_Token $token)
  44. {
  45. return $token->test(array('catch'));
  46. }
  47. public function decideEnd(\Twig_Token $token)
  48. {
  49. return $token->test(array('endtry')) || $token->test(array('endcatch'));
  50. }
  51. /**
  52. * Gets the tag name associated with this token parser.
  53. *
  54. * @return string The tag name
  55. */
  56. public function getTag()
  57. {
  58. return 'try';
  59. }
  60. }