Search code examples
jsonphpdocabstract-syntax-treejsduck

Parsing phpdoc to JSON


I would like to find a way to use phpdoc2 to parse PHP projects into JSON rather than into Abstract Syntax Tree XML. Although of course I could just parse the XML into JSON, it seems that creating XML would be unnecessary overhead here.

So, in a nut shell, the question is: is there an easy way to configure phpdoc2's parser to directly produce JSON instead of XML? Or maybe some clues on what to extend in phpdoc2 to route the parsing output into JSON?

The story behind this question is: I would like to create JSDuck-like documentation for my PHP project. Although I have found that JSDuck can be used with PHP projects I won't go that way for the two reasons:

  1. Don't want to part with phpdoc comments in my PHP classes or add something JSDuck-specific in there;
  2. Don't really need the whole JSDuck doc interface as I am going to create a very custom one myself;
  3. Prefer a PHP solution.

Solution

  • After half a day spent on phpdoc2 I finally found a solution which I believe is the right one. One should not worry or even know about Abstract Syntax Tree XML in phpdoc2 to achieve the goal.

    The solution is:

    Create a new writer class Json.php and place it in src/phpDocumentor/Plugin/Core/Transformer/Writer/ along with other writers. A good start point is to take the Graph.php writer and rewrite it to output JSON instead of SVG;

    Create and use a new simple template like:

    <?xml version="1.0" encoding="utf-8"?>
    <template>
        <transformations>
            <transformation writer="Json" artifact="classes.json" />
        </transformations>
    </template>
    

    Add Json writer to src/phpDocumentor/Plugin/Core/ServiceProvider.php's register method:

    $writerCollection['Json'] = new Writer\Json();
    

    And finally, just use the template when calling phpdoc on your project.