From a3eb1bc4577c9ca64e2a8677b8a910512fe6c428 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kuba=20Wer=C5=82os?= Date: Sat, 28 Jun 2025 13:05:38 +0200 Subject: [PATCH] `PromotedConstructorPropertyFixer` - do not promote when type of property is not nullable and type of parameter is nullable --- README.md | 2 +- src/Fixer/PromotedConstructorPropertyFixer.php | 11 +++++++++-- .../Fixer/PromotedConstructorPropertyFixerTest.php | 14 ++++++++++++-- 3 files changed, 22 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 937bce4b..639752a9 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ [![Latest stable version](https://img.shields.io/packagist/v/kubawerlos/php-cs-fixer-custom-fixers.svg?label=current%20version)](https://packagist.org/packages/kubawerlos/php-cs-fixer-custom-fixers) [![PHP version](https://img.shields.io/packagist/php-v/kubawerlos/php-cs-fixer-custom-fixers.svg)](https://php.net) [![License](https://img.shields.io/github/license/kubawerlos/php-cs-fixer-custom-fixers.svg)](LICENSE) -![Tests](https://img.shields.io/badge/tests-3795-brightgreen.svg) +![Tests](https://img.shields.io/badge/tests-3796-brightgreen.svg) [![Downloads](https://img.shields.io/packagist/dt/kubawerlos/php-cs-fixer-custom-fixers.svg)](https://packagist.org/packages/kubawerlos/php-cs-fixer-custom-fixers) [![CI status](https://github.com/kubawerlos/php-cs-fixer-custom-fixers/actions/workflows/ci.yaml/badge.svg)](https://github.com/kubawerlos/php-cs-fixer-custom-fixers/actions/workflows/ci.yaml) diff --git a/src/Fixer/PromotedConstructorPropertyFixer.php b/src/Fixer/PromotedConstructorPropertyFixer.php index 140f8f1b..2198edc4 100644 --- a/src/Fixer/PromotedConstructorPropertyFixer.php +++ b/src/Fixer/PromotedConstructorPropertyFixer.php @@ -275,11 +275,18 @@ private function typesAllowPromoting(string $propertyType, string $parameterType return true; } - if (\substr($propertyType, 0, 1) === '?') { + $isPropertyNullable = \substr($propertyType, 0, 1) === '?'; + $isParameterNullable = \substr($parameterType, 0, 1) === '?'; + + if ($isParameterNullable && !$isPropertyNullable) { + return false; + } + + if ($isPropertyNullable) { $propertyType = \substr($propertyType, 1); } - if (\substr($parameterType, 0, 1) === '?') { + if ($isParameterNullable) { $parameterType = \substr($parameterType, 1); } diff --git a/tests/Fixer/PromotedConstructorPropertyFixerTest.php b/tests/Fixer/PromotedConstructorPropertyFixerTest.php index bf2eb390..be55577b 100644 --- a/tests/Fixer/PromotedConstructorPropertyFixerTest.php +++ b/tests/Fixer/PromotedConstructorPropertyFixerTest.php @@ -100,6 +100,16 @@ public function __construct(string $x) { ', ]; + yield 'do not promote when type of property is not nullable and type of parameter is nullable' => [ + 'x = $x; + } + } + ', + ]; + yield 'do not promote when not simple assignment' => [ ' [ 'x = $x; $this->y = $y; - $this->z = $z; } } ',