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
|
9 |
|
public function convert(ElementInterface $element) |
15
|
|
|
{ |
16
|
9 |
|
$pre_content = html_entity_decode($element->getChildrenAsString()); |
17
|
9 |
|
$pre_content = str_replace(array('<pre>', '</pre>'), '', $pre_content); |
18
|
|
|
|
19
|
|
|
/* |
20
|
|
|
* Checking for the code tag. |
21
|
|
|
* Usually pre tags are used along with code tags. This conditional will check for already converted code tags, |
22
|
|
|
* which use backticks, and if those backticks are at the beginning and at the end of the string it means |
23
|
|
|
* there's no more information to convert. |
24
|
|
|
*/ |
25
|
|
|
|
26
|
9 |
|
$firstBacktick = strpos(trim($pre_content), '`'); |
27
|
9 |
|
$lastBacktick = strrpos(trim($pre_content), '`'); |
28
|
9 |
|
if ($firstBacktick === 0 && $lastBacktick === strlen(trim($pre_content)) - 1) { |
29
|
6 |
|
return $pre_content . "\n\n"; |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
// If the execution reaches this point it means it's just a pre tag, with no code tag nested |
33
|
|
|
|
34
|
|
|
// Empty lines are a special case |
35
|
3 |
|
if ($pre_content === '') { |
36
|
3 |
|
return "```\n```\n\n"; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
// Normalizing new lines |
40
|
3 |
|
$pre_content = preg_replace('/\r\n|\r|\n/', "\n", $pre_content); |
41
|
|
|
|
42
|
|
|
// Ensure there's a newline at the end |
43
|
3 |
|
if (strrpos($pre_content, "\n") !== strlen($pre_content) - strlen("\n")) { |
44
|
3 |
|
$pre_content .= "\n"; |
45
|
2 |
|
} |
46
|
|
|
|
47
|
|
|
// Use three backticks |
48
|
3 |
|
return "```\n" . $pre_content . "```\n\n"; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
/** |
52
|
|
|
* @return string[] |
53
|
|
|
*/ |
54
|
84 |
|
public function getSupportedTags() |
55
|
|
|
{ |
56
|
84 |
|
return array('pre'); |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|