|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Hyde\Framework\Actions; |
|
4
|
|
|
|
|
5
|
|
|
use Hyde\Framework\Contracts\ActionContract; |
|
6
|
|
|
use League\CommonMark\Environment\Environment; |
|
7
|
|
|
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; |
|
8
|
|
|
use League\CommonMark\Extension\HeadingPermalink\HeadingPermalinkExtension; |
|
9
|
|
|
use League\CommonMark\Extension\TableOfContents\TableOfContentsExtension; |
|
10
|
|
|
use League\CommonMark\MarkdownConverter; |
|
|
|
|
|
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* Generates a table of contents for the Markdown document. |
|
14
|
|
|
* |
|
15
|
|
|
* @see \Hyde\Framework\Testing\Feature\Actions\GeneratesSidebarTableOfContentsTest |
|
16
|
|
|
*/ |
|
17
|
|
|
class GeneratesSidebarTableOfContents implements ActionContract |
|
18
|
|
|
{ |
|
19
|
|
|
protected string $markdown; |
|
20
|
|
|
|
|
21
|
|
|
public function __construct(string $markdown) |
|
22
|
|
|
{ |
|
23
|
|
|
$this->markdown = $markdown; |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
|
|
public function execute(): string |
|
27
|
|
|
{ |
|
28
|
|
|
$config = [ |
|
29
|
|
|
'table_of_contents' => [ |
|
30
|
|
|
'html_class' => 'table-of-contents', |
|
31
|
|
|
'position' => 'top', |
|
32
|
|
|
'style' => 'bullet', |
|
33
|
|
|
'min_heading_level' => config('docs.table_of_contents.min_heading_level', 2), |
|
34
|
|
|
'max_heading_level' => config('docs.table_of_contents.max_heading_level', 4), |
|
35
|
|
|
'normalize' => 'relative', |
|
36
|
|
|
], |
|
37
|
|
|
'heading_permalink' => [ |
|
38
|
|
|
'fragment_prefix' => '', |
|
39
|
|
|
], |
|
40
|
|
|
]; |
|
41
|
|
|
|
|
42
|
|
|
$environment = new Environment($config); |
|
43
|
|
|
$environment->addExtension(new CommonMarkCoreExtension()); |
|
44
|
|
|
$environment->addExtension(new HeadingPermalinkExtension()); |
|
45
|
|
|
$environment->addExtension(new TableOfContentsExtension()); |
|
46
|
|
|
|
|
47
|
|
|
$converter = new MarkdownConverter($environment); |
|
48
|
|
|
$html = $converter->convert("[[END_TOC]]\n".$this->markdown)->getContent(); |
|
49
|
|
|
|
|
50
|
|
|
// Return everything before the [[END_TOC]] marker. |
|
51
|
|
|
return substr($html, 0, strpos($html, '<p>[[END_TOC]]')); |
|
52
|
|
|
} |
|
53
|
|
|
} |
|
54
|
|
|
|
Let?s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let?s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: