Skip to content

Commit

Permalink
Support adding class constants in trait builder
Browse files Browse the repository at this point in the history
These are allowed as of PHP 8.2.
  • Loading branch information
nikic committed Sep 11, 2022
1 parent 6af2044 commit c595989
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
6 changes: 5 additions & 1 deletion lib/PhpParser/Builder/Trait_.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ class Trait_ extends Declaration {
protected $name;
/** @var Stmt\TraitUse[] */
protected $uses = [];
/** @var Stmt\ClassConst[] */
protected $constants = [];
/** @var Stmt\Property[] */
protected $properties = [];
/** @var Stmt\ClassMethod[] */
Expand Down Expand Up @@ -44,6 +46,8 @@ public function addStmt($stmt) {
$this->methods[] = $stmt;
} elseif ($stmt instanceof Stmt\TraitUse) {
$this->uses[] = $stmt;
} elseif ($stmt instanceof Stmt\ClassConst) {
$this->constants[] = $stmt;
} else {
throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType()));
}
Expand Down Expand Up @@ -72,7 +76,7 @@ public function addAttribute($attribute) {
public function getNode(): PhpParser\Node {
return new Stmt\Trait_(
$this->name, [
'stmts' => array_merge($this->uses, $this->properties, $this->methods),
'stmts' => array_merge($this->uses, $this->constants, $this->properties, $this->methods),
'attrGroups' => $this->attributeGroups,
], $this->attributes
);
Expand Down
8 changes: 5 additions & 3 deletions test/PhpParser/Builder/TraitTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,11 @@
use PhpParser\Node\Arg;
use PhpParser\Node\Attribute;
use PhpParser\Node\AttributeGroup;
use PhpParser\Node\Const_;
use PhpParser\Node\Identifier;
use PhpParser\Node\Name;
use PhpParser\Node\Scalar\Int_;
use PhpParser\Node\Stmt;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\ClassConst;
use PhpParser\Node\Stmt\ClassMethod;
use PhpParser\Node\Stmt\Property;
Expand All @@ -28,18 +28,20 @@ public function testStmtAddition() {
$method2 = new Stmt\ClassMethod('test2');
$method3 = new Stmt\ClassMethod('test3');
$prop = new Stmt\Property(Modifiers::PUBLIC, [
new \PhpParser\Node\PropertyItem('test')
new PropertyItem('test')
]);
$const = new ClassConst([new Const_('FOO', new Int_(0))]);
$use = new Stmt\TraitUse([new Name('OtherTrait')]);
$trait = $this->createTraitBuilder('TestTrait')
->setDocComment('/** Nice trait */')
->addStmt($method1)
->addStmts([$method2, $method3])
->addStmt($prop)
->addStmt($use)
->addStmt($const)
->getNode();
$this->assertEquals(new Stmt\Trait_('TestTrait', [
'stmts' => [$use, $prop, $method1, $method2, $method3]
'stmts' => [$use, $const, $prop, $method1, $method2, $method3]
], [
'comments' => [
new Comment\Doc('/** Nice trait */')
Expand Down

0 comments on commit c595989

Please sign in to comment.