-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMarkdownProcessor.php
More file actions
180 lines (143 loc) · 5.64 KB
/
MarkdownProcessor.php
File metadata and controls
180 lines (143 loc) · 5.64 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
<?php
namespace Dandy\Book;
use Illuminate\Support\Str;
use JoliTypo\Fixer;
use Laravelsu\Highlight\Languages\Shell\ShellLanguage;
use League\CommonMark\Environment\Environment;
use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension;
use League\CommonMark\Extension\GithubFlavoredMarkdownExtension;
use League\CommonMark\Extension\TaskList\TaskListExtension;
use League\CommonMark\MarkdownConverter;
use Symfony\Component\DomCrawler\Crawler;
use Tempest\Highlight\CommonMark\HighlightExtension;
use Tempest\Highlight\Highlighter;
use Tempest\Highlight\Themes\InlineTheme;
use Vanderlee\Syllable\Syllable;
class MarkdownProcessor
{
protected MarkdownConverter $converter;
/**
* Initialize the Markdown converter with required extensions and renderers.
*/
public function __construct()
{
$environment = new Environment();
$environment->addExtension(new CommonMarkCoreExtension());
$environment->addExtension(new GithubFlavoredMarkdownExtension());
$environment->addExtension(new TaskListExtension());
$highlighter = new Highlighter(new InlineTheme(__DIR__.'/../assets/hightlight.css'));
$highlighter->addLanguage(
new ShellLanguage,
);
$environment->addExtension(new HighlightExtension($highlighter));
$this->converter = new MarkdownConverter($environment);
}
/**
* Convert markdown into PDF-ready HTML with typography and hyphenation.
*/
public function convert(string $markdown, int $index): string
{
$html = $this->converter->convert($markdown);
$html = $this->prepareForPdf($html, $index);
$fixer = new Fixer([
'Ellipsis',
'Dimension',
'Unit',
'Dash',
'SmartQuotes',
'NoSpaceBeforeComma',
'CurlyQuote',
'Trademark',
]);
$fixer->setLocale('ru');
$crawler = new Crawler($html);
$crawler
->filter('p,li')
->each(function (Crawler $elm) use ($fixer, &$html) {
$content = $elm->html();
$paragraph = $fixer->fix($content);
$html = Str::of($html)->replace($content, $paragraph);
$t = new \Akh\Typograf\Typograf();
$html = $t->apply($html);
});
$crawler
->filter('p,li')
->each(function (Crawler $elm) use (&$html) {
$content = $elm->html();
$paragraph = $this->preventShortWordOrphans($content, 4);
$html = Str::of($html)->replace($content, $paragraph);
});
$syllable = new Syllable('ru');
$syllable->setCache(null);
$syllable->setMinWordLength(2);
$html = $syllable->hyphenateHtmlText($html);
$html = Str::of($html)
->replace('✓', '<span style="font-family: dejavusans;">✓</span>')
->replace('✗', '<span style="font-family: dejavusans;">✗</span>')
->replace('TODO:', '<span style="font-weight: bold;">TODO:</span>')
->replace('HACK:', '<span style="font-weight: bold;">HACK:</span>')
->replace('FIXME:', '<span style="font-weight: bold;">FIXME:</span>');
$syllable->setLanguage('en-us');
return $syllable->hyphenateHtmlText($html);
}
protected function preventShortWordOrphans(string $text, int $maxLength = 2): string
{
// Регулярка ищет слова длиной <= maxLength перед пробелом или переносом строки
// \b — граница слова, \w{1,maxLength} — слово длиной 1 до maxLength букв
// \s+ — пробелы после слова
$pattern = '/\b(\w{1,'.$maxLength.'})\s+/u';
// Заменяем пробелы на неразрывный пробел
$replacement = '$1 ';
return preg_replace($pattern, $replacement, $text);
}
protected function wrapHeadersWithParagraphs(string $html): string
{
return Str::of($html)->replaceMatches(
'/<(h[1-6])([^>]*)>(.*?)<\/\1>\s*<p([^>]*)>(.*?)<\/p>/is',
function ($match) {
$headingTag = $match[1];
$headingAttr = $match[2];
$headingContent = $match[3];
$pAttr = $match[4];
$pContent = $match[5];
return '<div keep_block_together>'
."<$headingTag$headingAttr>$headingContent</$headingTag>"
."<p$pAttr>$pContent</p>"
.'</div>';
}
)
->toString();
}
/**
* Prepare HTML for PDF rendering (styling, breaks, and custom blocks).
*/
protected function prepareForPdf(string $html, int $index): string
{
$html = $this->wrapHeadersWithParagraphs($html);
$html = str_replace('<h1>', <<<'HTML'
<span style="display: block;"></span>
<div class="chapter-padding">
<table class="chapter-table">
<tr class="chapter-row">
<td class="chapter-icon-cell">>_</td>
<td class="chapter-cell"></td>
<td class="chapter-cell"></td>
</tr>
</table>
</div>
<h1>
HTML, $html);
$html = str_replace([
"<blockquote>\n<p>{notice}",
"<blockquote>\n<p>{warning}",
"<blockquote>\n<p>{quote}",
'[break]',
], [
"<blockquote class='notice'><p>",
"<blockquote class='warning'><p>",
"<blockquote class='quote'><p>",
'<div style="page-break-after: always;"></div>',
], $html);
return $html;
}
}