Also add new() builder

This commit is contained in:
Nikita Popov 2018-03-03 22:25:58 +01:00
parent ff2d85dc6b
commit 610617fe93
4 changed files with 33 additions and 0 deletions

View File

@ -12,6 +12,7 @@ Version 4.0.1-dev
* `funcCall()`
* `methodCall()`
* `staticCall()`
* `new()`
* `constFetch()`
* `classConstFetch()`

View File

@ -106,6 +106,8 @@ nodes. The following methods are currently available:
an `Identifier` node and normalizes arguments.
* `staticCall($class, $name, array $args = [])`: Create a static method call node. Converts
`$class` to a `Name` node, `$name` to an `Identifier` node and normalizes arguments.
* `new($class, array $args = [])`: Create a "new" (object creation) node. Converts `$class` to a
`Name` node.
* `constFetch($name)`: Create a constant fetch node. Converts `$name` to a `Name` node.
* `classConstFetch($class, $name)`: Create a class constant fetch node. Converts `$class` to a
`Name` node and `$name` to an `Identifier` node.

View File

@ -8,6 +8,7 @@ use PhpParser\Node\Expr\BinaryOp\Concat;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Use_;
class BuilderFactory
@ -192,6 +193,21 @@ class BuilderFactory
);
}
/**
* Creates an object creation node.
*
* @param string|Name|Expr $class Class name
* @param array $args Constructor arguments
*
* @return Expr\New_
*/
public function new($class, array $args = []) : Expr\New_ {
return new Expr\New_(
BuilderHelpers::normalizeNameOrExpr($class),
$this->args($args)
);
}
/**
* Creates a constant fetch node.
*

View File

@ -156,6 +156,20 @@ class BuilderFactoryTest extends TestCase
),
$factory->staticCall(new Expr\Variable('foo'), new Expr\Variable('bar'))
);
// Simple new call
$this->assertEquals(
new Expr\New_(new Name\FullyQualified('stdClass')),
$factory->new('\stdClass')
);
// Dynamic new call
$this->assertEquals(
new Expr\New_(
new Expr\Variable('foo'),
[new Arg(new String_('bar'))]
),
$factory->new(new Expr\Variable('foo'), ['bar'])
);
}
public function testConstFetches() {