Trait_.php 2.3 KB

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