Interface_.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php declare(strict_types=1);
  2. namespace PhpParser\Builder;
  3. use PhpParser;
  4. use PhpParser\BuilderHelpers;
  5. use PhpParser\Node\Name;
  6. use PhpParser\Node\Stmt;
  7. class Interface_ extends Declaration
  8. {
  9. protected $name;
  10. protected $extends = [];
  11. protected $constants = [];
  12. protected $methods = [];
  13. /**
  14. * Creates an interface builder.
  15. *
  16. * @param string $name Name of the interface
  17. */
  18. public function __construct(string $name) {
  19. $this->name = $name;
  20. }
  21. /**
  22. * Extends one or more interfaces.
  23. *
  24. * @param Name|string ...$interfaces Names of interfaces to extend
  25. *
  26. * @return $this The builder instance (for fluid interface)
  27. */
  28. public function extend(...$interfaces) {
  29. foreach ($interfaces as $interface) {
  30. $this->extends[] = BuilderHelpers::normalizeName($interface);
  31. }
  32. return $this;
  33. }
  34. /**
  35. * Adds a statement.
  36. *
  37. * @param Stmt|PhpParser\Builder $stmt The statement to add
  38. *
  39. * @return $this The builder instance (for fluid interface)
  40. */
  41. public function addStmt($stmt) {
  42. $stmt = BuilderHelpers::normalizeNode($stmt);
  43. if ($stmt instanceof Stmt\ClassConst) {
  44. $this->constants[] = $stmt;
  45. } elseif ($stmt instanceof Stmt\ClassMethod) {
  46. // we erase all statements in the body of an interface method
  47. $stmt->stmts = null;
  48. $this->methods[] = $stmt;
  49. } else {
  50. throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType()));
  51. }
  52. return $this;
  53. }
  54. /**
  55. * Returns the built interface node.
  56. *
  57. * @return Stmt\Interface_ The built interface node
  58. */
  59. public function getNode() : PhpParser\Node {
  60. return new Stmt\Interface_($this->name, [
  61. 'extends' => $this->extends,
  62. 'stmts' => array_merge($this->constants, $this->methods),
  63. ], $this->attributes);
  64. }
  65. }