]> git.mxchange.org Git - friendica.git/blob - vendor/league/html-to-markdown/src/Converter/PreformattedConverter.php
Move HTML to Markdown library to Composer
[friendica.git] / vendor / league / html-to-markdown / src / Converter / PreformattedConverter.php
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     public function convert(ElementInterface $element)
15     {
16         $markdown = '';
17
18         $pre_content = html_entity_decode($element->getChildrenAsString());
19         $pre_content = str_replace(array('<pre>', '</pre>'), '', $pre_content);
20
21         /*
22          * Checking for the code tag.
23          * Usually pre tags are used along with code tags. This conditional will check for already 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         $firstBacktick = strpos(trim($pre_content), '`');
29         $lastBacktick = strrpos(trim($pre_content), '`');
30         if ($firstBacktick === 0 && $lastBacktick === strlen(trim($pre_content)) - 1) {
31             return $pre_content;
32         }
33
34         // If the execution reaches this point it means it's just a pre tag, with no code tag nested
35
36         // Normalizing new lines
37         $pre_content = preg_replace('/\r\n|\r|\n/', PHP_EOL, $pre_content);
38
39         // Checking if the string has multiple lines
40         $lines = preg_split('/\r\n|\r|\n/', $pre_content);
41         if (count($lines) > 1) {
42             // Multiple lines detected, adding three backticks and newlines
43             $markdown .= '```' . "\n" . $pre_content . "\n" . '```';
44         } else {
45             // One line of code, wrapping it on one backtick.
46             $markdown .= '`' . $pre_content . '`';
47         }
48
49         return $markdown;
50     }
51
52     /**
53      * @return string[]
54      */
55     public function getSupportedTags()
56     {
57         return array('pre');
58     }
59 }