-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add sample codemod for renaming old-style constructors
- Loading branch information
Showing
2 changed files
with
49 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
<?php | ||
|
||
use \Codeshift\AbstractCodemod; | ||
use \PhpParser\{Node, NodeVisitorAbstract}; | ||
|
||
|
||
// Visitor, which renames old-style constructors of PHP <= 4 to the new style. | ||
// Practically speaking, it searches for class methods named like their class. | ||
class ConstructorRenamingVisitor extends NodeVisitorAbstract { | ||
private $currClassName = ''; | ||
|
||
public function enterNode(Node $node) { | ||
if ($node instanceof Node\Stmt\Class_) { | ||
$identifier = $node->name; | ||
$this->currClassName = $identifier->name; // Remember class name | ||
} | ||
} | ||
|
||
public function leaveNode(Node $node) { | ||
if ($node instanceof Node\Stmt\ClassMethod) { | ||
$identifier = $node->name; | ||
|
||
// Replace method name, if it matches class name | ||
if ($identifier == $this->currClassName AND $identifier != '') { | ||
$node->name = new Node\Identifier('__construct'); | ||
} | ||
} | ||
} | ||
} | ||
|
||
|
||
// Codemod definition class | ||
class ConstructorRenamingCodemod extends AbstractCodemod { | ||
|
||
// @override | ||
public function init() { | ||
// Init the renaming visitor | ||
$visitor = new ConstructorRenamingVisitor(); | ||
|
||
// Schedule a traversal run on the code that uses the visitor | ||
$this->addTraversalTransform($visitor); | ||
} | ||
|
||
}; | ||
|
||
|
||
// Important: Export the codemod class | ||
return ConstructorRenamingCodemod; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters