Parsing PHP Doc Comments into a Data Structure

Issue

I’m using the Reflection API in PHP to pull a DocComment (PHPDoc) string from a method

$r = new ReflectionMethod($object);
$comment = $r->getDocComment();

This will return a string that looks something like this (depending on how well the method was documented)

/**
* Does this great things
*
* @param string $thing
* @return Some_Great_Thing
*/

Are there any built-in methods or functions that can parse a PHP Doc Comment String into a data structure?

$object = some_magic_function_or_method($comment_string);

echo 'Returns a: ', $object->return;

Lacking that, what part of the PHPDoc source code should I be looking at the do this myself.

Lacking and/or in addition to that, is there third party code that’s considered “better” at this that the PHPDoc code?

I realize parsing these strings isn’t rocket science, or even computer science, but I’d prefer a well tested library/routine/method that’s been built to deal with a lot of the janky, semi-non-correct PHP Doc code that might exist in the wild.

Solution

I am surprised this wasn’t mentioned yet: what about using Zend_Reflection of Zend Framework? This may come in handy especially if you work with a software built on Zend Framework like Magento.

See the Zend Framework Manual for some code examples and the API Documentation for the available methods.

There are different ways to do this:

  • Pass a file name to Zend_Reflection_File.
  • Pass an object to Zend_Reflection_Class.
  • Pass an object and a method name to Zend_Reflection_Method.
  • If you really only have the comment string at hand, you even could throw together the code for a small dummy class, save it to a temporary file and pass that file to Zend_Reflection_File.

Let’s go for the simple case and assume you have an existing class you want to inspect.

The code would be like this (untested, please forgive me):

$method = new Zend_Reflection_Method($class, 'yourMethod');
$docblock = $method->getDocBlock();

if ($docBlock->hasTag('return')) {
    $tagReturn = $docBlock->getTag('return'); // $tagReturn is an instance of Zend_Reflection_Docblock_Tag_Return
    echo "Returns a: " . $tagReturn->getType() . "<br>";
    echo "Comment for return type: " . $tagReturn->getDescription();
}

Answered By – Matthias Zeis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published