Skip to content

Extending

Custom tags

No tag is special to the parser: @param, @see and a tag of your own are declared the same way. A tag takes three parts:

@money 100 USD The price
MoneyTag the object a line becomes
MoneyTagDefinition the grammar of the line and how the tag is created
MoneyPlatform registers the definition in the parser

A tag is a value object of what the line holds:

use TypeLang\PhpDoc\DocBlock\Tag\Tag;
final class MoneyTag extends Tag
{
public function __construct(
string $name,
public readonly int $amount,
public readonly string $currency,
?DescriptionInterface $description = null,
) {
parent::__construct($name, $description);
}
}

A definition declares the grammar of the line and creates the tag from what the grammar captured:

use TypeLang\PhpDoc\DocBlock\TagDefinition\Spec;
use TypeLang\PhpDoc\DocBlock\TagDefinition\TagDefinition;
use TypeLang\PhpDoc\DocBlock\TagDefinition\TagPayload;
final class MoneyTagDefinition extends TagDefinition
{
public function __construct()
{
// "@money" <Amount> <Currency> [ <Description> ]
parent::__construct('money', Spec::sequence(
Spec::rule(IntegerCombinator::NAME, 'amount', 'Amount'),
Spec::rule(NameCombinator::NAME, 'currency', 'Currency'),
Spec::maybe(
Spec::rule(DescriptionCombinator::NAME, 'description'),
),
));
}
public function create(string $name, TagPayload $result): MoneyTag
{
return new MoneyTag(
name: $name,
amount: $result->get('amount'),
currency: $result->get('currency'),
description: $result->find('description'),
);
}
}

Spec::rule() takes the combinator that reads the part of the line, the alias its value is captured under and the name it has in the printed grammar.

A platform registers the definition:

use TypeLang\PhpDoc\DocBlockParser;
use TypeLang\PhpDoc\Platform\Platform;
final class MoneyPlatform extends Platform
{
public function getTags(): iterable
{
return ['money' => new MoneyTagDefinition()];
}
}
$parser = DocBlockParser::createDefault(additionalPlatforms: [
new MoneyPlatform(),
]);
$block = $parser->parse('/** @money 100 USD The price */');
$block[0]; // MoneyTag { amount: 100, currency: 'USD' }