1: <?php
2: namespace Pharborist\Namespaces;
3:
4: use Pharborist\Constants\ConstantDeclarationNode;
5: use Pharborist\Filter;
6: use Pharborist\Functions\FunctionDeclarationNode;
7: use Pharborist\Node;
8: use Pharborist\Objects\ClassNode;
9: use Pharborist\Objects\InterfaceNode;
10: use Pharborist\Objects\TraitNode;
11: use Pharborist\Parser;
12: use Pharborist\StatementNode;
13: use Pharborist\DocCommentTrait;
14: use Pharborist\StatementBlockNode;
15:
16: /**
17: * A namespace declaration.
18: *
19: * This node is used for both forms of namespace declaration:
20: *
21: * ```
22: * namespace \Foo\Bar;
23: * ```
24: * and
25: * ```
26: * namespace \Foo\Baz {
27: * // Do amazing things here
28: * }
29: * ```
30: *
31: * Everything in the namespace is part of the namespace's body. This is
32: * the case even with the first form of the namespace. A parsed file with
33: * a namespace declaration at the top will have the declaration as one of
34: * its children (alongside any preceding comments and whitespace), and
35: * everything else in the file after the namespace declaration will be
36: * a descendant of that NamespaceNode.
37: *
38: * @see \Pharborist\NameNode
39: */
40: class NamespaceNode extends StatementNode {
41: use DocCommentTrait;
42:
43: /**
44: * Create namespace declaration.
45: *
46: * @param NameNode|string $name
47: * Namespace path.
48: *
49: * @return NamespaceNode
50: */
51: public static function create($name) {
52: $name = (string) $name;
53: $name = ltrim($name, '\\');
54: $namespace_node = Parser::parseSnippet("namespace $name;");
55: return $namespace_node;
56: }
57:
58: /**
59: * @var NameNode
60: */
61: protected $name;
62:
63: /**
64: * @var StatementBlockNode
65: */
66: protected $body;
67:
68: /**
69: * @return NameNode
70: */
71: public function getName() {
72: return $this->name;
73: }
74:
75: /**
76: * @return StatementBlockNode
77: */
78: public function getBody() {
79: return $this->body;
80: }
81:
82: /**
83: * Determine if the node belongs to this namespace.
84: *
85: * @param ClassNode|InterfaceNode|TraitNode|FunctionDeclarationNode|ConstantDeclarationNode $node
86: * Node to test if owned by namespace.
87: *
88: * @return bool
89: */
90: public function owns($node) {
91: return $this === $node->getName()->getNamespace();
92: }
93:
94: /**
95: * Get use declarations.
96: *
97: * @return UseDeclarationNode[]|\Pharborist\NodeCollection
98: * Use declarations.
99: */
100: public function getUseDeclarations() {
101: return $this->body->getUseDeclarations();
102: }
103:
104: /**
105: * Return mapping of class names to fully qualified names.
106: *
107: * @return array
108: * Associative array of namespace alias to fully qualified names.
109: */
110: public function getClassAliases() {
111: return $this->body->getClassAliases();
112: }
113: }
114: