annotate vendor/psy/psysh/src/Psy/CodeCleaner/NamespacePass.php @ 0:4c8ae668cc8c

Initial import (non-working)
author Chris Cannam
date Wed, 29 Nov 2017 16:09:58 +0000
parents
children
rev   line source
Chris@0 1 <?php
Chris@0 2
Chris@0 3 /*
Chris@0 4 * This file is part of Psy Shell.
Chris@0 5 *
Chris@0 6 * (c) 2012-2017 Justin Hileman
Chris@0 7 *
Chris@0 8 * For the full copyright and license information, please view the LICENSE
Chris@0 9 * file that was distributed with this source code.
Chris@0 10 */
Chris@0 11
Chris@0 12 namespace Psy\CodeCleaner;
Chris@0 13
Chris@0 14 use PhpParser\Node\Name;
Chris@0 15 use PhpParser\Node\Stmt\Namespace_;
Chris@0 16 use Psy\CodeCleaner;
Chris@0 17
Chris@0 18 /**
Chris@0 19 * Provide implicit namespaces for subsequent execution.
Chris@0 20 *
Chris@0 21 * The namespace pass remembers the last standalone namespace line encountered:
Chris@0 22 *
Chris@0 23 * namespace Foo\Bar;
Chris@0 24 *
Chris@0 25 * ... which it then applies implicitly to all future evaluated code, until the
Chris@0 26 * namespace is replaced by another namespace. To reset to the top level
Chris@0 27 * namespace, enter `namespace {}`. This is a bit ugly, but it does the trick :)
Chris@0 28 */
Chris@0 29 class NamespacePass extends CodeCleanerPass
Chris@0 30 {
Chris@0 31 private $namespace = null;
Chris@0 32 private $cleaner;
Chris@0 33
Chris@0 34 /**
Chris@0 35 * @param CodeCleaner $cleaner
Chris@0 36 */
Chris@0 37 public function __construct(CodeCleaner $cleaner)
Chris@0 38 {
Chris@0 39 $this->cleaner = $cleaner;
Chris@0 40 }
Chris@0 41
Chris@0 42 /**
Chris@0 43 * If this is a standalone namespace line, remember it for later.
Chris@0 44 *
Chris@0 45 * Otherwise, apply remembered namespaces to the code until a new namespace
Chris@0 46 * is encountered.
Chris@0 47 *
Chris@0 48 * @param array $nodes
Chris@0 49 */
Chris@0 50 public function beforeTraverse(array $nodes)
Chris@0 51 {
Chris@0 52 if (empty($nodes)) {
Chris@0 53 return $nodes;
Chris@0 54 }
Chris@0 55
Chris@0 56 $last = end($nodes);
Chris@0 57 if (!$last instanceof Namespace_) {
Chris@0 58 return $this->namespace ? array(new Namespace_($this->namespace, $nodes)) : $nodes;
Chris@0 59 }
Chris@0 60
Chris@0 61 $this->setNamespace($last->name);
Chris@0 62
Chris@0 63 return $nodes;
Chris@0 64 }
Chris@0 65
Chris@0 66 /**
Chris@0 67 * Remember the namespace and (re)set the namespace on the CodeCleaner as
Chris@0 68 * well.
Chris@0 69 *
Chris@0 70 * @param null|Name $namespace
Chris@0 71 */
Chris@0 72 private function setNamespace($namespace)
Chris@0 73 {
Chris@0 74 $this->namespace = $namespace;
Chris@0 75 $this->cleaner->setNamespace($namespace === null ? null : $namespace->parts);
Chris@0 76 }
Chris@0 77 }