Chris@13
|
1 <?php
|
Chris@13
|
2
|
Chris@13
|
3 /*
|
Chris@13
|
4 * This file is part of Psy Shell.
|
Chris@13
|
5 *
|
Chris@13
|
6 * (c) 2012-2018 Justin Hileman
|
Chris@13
|
7 *
|
Chris@13
|
8 * For the full copyright and license information, please view the LICENSE
|
Chris@13
|
9 * file that was distributed with this source code.
|
Chris@13
|
10 */
|
Chris@13
|
11
|
Chris@13
|
12 namespace Psy\CodeCleaner;
|
Chris@13
|
13
|
Chris@13
|
14 use PhpParser\Node;
|
Chris@13
|
15 use PhpParser\Node\Name;
|
Chris@13
|
16 use PhpParser\Node\Name\FullyQualified as FullyQualifiedName;
|
Chris@13
|
17 use PhpParser\Node\Stmt\Namespace_;
|
Chris@13
|
18
|
Chris@13
|
19 /**
|
Chris@13
|
20 * Abstract namespace-aware code cleaner pass.
|
Chris@13
|
21 */
|
Chris@13
|
22 abstract class NamespaceAwarePass extends CodeCleanerPass
|
Chris@13
|
23 {
|
Chris@13
|
24 protected $namespace;
|
Chris@13
|
25 protected $currentScope;
|
Chris@13
|
26
|
Chris@13
|
27 /**
|
Chris@13
|
28 * @todo should this be final? Extending classes should be sure to either
|
Chris@13
|
29 * use afterTraverse or call parent::beforeTraverse() when overloading.
|
Chris@13
|
30 *
|
Chris@13
|
31 * Reset the namespace and the current scope before beginning analysis
|
Chris@13
|
32 */
|
Chris@13
|
33 public function beforeTraverse(array $nodes)
|
Chris@13
|
34 {
|
Chris@13
|
35 $this->namespace = [];
|
Chris@13
|
36 $this->currentScope = [];
|
Chris@13
|
37 }
|
Chris@13
|
38
|
Chris@13
|
39 /**
|
Chris@13
|
40 * @todo should this be final? Extending classes should be sure to either use
|
Chris@13
|
41 * leaveNode or call parent::enterNode() when overloading
|
Chris@13
|
42 *
|
Chris@13
|
43 * @param Node $node
|
Chris@13
|
44 */
|
Chris@13
|
45 public function enterNode(Node $node)
|
Chris@13
|
46 {
|
Chris@13
|
47 if ($node instanceof Namespace_) {
|
Chris@13
|
48 $this->namespace = isset($node->name) ? $node->name->parts : [];
|
Chris@13
|
49 }
|
Chris@13
|
50 }
|
Chris@13
|
51
|
Chris@13
|
52 /**
|
Chris@13
|
53 * Get a fully-qualified name (class, function, interface, etc).
|
Chris@13
|
54 *
|
Chris@13
|
55 * @param mixed $name
|
Chris@13
|
56 *
|
Chris@13
|
57 * @return string
|
Chris@13
|
58 */
|
Chris@13
|
59 protected function getFullyQualifiedName($name)
|
Chris@13
|
60 {
|
Chris@13
|
61 if ($name instanceof FullyQualifiedName) {
|
Chris@17
|
62 return \implode('\\', $name->parts);
|
Chris@13
|
63 } elseif ($name instanceof Name) {
|
Chris@13
|
64 $name = $name->parts;
|
Chris@17
|
65 } elseif (!\is_array($name)) {
|
Chris@13
|
66 $name = [$name];
|
Chris@13
|
67 }
|
Chris@13
|
68
|
Chris@17
|
69 return \implode('\\', \array_merge($this->namespace, $name));
|
Chris@13
|
70 }
|
Chris@13
|
71 }
|