Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read comment blocks in PHP?

I'm doing some home-brewed automated documentation, since I have a codebase which is not very standard in its layout, and I was wondering what the best way was to read a PHP file and grab the contents of a comment block. The only way I can think to do it is to open the file and read it line-by-line, but thought that maybe there was some built-in magic that would parse the document for me, similar to the Reflection functions.

The basic layout of each file is like this:

<?php // $Id$
/**
 * Here is this script's documentation, with information in pseudo-javadoc
 * type tags and whatnot.
 *
 * @attr    something    some information about something
 * @attr    etc          etc etc
 */
 // rest of the code goes here.

It's important to note that these files don't have any functions or classes defined in them. The comments relate to the script as a whole.

like image 850
nickf Avatar asked Apr 02 '09 02:04

nickf


2 Answers

Check out Tokenizer.

To get all the comments in a file named test.php you'd do:

$tokens = token_get_all(file_get_contents("test.php"));
$comments = array();
foreach($tokens as $token) {
    if($token[0] == T_COMMENT || $token[0] == T_DOC_COMMENT) {
        $comments[] = $token[1];
    }
}
print_r($comments);
like image 85
Paolo Bergantino Avatar answered Oct 16 '22 11:10

Paolo Bergantino


Have a look at the Reflection API that comes with PHP5, more specifically getDocComment():

PHP 5 comes with a complete reflection API that adds the ability to reverse-engineer classes, interfaces, functions and methods as well as extensions. Additionally, the reflection API also offers ways of retrieving doc comments for functions, classes and methods.

Also, depending on the size of your codebase, you might work less by modifying your comments to fit the phpDocumentor syntax, which is already seems pretty close to.

like image 25
lpfavreau Avatar answered Oct 16 '22 11:10

lpfavreau