문제

I am parsing the @returns phpdoc annotations of several methods. Is there a way to get somehow the absolute name of classes?

For example:

namespace Y;

use X\A;

class B {

}

class C {
    /** @return A */
    public function getA(){}

    /** @return B */
    public function getB(){}
}

I need something like this

array(
    'Y\C' => array(
        'getA' => array(
            'returns' => 'X\A'
        ),
        'getB' => array(
            'returns' => 'Y\B'
        )
    )
);

Currently I have this:

array(
    'Y\C' => array(
        'getA' => array(
            'return' => 'A'
        ),
        'getB' => array(
            'return' => 'B'
        )
    )
);

note: I can deal with the Y\B, because I can read the namespace of the reflectionClass, but I don't know what to do with the use statements...

도움이 되었습니까?

해결책

If I am right currently the only solution to get the file of the class ReflectionClass::getFileName(), parse the use tokens and by traits and inheritance parse other files as well. After that you can create an alias map for the class, and use that alias map to get the absolute class names of the classes or interfaces we describe in the @return annotations. For example Doctrine TokenParser is an implementation of getting use statements by this approach...

So yes, it is possible to get the aliases, but there is no native support for annotations in php, so this is just a workaround...

A simple example:

use Doctrine\Common\Annotations\TokenParser;
use ReflectionClass;

function getAliases($className){
    $annotatedClass = new ReflectionClass($className);
    $namespace = $annotatedClass->getNamespaceName();
    $aliases = array();
    $classFile = $annotatedClass->getFileName();
    if ($classFile) {
        $classCode = file_get_contents($classFile);
        $tokenParser = new TokenParser($classCode);
        $aliases = $tokenParser->parseUseStatements($namespace);
    return $aliases;
}

Returns

array(
    strtolower($aliasName) => $className,
    ...
)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top