Jump to content

Make interface from class


Mastodont

Recommended Posts

I wrote function for extracting class members from class into interface - without reflection. Any comments are welcomed.

 

It takes into account only first class in source file. Constants are omitted.

 

function makeInterfaceFromClassCode($file) {
    // open a file
    $contents = file_get_contents($file);
    if (!$contents)
        return false;
    // is there a definition of class in file?
    if (preg_match('/^[^\w]*class/mU',$contents)) {
        // trim opening part
        $contents = strstr($contents, 'class');
        $contents = ltrim(strstr($contents, ' '));
        // pick up a name of class
        $success = preg_match('/^(\w+)[^\w]/U',$contents, $name);
        if ($success)
            $className = $name[1];
        // trim other opening part
        $length = strlen($className);
        $contents = substr($contents, $length);
        // now we have to find end of class
        $length = strlen($contents);
        $counter = 1;
        for ($i=1; $i<=$length; $i++ ) {
            if ($contents{$i} == '{')
                $counter++;
            if ($contents{$i} == '}')
                $counter--;
            if (!isset($helper) && $counter > 1 )
                $helper = true;
            if ($helper && $counter == 1)
                break;
        }
        $contents = substr($contents, 1, $i);
        // now $contents contains only class definition
        // pick up properties and methods
        $success = preg_match_all('/(private|public|var)\s+(\$[a-zA-Z0-9_]+)[^;]*;/U',$contents, $vars);
        $success = preg_match_all('/function\s*(\w+)\s*\((.*)\)/U',$contents, $methods);
        
        // build output string
        $output = "interface i$className {\n\t";
        foreach ($vars[0] as $value) {
            $output .= "$value\n\t";  
        }
        $output .= "\n\t";
        foreach ($methods[0] as $value) {
            $output .= "$value;\n\t";  
        }
        $output = rtrim($output);
        return $output."\n}";
    } else {
        return false;
    }
} // end of function makeInterfaceFromClassCode

Link to comment
Share on other sites

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.