Determining what classes are defined in a PHP class file

后端 未结 8 1367
-上瘾入骨i
-上瘾入骨i 2020-11-27 14:56

Given that each PHP file in our project contains a single class definition, how can I determine what class or classes are defined within the file?

I know I could jus

8条回答
  •  忘掉有多难
    2020-11-27 15:00

    My snippet too. Can parse files with multiple classes, interfaces, arrays and namespaces. Returns an array with classes+types (class, interface, abstract) divided by namespaces.

    = 0 && $tokens[$i - 2][0] == T_CLASS && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING) 
                {
                    if($i-4 >=0 && $tokens[$i - 4][0] == T_ABSTRACT)
                    {
                        $classes[$ii][] = array('name' => $tokens[$i][1], 'type' => 'ABSTRACT CLASS');
                    }
                    else
                    {
                        $classes[$ii][] = array('name' => $tokens[$i][1], 'type' => 'CLASS');
                    }
                }
                elseif ($i-2 >= 0 && $tokens[$i - 2][0] == T_INTERFACE && $tokens[$i - 1][0] == T_WHITESPACE && $tokens[$i][0] == T_STRING)
                {
                    $classes[$ii][] = array('name' => $tokens[$i][1], 'type' => 'INTERFACE');
                }
            }
            error_reporting($er);
            if (empty($classes)) return NULL;
    
            if(!empty($nsPos))
            {
                foreach($nsPos as $k => $p)
                {
                    $ns = '';
                    for($i = $p['start'] + 1; $i < $p['end']; $i++)
                        $ns .= $tokens[$i][1];
    
                    $ns = trim($ns);
                    $final[$k] = array('namespace' => $ns, 'classes' => $classes[$k+1]);
                }
                $classes = $final;
            }
            return $classes;
        }
    

    Outputs something like this...

    array
      'namespace' => string 'test\foo' (length=8)
      'classes' => 
        array
          0 => 
            array
              'name' => string 'bar' (length=3)
              'type' => string 'CLASS' (length=5)
          1 => 
            array
              'name' => string 'baz' (length=3)
              'type' => string 'INTERFACE' (length=9)
    array
      'namespace' => string 'this\is\a\really\big\namespace\for\testing\dont\you\think' (length=57)
      'classes' => 
        array
          0 => 
            array
              'name' => string 'yes_it_is' (length=9)
              'type' => string 'CLASS' (length=5)
          1 => 
            array
              'name' => string 'damn_too_big' (length=12)
              'type' => string 'ABSTRACT CLASS' (length=14)
          2 => 
            array
              'name' => string 'fogo' (length=6)
              'type' => string 'INTERFACE' (length=9)
    

    Might help someone!

提交回复
热议问题