Skip to content

Commit 131a51b

Browse files
committed
Better ReturnTypeDeclaration nullable returns compat
1 parent b7fa6ea commit 131a51b

File tree

2 files changed

+31
-10
lines changed

2 files changed

+31
-10
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
# Changelog
22

3+
## Not released
4+
- Fix false positive in `ReturnTypeDeclarationSniff` with nullable types.
5+
36
## 0.10.0
47
- Renamed sniffs namespace (**breaking change**).
58
Sniff are now referenced via `Inpsyde.CodeQuality...` instead of `InpsydeCodingStandard.CodeQuality...`

Inpsyde/Sniffs/CodeQuality/ReturnTypeDeclarationSniff.php

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -51,16 +51,22 @@ public function process(File $file, $position)
5151
return;
5252
}
5353

54-
list($hasNonVoidReturnType, $hasVoidReturnType, $hasNoReturnType) = $this->returnTypeInfo(
55-
$file,
56-
$position
57-
);
54+
list(
55+
$hasNonVoidReturnType,
56+
$hasVoidReturnType,
57+
$hasNoReturnType,
58+
$hasNullable
59+
) = $this->returnTypeInfo($file, $position);
5860

5961
list($nonVoidReturnCount, $voidReturnCount, $nullReturnCount) = PhpcsHelpers::countReturns(
6062
$file,
6163
$position
6264
);
6365

66+
if ($hasNullable) {
67+
$voidReturnCount -= $nullReturnCount;
68+
}
69+
6470
$this->maybeErrors(
6571
$hasNonVoidReturnType,
6672
$hasVoidReturnType,
@@ -151,15 +157,27 @@ private function returnTypeInfo(File $file, int $functionPosition): array
151157
);
152158

153159
$returnType = $tokens[$returnTypeToken] ?? null;
154-
if ($returnType && $returnType['type'] !== "T_RETURN_TYPE") {
155-
$returnType = null;
160+
if ($returnType && $returnType['code'] !== T_RETURN_TYPE) {
161+
return [false, false, true, false];
162+
}
163+
164+
$start = $tokens[$functionPosition]['parenthesis_closer'] + 1;
165+
$end = $tokens[$functionPosition]['scope_opener'];
166+
$hasNullable = false;
167+
for ($i = $start; $i < $end; $i++) {
168+
if ($tokens[$i]['code'] === T_NULLABLE) {
169+
$hasNullable = true;
170+
break;
171+
}
172+
if ($tokens[$i]['code'] === T_WHITESPACE) {
173+
continue;
174+
}
156175
}
157176

158-
$hasNonVoidReturnType = $returnType && $returnType['content'] !== 'void';
159-
$hasVoidReturnType = $returnType && $returnType['content'] === 'void';
160-
$hasNoReturnType = !$returnType;
177+
$hasNonVoidReturnType = $returnType['content'] !== 'void';
178+
$hasVoidReturnType = $returnType['content'] === 'void';
161179

162-
return [$hasNonVoidReturnType, $hasVoidReturnType, $hasNoReturnType];
180+
return [$hasNonVoidReturnType, $hasVoidReturnType, false, $hasNullable];
163181
}
164182

165183
/**

0 commit comments

Comments
 (0)