Skip to content

Commit

Permalink
Add sample codemod for renaming old-style constructors
Browse files Browse the repository at this point in the history
  • Loading branch information
Atanamo committed Apr 22, 2018
1 parent 8a7ec7c commit 3bbc250
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
48 changes: 48 additions & 0 deletions samples/class_constructor_rename.php
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;
1 change: 1 addition & 0 deletions samples/foobar_codemod.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public function leaveNode(Node $node) {
}


// Codemod definition class
class FoobarCodemod extends AbstractCodemod {

// Example: Traverse with visitor "FooReplaceVisitor"
Expand Down

0 comments on commit 3bbc250

Please sign in to comment.