Interface_.php 2.6 KB

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