fix redirects
[mdref/mdref] / mdref / Formatter / League.php
1 <?php
2
3 namespace mdref\Formatter;
4
5 use mdref\Exception;
6 use mdref\Formatter;
7
8 use League\CommonMark\Extension;
9 use League\CommonMark\GithubFlavoredMarkdownConverter;
10 use League\CommonMark\Normalizer;
11
12 use function file_get_contents;
13 use function preg_replace;
14
15 class League extends Formatter {
16 private $md;
17
18 function __construct() {
19 $this->md = new GithubFlavoredMarkdownConverter([
20 "slug_normalizer" => [
21 "instance" => new class implements Normalizer\TextNormalizerInterface {
22 function normalize(string $text, $context = null) : string {
23 return preg_replace("/[^[:alnum:]:._-]/", ".", $text);
24 }
25 }
26 ],
27 "heading_permalink" => [
28 "html_class" => "permalink",
29 "id_prefix" => "",
30 "fragment_prefix" => "",
31 "title" => "",
32 "symbol" => "#",
33 "insert" => "after",
34 "min_heading_level" => 2,
35 ]
36 ]);
37 $this->md->getEnvironment()->addExtension(
38 new Extension\DescriptionList\DescriptionListExtension
39 );
40 $this->md->getEnvironment()->addExtension(
41 new Extension\HeadingPermalink\HeadingPermalinkExtension
42 );
43 $this->md->getEnvironment()->addExtension(
44 new Extension\Attributes\AttributesExtension
45 );
46 }
47
48 function formatString(string $string) : string {
49 return $this->md->convertToHtml($string);
50 }
51
52 function formatFile(string $file) : string {
53 $string = file_get_contents($file);
54 if ($string === false) {
55 throw Exception::fromLastError();
56 }
57 return $this->md->convertToHtml($string);
58 }
59 }