1<?php declare(strict_types=1); 2 3namespace PhpParser\Builder; 4 5use PhpParser; 6use PhpParser\BuilderHelpers; 7use PhpParser\Node; 8use PhpParser\Node\Stmt; 9 10class Trait_ extends Declaration { 11 protected string $name; 12 /** @var list<Stmt\TraitUse> */ 13 protected array $uses = []; 14 /** @var list<Stmt\ClassConst> */ 15 protected array $constants = []; 16 /** @var list<Stmt\Property> */ 17 protected array $properties = []; 18 /** @var list<Stmt\ClassMethod> */ 19 protected array $methods = []; 20 /** @var list<Node\AttributeGroup> */ 21 protected array $attributeGroups = []; 22 23 /** 24 * Creates an interface builder. 25 * 26 * @param string $name Name of the interface 27 */ 28 public function __construct(string $name) { 29 $this->name = $name; 30 } 31 32 /** 33 * Adds a statement. 34 * 35 * @param Stmt|PhpParser\Builder $stmt The statement to add 36 * 37 * @return $this The builder instance (for fluid interface) 38 */ 39 public function addStmt($stmt) { 40 $stmt = BuilderHelpers::normalizeNode($stmt); 41 42 if ($stmt instanceof Stmt\Property) { 43 $this->properties[] = $stmt; 44 } elseif ($stmt instanceof Stmt\ClassMethod) { 45 $this->methods[] = $stmt; 46 } elseif ($stmt instanceof Stmt\TraitUse) { 47 $this->uses[] = $stmt; 48 } elseif ($stmt instanceof Stmt\ClassConst) { 49 $this->constants[] = $stmt; 50 } else { 51 throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType())); 52 } 53 54 return $this; 55 } 56 57 /** 58 * Adds an attribute group. 59 * 60 * @param Node\Attribute|Node\AttributeGroup $attribute 61 * 62 * @return $this The builder instance (for fluid interface) 63 */ 64 public function addAttribute($attribute) { 65 $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute); 66 67 return $this; 68 } 69 70 /** 71 * Returns the built trait node. 72 * 73 * @return Stmt\Trait_ The built interface node 74 */ 75 public function getNode(): PhpParser\Node { 76 return new Stmt\Trait_( 77 $this->name, [ 78 'stmts' => array_merge($this->uses, $this->constants, $this->properties, $this->methods), 79 'attrGroups' => $this->attributeGroups, 80 ], $this->attributes 81 ); 82 } 83} 84