Test.php 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. /*
  3. * This file is part of Twig.
  4. *
  5. * (c) 2010 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. class Twig_Node_Expression_Test extends Twig_Node_Expression
  11. {
  12. public function __construct(Twig_NodeInterface $node, $name, Twig_NodeInterface $arguments = null, $lineno)
  13. {
  14. parent::__construct(array('node' => $node, 'arguments' => $arguments), array('name' => $name), $lineno);
  15. }
  16. public function compile(Twig_Compiler $compiler)
  17. {
  18. $testMap = $compiler->getEnvironment()->getTests();
  19. if (!isset($testMap[$this->getAttribute('name')])) {
  20. throw new Twig_Error_Syntax(sprintf('The test "%s" does not exist', $this->getAttribute('name')), $this->getLine());
  21. }
  22. $name = $this->getAttribute('name');
  23. $node = $this->getNode('node');
  24. // defined is a special case
  25. if ('defined' === $name) {
  26. if ($node instanceof Twig_Node_Expression_Name || $node instanceof Twig_Node_Expression_GetAttr) {
  27. $node->setAttribute('is_defined_test', true);
  28. $compiler->subcompile($node);
  29. $node->removeAttribute('is_defined_test');
  30. } else {
  31. throw new Twig_Error_Syntax('The "defined" test only works with simple variables', $this->getLine());
  32. }
  33. return;
  34. }
  35. $compiler
  36. ->raw($testMap[$name]->compile().'(')
  37. ->subcompile($node)
  38. ;
  39. if (null !== $this->getNode('arguments')) {
  40. $compiler->raw(', ');
  41. $max = count($this->getNode('arguments')) - 1;
  42. foreach ($this->getNode('arguments') as $i => $arg) {
  43. $compiler->subcompile($arg);
  44. if ($i != $max) {
  45. $compiler->raw(', ');
  46. }
  47. }
  48. }
  49. $compiler->raw(')');
  50. }
  51. }