Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<?php

namespace Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\TypeWillReturnCallableArrowFunctionRector\Fixture;

use PHPUnit\Framework\TestCase;
use Rector\PHPUnit\Tests\CodeQuality\Rector\Class_\TypeWillReturnCallableArrowFunctionRector\Source\SomeMockedClass;

final class SkipReturnTypeMismatch extends TestCase
{
public function test($value): void
{
$this->createMock(SomeMockedClass::class)
->method('someMethod')
->with($this->callback(function (string $name) {
return true;
}));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use PhpParser\Node\Expr\Variable;
use PhpParser\Node\Scalar\String_;
use PhpParser\Node\Stmt\Class_;
use PhpParser\Node\Stmt\Return_;
use PhpParser\NodeFinder;
use PHPStan\Reflection\ClassReflection;
use PHPStan\Type\IntersectionType;
use PHPStan\Type\MixedType;
Expand Down Expand Up @@ -241,6 +243,10 @@ public function refactor(Node $node): ?Class_
return null;
}

if ($this->shouldSkipReturnForConflictWithReturnedNodeType($innerClosure, $returnType)) {
return null;
}

$returnTypeNode = $this->staticTypeMapper->mapPHPStanTypeToPhpParserNode(
$returnType,
TypeKind::RETURN
Expand Down Expand Up @@ -326,4 +332,28 @@ private function fallbackMockedObjectInSetUp(

return $callerType;
}

private function shouldSkipReturnForConflictWithReturnedNodeType(
Closure|ArrowFunction $functionLike,
Type $returnType
): bool {
// find return functionLike, to check current type
$nodeFinder = new NodeFinder();
$returns = $nodeFinder->findInstanceOf($functionLike, Return_::class);
$returnTypes = [];
foreach ($returns as $return) {
if ($return->expr instanceof Node) {
$returnTypes[] = $this->getType($return->expr);
}
}

if (count($returnTypes) === 1) {
$closureReturnedNodeType = $returnTypes[0];
if (! $closureReturnedNodeType->isSuperTypeOf($returnType)->yes()) {
return true;
}
}

return false;
}
}