phpstan-src icon indicating copy to clipboard operation
phpstan-src copied to clipboard

Add always used method extension

Open axlon opened this issue 1 year ago • 2 comments

This PR adds a new extension type to PHPStan. This new extension type allows developers to tell PHPStan when a private method is used.

My personal use case: I make use of a library that exposes a trait that dynamically calls methods on my objects, since I have no other uses for these methods I typically make them private. Since there are no direct references to these methods PHPStan reports them as unused.

I used #495 as a blueprint for this PR.

Lastly, one thing I'm somewhat unsure about is the positioning of the extension check within the rule, maybe moving it up or down somewhat could be beneficial to performance.

axlon avatar Feb 20 '24 20:02 axlon

@ondrejmirtes is this something you would consider adding to PHPStan? If something is missing or needs clarification please let me know, happy to look at it!

PS I noticed 2 actions are failing, but I don't know why or if it even related to this PR

axlon avatar Mar 12 '24 16:03 axlon

@axlon Don't worry, I really like this PR, it's well thought-out, I just didn't have much time to look into this thorougly.

ondrejmirtes avatar Mar 13 '24 12:03 ondrejmirtes

Perfect, thank you!

ondrejmirtes avatar Mar 20 '24 21:03 ondrejmirtes

I like the use case, I ran into something similar in the past. But I was wondering: Wouldn't an annotation be more suitable for this job rather than a plugin type?


/**
 * @phpstan-always-used
 */
private function my_method(): void {
}

thg2k avatar Mar 21 '24 09:03 thg2k

Wouldn't an annotation be more suitable for this job

You can write an annotation - an ignore annotation :)

The thing with extensions is that you can describe the logic generally. Instead of adding thousands of annotations in your code, you can write a single extension that describes the logic to mark the right methods as always used.

ondrejmirtes avatar Mar 21 '24 09:03 ondrejmirtes

You can write an annotation - an ignore annotation :)

That's surely a solution, but it would ignore every possible error, not only the intended one. I think I solved with a ignoreErrors template in the config file, like a regexp ignoring all kind of private unused errors, targeting the specific directory where the problematic classes reside.

The thing with extensions is that you can describe the logic generally. Instead of adding thousands of annotations in your code, you can write a single extension that describes the logic to mark the right methods as always used.

That's very true.

Thx!

thg2k avatar Mar 21 '24 09:03 thg2k

but it would ignore every possible error, not only the intended one

This is going to be solved in PHPStan 1.11 with error identifiers and new @phpstan-ignore tag. See: https://phpstan.org/user-guide/ignoring-errors#ignoring-in-code-using-phpdocs

ondrejmirtes avatar Mar 21 '24 09:03 ondrejmirtes