AutoEscape.php 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2009 Fabien Potencier
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * Marks a section of a template to be escaped or not.
  12. *
  13. * <pre>
  14. * {% autoescape true %}
  15. * Everything will be automatically escaped in this block
  16. * {% endautoescape %}
  17. *
  18. * {% autoescape false %}
  19. * Everything will be outputed as is in this block
  20. * {% endautoescape %}
  21. *
  22. * {% autoescape true js %}
  23. * Everything will be automatically escaped in this block
  24. * using the js escaping strategy
  25. * {% endautoescape %}
  26. * </pre>
  27. */
  28. class Twig_TokenParser_AutoEscape extends Twig_TokenParser
  29. {
  30. /**
  31. * Parses a token and returns a node.
  32. *
  33. * @param Twig_Token $token A Twig_Token instance
  34. *
  35. * @return Twig_NodeInterface A Twig_NodeInterface instance
  36. */
  37. public function parse(Twig_Token $token)
  38. {
  39. $lineno = $token->getLine();
  40. $value = $this->parser->getStream()->expect(Twig_Token::NAME_TYPE)->getValue();
  41. if (!in_array($value, array('true', 'false'))) {
  42. throw new Twig_Error_Syntax("Autoescape value must be 'true' or 'false'", $lineno);
  43. }
  44. $value = 'true' === $value ? 'html' : false;
  45. if ($this->parser->getStream()->test(Twig_Token::NAME_TYPE)) {
  46. if (false === $value) {
  47. throw new Twig_Error_Syntax('Unexpected escaping strategy as you set autoescaping to false.', $lineno);
  48. }
  49. $value = $this->parser->getStream()->next()->getValue();
  50. }
  51. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  52. $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  53. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  54. return new Twig_Node_AutoEscape($value, $body, $lineno, $this->getTag());
  55. }
  56. public function decideBlockEnd(Twig_Token $token)
  57. {
  58. return $token->test('endautoescape');
  59. }
  60. /**
  61. * Gets the tag name associated with this token parser.
  62. *
  63. * @param string The tag name
  64. */
  65. public function getTag()
  66. {
  67. return 'autoescape';
  68. }
  69. }