1 <?php declare(strict_types=1);
3 namespace PhpParser\Builder;
6 use PhpParser\BuilderHelpers;
8 use PhpParser\Node\Stmt;
10 class Method extends FunctionLike
15 /** @var array|null */
16 protected $stmts = [];
19 * Creates a method builder.
21 * @param string $name Name of the method
23 public function __construct(string $name) {
28 * Makes the method public.
30 * @return $this The builder instance (for fluid interface)
32 public function makePublic() {
33 $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_PUBLIC);
39 * Makes the method protected.
41 * @return $this The builder instance (for fluid interface)
43 public function makeProtected() {
44 $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_PROTECTED);
50 * Makes the method private.
52 * @return $this The builder instance (for fluid interface)
54 public function makePrivate() {
55 $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_PRIVATE);
61 * Makes the method static.
63 * @return $this The builder instance (for fluid interface)
65 public function makeStatic() {
66 $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_STATIC);
72 * Makes the method abstract.
74 * @return $this The builder instance (for fluid interface)
76 public function makeAbstract() {
77 if (!empty($this->stmts)) {
78 throw new \LogicException('Cannot make method with statements abstract');
81 $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_ABSTRACT);
82 $this->stmts = null; // abstract methods don't have statements
88 * Makes the method final.
90 * @return $this The builder instance (for fluid interface)
92 public function makeFinal() {
93 $this->flags = BuilderHelpers::addModifier($this->flags, Stmt\Class_::MODIFIER_FINAL);
101 * @param Node|PhpParser\Builder $stmt The statement to add
103 * @return $this The builder instance (for fluid interface)
105 public function addStmt($stmt) {
106 if (null === $this->stmts) {
107 throw new \LogicException('Cannot add statements to an abstract method');
110 $this->stmts[] = BuilderHelpers::normalizeStmt($stmt);
116 * Returns the built method node.
118 * @return Stmt\ClassMethod The built method node
120 public function getNode() : Node {
121 return new Stmt\ClassMethod($this->name, [
122 'flags' => $this->flags,
123 'byRef' => $this->returnByRef,
124 'params' => $this->params,
125 'returnType' => $this->returnType,
126 'stmts' => $this->stmts,
127 ], $this->attributes);