forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAddMockPropertiesRector.php
85 lines (68 loc) · 2.32 KB
/
AddMockPropertiesRector.php
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 Rector\PhpSpecToPHPUnit\Rector\Class_;
use PhpParser\Node;
use PhpParser\Node\Stmt\Class_;
use PHPStan\Type\ObjectType;
use PHPStan\Type\UnionType;
use Rector\Core\NodeManipulator\ClassInsertManipulator;
use Rector\NodeTypeResolver\Node\AttributeKey;
use Rector\PhpSpecToPHPUnit\PhpSpecMockCollector;
use Rector\PhpSpecToPHPUnit\Rector\AbstractPhpSpecToPHPUnitRector;
/**
* @see \Rector\Tests\PhpSpecToPHPUnit\Rector\Variable\PhpSpecToPHPUnitRector\PhpSpecToPHPUnitRectorTest
*/
final class AddMockPropertiesRector extends AbstractPhpSpecToPHPUnitRector
{
/**
* @var PhpSpecMockCollector
*/
private $phpSpecMockCollector;
/**
* @var ClassInsertManipulator
*/
private $classInsertManipulator;
public function __construct(
ClassInsertManipulator $classInsertManipulator,
PhpSpecMockCollector $phpSpecMockCollector
) {
$this->phpSpecMockCollector = $phpSpecMockCollector;
$this->classInsertManipulator = $classInsertManipulator;
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [Class_::class];
}
/**
* @param Class_ $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isInPhpSpecBehavior($node)) {
return null;
}
$classMocks = $this->phpSpecMockCollector->resolveClassMocksFromParam($node);
/** @var string $class */
$class = $node->getAttribute(AttributeKey::CLASS_NAME);
foreach ($classMocks as $name => $methods) {
if ((is_countable($methods) ? count($methods) : 0) <= 1) {
continue;
}
// non-ctor used mocks are probably local only
if (! in_array('let', $methods, true)) {
continue;
}
$this->phpSpecMockCollector->addPropertyMock($class, $name);
$variableType = $this->phpSpecMockCollector->getTypeForClassAndVariable($node, $name);
$unionType = new UnionType([
new ObjectType($variableType),
new ObjectType('PHPUnit\Framework\MockObject\MockObject'),
]);
$this->classInsertManipulator->addPropertyToClass($node, $name, $unionType);
}
return null;
}
}