Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Detect private property which is only ever used to write to itself #14573

@ondrejmirtes

Description

@ondrejmirtes

Feature request

  • We have a private promoted property
  • Which means it's written in the constructor
  • But in the class body is only ever used in new self argument or similar
  • Which means it's both read and written, but actually could be deleted

https://phpstan.org/r/0b433744-9bd4-415c-97dd-bc5cdeb9bf24

Expected output: Property Foo::$test is never read. (or a new message+identifier).

There's ClassPropertiesNode virtual node which contains propertyUsages (reads and writes). This node is used by UnusedPrivatePropertyRule.

We could detect this for private promoted properties (they are assigned in the constructor, no need to inspect contructor body). We could read each PropertyRead and check its Scope. Scope has getFunctionCallStackWithParameters which can be used to read in which call parameter we're currently in.

If the only PropertyReads are when the property is passed to itself as constructor argument of the same class (check declaringClass and concrete parameter of the called constructor), unset these reads, so they're not seen by the final evaluation and the wanted error message is output.

Include more tests with code that are not supposed to be reported (when the property is read by more non-eligible places).

Did PHPStan help you today? Did it make you happy in any way?

No response

Metadata

Metadata

Assignees

No one assigned

    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