4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\CodeCleaner;
14 use PhpParser\Node\Name;
15 use PhpParser\Node\Stmt\Namespace_;
19 * Provide implicit namespaces for subsequent execution.
21 * The namespace pass remembers the last standalone namespace line encountered:
25 * ... which it then applies implicitly to all future evaluated code, until the
26 * namespace is replaced by another namespace. To reset to the top level
27 * namespace, enter `namespace {}`. This is a bit ugly, but it does the trick :)
29 class NamespacePass extends CodeCleanerPass
31 private $namespace = null;
35 * @param CodeCleaner $cleaner
37 public function __construct(CodeCleaner $cleaner)
39 $this->cleaner = $cleaner;
43 * If this is a standalone namespace line, remember it for later.
45 * Otherwise, apply remembered namespaces to the code until a new namespace
50 public function beforeTraverse(array $nodes)
58 if ($last instanceof Namespace_) {
59 $kind = $last->getAttribute('kind');
61 // Treat all namespace statements pre-PHP-Parser v3.1.2 as "open",
62 // even though we really have no way of knowing.
63 if ($kind === null || $kind === Namespace_::KIND_SEMICOLON) {
64 // Save the current namespace for open namespaces
65 $this->setNamespace($last->name);
67 // Clear the current namespace after a braced namespace
68 $this->setNamespace(null);
74 return $this->namespace ? [new Namespace_($this->namespace, $nodes)] : $nodes;
78 * Remember the namespace and (re)set the namespace on the CodeCleaner as
81 * @param null|Name $namespace
83 private function setNamespace($namespace)
85 $this->namespace = $namespace;
86 $this->cleaner->setNamespace($namespace === null ? null : $namespace->parts);