AutoEscape.php (2541B)
1 <?php 2 3 /* 4 * This file is part of Twig. 5 * 6 * (c) 2009 Fabien Potencier 7 * 8 * For the full copyright and license information, please view the LICENSE 9 * file that was distributed with this source code. 10 */ 11 12 /** 13 * Marks a section of a template to be escaped or not. 14 * 15 * <pre> 16 * {% autoescape true %} 17 * Everything will be automatically escaped in this block 18 * {% endautoescape %} 19 * 20 * {% autoescape false %} 21 * Everything will be outputed as is in this block 22 * {% endautoescape %} 23 * 24 * {% autoescape true js %} 25 * Everything will be automatically escaped in this block 26 * using the js escaping strategy 27 * {% endautoescape %} 28 * </pre> 29 */ 30 class Twig_TokenParser_AutoEscape extends Twig_TokenParser 31 { 32 public function parse(Twig_Token $token) 33 { 34 $lineno = $token->getLine(); 35 $stream = $this->parser->getStream(); 36 37 if ($stream->test(Twig_Token::BLOCK_END_TYPE)) { 38 $value = 'html'; 39 } else { 40 $expr = $this->parser->getExpressionParser()->parseExpression(); 41 if (!$expr instanceof Twig_Node_Expression_Constant) { 42 throw new Twig_Error_Syntax('An escaping strategy must be a string or a bool.', $stream->getCurrent()->getLine(), $stream->getFilename()); 43 } 44 $value = $expr->getAttribute('value'); 45 46 $compat = true === $value || false === $value; 47 48 if (true === $value) { 49 $value = 'html'; 50 } 51 52 if ($compat && $stream->test(Twig_Token::NAME_TYPE)) { 53 @trigger_error('Using the autoescape tag with "true" or "false" before the strategy name is deprecated since version 1.21.', E_USER_DEPRECATED); 54 55 if (false === $value) { 56 throw new Twig_Error_Syntax('Unexpected escaping strategy as you set autoescaping to false.', $stream->getCurrent()->getLine(), $stream->getFilename()); 57 } 58 59 $value = $stream->next()->getValue(); 60 } 61 } 62 63 $stream->expect(Twig_Token::BLOCK_END_TYPE); 64 $body = $this->parser->subparse(array($this, 'decideBlockEnd'), true); 65 $stream->expect(Twig_Token::BLOCK_END_TYPE); 66 67 return new Twig_Node_AutoEscape($value, $body, $lineno, $this->getTag()); 68 } 69 70 public function decideBlockEnd(Twig_Token $token) 71 { 72 return $token->test('endautoescape'); 73 } 74 75 public function getTag() 76 { 77 return 'autoescape'; 78 } 79 }