From 0c11dd904d5caa4a3e889bb54d0b31d1ef314189 Mon Sep 17 00:00:00 2001 From: James Titcumb Date: Tue, 14 Jul 2015 19:26:42 +0100 Subject: [PATCH] Ignore any tokens within classes when looking for namespaces --- src/Types/ContextFactory.php | 20 ++++++++++++++++++++ tests/unit/Types/ContextFactoryTest.php | 20 ++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/src/Types/ContextFactory.php b/src/Types/ContextFactory.php index ffdbb77..3d279c4 100644 --- a/src/Types/ContextFactory.php +++ b/src/Types/ContextFactory.php @@ -70,6 +70,26 @@ public function createForNamespace($namespace, $fileContents) case T_NAMESPACE: $currentNamespace = $this->parseNamespace($tokens); break; + case T_CLASS: + // Fast-forward the iterator through the class so that any + // T_USE tokens found within are skipped - these are not + // valid namespace use statements so should be ignored. + $braceLevel = 0; + $firstBraceFound = false; + while ($tokens->valid() && ($braceLevel > 0 || !$firstBraceFound)) { + if ($tokens->current() === '{') { + if (!$firstBraceFound) { + $firstBraceFound = true; + } + $braceLevel++; + } + + if ($tokens->current() === '}') { + $braceLevel--; + } + $tokens->next(); + } + break; case T_USE: if ($currentNamespace === $namespace) { $useStatements = array_merge($useStatements, $this->parseUseStatement($tokens)); diff --git a/tests/unit/Types/ContextFactoryTest.php b/tests/unit/Types/ContextFactoryTest.php index 3eae452..213d0f7 100644 --- a/tests/unit/Types/ContextFactoryTest.php +++ b/tests/unit/Types/ContextFactoryTest.php @@ -88,6 +88,26 @@ public function testReadsAliasesFromProvidedNamespaceAndContent() $this->assertSame($expected, $context->getNamespaceAliases()); } + + public function testTraitUseIsNotDetectedAsNamespaceUse() + { + $fixture = new ContextFactory(); + + $php = "createForNamespace('Foo', $php); + + $this->assertSame([], $context->getNamespaceAliases()); + } } }