diff --git a/README.md b/README.md index df48b47..5c3aced 100644 --- a/README.md +++ b/README.md @@ -442,6 +442,7 @@ class Example ### uselessPrivatePropertyNullability: - Detects useless nullability of a private property by checking type of all assignments. +- Works only with natively typehinted properties - Recommended to be used with `uselessPrivatePropertyNullability` and `forbidUselessNullableReturn` as removing useless default value may cause useless nullability to be detected ```php class Example diff --git a/src/Rule/UselessPrivatePropertyNullabilityRule.php b/src/Rule/UselessPrivatePropertyNullabilityRule.php index 1861ed3..d53e5b0 100644 --- a/src/Rule/UselessPrivatePropertyNullabilityRule.php +++ b/src/Rule/UselessPrivatePropertyNullabilityRule.php @@ -83,12 +83,13 @@ public function processNode(Node $node, Scope $scope): array $propertyName = $property->getName(); $defaultValueNode = $property->getDefault(); $propertyReflection = $classReflection->getProperty($propertyName, $scope); + $definitionHasTypehint = $property->getNativeType() !== null; $definitionIsNullable = TypeCombinator::containsNull($propertyReflection->getWritableType()); $nullIsAssigned = $nullabilityNeeded[$propertyName] ?? false; $hasNullDefaultValue = $defaultValueNode instanceof ConstFetch && $scope->resolveName($defaultValueNode->name) === 'null'; $isUninitialized = isset($uninitializedProperties[$propertyName]); - if ($definitionIsNullable && !$nullIsAssigned && !$hasNullDefaultValue && !$isUninitialized) { + if ($definitionHasTypehint && $definitionIsNullable && !$nullIsAssigned && !$hasNullDefaultValue && !$isUninitialized) { $errors[] = RuleErrorBuilder::message("Property {$className}::{$propertyName} is defined as nullable, but null is never assigned")->line($property->getLine())->build(); } } diff --git a/tests/Rule/data/UselessPrivatePropertyNullabilityRule/code.php b/tests/Rule/data/UselessPrivatePropertyNullabilityRule/code.php index a29ae6f..2fa5d91 100644 --- a/tests/Rule/data/UselessPrivatePropertyNullabilityRule/code.php +++ b/tests/Rule/data/UselessPrivatePropertyNullabilityRule/code.php @@ -20,6 +20,9 @@ class ExampleClass private ?int $isUninitialized; + /** @var null|int */ + private $isUninitializedWithoutTypehint; + public function __construct( int $isPublic, int $isProtected,