Skip to content

Commit 5a78b78

Browse files
committed
RequireConstructorPropertyPromotionSniff: Fixed false positive
1 parent 6783711 commit 5a78b78

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

SlevomatCodingStandard/Sniffs/Classes/RequireConstructorPropertyPromotionSniff.php

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
use SlevomatCodingStandard\Helpers\SniffSettingsHelper;
1414
use SlevomatCodingStandard\Helpers\TokenHelper;
1515
use function array_filter;
16+
use function array_reverse;
1617
use function count;
1718
use function in_array;
1819
use function sprintf;
@@ -23,11 +24,15 @@
2324
use const T_CALLABLE;
2425
use const T_COMMA;
2526
use const T_ELLIPSIS;
27+
use const T_ELSE;
28+
use const T_ELSEIF;
2629
use const T_EQUAL;
2730
use const T_FUNCTION;
31+
use const T_IF;
2832
use const T_OBJECT_OPERATOR;
2933
use const T_OPEN_PARENTHESIS;
3034
use const T_SEMICOLON;
35+
use const T_SWITCH;
3136
use const T_VARIABLE;
3237
use const T_WHITESPACE;
3338

@@ -234,9 +239,17 @@ private function getAssignment(File $phpcsFile, int $constructorPointer, string
234239
}
235240

236241
$semicolonPointer = TokenHelper::findNextEffective($phpcsFile, $variablePointer + 1);
237-
if ($tokens[$semicolonPointer]['code'] === T_SEMICOLON) {
238-
return $i;
242+
if ($tokens[$semicolonPointer]['code'] !== T_SEMICOLON) {
243+
continue;
239244
}
245+
246+
foreach (array_reverse($tokens[$semicolonPointer]['conditions']) as $conditionTokenCode) {
247+
if (in_array($conditionTokenCode, [T_IF, T_ELSEIF, T_ELSE, T_SWITCH], true)) {
248+
return null;
249+
}
250+
}
251+
252+
return $i;
240253
}
241254

242255
return null;

tests/Sniffs/Classes/data/requireConstructorPropertyPromotionNoErrors.php

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,23 @@ public function __construct($a, $c, $d, $e, $f, $g, $h)
9292
}
9393

9494
}
95+
96+
class Foo
97+
{
98+
99+
private ?SimpleXMLElement $openingHours = null;
100+
101+
private ?string $formattedOpeningHours;
102+
103+
public function __construct(SimpleXMLElement|string|null $openingHours)
104+
{
105+
if ($openingHours instanceof SimpleXMLElement) {
106+
$this->openingHours = $openingHours;
107+
} elseif ($openingHours === null) {
108+
$this->openingHours = null;
109+
} else {
110+
$this->formattedOpeningHours = $openingHours;
111+
}
112+
}
113+
114+
}

0 commit comments

Comments
 (0)