website/src/developing-extensions/always-read-written-properties.md
PHPStan is able to detect unused, never-read and never-written private properties. There might be some cases where PHPStan thinks a property is unused, but the code might actually be correct. For example libraries like Doctrine ORM might take advantage of reflection to write and read private properties which static analysis cannot understand, but fortunately you can write a custom extension to make PHPStan understand what's going on and avoid false-positives.
The implementation is all about applying the core concepts like reflection so check out that guide first and then continue here.
This is the interface your extension needs to implement:
namespace PHPStan\Rules\Properties;
use PHPStan\Reflection\PropertyReflection;
interface ReadWritePropertiesExtension
{
public function isAlwaysRead(PropertyReflection $property, string $propertyName): bool;
public function isAlwaysWritten(PropertyReflection $property, string $propertyName): bool;
public function isInitialized(PropertyReflection $property, string $propertyName): bool;
}
The implementation needs to be registered in your configuration file:
services:
-
class: MyApp\PHPStan\PropertiesExtension
tags:
- phpstan.properties.readWriteExtension
Properties for Doctrine ORM are already covered by the official PHPStan extension. The following logic is applied (see the extension itself):