• This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn more.

Get classname from Path

xf_phantom

Well-known member
#1
Does a method in xf exist, where i could get the classname if i provide the path to a file or would i need to implement it myself?

e.g.
C:\xampp\htdocs\test1\library\XenForo\Model\Foo

would result in

XenForo_Model_Foo
 
Last edited:

xf_phantom

Well-known member
#3
That's what i'm using now (no namespace support, but works for most usecases ATM :) )
PHP:
    public static function getClassNameFromFilePath($file){

        $fp = fopen($file, 'r');
        $className = $buffer = '';
        $i = 0;
        while (!$className) {
            if (feof($fp)) break;

            $buffer .= fread($fp, 512);
            $tokens = token_get_all($buffer);

            if (strpos($buffer, '{') === false) continue;

            for (;$i<count($tokens);$i++) {
                if ($tokens[$i][0] === T_CLASS) {
                    for ($j=$i+1;$j<count($tokens);$j++) {
                        if ($tokens[$j] === '{') {
                            $className = $tokens[$i+2][1];
                        }
                    }
                }
            }
        }
        return $className;
    }
 

tyteen4a03

Well-known member
#4
That's what i'm using now
PHP:
    public static function getClassNameFromFilePath($file){

        $fp = fopen($file, 'r');
        $className = $buffer = '';
        $i = 0;
        while (!$className) {
            if (feof($fp)) break;

            $buffer .= fread($fp, 512);
            $tokens = token_get_all($buffer);

            if (strpos($buffer, '{') === false) continue;

            for (;$i<count($tokens);$i++) {
                if ($tokens[$i][0] === T_CLASS) {
                    for ($j=$i+1;$j<count($tokens);$j++) {
                        if ($tokens[$j] === '{') {
                            $className = $tokens[$i+2][1];
                        }
                    }
                }
            }
        }
        return $className;
    }
Why not just replace all slashes with underscores for the filename?

There is XenForo_Autoloader::autoloaderClassToFile but it seems to do the opposite.
 

xf_phantom

Well-known member
#5
Why not just replace all slashes with underscores for the filename?

There is XenForo_Autoloader::autoloaderClassToFile but it seems to do the opposite.
C:\xampp\htdocs\test1\library\XenForo\Model\Foo.php =>

c_xampp_htdocs_test1_library_xenforo_model_foo ?:D

I could probably remove the root dir and file extension and replace the slashes, but i'll stick with my current solution
 

tyteen4a03

Well-known member
#6
C:\xampp\htdocs\test1\library\XenForo\Model\Foo.php =>

c_xampp_htdocs_test1_library_xenforo_model_foo ?:D

I could probably remove the root dir and file extension and replace the slashes, but i'll stick with my current solution
You know the $rootDir and PATH_SEPARATOR, why not?