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        return sprintf('%s($context["%s"] ?? null)', $line, $name);
59    }
60
61    protected function getAttributeGetter()
62    {
63        return 'twig_get_attribute($this->env, $this->source, ';
64    }
65}
66
67class_alias('Twig\Test\NodeTestCase', 'Twig_Test_NodeTestCase');
68