Repository navigation
Expand file tree
/
Copy pathMockObjectTypeNodeResolverExtension.php
More file actions
85 lines (69 loc) · 2.31 KB
/
Copy pathMockObjectTypeNodeResolverExtension.php
File metadata and controls
85 lines (69 loc) · 2.31 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
<?php declare(strict_types = 1);
namespace PHPStan\PhpDoc\PHPUnit;
use PHPStan\Analyser\NameScope;
use PHPStan\PhpDoc\TypeNodeResolver;
use PHPStan\PhpDoc\TypeNodeResolverAwareExtension;
use PHPStan\PhpDoc\TypeNodeResolverExtension;
use PHPStan\PhpDocParser\Ast\Type\IdentifierTypeNode;
use PHPStan\PhpDocParser\Ast\Type\TypeNode;
use PHPStan\PhpDocParser\Ast\Type\UnionTypeNode;
use PHPStan\Type\NeverType;
use PHPStan\Type\Type;
use PHPStan\Type\TypeCombinator;
use function array_key_exists;
use function count;
class MockObjectTypeNodeResolverExtension implements TypeNodeResolverExtension, TypeNodeResolverAwareExtension
{
private TypeNodeResolver $typeNodeResolver;
public function setTypeNodeResolver(TypeNodeResolver $typeNodeResolver): void
{
$this->typeNodeResolver = $typeNodeResolver;
}
public function getCacheKey(): string
{
return 'phpunit-v1';
}
public function resolve(TypeNode $typeNode, NameScope $nameScope): ?Type
{
if (!$typeNode instanceof UnionTypeNode) {
return null;
}
static $mockClassNames = [
'PHPUnit_Framework_MockObject_MockObject' => true,
'PHPUnit\Framework\MockObject\MockObject' => true,
'PHPUnit\Framework\MockObject\Stub' => true,
];
// TypeNodeResolver resolves the union again when this returns null, so resolving every
// member here would resolve each nested union twice per level. Look at the direct
// identifier members first: they cannot nest, and a mock class in a union is written as one.
$hasMockClass = false;
foreach ($typeNode->types as $innerTypeNode) {
if (!$innerTypeNode instanceof IdentifierTypeNode) {
continue;
}
$classNames = $this->typeNodeResolver->resolve($innerTypeNode, $nameScope)->getObjectClassNames();
if (count($classNames) === 1 && array_key_exists($classNames[0], $mockClassNames)) {
$hasMockClass = true;
break;
}
}
if (!$hasMockClass) {
return null;
}
$types = $this->typeNodeResolver->resolveMultiple($typeNode->types, $nameScope);
foreach ($types as $type) {
$classNames = $type->getObjectClassNames();
if (count($classNames) !== 1) {
continue;
}
if (array_key_exists($classNames[0], $mockClassNames)) {
$resultType = TypeCombinator::intersect(...$types);
if ($resultType instanceof NeverType) {
continue;
}
return $resultType;
}
}
return null;
}
}