Defined.php 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2011 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. * Checks if a variable is defined in the current context.
  12. *
  13. * <pre>
  14. * {# defined works with variable names and variable attributes #}
  15. * {% if foo is defined %}
  16. * {# ... #}
  17. * {% endif %}
  18. * </pre>
  19. *
  20. * @package twig
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. */
  23. class Twig_Node_Expression_Test_Defined extends Twig_Node_Expression_Test
  24. {
  25. public function __construct(Twig_NodeInterface $node, $name, Twig_NodeInterface $arguments = null, $lineno)
  26. {
  27. parent::__construct($node, $name, $arguments, $lineno);
  28. if ($node instanceof Twig_Node_Expression_Name) {
  29. $node->setAttribute('is_defined_test', true);
  30. } elseif ($node instanceof Twig_Node_Expression_GetAttr) {
  31. $node->setAttribute('is_defined_test', true);
  32. $this->changeIgnoreStrictCheck($node);
  33. } else {
  34. throw new Twig_Error_Syntax('The "defined" test only works with simple variables', $this->getLine());
  35. }
  36. }
  37. protected function changeIgnoreStrictCheck(Twig_Node_Expression_GetAttr $node)
  38. {
  39. $node->setAttribute('ignore_strict_check', true);
  40. if ($node->getNode('node') instanceof Twig_Node_Expression_GetAttr) {
  41. $this->changeIgnoreStrictCheck($node->getNode('node'));
  42. }
  43. }
  44. public function compile(Twig_Compiler $compiler)
  45. {
  46. $compiler->subcompile($this->getNode('node'));
  47. }
  48. }