Skip to content

Commit

Permalink
Merge pull request #74 from ajthinking/fix-ast-insert-bug
Browse files Browse the repository at this point in the history
Guard clause so we do not insert on non exist match
  • Loading branch information
ajthinking authored May 25, 2022
2 parents 02e6d44 + b395250 commit 4d84592
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 1 deletion.
4 changes: 3 additions & 1 deletion src/Support/AST/ASTQueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -352,9 +352,11 @@ public function insertStmts($newNodes): self
public function insertStmt($newNode): self
{
$this->currentNodes()->each(function ($node) use ($newNode) {

$target = $node->result;

// Do not insert things on empty results
if(is_array($target) && empty($target)) return;

// Assume insertion targets namespace stmts (if present at index 0)
if (is_array($target) && !empty($target) && get_class($target[0]) == 'PhpParser\\Node\\Stmt\Namespace_') {
$target = $target[0];
Expand Down
21 changes: 21 additions & 0 deletions tests/Unit/Support/AST/ASTQueryBuilderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
use Archetype\Tests\Support\TestableASTQueryBuilder as ASTQueryBuilder;
use PhpParser\BuilderFactory;

use function PHPUnit\Framework\assertEquals;

it('can be instanciated using an ast object', function() {
$ast = LaravelFile::load('public/index.php')->ast();
(new ASTQueryBuilder($ast))->assertInstanceOf(ASTQueryBuilder::class);
Expand Down Expand Up @@ -182,4 +184,23 @@
})
->classMethod('name->name')
->assertMatches(collect(['c', 'b', 'a']));
});

it('does not insert statements when no matches', function() {
$original = PHPFile::load('app/Providers/AppServiceProvider.php')->render();
$after = PHPFile::load('app/Providers/AppServiceProvider.php')
->astQuery()
->classMethod()
->where('blabala', 'xyxy')
->assertMatchCount(0)
->insertStmt(
new \PhpParser\Node\Stmt\Return_(
new \PhpParser\Node\Expr\Variable('this')
)
)
->commit()
->end()
->render();

assertEquals($original, $after);
});

0 comments on commit 4d84592

Please sign in to comment.