Search each class for function names that match except for the underscore prefix

Bill Karwin posts a useful little snippet that will list and search each class for function names that match except for the underscore prefix, private / protected functions.

< ?php /** * Find methods that differ only by the underscore prefix. * by Bill Karwin August 2010 * * I release this code under the terms of the New BSD License: * http://framework.zend.com/license/new-bsd */ // Change this to suit your environment define("LIBRARY_DIR", "/Users/bill/Library/PHP/ZF/library"); // Pre-load some files to satisfy the autoloader. // We could also add the local PEAR library dir to the autoloader. require_once("PHPUnit/Framework/SelfDescribing.php"); require_once("PHPUnit/Framework/AssertionFailedError.php"); require_once("PHPUnit/Framework/Assert.php"); require_once("PHPUnit/Framework/Test.php"); require_once("PHPUnit/Extensions/Database/DataSet/ITable.php"); require_once("PHPUnit/Extensions/Database/DataSet/AbstractTable.php"); require_once("PHPUnit/Extensions/Database/DataSet/IDataSet.php"); require_once("PHPUnit/Extensions/Database/DataSet/AbstractDataSet.php"); require_once("PHPUnit/Extensions/Database/ITester.php"); require_once("PHPUnit/Extensions/Database/AbstractTester.php"); require_once(LIBRARY_DIR . "/Zend/Loader/Autoloader.php"); Zend_Loader_Autoloader::getInstance(); // Find every PHP file under the library dir and slurp them in. // Yes that's a lot of files. Deal with it. $Directory = new RecursiveDirectoryIterator(LIBRARY_DIR); $Iterator = new RecursiveIteratorIterator($Directory); $Regex = new RegexIterator($Iterator, '/^.+\.php$/i'); foreach ($Regex as $filename) { require_once($filename); } // Loop over each class now in the PHP runtime. // Filter by classes named Zend*. $classes = get_declared_classes(); $zendclasses = new RegexIterator(new ArrayIterator($classes), '/ ^Zend/'); foreach ($zendclasses as $classname) { // Search each class for function names that match except for the underscore prefix // Note this includes duplicates and magic methods, so you have to do some sorting // on the output. Hint: `sort -u`. $class = new ReflectionClass($classname); $methods = $class->getMethods();
foreach ($methods as $method) {
if (preg_match("/^__*(.*)/", $method->name, $matches)) {
$underscore = $method;
if ($class->hasMethod($matches[1])) {
$nonunderscore = $class->getMethod($matches[1]);
echo $underscore->getDeclaringClass()->name
. "::" . $underscore->name . "()" . " => ";
if ($underscore->getDeclaringClass() != $nonunderscore->getDeclaringClass()) {
echo $nonunderscore->getDeclaringClass()->name;
}
echo "::" . $nonunderscore->name . "()" . "\n";
}
}
}

}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.