|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * @see https://github.com/open-code-modeling/php-code-ast for the canonical source repository |
| 5 | + * @copyright https://github.com/open-code-modeling/php-code-ast/blob/master/COPYRIGHT.md |
| 6 | + * @license https://github.com/open-code-modeling/php-code-ast/blob/master/LICENSE.md MIT License |
| 7 | + */ |
| 8 | + |
| 9 | +declare(strict_types=1); |
| 10 | + |
| 11 | +namespace OpenCodeModelingTest\CodeAst\NodeVisitor; |
| 12 | + |
| 13 | +use OpenCodeModeling\CodeAst\NodeVisitor\ClassUseTrait; |
| 14 | +use PhpParser\NodeTraverser; |
| 15 | +use PhpParser\Parser; |
| 16 | +use PhpParser\ParserFactory; |
| 17 | +use PhpParser\PrettyPrinter\Standard; |
| 18 | +use PHPUnit\Framework\TestCase; |
| 19 | + |
| 20 | +final class ClassUseTraitTest extends TestCase |
| 21 | +{ |
| 22 | + /** |
| 23 | + * @var Parser |
| 24 | + */ |
| 25 | + private $parser; |
| 26 | + |
| 27 | + /** |
| 28 | + * @var Standard |
| 29 | + */ |
| 30 | + private $printer; |
| 31 | + |
| 32 | + public function setUp(): void |
| 33 | + { |
| 34 | + $this->parser = (new ParserFactory())->create(ParserFactory::ONLY_PHP7); |
| 35 | + $this->printer = new Standard(['shortArraySyntax' => true]); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * @test |
| 40 | + */ |
| 41 | + public function it_add_namespace_imports_in_correct_order(): void |
| 42 | + { |
| 43 | + $ast = $this->parser->parse($this->classCode()); |
| 44 | + |
| 45 | + $nodeTraverser = new NodeTraverser(); |
| 46 | + $nodeTraverser->addVisitor(new ClassUseTrait('MyService\Foo', 'MyService\Bar')); |
| 47 | + |
| 48 | + $this->assertSame($this->expectedClassCode(), $this->printer->prettyPrintFile($nodeTraverser->traverse($ast))); |
| 49 | + } |
| 50 | + |
| 51 | + private function classCode(): string |
| 52 | + { |
| 53 | + return <<<'EOF' |
| 54 | + <?php |
| 55 | +
|
| 56 | + declare(strict_types=1); |
| 57 | +
|
| 58 | + namespace My\Awesome\Service; |
| 59 | +
|
| 60 | + class TestClass |
| 61 | + { |
| 62 | + use MyService\Foo; |
| 63 | +
|
| 64 | + public function testMethod() |
| 65 | + { |
| 66 | + } |
| 67 | + } |
| 68 | + EOF; |
| 69 | + } |
| 70 | + |
| 71 | + private function expectedClassCode(): string |
| 72 | + { |
| 73 | + return <<<'EOF' |
| 74 | + <?php |
| 75 | +
|
| 76 | + declare (strict_types=1); |
| 77 | + namespace My\Awesome\Service; |
| 78 | +
|
| 79 | + class TestClass |
| 80 | + { |
| 81 | + use MyService\Bar; |
| 82 | + use MyService\Foo; |
| 83 | + public function testMethod() |
| 84 | + { |
| 85 | + } |
| 86 | + } |
| 87 | + EOF; |
| 88 | + } |
| 89 | +} |
0 commit comments