Trait_.php 2.0 KB

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