1 | <?php |
||
7 | class PreformattedConverter implements ConverterInterface |
||
8 | { |
||
9 | /** |
||
10 | * @param ElementInterface $element |
||
11 | * |
||
12 | * @return string |
||
13 | */ |
||
14 | 12 | public function convert(ElementInterface $element) |
|
15 | { |
||
16 | // Store the content of the code block in an array, one entry for each line |
||
17 | |||
18 | 12 | $markdown = ''; |
|
19 | |||
20 | 12 | $code_content = html_entity_decode($element->getChildrenAsString()); |
|
21 | 12 | $code_content = str_replace(array('<code>', '</code>'), '', $code_content); |
|
22 | 12 | $code_content = str_replace(array('<pre>', '</pre>'), '', $code_content); |
|
23 | |||
24 | 12 | $lines = preg_split('/\r\n|\r|\n/', $code_content); |
|
25 | 12 | $total = count($lines); |
|
26 | |||
27 | // If there's more than one line of code, prepend each line with four spaces and no backticks. |
||
28 | 12 | if ($total > 1 || $element->getTagName() === 'pre') { |
|
29 | // Remove the first and last line if they're empty |
||
30 | 6 | $first_line = trim($lines[0]); |
|
31 | 6 | $last_line = trim($lines[$total - 1]); |
|
32 | 6 | $first_line = trim($first_line, '
'); //trim XML style carriage returns too |
|
33 | 6 | $last_line = trim($last_line, '
'); |
|
34 | |||
35 | 6 | if (empty($first_line)) { |
|
36 | array_shift($lines); |
||
37 | } |
||
38 | |||
39 | 6 | if (empty($last_line)) { |
|
40 | 3 | array_pop($lines); |
|
41 | 3 | } |
|
42 | |||
43 | 6 | $count = 1; |
|
44 | 6 | foreach ($lines as $line) { |
|
45 | 6 | $line = str_replace('
', '', $line); |
|
46 | 6 | $markdown .= ' ' . $line; |
|
47 | // Add newlines, except final line of the code |
||
48 | 6 | if ($count !== $total) { |
|
49 | 3 | $markdown .= "\n"; |
|
50 | 3 | } |
|
51 | 6 | $count++; |
|
52 | 6 | } |
|
53 | 6 | $markdown .= "\n"; |
|
54 | 6 | } else { |
|
55 | // There's only one line of code. It's a code span, not a block. Just wrap it with backticks. |
||
56 | 6 | $markdown .= '`' . $lines[0] . '`'; |
|
57 | } |
||
58 | |||
59 | 12 | if ($element->getTagName() === 'pre') { |
|
60 | 3 | $markdown = "\n" . $markdown . "\n"; |
|
61 | 3 | } |
|
62 | |||
63 | 12 | return $markdown; |
|
64 | } |
||
65 | |||
66 | /** |
||
67 | * @return string[] |
||
68 | */ |
||
69 | 78 | public function getSupportedTags() |
|
73 | } |
||
74 |