-
-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathMarkdownRuntime.php
More file actions
76 lines (63 loc) · 1.94 KB
/
Copy pathMarkdownRuntime.php
File metadata and controls
76 lines (63 loc) · 1.94 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
<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extra\Markdown;
class MarkdownRuntime
{
private $converter;
public function __construct(MarkdownInterface $converter)
{
$this->converter = $converter;
}
public function convert(string $body): string
{
return $this->converter->convert(self::stripCommonIndentation($body));
}
/**
* Removes the indentation shared by all non-blank lines.
*
* This lets authors indent a `{% apply markdown_to_html %}` block to match
* the surrounding template without that indentation leaking into Markdown
* (where leading whitespace is significant, e.g. code blocks).
*/
private static function stripCommonIndentation(string $body): string
{
$lines = explode("\n", $body);
$indent = null;
foreach ($lines as $line) {
if ('' === trim($line)) {
continue;
}
$lineIndent = substr($line, 0, strspn($line, " \t"));
if (null === $indent) {
$indent = $lineIndent;
continue;
}
$max = min(\strlen($indent), \strlen($lineIndent));
$common = 0;
while ($common < $max && $indent[$common] === $lineIndent[$common]) {
++$common;
}
$indent = substr($indent, 0, $common);
if ('' === $indent) {
return $body;
}
}
if (null === $indent || '' === $indent) {
return $body;
}
$length = \strlen($indent);
foreach ($lines as $i => $line) {
if (str_starts_with($line, $indent)) {
$lines[$i] = substr($line, $length);
}
}
return implode("\n", $lines);
}
}