1<?php 2 3/* 4 * This file is part of Twig. 5 * 6 * (c) 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 12namespace Twig\Test; 13 14use PHPUnit\Framework\TestCase; 15use Twig\Compiler; 16use Twig\Environment; 17use Twig\Loader\ArrayLoader; 18use Twig\Node\Node; 19 20abstract class NodeTestCase extends TestCase 21{ 22 abstract public function getTests(); 23 24 /** 25 * @dataProvider getTests 26 */ 27 public function testCompile($node, $source, $environment = null, $isPattern = false) 28 { 29 $this->assertNodeCompilation($source, $node, $environment, $isPattern); 30 } 31 32 public function assertNodeCompilation($source, Node $node, Environment $environment = null, $isPattern = false) 33 { 34 $compiler = $this->getCompiler($environment); 35 $compiler->compile($node); 36 37 if ($isPattern) { 38 $this->assertStringMatchesFormat($source, trim($compiler->getSource())); 39 } else { 40 $this->assertEquals($source, trim($compiler->getSource())); 41 } 42 } 43 44 protected function getCompiler(Environment $environment = null) 45 { 46 return new Compiler(null === $environment ? $this->getEnvironment() : $environment); 47 } 48 49 protected function getEnvironment() 50 { 51 return new Environment(new ArrayLoader([])); 52 } 53 54 protected function getVariableGetter($name, $line = false) 55 { 56 $line = $line > 0 ? "// line {$line}\n" : ''; 57 58 if (\PHP_VERSION_ID >= 70000) { 59 return sprintf('%s($context["%s"] ?? null)', $line, $name, $name); 60 } 61 62 if (\PHP_VERSION_ID >= 50400) { 63 return sprintf('%s(isset($context["%s"]) ? $context["%s"] : null)', $line, $name, $name); 64 } 65 66 return sprintf('%s$this->getContext($context, "%s")', $line, $name); 67 } 68 69 protected function getAttributeGetter() 70 { 71 if (\function_exists('twig_template_get_attributes')) { 72 return 'twig_template_get_attributes($this, '; 73 } 74 75 return '$this->getAttribute('; 76 } 77} 78 79class_alias('Twig\Test\NodeTestCase', 'Twig_Test_NodeTestCase'); 80