1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace League\HTMLToMarkdown\Converter; |
4
|
|
|
|
5
|
|
|
use League\HTMLToMarkdown\ElementInterface; |
6
|
|
|
|
7
|
|
|
class PreformattedConverter implements ConverterInterface |
8
|
|
|
{ |
9
|
|
|
/** |
10
|
|
|
* @param ElementInterface $element |
11
|
|
|
* |
12
|
|
|
* @return string |
13
|
|
|
*/ |
14
|
6 |
|
public function convert(ElementInterface $element) |
15
|
|
|
{ |
16
|
6 |
|
$markdown = ''; |
17
|
|
|
|
18
|
6 |
|
$code_content = html_entity_decode($element->getChildrenAsString()); |
19
|
6 |
|
$code_content = str_replace(array('<pre>', '</pre>'), '', $code_content); |
20
|
|
|
|
21
|
|
|
/* |
22
|
|
|
* Checking for the code tag. |
23
|
|
|
* Usually pre tags are used along with code tags. This conditional will check for converted code tags, |
24
|
|
|
* which use backticks, and if those backticks are at the beginning and at the end of the string it means |
25
|
|
|
* there's no more information to convert. |
26
|
|
|
*/ |
27
|
|
|
|
28
|
6 |
|
$firstBacktick = strpos(trim($code_content), '`'); |
29
|
6 |
|
$lastBacktick = strrpos(trim($code_content), '`'); |
30
|
6 |
|
if ($firstBacktick === 0 && $lastBacktick === strlen(trim($code_content)) - 1) { |
31
|
3 |
|
return $code_content; |
32
|
|
|
} |
33
|
|
|
|
34
|
|
|
/* |
35
|
|
|
* If the execution reaches this point it means either the pre tag has more information besides the one inside |
36
|
|
|
* the code tag or there's no code tag. |
37
|
|
|
*/ |
38
|
|
|
|
39
|
|
|
// Store the content of the code block in an array, one entry for each line |
40
|
3 |
|
$lines = preg_split('/\r\n|\r|\n/', $code_content); |
41
|
|
|
|
42
|
|
|
// Checking if the string has multiple lines |
43
|
3 |
|
if (count($lines) > 1) { |
44
|
|
|
// Multiple lines detected, adding three backticks and newlines |
45
|
3 |
|
$markdown .= '```' . "\n" . $code_content . "\n" . '```'; |
46
|
3 |
|
} else { |
47
|
|
|
// One line of code, wrapping it on one backtick. |
48
|
|
|
$markdown .= '`' . ' ' . $code_content . '`'; |
49
|
|
|
} |
50
|
|
|
|
51
|
3 |
|
return $markdown; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @return string[] |
56
|
|
|
*/ |
57
|
78 |
|
public function getSupportedTags() |
58
|
|
|
{ |
59
|
78 |
|
return array('pre'); |
60
|
|
|
} |
61
|
|
|
} |
62
|
|
|
|