Interface_.php 2.4 KB

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