Automatically wrap in Stmt\Expression in builders

This commit is contained in:
Nikita Popov 2017-01-19 22:39:21 +01:00
parent 33552764ad
commit 7623d20f69
6 changed files with 44 additions and 5 deletions

View File

@ -28,7 +28,7 @@ class Function_ extends FunctionLike
* @return $this The builder instance (for fluid interface)
*/
public function addStmt($stmt) {
$this->stmts[] = $this->normalizeNode($stmt);
$this->stmts[] = $this->normalizeStmt($stmt);
return $this;
}

View File

@ -106,7 +106,7 @@ class Method extends FunctionLike
throw new \LogicException('Cannot add statements to an abstract method');
}
$this->stmts[] = $this->normalizeNode($stmt);
$this->stmts[] = $this->normalizeStmt($stmt);
return $this;
}

View File

@ -28,7 +28,7 @@ class Namespace_ extends PhpParser\BuilderAbstract
* @return $this The builder instance (for fluid interface)
*/
public function addStmt($stmt) {
$this->stmts[] = $this->normalizeNode($stmt);
$this->stmts[] = $this->normalizeStmt($stmt);
return $this;
}

View File

@ -27,6 +27,28 @@ abstract class BuilderAbstract implements Builder {
throw new \LogicException('Expected node or builder object');
}
/**
* Normalizes a node to a statement.
*
* Expressions are wrapped in a Stmt\Expression node.
*
* @param Node|Builder $node The node to normalize
*
* @return Stmt The normalized statement node
*/
protected function normalizeStmt($node) {
$node = $this->normalizeNode($node);
if ($node instanceof Stmt) {
return $node;
}
if ($node instanceof Expr) {
return new Stmt\Expression($node);
}
throw new \LogicException('Expected statement or expression node');
}
/**
* Normalizes a name: Converts plain string names to PhpParser\Node\Name.
*

View File

@ -60,7 +60,11 @@ class FunctionTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(
new Stmt\Function_('test', array(
'stmts' => array($stmt1, $stmt2, $stmt3)
'stmts' => array(
new Stmt\Expression($stmt1),
new Stmt\Expression($stmt2),
new Stmt\Expression($stmt3),
)
)),
$node
);
@ -103,4 +107,13 @@ class FunctionTest extends \PHPUnit_Framework_TestCase
->addParam(new Node\Name('foo'))
;
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage Expected statement or expression node
*/
public function testAddNonStmt() {
$this->createFunctionBuilder('test')
->addStmt(new Node\Name('Test'));
}
}

View File

@ -105,7 +105,11 @@ class MethodTest extends \PHPUnit_Framework_TestCase
$this->assertEquals(
new Stmt\ClassMethod('test', array(
'stmts' => array($stmt1, $stmt2, $stmt3)
'stmts' => array(
new Stmt\Expression($stmt1),
new Stmt\Expression($stmt2),
new Stmt\Expression($stmt3),
)
)),
$node
);