Skip to content

StringClassNameToClassConstantRector drops the leading backslash from a fully qualified class name #9343

Description

@pawel-slowik

Bug Report

Subject Details
Rector version 2.1.4

Given the following code:

use App\Foo\Bar;

echo '\App\Foo\Bar' . PHP_EOL;

Rector will transform it into:

use App\Foo\Bar;

echo \App\Foo\Bar::class . PHP_EOL;

I believe this is incorrect, because the ::class constant doesn't include the leading backslash. Therefore this transformation will change the output of the script from \App\Foo\Bar to App\Foo\Bar.

Note that this transformation is consistent with the official PHP documentation, but the documentation is wrong: php/doc-en#2138.

Minimal PHP Code Causing Issue

Minimal reproduction example: https://github.com/pawel-slowik/rector-class-constant-bug.

I can't provide a link to the issue reproduced on https://getrector.com/demo/, because for the issue to manifest itself Rector needs to be configured with an existing path like this:

    ->withPaths(
        [
            __DIR__ . '/src',
        ]
    )

This configuration causes an error in the demo app (but not while running Rector from the CLI).

Expected Behaviour

When replacing a fully qualified class name (i.e. a name starting with a backslash \), Rector should prefix the ::class constant with a backslash like this: '\' . \App\Foo\Bar::class.

Alternatively, it shouldn't attempt to replace these names at all.

Impact

I expect the bug's impact to be limited to certain "weird", rare scenarios. In my case, fully qualified class names are used as WSDL type names when communicating via SOAP with a legacy system. Therefore they can't be easily changed from \SomeVendor\Order to SomeVendor\Order.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions