Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sniff to flag is_a() and possibly replace with instanceof #260

Open
jrfnl opened this issue Jul 31, 2023 · 0 comments
Open

Sniff to flag is_a() and possibly replace with instanceof #260

jrfnl opened this issue Jul 31, 2023 · 0 comments

Comments

@jrfnl
Copy link
Member

jrfnl commented Jul 31, 2023

Is your feature request related to a problem?

PHP has tried to deprecate the use of is_a() a couple of times already, so it is probably a good idea to have a sniff which can detect and (whenever possible) auto-fix any calls to is_a() with instanceof comparisons.

Additional reasons why this sniff would be a nice idea:

  • Performance: using a PHP native operator will generally be faster than a function call, though it is a micro-optimization.
  • IDE support: IDEs will be able to automatically fix/replace all uses of a class name when a class is renamed when the class name is used like a plain name and will, in most cases, not do so when a class name is in a text string.

Refs:

Describe the solution you'd like

A new sniff in the Modernize standard.

Some example code:

// Bad.
if ( is_a( $var, 'MyClass' ) ) {}
if ( is_a( $var, MyClass::class ) ) {}
if ( is_a( $var, self::class ) ) {}

// Okay.
if ( $var instanceof \MyClass ) {}
if ( $var instanceof MyClass ) {} // If file is non-namespaced and/or there is an import `use` statement for the class.
if ( $var instanceof self ) {}

// Should probably be ignored by this sniff, or only flagged, but not auto-fixed ?
if ( is_a( $var, get_class( $obj ) ) ) {}
if ( is_a( $var, get_parent_class( $obj ) ) ) {}

Additional context (optional)

The sniff will need to take namespace/use statement resolution into account and be wary of creative code in the second parameter of the call to is_a() as it should be careful not to create bugs when auto-fixing.

Also note that since PHP 8.0 $obj::class is supported, so is_a( $var, $obj::class ) should be replaceable by ( $var instanceof $obj ).

Also be wary of the PHP 8.0 change that instanceof can then be used in arbitrary expressions, which means this wasn't allowed before and the auto-fixer should take this into account and be wary of this when auto-fixing.

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

No branches or pull requests

1 participant