採用 模板方法模式 分離「遍歷邏輯」與「具體處理」:
FindFile:基類,負責遞歸遍歷目錄、深度控制、文件收集handle($file) 實現具體業務(如去 BOM、掃描病毒、統計代碼行)<?php
/**
* 文件遍歷基類
* 支持最大深度控制,收集所有文件路徑
*/
class FindFile {
public $files = []; // 收集的文件路徑
protected $maxdepth = 0; // 0 = 無限制
/** 入口方法
* @param string $spath 起始目錄
* @param int $maxdepth 最大深度
*/
public function process($spath, $maxdepth = 0) {
$this->maxdepth = (is_numeric($maxdepth) && $maxdepth > 0) ? $maxdepth : 0;
$this->files = [];
$this->traversing($spath);
}
/** 遞歸遍歷(模板方法核心) */
private function traversing($spath, $depth = 1) {
if (!is_dir($spath) || !$handle = opendir($spath)) return;
while (($file = readdir($handle)) !== false) {
if ($file === '.' || $file === '..') continue;
$curfile = $spath . '/' . $file;
if (is_dir($curfile)) {
// 目錄:判斷深度後遞歸
if ($this->maxdepth === 0 || $depth < $this->maxdepth) {
$this->traversing($curfile, $depth + 1);
}
} else {
// 文件:交給 handle 處理
$this->handle($curfile);
}
}
closedir($handle);
}
/** 鉤子方法:子類重寫實現具體處理
* @param string $file 文件絕對路徑
*/
protected function handle($file) {
$this->files[] = $file; // 默認僅收集路徑
}
}
?>
UTF-8 BOM (EF BB BF) 會導致 PHP 輸出異常、JSON 解析失敗、HTTP Header 提前發送等問題。
<?php
/**
* 清除 UTF-8 BOM 處理器
* 繼承 FindFile,指定處理文件類型
*/
class UnsetBom extends FindFile {
private $filetype = []; // 允許處理的副檔名
public function __construct(array $filetype = []) {
$this->filetype = $filetype;
}
protected function handle($file) {
// 雙重過濾:副檔名 + 實際 BOM 檢測
if ($this->check_ext($file) && $this->check_utf8bom($file)) {
$this->clear_utf8bom($file);
$this->files[] = $file; // 記錄已處理文件
}
}
/** 檢測 BOM:讀取前 3 字節 */
private function check_utf8bom($file) {
$content = file_get_contents($file, false, null, 0, 3);
return strlen($content) === 3 &&
ord($content[0]) === 0xEF &&
ord($content[1]) === 0xBB &&
ord($content[2]) === 0xBF;
}
/** 清除 BOM:去掉前 3 字節重寫 */
private function clear_utf8bom($file) {
$content = file_get_contents($file);
file_put_contents($file, substr($content, 3), LOCK_EX);
}
/** 副檔名過濾(不區分大小寫) */
private function check_ext($file) {
if (empty($this->filetype)) return true; // 無限制則全處理
$ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
return in_array($ext, $this->filetype);
}
}
?>
<?php
require 'FindFile.class.php';
require 'UnsetBom.class.php';
$project_root = dirname(__FILE__);
// 處理 php、css、js 文件
$cleaner = new UnsetBom(['php', 'css', 'js', 'html', 'xml', 'json']);
$cleaner->process($project_root);
echo "已清除 BOM 的文件 (" . count($cleaner->files) . "):\n";
print_r($cleaner->files);
?>
class CodeCounter extends FindFile {
private $total_lines = 0;
private $code_lines = 0;
private $comment_lines = 0;
private $blank_lines = 0;
protected function handle($file) {
if (!$this->check_ext($file)) return;
$content = file_get_contents($file);
$lines = explode("\n", $content);
$this->total_lines += count($lines);
foreach ($lines as $line) {
$trimmed = trim($line);
if ($trimmed === '') $this->blank_lines++;
elseif (strpos($trimmed, '//') === 0 || strpos($trimmed, '#') === 0) $this->comment_lines++;
else $this->code_lines++;
}
}
// ... getter 方法
}
class MalwareScanner extends FindFile {
private $patterns = [
'/eval\s*\(/i', '/base64_decode\s*\(/i', '/gzinflate\s*\(/i',
'/shell_exec\s*\(/i', '/system\s*\(/i', '/passthru\s*\(/i'
];
public $suspects = [];
protected function handle($file) {
if (!$this->check_ext($file)) return;
$content = file_get_contents($file);
foreach ($this->patterns as $pattern) {
if (preg_match($pattern, $content)) {
$this->suspects[$file][] = $pattern;
break;
}
}
}
}
RecursiveDirectoryIterator + RecursiveIteratorIterator 替代 opendir/readdir,C 層實現更快pcntl_fork 或進程池並行處理多個子目錄這套類庫結構清晰、擴展性強,是構建各類文件系統維護工具的理想基礎。