Skip to content

Set correct types for mocks of multiple classes #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: 1.1.x
Choose a base branch
from
Open
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
10 changes: 8 additions & 2 deletions extension.neon
Original file line number Diff line number Diff line change
@@ -5,9 +5,7 @@ parameters:
- markTestIncomplete
- markTestSkipped
stubFiles:
- stubs/MockBuilder.stub
- stubs/MockObject.stub
- stubs/TestCase.stub

services:
-
@@ -26,6 +24,14 @@ services:
class: PHPStan\Type\PHPUnit\Assert\AssertStaticMethodTypeSpecifyingExtension
tags:
- phpstan.typeSpecifier.staticMethodTypeSpecifyingExtension
-
class: PHPStan\Type\PHPUnit\CreateMockDynamicReturnTypeExtension
tags:
- phpstan.broker.dynamicMethodReturnTypeExtension
-
class: PHPStan\Type\PHPUnit\GetMockBuilderDynamicReturnTypeExtension
tags:
- phpstan.broker.dynamicMethodReturnTypeExtension
-
class: PHPStan\Type\PHPUnit\MockBuilderDynamicReturnTypeExtension
tags:
1 change: 1 addition & 0 deletions phpstan.neon
Original file line number Diff line number Diff line change
@@ -7,6 +7,7 @@ includes:
parameters:
excludes_analyse:
- tests/*/data/*
treatPhpDocTypesAsCertain: false

services:
scopeIsInClass:
70 changes: 70 additions & 0 deletions src/Type/PHPUnit/CreateMockDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\PHPUnit;

use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;

class CreateMockDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension
{

/** @var int[] */
private $methods = [
'createMock' => 0,
'createConfiguredMock' => 0,
'createPartialMock' => 0,
'createTestProxy' => 0,
'getMockForAbstractClass' => 0,
'getMockFromWsdl' => 1,
];

public function getClass(): string
{
return 'PHPUnit\Framework\TestCase';
}

public function isMethodSupported(MethodReflection $methodReflection): bool
{
$name = $methodReflection->getName();
return array_key_exists($methodReflection->getName(), $this->methods);
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
$argumentIndex = $this->methods[$methodReflection->getName()];
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants());
if (!isset($methodCall->args[$argumentIndex])) {
return $parametersAcceptor->getReturnType();
}
$argType = $scope->getType($methodCall->args[$argumentIndex]->value);

$types = [];
if ($argType instanceof ConstantStringType) {
$types[] = new ObjectType($argType->getValue());
}

if ($argType instanceof ConstantArrayType) {
$types = array_map(function (ConstantStringType $argType): ObjectType {
return new ObjectType($argType->getValue());
}, $argType->getValueTypes());
}

if (count($types) === 0) {
return $parametersAcceptor->getReturnType();
}

return TypeCombinator::intersect(
$parametersAcceptor->getReturnType(),
...$types
);
}

}
57 changes: 57 additions & 0 deletions src/Type/PHPUnit/GetMockBuilderDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\PHPUnit;

use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\Constant\ConstantArrayType;
use PHPStan\Type\Constant\ConstantStringType;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\Type;
use PHPStan\Type\TypeWithClassName;

class GetMockBuilderDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension
{

public function getClass(): string
{
return 'PHPUnit\Framework\TestCase';
}

public function isMethodSupported(MethodReflection $methodReflection): bool
{
return $methodReflection->getName() === 'getMockBuilder';
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants());
$mockBuilderType = $parametersAcceptor->getReturnType();
if (count($methodCall->args) === 0) {
return $mockBuilderType;
}
if (!$mockBuilderType instanceof TypeWithClassName) {
throw new \PHPStan\ShouldNotHappenException();
}

$argType = $scope->getType($methodCall->args[0]->value);
if ($argType instanceof ConstantStringType) {
$class = $argType->getValue();

return new MockBuilderType($mockBuilderType, $class);
}

if ($argType instanceof ConstantArrayType) {
$classes = array_map(function (ConstantStringType $argType): string {
return $argType->getValue();
}, $argType->getValueTypes());

return new MockBuilderType($mockBuilderType, ...$classes);
}

return $mockBuilderType;
}

}
58 changes: 48 additions & 10 deletions src/Type/PHPUnit/MockBuilderDynamicReturnTypeExtension.php
Original file line number Diff line number Diff line change
@@ -4,34 +4,72 @@

use PhpParser\Node\Expr\MethodCall;
use PHPStan\Analyser\Scope;
use PHPStan\Broker\Broker;
use PHPStan\Reflection\BrokerAwareExtension;
use PHPStan\Reflection\MethodReflection;
use PHPStan\Reflection\ParametersAcceptorSelector;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\ObjectType;
use PHPStan\Type\Type;
use PHPUnit\Framework\MockObject\MockBuilder;
use PHPStan\Type\TypeCombinator;
use PHPStan\Type\TypeWithClassName;

class MockBuilderDynamicReturnTypeExtension implements \PHPStan\Type\DynamicMethodReturnTypeExtension
class MockBuilderDynamicReturnTypeExtension implements DynamicMethodReturnTypeExtension, BrokerAwareExtension
{

/** @var \PHPStan\Broker\Broker */
private $broker;

public function setBroker(Broker $broker): void
{
$this->broker = $broker;
}

public function getClass(): string
{
return MockBuilder::class;
$testCase = $this->broker->getClass('PHPUnit\Framework\TestCase');
$mockBuilderType = ParametersAcceptorSelector::selectSingle(
$testCase->getNativeMethod('getMockBuilder')->getVariants()
)->getReturnType();
if (!$mockBuilderType instanceof TypeWithClassName) {
throw new \PHPStan\ShouldNotHappenException();
}

return $mockBuilderType->getClassName();
}

public function isMethodSupported(MethodReflection $methodReflection): bool
{
return !in_array(
return true;
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
$calledOnType = $scope->getType($methodCall->var);
if (!in_array(
$methodReflection->getName(),
[
'getMock',
'getMockForAbstractClass',
'getMockForTrait',
],
true
);
}
)) {
return $calledOnType;
}

public function getTypeFromMethodCall(MethodReflection $methodReflection, MethodCall $methodCall, Scope $scope): Type
{
return $scope->getType($methodCall->var);
$parametersAcceptor = ParametersAcceptorSelector::selectSingle($methodReflection->getVariants());

if (!$calledOnType instanceof MockBuilderType) {
return $parametersAcceptor->getReturnType();
}
$types = array_map(function (string $type): ObjectType {
return new ObjectType($type);
}, $calledOnType->getMockedClasses());

return TypeCombinator::intersect(
$parametersAcceptor->getReturnType(),
...$types
);
}

}
37 changes: 37 additions & 0 deletions src/Type/PHPUnit/MockBuilderType.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\PHPUnit;

use PHPStan\Type\ObjectType;
use PHPStan\Type\TypeWithClassName;
use PHPStan\Type\VerbosityLevel;

class MockBuilderType extends ObjectType
{

/** @var array<string> */
private $mockedClasses;

public function __construct(
TypeWithClassName $mockBuilderType,
string ...$mockedClasses
)
{
parent::__construct($mockBuilderType->getClassName());
$this->mockedClasses = $mockedClasses;
}

/**
* @return array<string>
*/
public function getMockedClasses(): array
{
return $this->mockedClasses;
}

public function describe(VerbosityLevel $level): string
{
return sprintf('%s<%s>', parent::describe($level), implode('&', $this->mockedClasses));
}

}
29 changes: 0 additions & 29 deletions stubs/MockBuilder.stub

This file was deleted.

80 changes: 0 additions & 80 deletions stubs/TestCase.stub

This file was deleted.

37 changes: 37 additions & 0 deletions tests/Type/PHPUnit/CreateMockExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\PHPUnit;

use ExampleTestCase\BarInterface;
use ExampleTestCase\FooInterface;
use Iterator;
use PHPUnit\Framework\MockObject\MockObject;

class CreateMockExtensionTest extends ExtensionTestCase
{

/**
* @dataProvider getProvider
* @param string $expression
* @param string $type
*/
public function testCreateMock(string $expression, string $type): void
{
$this->processFile(
__DIR__ . '/data/create-mock.php',
$expression,
$type,
[new CreateMockDynamicReturnTypeExtension()]
);
}

/**
* @return Iterator<mixed>
*/
public function getProvider(): Iterator
{
yield ['$simpleInterface', implode('&', [FooInterface::class, MockObject::class])];
yield ['$doubleInterface', implode('&', [BarInterface::class, FooInterface::class, MockObject::class])];
}

}
89 changes: 89 additions & 0 deletions tests/Type/PHPUnit/ExtensionTestCase.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\PHPUnit;

use PhpParser\Node;
use PhpParser\PrettyPrinter\Standard;
use PHPStan\Analyser\NodeScopeResolver;
use PHPStan\Analyser\Scope;
use PHPStan\Analyser\ScopeContext;
use PHPStan\Broker\AnonymousClassNameHelper;
use PHPStan\Cache\Cache;
use PHPStan\File\FileHelper;
use PHPStan\Node\VirtualNode;
use PHPStan\PhpDoc\PhpDocNodeResolver;
use PHPStan\PhpDoc\PhpDocStringResolver;
use PHPStan\Testing\TestCase;
use PHPStan\Type\DynamicMethodReturnTypeExtension;
use PHPStan\Type\FileTypeMapper;
use PHPStan\Type\VerbosityLevel;

abstract class ExtensionTestCase extends TestCase
{

/**
* @param string $file
* @param string $expression
* @param string $type
* @param array<DynamicMethodReturnTypeExtension> $extensions
*/
protected function processFile(
string $file,
string $expression,
string $type,
array $extensions
): void
{
foreach ($extensions as $extension) {
if (!$extension instanceof DynamicMethodReturnTypeExtension) {
throw new \InvalidArgumentException();
}
}
$broker = $this->createBroker($extensions);
$parser = $this->getParser();
$currentWorkingDirectory = $this->getCurrentWorkingDirectory();
$fileHelper = new FileHelper($currentWorkingDirectory);
$typeSpecifier = $this->createTypeSpecifier(new Standard(), $broker);
/** @var \PHPStan\PhpDoc\PhpDocStringResolver $phpDocStringResolver */
$phpDocStringResolver = self::getContainer()->getByType(PhpDocStringResolver::class);
$resolver = new NodeScopeResolver(
$broker,
$parser,
new FileTypeMapper(
$parser,
$phpDocStringResolver,
self::getContainer()->getByType(PhpDocNodeResolver::class),
$this->createMock(Cache::class),
$this->createMock(AnonymousClassNameHelper::class)
),
$fileHelper,
$typeSpecifier,
true,
true,
true,
[],
[]
);
$resolver->setAnalysedFiles([$fileHelper->normalizePath($file)]);

$run = false;
$resolver->processNodes(
$parser->parseFile($file),
$this->createScopeFactory($broker, $typeSpecifier)->create(ScopeContext::create($file)),
function (Node $node, Scope $scope) use ($expression, $type, &$run): void {
if ($node instanceof VirtualNode) {
return;
}
if ((new Standard())->prettyPrint([$node]) !== 'die') {
return;
}
/** @var \PhpParser\Node\Stmt\Expression $expNode */
$expNode = $this->getParser()->parseString(sprintf('<?php %s;', $expression))[0];
self::assertSame($type, $scope->getType($expNode->expr)->describe(VerbosityLevel::typeOnly()));
$run = true;
}
);
self::assertTrue($run);
}

}
37 changes: 37 additions & 0 deletions tests/Type/PHPUnit/MockBuilderTypeExtensionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php declare(strict_types = 1);

namespace PHPStan\Type\PHPUnit;

use ExampleTestCase\BarInterface;
use ExampleTestCase\FooInterface;
use Iterator;
use PHPUnit\Framework\MockObject\MockObject;

class MockBuilderTypeExtensionTest extends ExtensionTestCase
{

/**
* @dataProvider getProvider
* @param string $expression
* @param string $type
*/
public function testMockBuilder(string $expression, string $type): void
{
$this->processFile(
__DIR__ . '/data/mock-builder.php',
$expression,
$type,
[new MockBuilderDynamicReturnTypeExtension(), new GetMockBuilderDynamicReturnTypeExtension()]
);
}

/**
* @return Iterator<mixed>
*/
public function getProvider(): Iterator
{
yield ['$simpleInterface', implode('&', [FooInterface::class, MockObject::class])];
yield ['$doubleInterface', implode('&', [BarInterface::class, FooInterface::class, MockObject::class])];
}

}
9 changes: 9 additions & 0 deletions tests/Type/PHPUnit/data/BarInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php declare(strict_types=1);


namespace ExampleTestCase;


interface BarInterface
{
}
9 changes: 9 additions & 0 deletions tests/Type/PHPUnit/data/FooInterface.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php declare(strict_types=1);


namespace ExampleTestCase;


interface FooInterface
{
}
12 changes: 12 additions & 0 deletions tests/Type/PHPUnit/data/create-mock.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?php

use PHPUnit\Framework\TestCase;

$test = new class () extends TestCase {};

$reflection = new ReflectionObject($test);
$reflection->getMethod('createMock')->setAccessible(true);
$simpleInterface = $test->createMock(\ExampleTestCase\FooInterface::class);
$doubleInterface = $test->createMock([\ExampleTestCase\FooInterface::class, \ExampleTestCase\BarInterface::class]);

die;
10 changes: 10 additions & 0 deletions tests/Type/PHPUnit/data/mock-builder.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

use PHPUnit\Framework\TestCase;

$test = new class () extends TestCase {};

$simpleInterface = $test->getMockBuilder(\ExampleTestCase\FooInterface::class)->getMock();
$doubleInterface = $test->getMockBuilder([\ExampleTestCase\FooInterface::class, \ExampleTestCase\BarInterface::class])->getMock();

die;