TransNodeTest.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Bridge\Twig\Tests\Node;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Bridge\Twig\Node\TransNode;
  13. use Twig\Compiler;
  14. use Twig\Environment;
  15. use Twig\Node\Expression\NameExpression;
  16. use Twig\Node\TextNode;
  17. /**
  18. * @author Asmir Mustafic <goetas@gmail.com>
  19. */
  20. class TransNodeTest extends TestCase
  21. {
  22. public function testCompileStrict()
  23. {
  24. $body = new TextNode('trans %var%', 0);
  25. $vars = new NameExpression('foo', 0);
  26. $node = new TransNode($body, null, null, $vars);
  27. $env = new Environment($this->getMockBuilder('Twig\Loader\LoaderInterface')->getMock(), array('strict_variables' => true));
  28. $compiler = new Compiler($env);
  29. $this->assertEquals(
  30. sprintf(
  31. 'echo $this->env->getExtension(\'Symfony\Bridge\Twig\Extension\TranslationExtension\')->getTranslator()->trans("trans %%var%%", array_merge(array("%%var%%" => %s), %s), "messages");',
  32. $this->getVariableGetterWithoutStrictCheck('var'),
  33. $this->getVariableGetterWithStrictCheck('foo')
  34. ),
  35. trim($compiler->compile($node)->getSource())
  36. );
  37. }
  38. protected function getVariableGetterWithoutStrictCheck($name)
  39. {
  40. if (\PHP_VERSION_ID >= 70000) {
  41. return sprintf('($context["%s"] ?? null)', $name, $name);
  42. }
  43. return sprintf('(isset($context["%s"]) ? $context["%s"] : null)', $name, $name);
  44. }
  45. protected function getVariableGetterWithStrictCheck($name)
  46. {
  47. if (Environment::MAJOR_VERSION >= 2) {
  48. return sprintf('(isset($context["%s"]) || array_key_exists("%s", $context) ? $context["%s"] : (function () { throw new Twig_Error_Runtime(\'Variable "%s" does not exist.\', 0, $this->getSourceContext()); })())', $name, $name, $name, $name);
  49. }
  50. if (\PHP_VERSION_ID >= 70000) {
  51. return sprintf('($context["%s"] ?? $this->getContext($context, "%s"))', $name, $name, $name);
  52. }
  53. return sprintf('(isset($context["%s"]) ? $context["%s"] : $this->getContext($context, "%s"))', $name, $name, $name);
  54. }
  55. }