|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Markdown\Symbols; |
| 4 | + |
| 5 | +use League\CommonMark\Extension\CommonMark\Node\Inline\Code; |
| 6 | +use League\CommonMark\Extension\CommonMark\Node\Inline\Link; |
| 7 | +use League\CommonMark\Parser\Inline\InlineParserInterface; |
| 8 | +use League\CommonMark\Parser\Inline\InlineParserMatch; |
| 9 | +use League\CommonMark\Parser\InlineParserContext; |
| 10 | + |
| 11 | +use function Tempest\Support\str; |
| 12 | +use function Tempest\Support\Str\class_basename; |
| 13 | +use function Tempest\Support\Str\strip_start; |
| 14 | + |
| 15 | +final readonly class AttributeParser implements InlineParserInterface |
| 16 | +{ |
| 17 | + #[\Override] |
| 18 | + public function getMatchDefinition(): InlineParserMatch |
| 19 | + { |
| 20 | + return InlineParserMatch::regex("{(b)?`#\[((?:\\\{1,2}\w+|\w+\\\{1,2})(?:\w+\\\{0,2})+)\]`}"); |
| 21 | + } |
| 22 | + |
| 23 | + #[\Override] |
| 24 | + public function parse(InlineParserContext $inlineContext): bool |
| 25 | + { |
| 26 | + $cursor = $inlineContext->getCursor(); |
| 27 | + $previousChar = $cursor->peek(-1); |
| 28 | + |
| 29 | + if ($previousChar !== null && $previousChar !== ' ') { |
| 30 | + return false; |
| 31 | + } |
| 32 | + |
| 33 | + $cursor->advanceBy($inlineContext->getFullMatchLength()); |
| 34 | + |
| 35 | + [$flag, $fqcn] = $inlineContext->getSubMatches(); |
| 36 | + $url = str($fqcn) |
| 37 | + ->stripStart(['\\Tempest\\', 'Tempest\\']) |
| 38 | + ->replaceRegex("/^(\w+)/", 'src/Tempest/$0/src') |
| 39 | + ->replace('\\', '/') |
| 40 | + ->prepend('https://github.com/tempestphp/tempest-framework/blob/main/') |
| 41 | + ->append('.php'); |
| 42 | + |
| 43 | + $attribute = str($fqcn) |
| 44 | + ->stripStart('\\') |
| 45 | + ->when($flag === 'b', fn ($s) => $s->classBasename()) |
| 46 | + ->wrap(before: '#[', after: ']') |
| 47 | + ->toString(); |
| 48 | + |
| 49 | + $link = new Link($url); |
| 50 | + $link->appendChild(new Code($attribute)); |
| 51 | + $inlineContext->getContainer()->appendChild($link); |
| 52 | + |
| 53 | + return true; |
| 54 | + } |
| 55 | +} |
0 commit comments