Skip to content

Instantly share code, notes, and snippets.

@kukulich
Created March 21, 2017 11:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kukulich/87f9e322be419a5d1978fa308cc38556 to your computer and use it in GitHub Desktop.
Save kukulich/87f9e322be419a5d1978fa308cc38556 to your computer and use it in GitHub Desktop.
PHPUnit PHPStan extension
<?php declare(strict_types = 1);
namespace Slevomat\PHPStan;
use Slevomat\TestCase;
class TestCaseDynamicReturnTypeExtension implements \PHPStan\Type\DynamicMethodReturnTypeExtension
{
public static function getClass(): string
{
return TestCase::class;
}
public function isMethodSupported(\PHPStan\Reflection\MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'createMock';
}
public function getTypeFromMethodCall(
\PHPStan\Reflection\MethodReflection $methodReflection,
\PhpParser\Node\Expr\MethodCall $methodCall,
\PHPStan\Analyser\Scope $scope
): \PHPStan\Type\Type
{
if (count($methodCall->args) === 0) {
return $methodReflection->getReturnType();
}
$arg = $methodCall->args[0]->value;
if (!($arg instanceof \PhpParser\Node\Expr\ClassConstFetch)) {
return $methodReflection->getReturnType();
}
$class = $arg->class;
if (!($class instanceof \PhpParser\Node\Name)) {
return $methodReflection->getReturnType();
}
$class = (string) $class;
if ($class === 'static') {
return $methodReflection->getReturnType();
}
if ($class === 'self') {
$class = $scope->getClass();
}
return new \PHPStan\Type\CommonUnionType(
[
new \PHPStan\Type\ObjectType($class, false),
new \PHPStan\Type\ObjectType(\PHPUnit_Framework_MockObject_MockObject::class, false),
],
false
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment