Use DocBlox in Symfony2 for inspecting DocComment blocks
Matthias Noback
I was looking for a way to automatically generate some documentation, and because all the required information was already in the DocComment
blocks. I downloaded the great documentation generator DocBlox (which is a PHP application by itself) and looked in it’s source code. Soon I found DocBlox’s Reflection
classes which are able to parse a DocComment
block. So I wanted to use these classes! Here is how you can do it:
-
Download the latest DocBlox zip file
-
Unzip the archive
-
Create the directory
/vendor/docblox/src/DocBlox
in your Symfony2 project -
From the archive:
* copy `/src/DocBlox/Reflection` and it's contents to the directory you have just created
* copy `/src/markdown.php` and the directory `/src/markdown` and it's contents to `/src/vendor/docblox/src`
* Copy `/LICENSE` to `/vendor/docblox`
Now your directory structure should look like:
/vendor
/docblox
/src
/DocBlox
/Reflection/*
/markdown/*
/markdown.php
/LICENSE
The license requires you to copy it with the code, even if you use part of it.
Now open /app/autoload.php
and add the “DocBlox_” prefix to the autoloader:
$loader->registerPrefixes(array(
'Twig_Extensions_' => __DIR__.'/../vendor/twig-extensions/lib',
'Twig_' => __DIR__.'/../vendor/twig/lib',
// ...
'DocBlox_' => __DIR__.'/../vendor/docblox/src',
));
Also add this line to /app/autoload.php
:
require_once __DIR__.'/../vendor/docblox/src/markdown.php';
This will enable you to use Markdown formatting in your DocBlocks
.
The DocBlox reflection classes are now available in your project. I tested my configuration by creating the following action, which displays the type and description of it’s own return value:
/**
* Displays it's own "return" tag
*
* The "docBlox" action uses the DocBlox "DocBlock" reflection class
*
* @return Symfony\Component\HttpFoundation\Response The response
*/
public function docBloxAction()
{
$reflectionMethod = new \ReflectionMethod($this, 'docBloxAction');
$docBlock = new \DocBlox_Reflection_DocBlock($reflectionMethod);
$returns = $docBlock->getTagsByName('return');
if (!empty($returns)) {
$return = reset($returns); // get the first "return" tag
/* @var $return DocBlox_Reflection_DocBlock_Tag_Return */
$type = $return->getType();
$description = $return->getDescription();
return new Response(sprintf('This method returns a %s which is %s', $type, lcfirst($description)));
}
return new Response('No return parameter was defined');
}
As you can see, there is a limitation to the API of DocBlox: there is no getTag() method, only a getTags() and a getTagsByName() method, that both return an array. So you will have to reduce this to one tag yourself (for example by calling reset() on the array).
When this action is called, it renders the following text:
This method returns a Symfony\Component\HttpFoundation\Response which is the response