AutoEscape.php 2.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. if ($this->parser->getStream()->test(Twig_Token::BLOCK_END_TYPE)) {
  41. $value = 'html';
  42. } else {
  43. $expr = $this->parser->getExpressionParser()->parseExpression();
  44. if (!$expr instanceof Twig_Node_Expression_Constant) {
  45. throw new Twig_Error_Syntax('An escaping strategy must be a string or a Boolean.', $lineno);
  46. }
  47. $value = $expr->getAttribute('value');
  48. $compat = true === $value || false === $value;
  49. if (true === $value) {
  50. $value = 'html';
  51. }
  52. if ($compat && $this->parser->getStream()->test(Twig_Token::NAME_TYPE)) {
  53. if (false === $value) {
  54. throw new Twig_Error_Syntax('Unexpected escaping strategy as you set autoescaping to false.', $lineno);
  55. }
  56. $value = $this->parser->getStream()->next()->getValue();
  57. }
  58. }
  59. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  60. $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true);
  61. $this->parser->getStream()->expect(Twig_Token::BLOCK_END_TYPE);
  62. return new Twig_Node_AutoEscape($value, $body, $lineno, $this->getTag());
  63. }
  64. public function decideBlockEnd(Twig_Token $token)
  65. {
  66. return $token->test('endautoescape');
  67. }
  68. /**
  69. * Gets the tag name associated with this token parser.
  70. *
  71. * @return string The tag name
  72. */
  73. public function getTag()
  74. {
  75. return 'autoescape';
  76. }
  77. }