ClassFinder.php

<?php
/**
 * Copyright 2021 Reed Sutman, Taeluf
 * MIT License
 * See tluf.me/utils
 *
 * Please retain this notice
 */

namespace Lia\Utility;

/**
 * Find a fully qualified classname in a file. (or for multiple files in a directory)
 * @todo link this up with my util repo to keep it up to date
 */
class ClassFinder {


    static public function classesFromDir($classDir){
        $classes = [];
        if (is_dir($classDir)){
            $files = scandir($classDir);
            foreach ($files as $file){
                if ($file=='.'||$file=='..'){
                    continue;
                } 
                $path = $classDir.'/'.$file;
                $ext = pathinfo($path,PATHINFO_EXTENSION);
                if ($ext!='php')continue;
                include_once($path);
                $class = self::getClassFromFile($path);
                $classes[] = ['class'=>$class, 'interfaces'=>self::getInterfacesFromClass($class)];
            }
        }
        return $classes;
    }

    static public function getClassFromFile($file){
        $fp = fopen($file, 'r');
        $class = $namespace = $buffer = '';
        $i = 0;
        while (!$class) {
            if (feof($fp)) break;

            $buffer .= fread($fp, 512);
            ob_start();
            $tokens = @token_get_all($buffer);
            $err = ob_get_clean();
            // if (true&&strlen($err)>0){
                // echo $buffer;
                // echo $err."\n";
                // echo $class."\n";
                // echo "\n".$file;
                // print_r($tokens);
            // }
            if (strpos($buffer, '{') === false) continue;

            for (;$i<count($tokens);$i++) {
                if ($tokens[$i][0] === T_NAMESPACE) {
                    for ($j=$i+1;$j<count($tokens); $j++) {
                        if ($tokens[$j][0] === T_STRING) {
                            $namespace .= '\\'.$tokens[$j][1];
                        } else if ($tokens[$j] === '{' || $tokens[$j] === ';') {
                            break;
                        }
                    }
                }

                if ($tokens[$i][0] === T_CLASS) {
                    for ($j=$i+1;$j<count($tokens);$j++) {
                        if ($tokens[$j] === '{') {
                            $class = $tokens[$i+2][1];
                        }
                    }
                }
            }
        }
        if ($class=='')return '';
        return $namespace.'\\'.$class;
        
    }
    static public function getInterfacesFromClass($class){
        if ($class=='')return [];
        $ref = new \ReflectionClass($class);
        return $ref->getInterfaceNames();
    }
}