xref: /PHP-Parser/lib/PhpParser/Builder/Use_.php (revision ab51e9d3)
1<?php declare(strict_types=1);
2
3namespace PhpParser\Builder;
4
5use PhpParser\Builder;
6use PhpParser\BuilderHelpers;
7use PhpParser\Node;
8use PhpParser\Node\Stmt;
9
10class Use_ implements Builder {
11    protected Node\Name $name;
12    /** @var Stmt\Use_::TYPE_* */
13    protected int $type;
14    protected ?string $alias = null;
15
16    /**
17     * Creates a name use (alias) builder.
18     *
19     * @param Node\Name|string $name Name of the entity (namespace, class, function, constant) to alias
20     * @param Stmt\Use_::TYPE_* $type One of the Stmt\Use_::TYPE_* constants
21     */
22    public function __construct($name, int $type) {
23        $this->name = BuilderHelpers::normalizeName($name);
24        $this->type = $type;
25    }
26
27    /**
28     * Sets alias for used name.
29     *
30     * @param string $alias Alias to use (last component of full name by default)
31     *
32     * @return $this The builder instance (for fluid interface)
33     */
34    public function as(string $alias) {
35        $this->alias = $alias;
36        return $this;
37    }
38
39    /**
40     * Returns the built node.
41     *
42     * @return Stmt\Use_ The built node
43     */
44    public function getNode(): Node {
45        return new Stmt\Use_([
46            new Node\UseItem($this->name, $this->alias)
47        ], $this->type);
48    }
49}
50