Created
January 20, 2025 01:29
-
-
Save gurubobnz/2ae85e5010158896789e75f3ea375803 to your computer and use it in GitHub Desktop.
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
<?php | |
// composer require nikic/php-parser | |
require 'vendor/autoload.php'; | |
use PhpParser\{Error, Node, NodeTraverser, NodeVisitorAbstract, ParserFactory, PhpVersion}; | |
class NoReturnMethodsVisitor extends NodeVisitorAbstract { | |
private array $noReturnMethods = []; | |
public function getNoReturnMethods(): array { | |
return $this->noReturnMethods; | |
} | |
public function enterNode(Node $node) { | |
// Look for method declarations | |
if ($node instanceof Node\Stmt\ClassMethod) { | |
$methodName = $node->name->toString(); | |
$methodBody = $node->stmts; | |
// If the method body is null (e.g., abstract or interface methods), skip it | |
if ($methodBody === null) { | |
return; | |
} | |
// Check if the method contains a return statement | |
$hasReturn = false; | |
foreach ($methodBody as $stmt) { | |
if ($stmt instanceof Node\Stmt\Return_) { | |
$hasReturn = true; | |
break; | |
} | |
} | |
// If no return statement is found, add the method name | |
if (!$hasReturn) { | |
$this->noReturnMethods[] = $methodName; | |
} | |
} | |
} | |
} | |
function getMethodsWithNoReturn(string $classSource): array { | |
// Create a parser | |
$parser = (new ParserFactory)->createForVersion(PhpVersion::getNewestSupported()); | |
try { | |
// Parse the PHP code into an abstract syntax tree (AST) | |
$ast = $parser->parse($classSource); | |
// Create a traverser and our custom visitor | |
$traverser = new NodeTraverser(); | |
$visitor = new NoReturnMethodsVisitor(); | |
$traverser->addVisitor($visitor); | |
// Traverse the AST | |
$traverser->traverse($ast); | |
// Return the collected methods | |
return $visitor->getNoReturnMethods(); | |
} catch (Error $e) { | |
echo 'Parse error: ', $e->getMessage(); | |
return []; | |
} | |
} | |
// Example usage: | |
$classSource = file_get_contents('path/to/source/file.php'); | |
$methods = getMethodsWithNoReturn($classSource); | |
echo "Methods with no return values:\n"; | |
print_r($methods); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment