|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +/** |
| 6 | + * This file is part of phpDocumentor. |
| 7 | + * |
| 8 | + * For the full copyright and license information, please view the LICENSE |
| 9 | + * file that was distributed with this source code. |
| 10 | + * |
| 11 | + * @link https://phpdoc.org |
| 12 | + */ |
| 13 | + |
| 14 | +namespace phpDocumentor\Guides\RestructuredText\Directives; |
| 15 | + |
| 16 | +use phpDocumentor\Guides\Nodes\AuthorNode; |
| 17 | +use phpDocumentor\Guides\Nodes\Node; |
| 18 | +use phpDocumentor\Guides\RestructuredText\Parser\BlockContext; |
| 19 | +use phpDocumentor\Guides\RestructuredText\Parser\Directive; |
| 20 | +use Psr\Log\LoggerInterface; |
| 21 | + |
| 22 | +use function preg_match; |
| 23 | + |
| 24 | +final class SectionauthorDirective extends BaseDirective |
| 25 | +{ |
| 26 | + public const NAME_EMAIL_REGEX = '/^(?P<name>[\w\s]+)(?: <(?P<email>[^>]+)>)?$/'; |
| 27 | + |
| 28 | + public function __construct( |
| 29 | + private readonly LoggerInterface $logger, |
| 30 | + ) { |
| 31 | + } |
| 32 | + |
| 33 | + public function getName(): string |
| 34 | + { |
| 35 | + return 'sectionauthor'; |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * When the default domain contains a class directive, this directive will be shadowed. Therefore, Sphinx re-exports it as rst-class. |
| 40 | + * |
| 41 | + * See https://www.sphinx-doc.org/en/master/usage/restructuredtext/basics.html#rstclass |
| 42 | + * |
| 43 | + * @return string[] |
| 44 | + */ |
| 45 | + public function getAliases(): array |
| 46 | + { |
| 47 | + return ['codeauthor']; |
| 48 | + } |
| 49 | + |
| 50 | + /** {@inheritDoc} |
| 51 | + * |
| 52 | + * @param Directive $directive |
| 53 | + */ |
| 54 | + public function process( |
| 55 | + BlockContext $blockContext, |
| 56 | + Directive $directive, |
| 57 | + ): Node|null { |
| 58 | + $input = $directive->getData(); |
| 59 | + $directiveName = $directive->getName(); |
| 60 | + if ($input === '') { |
| 61 | + $this->logger->warning('`.. ' . $directiveName . ' ::` directive could not be parsed: `' . $input . '`', $blockContext->getLoggerInformation()); |
| 62 | + |
| 63 | + return null; |
| 64 | + } |
| 65 | + |
| 66 | + if (!preg_match(self::NAME_EMAIL_REGEX, $input, $matches)) { |
| 67 | + $this->logger->warning('Content of `.. ' . $directiveName . ':: name <email>` must specify a name and can also specify an email', $blockContext->getLoggerInformation()); |
| 68 | + |
| 69 | + return null; |
| 70 | + } |
| 71 | + |
| 72 | + $name = $matches['name']; |
| 73 | + $email = $matches['email'] ?? null; |
| 74 | + $context = match ($directiveName) { |
| 75 | + 'sectionauthor' => AuthorNode::CONTEXT_SECTION, |
| 76 | + default => AuthorNode::CONTEXT_CODE, |
| 77 | + }; |
| 78 | + |
| 79 | + return new AuthorNode($name, [], $context, $email); |
| 80 | + } |
| 81 | +} |
0 commit comments