Skip to content

String to ::class with leading backslash vs no leading backslash #9595

@joshbmarshall

Description

@joshbmarshall

Bug Report

Subject Details
Rector version v2.1.4

StringClassNameToClassConstantRector is replacing strings with leading backslashes, causing potential string mismatches.

I have a legacy application that stores the user's selection of a class in the database. At some point it was updated to use ::class which does not have leading backslashes, but some data remains with the leading backslash.

So e.g. the code:

if ($var == 'Foo\Bar' || $var == '\Foo\Bar') {}

gets replaced with:

if ($var == \Foo\Bar::class || $var == \Foo\Bar::class) {}

Minimal PHP Code Causing Issue

https://getrector.com/demo/3b6c7c8d-cf8f-464e-90d6-0e2bffe91f78

Expected Behaviour

I expect it not to change the comparison. Options might include leaving it unchanged or to have the leading slash when doing string comparisons?

if ($var == \Foo\Bar::class || $var == '\' . \Foo\Bar::class) {}

It might not just be for string comparisons. What if it was to output to the browser or was used as an api result, where it is actually being used as a string?

Note: I saw #9343 but I believe this is a slightly different issue - that one the outcome was to change the configuration, but I think that would only handle having one or the other but not both?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions