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){
        // var_dump($classDir);
        // exit;
        $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;
    }

    /**
     * @see Tlf\Util::getClassFromFile()
     */
    static public function getClassFromFile($file){
        return \Tlf\Util::getClassFromFile($file);
    }

    static public function getInterfacesFromClass($class){
        if ($class=='')return [];
        // if ($class=='' || !class_exists($class, true))return [];
        $ref = new \ReflectionClass($class);
        return $ref->getInterfaceNames();
    }
}