This feature is still under development and only available in the nightly docker builds.
Custom directives
RestructuredText supports directives, blocks of the
form .. name:: data
that can be used to extend the markup language with new behavior. phpDocumentor ships with
directives for things like .. toctree::
and .. code-block::
, and you can add your own through an extension.
read first how to setup an phpDocumentor extension before you continue this guide.
In our example we will create a .. hello::
directive that takes a name and greets it, e.g.:
.. hello:: World
A directive is a plain PHP class that extends . It needs a name, and it turns the parsed directive into a node:
<?php
declare(strict_types=1);
namespace phpDocumentor\Example\Directives;
use phpDocumentor\Example\Nodes\HelloNode;
use phpDocumentor\Guides\Nodes\Node;
use phpDocumentor\Guides\RestructuredText\Directives\BaseDirective;
use phpDocumentor\Guides\RestructuredText\Parser\BlockContext;
use phpDocumentor\Guides\RestructuredText\Parser\Directive;
final class HelloDirective extends BaseDirective
{
public function getName(): string
{
return 'hello';
}
public function processNode(BlockContext $blockContext, Directive $directive): Node
{
return new HelloNode($directive->getData());
}
}
getName()returns the name that is used in the RST syntax, in our casehello.processNode()is called by the parser with the parsed (containing the data and options that were written after the directive) and returns the node that represents it in the document tree.
Need access to the raw options that were passed to the directive (:option: value
)? They are available
through $directive->getOptions()
, $directive->getOptionString()
, $directive->getOptionBool()
and
$directive->getOptionInt()
.
Register the directive
Like any other service, the directive needs to be registered in the container and tagged with
phpdoc.guides.directive
so that the parser can find it:
<?php
declare(strict_types=1);
use phpDocumentor\Example\Directives\HelloDirective;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $container): void {
$container->services()
->defaults()
->autowire()
->autoconfigure()
->set(HelloDirective::class)
->tag('phpdoc.guides.directive')
;
};
Once this is loaded, phpDocumentor will recognise .. hello::
while parsing RestructuredText documents. The next
step is to make sure the node it produces can also be rendered, which is covered in Custom nodes and
Node templates.