首页 > 解决方案 > Scan files in a directory to get the number of methods and PHP classes in a directory

问题描述

Im trying to get the number of class and methods in a specific directory which contain sub folder and scan through them. So far I can only count the number of files.

$ite=new RecursiveDirectoryIterator("scanME");

//keyword search
$classWords = array('class');
$functionWords = array('function');

//Global Counts
$bytestotal=0;
$nbfiles=0;
$classCount = 0;
$methodCount = 0;

foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
    $filesize=$cur->getSize();
    $bytestotal+=$filesize;
    if(is_file($cur)) 
    {   
        $nbfiles++;
        foreach ($classWords as $classWord) {
            $fileContents = file_get_contents($cur);
            $place = strpos($fileContents, $classWord);
            if (!empty($place)) { 
                $classCount++;
            } 
        }

        foreach($functionWords as $functionWord) {
            $fileContents = file_get_contents($cur);
            $place = strpos($fileContents, $functionWord);
            if (!empty($place)) { 
                $methodCount++;
            } 
        }

    }

}

EDIT: I manage to count the keyword class and function but the problem is it only concatenate for each file. Eg: I have 2 class in one file it will just count 1. How do I count for each keyword in a file?

标签: php

解决方案


使用令牌而不是关键字是更好的解决方案

$bytestotal=0;
$nbfiles=0;
$fileToString;
$token;
$pathInfo;


$classCount = 0;
$methodCount = 0;


foreach (new RecursiveIteratorIterator($ite) as $filename=>$cur) {
    $filesize=$cur->getSize();
    $bytestotal+=$filesize;
    if(is_file($cur)) 
    {   
        $nbfiles++;
        $fileToString = file_get_contents($cur);
        $token = token_get_all($fileToString);
        $tokenCount = count($token);

        //Class Count
        $pathInfo = pathinfo($cur);
        if ($pathInfo['extension'] === 'php') {
            for ($i = 2; $i < $tokenCount; $i++) {
                if ($token[$i-2][0] === T_CLASS && $token[$i-1][0] === T_WHITESPACE && $token[$i][0] === T_STRING ) {
                $classCount++;
                }
            }
        } else {
            error_reporting(E_ALL & ~E_NOTICE);
        }

        //Method Count 

        for ($i = 2; $i < $tokenCount; $i++) {
            if ($token[$i-2][0] === T_FUNCTION && $token[$i-1][0] === T_WHITESPACE && $token[$i][0] === T_STRING) {
                $methodCount++;
            }
        }
    }
}

推荐阅读