Skip to content

Commit da60c46

Browse files
dktappsondrejmirtes
authored andcommitted
Implemented checks for use of void return of yield
this fixes #2873.
1 parent 7af00e2 commit da60c46

File tree

3 files changed

+39
-0
lines changed

3 files changed

+39
-0
lines changed

src/Rules/Generators/YieldTypeRule.php

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
use PHPStan\Type\MixedType;
1313
use PHPStan\Type\NullType;
1414
use PHPStan\Type\VerbosityLevel;
15+
use PHPStan\Type\VoidType;
1516

1617
/**
1718
* @implements \PHPStan\Rules\Rule<\PhpParser\Node\Expr\Yield_>
@@ -78,6 +79,9 @@ public function processNode(Node $node, Scope $scope): array
7879
$valueType->describe($verbosityLevel)
7980
))->build();
8081
}
82+
if ($scope->getType($node) instanceof VoidType && !$scope->isInFirstLevelStatement()) {
83+
$messages[] = RuleErrorBuilder::message('Result of yield (void) is used.')->build();
84+
}
8185

8286
return $messages;
8387
}

tests/PHPStan/Rules/Generators/YieldTypeRuleTest.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,14 @@ public function testRule(): void
4848
'Generator expects value type array(0 => DateTime, 1 => DateTime, 2 => stdClass, 4 => DateTimeImmutable), array(DateTime, DateTime, stdClass, DateTimeImmutable) given.',
4949
25,
5050
],
51+
[
52+
'Result of yield (void) is used.',
53+
137,
54+
],
55+
[
56+
'Result of yield (void) is used.',
57+
138,
58+
],
5159
]);
5260
}
5361

tests/PHPStan/Rules/Generators/data/yield.php

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,3 +119,30 @@ function hash_to_alt_sequence2(iterable $hash): iterable
119119
}
120120

121121
}
122+
123+
/**
124+
* @return \Generator<int, int, int, void>
125+
*/
126+
function yieldWithIntSendType(){
127+
yield 1;
128+
$something = yield 1;
129+
var_dump(yield 1);
130+
}
131+
132+
/**
133+
* @return \Generator<int, int, void, void>
134+
*/
135+
function yieldWithVoidSendType(){
136+
yield 1;
137+
$something = yield 1;
138+
var_dump(yield 1);
139+
}
140+
141+
/**
142+
* @return \Generator<int, int>
143+
*/
144+
function yieldWithoutSendType(){
145+
yield 1;
146+
$something = yield 1;
147+
var_dump(yield 1);
148+
}

0 commit comments

Comments
 (0)