|
| 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 | +use Override; |
| 11 | +use ReflectionFunction; |
| 12 | +use Tempest\Support\Str\ImmutableString; |
| 13 | +use Throwable; |
| 14 | + |
| 15 | +use function Tempest\Support\str; |
| 16 | + |
| 17 | +final readonly class FunctionParser implements InlineParserInterface |
| 18 | +{ |
| 19 | + #[Override] |
| 20 | + public function getMatchDefinition(): InlineParserMatch |
| 21 | + { |
| 22 | + return InlineParserMatch::regex("{(b)?`((?:\\\{1,2}\w+|\w+\\\{1,2})(?:\w+\\\{0,2})+)\(\)`}"); |
| 23 | + } |
| 24 | + |
| 25 | + #[Override] |
| 26 | + public function parse(InlineParserContext $inlineContext): bool |
| 27 | + { |
| 28 | + $cursor = $inlineContext->getCursor(); |
| 29 | + $previousChar = $cursor->peek(-1); |
| 30 | + |
| 31 | + if ($previousChar !== null && $previousChar !== ' ') { |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + $cursor->advanceBy($inlineContext->getFullMatchLength()); |
| 36 | + |
| 37 | + [$flag, $fqf] = $inlineContext->getSubMatches(); |
| 38 | + |
| 39 | + $reflection = $this->createReflectionFromFqf($fqf); |
| 40 | + $function = str($fqf) |
| 41 | + ->stripStart('\\') |
| 42 | + ->when($flag === 'b', fn (ImmutableString $s) => $s->afterLast('\\')) |
| 43 | + ->append('()') |
| 44 | + ->toString(); |
| 45 | + |
| 46 | + if (! $reflection) { |
| 47 | + $inlineContext->getContainer()->appendChild(new Code($function)); |
| 48 | + |
| 49 | + return true; |
| 50 | + } |
| 51 | + |
| 52 | + $url = str($reflection->getFileName()) |
| 53 | + ->afterLast('tempest/framework/') |
| 54 | + ->prepend('https://github.com/tempestphp/tempest-framework/blob/main/') |
| 55 | + ->append("#L{$reflection->getStartLine()}-L{$reflection->getEndLine()}") |
| 56 | + ->toString(); |
| 57 | + |
| 58 | + $link = new Link($url); |
| 59 | + $link->appendChild(new Code($function)); |
| 60 | + $inlineContext->getContainer()->appendChild($link); |
| 61 | + |
| 62 | + return true; |
| 63 | + } |
| 64 | + |
| 65 | + private function createReflectionFromFqf(string $fqf): ?ReflectionFunction |
| 66 | + { |
| 67 | + try { |
| 68 | + return new ReflectionFunction($fqf); |
| 69 | + } catch (Throwable) { |
| 70 | + return null; |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments