Test.php 1.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. $name = $this->getAttribute('name');
  19. $testMap = $compiler->getEnvironment()->getTests();
  20. if (!isset($testMap[$name])) {
  21. $message = sprintf('The test "%s" does not exist', $name);
  22. if ($alternatives = $compiler->getEnvironment()->computeAlternatives($name, array_keys($compiler->getEnvironment()->getTests()))) {
  23. $message = sprintf('%s. Did you mean "%s"', $message, implode('", "', $alternatives));
  24. }
  25. throw new Twig_Error_Syntax($message, $this->getLine());
  26. }
  27. $name = $this->getAttribute('name');
  28. $node = $this->getNode('node');
  29. $compiler
  30. ->raw($testMap[$name]->compile().'(')
  31. ->subcompile($node)
  32. ;
  33. if (null !== $this->getNode('arguments')) {
  34. $compiler->raw(', ');
  35. $max = count($this->getNode('arguments')) - 1;
  36. foreach ($this->getNode('arguments') as $i => $arg) {
  37. $compiler->subcompile($arg);
  38. if ($i != $max) {
  39. $compiler->raw(', ');
  40. }
  41. }
  42. }
  43. $compiler->raw(')');
  44. }
  45. }