Menu
Custom Deprecations
Available in PHPStan 2.1.12
PHPStan allows you adjust behaviour of reflection methods ->isDeprecated() and ->getDeprecationDescription() to return custom deprecation information based on e.g. custom PHP attributes.
This is useful when you want to mark a class, method, constant or property as deprecated in a way that PHPStan can understand.
There are several interfaces you can implement to achieve this:
PHPStan\Reflection\Deprecation\ClassConstantDeprecationExtensionPHPStan\Reflection\Deprecation\ClassDeprecationExtensionPHPStan\Reflection\Deprecation\ConstantDeprecationExtensionPHPStan\Reflection\Deprecation\EnumCaseDeprecationExtensionPHPStan\Reflection\Deprecation\FunctionDeprecationExtensionPHPStan\Reflection\Deprecation\MethodDeprecationExtensionPHPStan\Reflection\Deprecation\PropertyDeprecationExtension
For example, if you want to mark a class as deprecated using the #[MyDeprecated] attribute, you can implement the ClassDeprecationExtension interface like this:
namespace App;
use App\MyDeprecated;
use PHPStan\Reflection\Deprecation\Deprecation;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionClass;
use PHPStan\BetterReflection\Reflection\Adapter\ReflectionEnum;
use PHPStan\Reflection\Deprecation\ClassDeprecationExtension;
class CustomDeprecationExtension implements ClassDeprecationExtension
{
/**
* @param ReflectionClass|ReflectionEnum $reflection
*/
public function getClassDeprecation($reflection): ?Deprecation
{
foreach ($reflection->getAttributes(MyDeprecated::class) as $attribute) {
$description = $attribute->getArguments()[0] ?? $attribute->getArguments()['description'] ?? null;
return $description === null
? Deprecation::create()
: Deprecation::createWithDescription($description);
}
return null;
}
}
The implementation needs to be registered in your configuration file:
services:
-
class: App\CustomDeprecationExtension
tags:
- phpstan.classDeprecationExtension