Support adding class constants in trait builder

These are allowed as of PHP 8.2.
This commit is contained in:
Nikita Popov 2022-09-11 19:34:27 +02:00
parent 6af204467c
commit c595989e4d
2 changed files with 10 additions and 4 deletions

View File

@ -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[] */
@ -44,6 +46,8 @@ class Trait_ extends Declaration {
$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()));
}
@ -72,7 +76,7 @@ class Trait_ extends Declaration {
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
);

View File

@ -7,11 +7,11 @@ use PhpParser\Modifiers;
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;
@ -28,8 +28,9 @@ class TraitTest extends \PHPUnit\Framework\TestCase {
$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 */')
@ -37,9 +38,10 @@ class TraitTest extends \PHPUnit\Framework\TestCase {
->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 */')