1<?php declare(strict_types=1);
2
3namespace PhpParser;
4
5use PhpParser\Node\ComplexType;
6use PhpParser\Node\Expr;
7use PhpParser\Node\Identifier;
8use PhpParser\Node\Name;
9use PhpParser\Node\NullableType;
10use PhpParser\Node\Scalar;
11use PhpParser\Node\Stmt;
12
13/**
14 * This class defines helpers used in the implementation of builders. Don't use it directly.
15 *
16 * @internal
17 */
18final class BuilderHelpers {
19    /**
20     * Normalizes a node: Converts builder objects to nodes.
21     *
22     * @param Node|Builder $node The node to normalize
23     *
24     * @return Node The normalized node
25     */
26    public static function normalizeNode($node): Node {
27        if ($node instanceof Builder) {
28            return $node->getNode();
29        }
30
31        if ($node instanceof Node) {
32            return $node;
33        }
34
35        throw new \LogicException('Expected node or builder object');
36    }
37
38    /**
39     * Normalizes a node to a statement.
40     *
41     * Expressions are wrapped in a Stmt\Expression node.
42     *
43     * @param Node|Builder $node The node to normalize
44     *
45     * @return Stmt The normalized statement node
46     */
47    public static function normalizeStmt($node): Stmt {
48        $node = self::normalizeNode($node);
49        if ($node instanceof Stmt) {
50            return $node;
51        }
52
53        if ($node instanceof Expr) {
54            return new Stmt\Expression($node);
55        }
56
57        throw new \LogicException('Expected statement or expression node');
58    }
59
60    /**
61     * Normalizes strings to Identifier.
62     *
63     * @param string|Identifier $name The identifier to normalize
64     *
65     * @return Identifier The normalized identifier
66     */
67    public static function normalizeIdentifier($name): Identifier {
68        if ($name instanceof Identifier) {
69            return $name;
70        }
71
72        if (\is_string($name)) {
73            return new Identifier($name);
74        }
75
76        throw new \LogicException('Expected string or instance of Node\Identifier');
77    }
78
79    /**
80     * Normalizes strings to Identifier, also allowing expressions.
81     *
82     * @param string|Identifier|Expr $name The identifier to normalize
83     *
84     * @return Identifier|Expr The normalized identifier or expression
85     */
86    public static function normalizeIdentifierOrExpr($name) {
87        if ($name instanceof Identifier || $name instanceof Expr) {
88            return $name;
89        }
90
91        if (\is_string($name)) {
92            return new Identifier($name);
93        }
94
95        throw new \LogicException('Expected string or instance of Node\Identifier or Node\Expr');
96    }
97
98    /**
99     * Normalizes a name: Converts string names to Name nodes.
100     *
101     * @param Name|string $name The name to normalize
102     *
103     * @return Name The normalized name
104     */
105    public static function normalizeName($name): Name {
106        if ($name instanceof Name) {
107            return $name;
108        }
109
110        if (is_string($name)) {
111            if (!$name) {
112                throw new \LogicException('Name cannot be empty');
113            }
114
115            if ($name[0] === '\\') {
116                return new Name\FullyQualified(substr($name, 1));
117            }
118
119            if (0 === strpos($name, 'namespace\\')) {
120                return new Name\Relative(substr($name, strlen('namespace\\')));
121            }
122
123            return new Name($name);
124        }
125
126        throw new \LogicException('Name must be a string or an instance of Node\Name');
127    }
128
129    /**
130     * Normalizes a name: Converts string names to Name nodes, while also allowing expressions.
131     *
132     * @param Expr|Name|string $name The name to normalize
133     *
134     * @return Name|Expr The normalized name or expression
135     */
136    public static function normalizeNameOrExpr($name) {
137        if ($name instanceof Expr) {
138            return $name;
139        }
140
141        if (!is_string($name) && !($name instanceof Name)) {
142            throw new \LogicException(
143                'Name must be a string or an instance of Node\Name or Node\Expr'
144            );
145        }
146
147        return self::normalizeName($name);
148    }
149
150    /**
151     * Normalizes a type: Converts plain-text type names into proper AST representation.
152     *
153     * In particular, builtin types become Identifiers, custom types become Names and nullables
154     * are wrapped in NullableType nodes.
155     *
156     * @param string|Name|Identifier|ComplexType $type The type to normalize
157     *
158     * @return Name|Identifier|ComplexType The normalized type
159     */
160    public static function normalizeType($type) {
161        if (!is_string($type)) {
162            if (
163                !$type instanceof Name && !$type instanceof Identifier &&
164                !$type instanceof ComplexType
165            ) {
166                throw new \LogicException(
167                    'Type must be a string, or an instance of Name, Identifier or ComplexType'
168                );
169            }
170            return $type;
171        }
172
173        $nullable = false;
174        if (strlen($type) > 0 && $type[0] === '?') {
175            $nullable = true;
176            $type = substr($type, 1);
177        }
178
179        $builtinTypes = [
180            'array',
181            'callable',
182            'bool',
183            'int',
184            'float',
185            'string',
186            'iterable',
187            'void',
188            'object',
189            'null',
190            'false',
191            'mixed',
192            'never',
193            'true',
194        ];
195
196        $lowerType = strtolower($type);
197        if (in_array($lowerType, $builtinTypes)) {
198            $type = new Identifier($lowerType);
199        } else {
200            $type = self::normalizeName($type);
201        }
202
203        $notNullableTypes = [
204            'void', 'mixed', 'never',
205        ];
206        if ($nullable && in_array((string) $type, $notNullableTypes)) {
207            throw new \LogicException(sprintf('%s type cannot be nullable', $type));
208        }
209
210        return $nullable ? new NullableType($type) : $type;
211    }
212
213    /**
214     * Normalizes a value: Converts nulls, booleans, integers,
215     * floats, strings and arrays into their respective nodes
216     *
217     * @param Node\Expr|bool|null|int|float|string|array $value The value to normalize
218     *
219     * @return Expr The normalized value
220     */
221    public static function normalizeValue($value): Expr {
222        if ($value instanceof Node\Expr) {
223            return $value;
224        }
225
226        if (is_null($value)) {
227            return new Expr\ConstFetch(
228                new Name('null')
229            );
230        }
231
232        if (is_bool($value)) {
233            return new Expr\ConstFetch(
234                new Name($value ? 'true' : 'false')
235            );
236        }
237
238        if (is_int($value)) {
239            return new Scalar\Int_($value);
240        }
241
242        if (is_float($value)) {
243            return new Scalar\Float_($value);
244        }
245
246        if (is_string($value)) {
247            return new Scalar\String_($value);
248        }
249
250        if (is_array($value)) {
251            $items = [];
252            $lastKey = -1;
253            foreach ($value as $itemKey => $itemValue) {
254                // for consecutive, numeric keys don't generate keys
255                if (null !== $lastKey && ++$lastKey === $itemKey) {
256                    $items[] = new Node\ArrayItem(
257                        self::normalizeValue($itemValue)
258                    );
259                } else {
260                    $lastKey = null;
261                    $items[] = new Node\ArrayItem(
262                        self::normalizeValue($itemValue),
263                        self::normalizeValue($itemKey)
264                    );
265                }
266            }
267
268            return new Expr\Array_($items);
269        }
270
271        throw new \LogicException('Invalid value');
272    }
273
274    /**
275     * Normalizes a doc comment: Converts plain strings to PhpParser\Comment\Doc.
276     *
277     * @param Comment\Doc|string $docComment The doc comment to normalize
278     *
279     * @return Comment\Doc The normalized doc comment
280     */
281    public static function normalizeDocComment($docComment): Comment\Doc {
282        if ($docComment instanceof Comment\Doc) {
283            return $docComment;
284        }
285
286        if (is_string($docComment)) {
287            return new Comment\Doc($docComment);
288        }
289
290        throw new \LogicException('Doc comment must be a string or an instance of PhpParser\Comment\Doc');
291    }
292
293    /**
294     * Normalizes a attribute: Converts attribute to the Attribute Group if needed.
295     *
296     * @param Node\Attribute|Node\AttributeGroup $attribute
297     *
298     * @return Node\AttributeGroup The Attribute Group
299     */
300    public static function normalizeAttribute($attribute): Node\AttributeGroup {
301        if ($attribute instanceof Node\AttributeGroup) {
302            return $attribute;
303        }
304
305        if (!($attribute instanceof Node\Attribute)) {
306            throw new \LogicException('Attribute must be an instance of PhpParser\Node\Attribute or PhpParser\Node\AttributeGroup');
307        }
308
309        return new Node\AttributeGroup([$attribute]);
310    }
311
312    /**
313     * Adds a modifier and returns new modifier bitmask.
314     *
315     * @param int $modifiers Existing modifiers
316     * @param int $modifier Modifier to set
317     *
318     * @return int New modifiers
319     */
320    public static function addModifier(int $modifiers, int $modifier): int {
321        Modifiers::verifyModifier($modifiers, $modifier);
322        return $modifiers | $modifier;
323    }
324
325    /**
326     * Adds a modifier and returns new modifier bitmask.
327     * @return int New modifiers
328     */
329    public static function addClassModifier(int $existingModifiers, int $modifierToSet): int {
330        Modifiers::verifyClassModifier($existingModifiers, $modifierToSet);
331        return $existingModifiers | $modifierToSet;
332    }
333}
334