Skip to content

Commit

Permalink
Fix: False positive for invalid Generator return type
Browse files Browse the repository at this point in the history
  • Loading branch information
gmazzap committed Feb 28, 2024
1 parent b53f4bf commit 542d903
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
7 changes: 5 additions & 2 deletions Inpsyde/Sniffs/CodeQuality/ReturnTypeDeclarationSniff.php
Original file line number Diff line number Diff line change
Expand Up @@ -347,10 +347,13 @@ private function checkInvalidGenerator(
): bool {

$hasGenerator = false;
$hasIterator = false;
while (!$hasGenerator && $returnTypes) {
$returnType = explode('&', rtrim(ltrim(array_shift($returnTypes), '('), ')'));
$hasGenerator = in_array('Generator', $returnType, true)
|| in_array('\Generator', $returnType, true)
|| in_array('\Generator', $returnType, true);
$hasIterator = $hasIterator
|| $hasGenerator
|| in_array('Traversable', $returnType, true)
|| in_array('\Traversable', $returnType, true)
|| in_array('Iterator', $returnType, true)
Expand Down Expand Up @@ -383,7 +386,7 @@ private function checkInvalidGenerator(
return true;
}

if (!$hasGenerator && ($yieldCount > 0)) {
if (!$hasIterator && ($yieldCount > 0)) {
$file->addError(
'Return type does not contain "Generator" but yield found in the function body',
$position,
Expand Down
14 changes: 14 additions & 0 deletions tests/fixtures/return-type-declaration.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
<?php
// @phpcsSniff Inpsyde.CodeQuality.ReturnTypeDeclaration

use Brain\Assets\Enqueue\Enqueue;
use Psr\Container\ContainerInterface as PsrContainer;

class FooIterator implements IteratorAggregate
{
private array $collection = [];

/**
* @return Iterator<int, Foo>
*/
public function getIterator(): \Iterator
{
return new ArrayIterator($this->collection);
}
}

function returnMixed(): mixed
{
return null;
Expand Down

0 comments on commit 542d903

Please sign in to comment.