-
Notifications
You must be signed in to change notification settings - Fork 1
/
foobar_codemod.php
64 lines (46 loc) · 1.74 KB
/
foobar_codemod.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
<?php
namespace MyExampleNamespace;
use Codeshift\AbstractCodemod;
use PhpParser\{Node, NodeFinder, NodeVisitorAbstract};
// Example visitor: Replace any string to "foo"
class FooReplaceVisitor extends NodeVisitorAbstract {
public function leaveNode(Node $node) {
if ($node instanceof Node\Scalar\String_) {
$node->value = 'foo';
}
}
}
// Codemod definition class
class FoobarCodemod extends AbstractCodemod {
// Example: Traverse with visitor "FooReplaceVisitor"
// @override
public function init() {
// Init the example visitor
$visitor = new FooReplaceVisitor();
// Schedule a traversal run on the code that uses the visitor
$this->addTraversalTransform($visitor);
}
// Example: Get information about current transformed code/file.
// @override
public function beforeTraversalTransform(array $statements): array {
$infoMap = $this->getCodeInformation();
$tracer = $this->getTracer();
$tracer->writeLine();
$tracer->inform("Will now transform: '{$infoMap['inputFile']}'");
$tracer->inform("Will output to: '{$infoMap['outputFile']}'");
$tracer->writeLine();
return $statements;
}
// Example: Rename first declared function to "bar"
// @override
public function afterTraversalTransform(array $statements): array {
$nodeFinder = new NodeFinder();
$functionNode = $nodeFinder->findFirstInstanceOf($statements, Node\Stmt\Function_::class);
if ($functionNode != null) {
$functionNode->name = new Node\Identifier('bar');
}
return $statements;
}
};
// Important: Export the full name of the codemod class
return '\MyExampleNamespace\FoobarCodemod';