Skip to content

ContextFactory is not clever enough about use statements #8

Closed
@asgrim

Description

@asgrim

I have a use case where used traits are being incorrectly detected as namespace imports.

Looking at ContextFactory->createForNamespace, it seems that the check is simply looking for all T_USE tokens, and not checking whether they are within the context of a T_CLASS token.

For example, given this PHP code:

<?php
namespace Foo;

trait FooTrait {}

class FooClass {
    use FooTrait;
}

... when creating context for this, the namespace aliases should be simply empty array [] as there ARE no namespace aliases. However, ContextFactory currently picks up the use FooTrait; and thinks it is a namespace alias.

I have provided a failing test case that can be added to tests/unit/Types/ContextFactoryTest.php:

public function testTraitUseIsNotDetectedAsNamespaceUse()
{
    $fixture = new ContextFactory();

    $php = "<?php
    namespace Foo;

    trait FooTrait {}

    class FooClass {
        use FooTrait;
    }
    ";

    $fixture = new ContextFactory();
    $context = $fixture->createForNamespace('Foo', $php);

    $this->assertSame([], $context->getNamespaceAliases());
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions