forked from rectorphp/rector
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPhpSpecMethodToPHPUnitMethodRector.php
95 lines (81 loc) · 2.88 KB
/
PhpSpecMethodToPHPUnitMethodRector.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
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace Rector\PhpSpecToPHPUnit\Rector\ClassMethod;
use Nette\Utils\Strings;
use PhpParser\Node;
use PhpParser\Node\Identifier;
use PhpParser\Node\Stmt\ClassMethod;
use Rector\Core\ValueObject\MethodName;
use Rector\PhpSpecToPHPUnit\Naming\PhpSpecRenaming;
use Rector\PhpSpecToPHPUnit\PHPUnitTypeDeclarationDecorator;
use Rector\PhpSpecToPHPUnit\Rector\AbstractPhpSpecToPHPUnitRector;
/**
* @see \Rector\Tests\PhpSpecToPHPUnit\Rector\Variable\PhpSpecToPHPUnitRector\PhpSpecToPHPUnitRectorTest
*/
final class PhpSpecMethodToPHPUnitMethodRector extends AbstractPhpSpecToPHPUnitRector
{
/**
* @var PhpSpecRenaming
*/
private $phpSpecRenaming;
/**
* @var PHPUnitTypeDeclarationDecorator
*/
private $phpUnitTypeDeclarationDecorator;
public function __construct(
PHPUnitTypeDeclarationDecorator $phpUnitTypeDeclarationDecorator,
PhpSpecRenaming $phpSpecRenaming
) {
$this->phpSpecRenaming = $phpSpecRenaming;
$this->phpUnitTypeDeclarationDecorator = $phpUnitTypeDeclarationDecorator;
}
/**
* @return array<class-string<Node>>
*/
public function getNodeTypes(): array
{
return [ClassMethod::class];
}
/**
* @param ClassMethod $node
*/
public function refactor(Node $node): ?Node
{
if (! $this->isInPhpSpecBehavior($node)) {
return null;
}
if ($this->isName($node, 'letGo')) {
$node->name = new Identifier(MethodName::TEAR_DOWN);
$this->visibilityManipulator->makeProtected($node);
$this->phpUnitTypeDeclarationDecorator->decorate($node);
} elseif ($this->isName($node, 'let')) {
$node->name = new Identifier(MethodName::SET_UP);
$this->visibilityManipulator->makeProtected($node);
$this->phpUnitTypeDeclarationDecorator->decorate($node);
} else {
$this->processTestMethod($node);
}
return $node;
}
private function processTestMethod(ClassMethod $classMethod): void
{
// special case, @see https://johannespichler.com/writing-custom-phpspec-matchers/
if ($this->isName($classMethod, 'getMatchers')) {
return;
}
// change name to phpunit test case format
$this->phpSpecRenaming->renameMethod($classMethod);
// reorder instantiation + expected exception
$previousStmt = null;
foreach ((array) $classMethod->stmts as $key => $stmt) {
if ($previousStmt &&
Strings::contains($this->print($stmt), 'duringInstantiation') &&
Strings::contains($this->print($previousStmt), 'beConstructedThrough')
) {
$classMethod->stmts[$key - 1] = $stmt;
$classMethod->stmts[$key] = $previousStmt;
}
$previousStmt = $stmt;
}
}
}