1: <?php declare(strict_types=1);
2:
3: namespace PhpParser\Builder;
4:
5: use PhpParser;
6: use PhpParser\BuilderHelpers;
7: use PhpParser\Node;
8: use PhpParser\Node\Identifier;
9: use PhpParser\Node\Name;
10: use PhpParser\Node\Stmt;
11:
12: class Enum_ extends Declaration
13: {
14: protected $name;
15: protected $scalarType = null;
16:
17: protected $implements = [];
18:
19: protected $uses = [];
20: protected $enumCases = [];
21: protected $constants = [];
22: protected $methods = [];
23:
24: /** @var Node\AttributeGroup[] */
25: protected $attributeGroups = [];
26:
27: /**
28: * Creates an enum builder.
29: *
30: * @param string $name Name of the enum
31: */
32: public function __construct(string $name) {
33: $this->name = $name;
34: }
35:
36: /**
37: * Sets the scalar type.
38: *
39: * @param string|Identifier $type
40: *
41: * @return $this
42: */
43: public function setScalarType($scalarType) {
44: $this->scalarType = BuilderHelpers::normalizeType($scalarType);
45:
46: return $this;
47: }
48:
49: /**
50: * Implements one or more interfaces.
51: *
52: * @param Name|string ...$interfaces Names of interfaces to implement
53: *
54: * @return $this The builder instance (for fluid interface)
55: */
56: public function implement(...$interfaces) {
57: foreach ($interfaces as $interface) {
58: $this->implements[] = BuilderHelpers::normalizeName($interface);
59: }
60:
61: return $this;
62: }
63:
64: /**
65: * Adds a statement.
66: *
67: * @param Stmt|PhpParser\Builder $stmt The statement to add
68: *
69: * @return $this The builder instance (for fluid interface)
70: */
71: public function addStmt($stmt) {
72: $stmt = BuilderHelpers::normalizeNode($stmt);
73:
74: $targets = [
75: Stmt\TraitUse::class => &$this->uses,
76: Stmt\EnumCase::class => &$this->enumCases,
77: Stmt\ClassConst::class => &$this->constants,
78: Stmt\ClassMethod::class => &$this->methods,
79: ];
80:
81: $class = \get_class($stmt);
82: if (!isset($targets[$class])) {
83: throw new \LogicException(sprintf('Unexpected node of type "%s"', $stmt->getType()));
84: }
85:
86: $targets[$class][] = $stmt;
87:
88: return $this;
89: }
90:
91: /**
92: * Adds an attribute group.
93: *
94: * @param Node\Attribute|Node\AttributeGroup $attribute
95: *
96: * @return $this The builder instance (for fluid interface)
97: */
98: public function addAttribute($attribute) {
99: $this->attributeGroups[] = BuilderHelpers::normalizeAttribute($attribute);
100:
101: return $this;
102: }
103:
104: /**
105: * Returns the built class node.
106: *
107: * @return Stmt\Enum_ The built enum node
108: */
109: public function getNode() : PhpParser\Node {
110: return new Stmt\Enum_($this->name, [
111: 'scalarType' => $this->scalarType,
112: 'implements' => $this->implements,
113: 'stmts' => array_merge($this->uses, $this->enumCases, $this->constants, $this->methods),
114: 'attrGroups' => $this->attributeGroups,
115: ], $this->attributes);
116: }
117: }
118: