题
如何找到 PHP 项目中未使用的函数?
PHP 中是否有内置的功能或 API 可以让我分析我的代码库 - 例如 反射, token_get_all()
?
这些 API 的功能是否足够丰富,让我不必依赖第三方工具来执行此类分析?
解决方案 2
感谢格雷格和戴夫的反馈。这并不完全是我想要的,但我决定花一些时间研究它并提出这个快速而肮脏的解决方案:
<?php
$functions = array();
$path = "/path/to/my/php/project";
define_dir($path, $functions);
reference_dir($path, $functions);
echo
"<table>" .
"<tr>" .
"<th>Name</th>" .
"<th>Defined</th>" .
"<th>Referenced</th>" .
"</tr>";
foreach ($functions as $name => $value) {
echo
"<tr>" .
"<td>" . htmlentities($name) . "</td>" .
"<td>" . (isset($value[0]) ? count($value[0]) : "-") . "</td>" .
"<td>" . (isset($value[1]) ? count($value[1]) : "-") . "</td>" .
"</tr>";
}
echo "</table>";
function define_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
define_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
define_file($path . "/" . $file, $functions);
}
}
}
}
function define_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_FUNCTION) continue;
$i++;
$token = $tokens[$i];
if ($token[0] != T_WHITESPACE) die("T_WHITESPACE");
$i++;
$token = $tokens[$i];
if ($token[0] != T_STRING) die("T_STRING");
$functions[$token[1]][0][] = array($path, $token[2]);
}
}
}
function reference_dir($path, &$functions) {
if ($dir = opendir($path)) {
while (($file = readdir($dir)) !== false) {
if (substr($file, 0, 1) == ".") continue;
if (is_dir($path . "/" . $file)) {
reference_dir($path . "/" . $file, $functions);
} else {
if (substr($file, - 4, 4) != ".php") continue;
reference_file($path . "/" . $file, $functions);
}
}
}
}
function reference_file($path, &$functions) {
$tokens = token_get_all(file_get_contents($path));
for ($i = 0; $i < count($tokens); $i++) {
$token = $tokens[$i];
if (is_array($token)) {
if ($token[0] != T_STRING) continue;
if ($tokens[$i + 1] != "(") continue;
$functions[$token[1]][1][] = array($path, $token[2]);
}
}
}
?>
我可能会花更多的时间,这样我就可以快速找到函数定义和引用的文件和行号;这些信息正在被收集,只是不被显示。
其他提示
您可以尝试 Sebastian Bergmann 的死代码检测器:
phpdcd
是 PHP 代码的死代码检测器 (DCD)。它扫描 PHP 项目中所有声明的函数和方法,并将那些至少未调用一次的“死代码”报告为“死代码”。
来源: https://github.com/sebastianbergmann/phpdcd
请注意,它是一个静态代码分析器,因此它可能会对仅动态调用的方法给出误报,例如它无法检测到 $foo = 'fn'; $foo();
您可以通过 PEAR 安装它:
pear install phpunit/phpdcd-beta
之后您可以使用以下选项:
Usage: phpdcd [switches] <directory|file> ...
--recursive Report code as dead if it is only called by dead code.
--exclude <dir> Exclude <dir> from code analysis.
--suffixes <suffix> A comma-separated list of file suffixes to check.
--help Prints this usage information.
--version Prints the version and exits.
--verbose Print progress bar.
更多工具:
笔记: 根据存储库通知, 该项目不再维护,其存储库仅用于存档目的. 。所以你的里程可能会有所不同。
这段 bash 脚本可能会有所帮助:
grep -rhio ^function\ .*\( .|awk -F'[( ]' '{print "echo -n " $2 " && grep -rin " $2 " .|grep -v function|wc -l"}'|bash|grep 0
这基本上递归地在当前目录中查找函数定义,将命中结果传递给 awk,这形成一个命令来执行以下操作:
- 打印函数名称
- 再次递归地 grep 查找它
- 输出到 grep -v 的管道以过滤掉函数定义以保留对函数的调用
- 将此输出通过管道传输到 wc -l 来打印行数
然后,该命令被发送到 bash 执行,并且输出被 grep 为 0,这表示对该函数的调用有 0 次。
请注意,这将 不是 解决上面 calebbrown 引用的问题,因此输出中可能存在一些误报。
用法: find_unused_functions.php <根目录>
笔记:这是解决问题的“快速但肮脏”的方法。该脚本仅对文件执行词法传递,并且不考虑不同模块定义相同名称的函数或方法的情况。如果您使用 IDE 进行 PHP 开发,它可能会提供更全面的解决方案。
需要 PHP 5
为了节省您的复制和粘贴、直接下载以及任何新版本, 可以在这里找到.
#!/usr/bin/php -f
<?php
// ============================================================================
//
// find_unused_functions.php
//
// Find unused functions in a set of PHP files.
// version 1.3
//
// ============================================================================
//
// Copyright (c) 2011, Andrey Butov. All Rights Reserved.
// This script is provided as is, without warranty of any kind.
//
// http://www.andreybutov.com
//
// ============================================================================
// This may take a bit of memory...
ini_set('memory_limit', '2048M');
if ( !isset($argv[1]) )
{
usage();
}
$root_dir = $argv[1];
if ( !is_dir($root_dir) || !is_readable($root_dir) )
{
echo "ERROR: '$root_dir' is not a readable directory.\n";
usage();
}
$files = php_files($root_dir);
$tokenized = array();
if ( count($files) == 0 )
{
echo "No PHP files found.\n";
exit;
}
$defined_functions = array();
foreach ( $files as $file )
{
$tokens = tokenize($file);
if ( $tokens )
{
// We retain the tokenized versions of each file,
// because we'll be using the tokens later to search
// for function 'uses', and we don't want to
// re-tokenize the same files again.
$tokenized[$file] = $tokens;
for ( $i = 0 ; $i < count($tokens) ; ++$i )
{
$current_token = $tokens[$i];
$next_token = safe_arr($tokens, $i + 2, false);
if ( is_array($current_token) && $next_token && is_array($next_token) )
{
if ( safe_arr($current_token, 0) == T_FUNCTION )
{
// Find the 'function' token, then try to grab the
// token that is the name of the function being defined.
//
// For every defined function, retain the file and line
// location where that function is defined. Since different
// modules can define a functions with the same name,
// we retain multiple definition locations for each function name.
$function_name = safe_arr($next_token, 1, false);
$line = safe_arr($next_token, 2, false);
if ( $function_name && $line )
{
$function_name = trim($function_name);
if ( $function_name != "" )
{
$defined_functions[$function_name][] = array('file' => $file, 'line' => $line);
}
}
}
}
}
}
}
// We now have a collection of defined functions and
// their definition locations. Go through the tokens again,
// and find 'uses' of the function names.
foreach ( $tokenized as $file => $tokens )
{
foreach ( $tokens as $token )
{
if ( is_array($token) && safe_arr($token, 0) == T_STRING )
{
$function_name = safe_arr($token, 1, false);
$function_line = safe_arr($token, 2, false);;
if ( $function_name && $function_line )
{
$locations_of_defined_function = safe_arr($defined_functions, $function_name, false);
if ( $locations_of_defined_function )
{
$found_function_definition = false;
foreach ( $locations_of_defined_function as $location_of_defined_function )
{
$function_defined_in_file = $location_of_defined_function['file'];
$function_defined_on_line = $location_of_defined_function['line'];
if ( $function_defined_in_file == $file &&
$function_defined_on_line == $function_line )
{
$found_function_definition = true;
break;
}
}
if ( !$found_function_definition )
{
// We found usage of the function name in a context
// that is not the definition of that function.
// Consider the function as 'used'.
unset($defined_functions[$function_name]);
}
}
}
}
}
}
print_report($defined_functions);
exit;
// ============================================================================
function php_files($path)
{
// Get a listing of all the .php files contained within the $path
// directory and its subdirectories.
$matches = array();
$folders = array(rtrim($path, DIRECTORY_SEPARATOR));
while( $folder = array_shift($folders) )
{
$matches = array_merge($matches, glob($folder.DIRECTORY_SEPARATOR."*.php", 0));
$moreFolders = glob($folder.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
$folders = array_merge($folders, $moreFolders);
}
return $matches;
}
// ============================================================================
function safe_arr($arr, $i, $default = "")
{
return isset($arr[$i]) ? $arr[$i] : $default;
}
// ============================================================================
function tokenize($file)
{
$file_contents = file_get_contents($file);
if ( !$file_contents )
{
return false;
}
$tokens = token_get_all($file_contents);
return ($tokens && count($tokens) > 0) ? $tokens : false;
}
// ============================================================================
function usage()
{
global $argv;
$file = (isset($argv[0])) ? basename($argv[0]) : "find_unused_functions.php";
die("USAGE: $file <root_directory>\n\n");
}
// ============================================================================
function print_report($unused_functions)
{
if ( count($unused_functions) == 0 )
{
echo "No unused functions found.\n";
}
$count = 0;
foreach ( $unused_functions as $function => $locations )
{
foreach ( $locations as $location )
{
echo "'$function' in {$location['file']} on line {$location['line']}\n";
$count++;
}
}
echo "=======================================\n";
echo "Found $count unused function" . (($count == 1) ? '' : 's') . ".\n\n";
}
// ============================================================================
/* EOF */
如果我没记错的话你可以使用 phpCallGraph 要做到这一点。它会使用所涉及的所有方法为您生成一个漂亮的图表(图像)。如果一个方法没有连接到任何其他方法,则表明该方法是孤立的。
这是一个例子: 类GallerySystem.png
方法 getKeywordSetOfCategories()
是孤儿。
顺便说一下,你不必拍摄图像——phpCallGraph 也可以 产生 文本文件或 PHP 数组等。
由于 PHP 函数/方法可以动态调用,因此没有编程方法可以确定函数是否永远不会被调用。
唯一确定的方法是通过手动分析。
2019+ 更新
我受到启发 安德烈的回答 并将其转化为编码标准嗅探。
检测非常简单但功能强大:
- 查找所有方法
public function someMethod()
- 然后找到所有方法调用
${anything}->someMethod()
- 简单地 报告那些从未被调用过的公共函数
3 步骤找到他们
安装弹性云服务器:
composer require symplify/easy-coding-standard --dev
设置 ecs.yaml
配置:
# ecs.yaml
services:
Symplify\CodingStandard\Sniffs\DeadCode\UnusedPublicMethodSniff: ~
运行命令:
vendor/bin/ecs check src
查看报告的方法并删除那些您不认为有用的方法👍
你可以在这里读更多关于它的内容: 从代码中删除无效的公共方法
据我所知,没有办法。要知道哪些函数“属于谁”,您需要执行系统(运行时后期绑定函数查找)。
但重构工具是基于静态代码分析的。我真的很喜欢动态类型语言,但在我看来它们很难扩展。大型代码库和动态类型语言中缺乏安全重构是可维护性和处理软件演化的主要缺点。
phpxref 将确定从哪里调用函数,这将有助于分析 - 但仍然涉及一定量的手动工作。