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()); + } } }