From a82cc3b9b6187501a6cfab3b986b2a28e96b6c68 Mon Sep 17 00:00:00 2001 From: upstream Date: Sat, 3 Oct 2026 02:27:25 +0200 Subject: [PATCH] Upstream thephpleague/html-to-markdown state of the touched files before f345fb4bc5 --- src/Converter/LinkConverter.php | 77 +++++++++++++++++++++++++++++++++ tests/HtmlConverterTest.php | 4 -- 2 files changed, 77 insertions(+), 4 deletions(-) create mode 100644 src/Converter/LinkConverter.php diff --git a/src/Converter/LinkConverter.php b/src/Converter/LinkConverter.php new file mode 100644 index 0000000..f0ba157 --- /dev/null +++ b/src/Converter/LinkConverter.php @@ -0,0 +1,77 @@ +config = $config; + } + + public function convert(ElementInterface $element): string + { + $href = $element->getAttribute('href'); + $title = $element->getAttribute('title'); + $text = \trim($element->getValue(), "\t\n\r\0\x0B"); + + if ($title !== '') { + $markdown = '[' . $text . '](' . $href . ' "' . $title . '")'; + } elseif ($href === $text && $this->isValidAutolink($href)) { + $markdown = '<' . $href . '>'; + } elseif ($href === 'mailto:' . $text && $this->isValidEmail($text)) { + $markdown = '<' . $text . '>'; + } else { + if (\stristr($href, ' ')) { + $href = '<' . $href . '>'; + } + + $markdown = '[' . $text . '](' . $href . ')'; + } + + if (! $href) { + if ($this->shouldStrip()) { + $markdown = $text; + } else { + $markdown = \html_entity_decode($element->getChildrenAsString()); + } + } + + return $markdown; + } + + /** + * @return string[] + */ + public function getSupportedTags(): array + { + return ['a']; + } + + private function isValidAutolink(string $href): bool + { + $useAutolinks = $this->config->getOption('use_autolinks'); + + return $useAutolinks && (\preg_match('/^[A-Za-z][A-Za-z0-9.+-]{1,31}:[^<>\x00-\x20]*/i', $href) === 1); + } + + private function isValidEmail(string $email): bool + { + // Email validation is messy business, but this should cover most cases + return \filter_var($email, FILTER_VALIDATE_EMAIL) !== false; + } + + private function shouldStrip(): bool + { + return \boolval($this->config->getOption('strip_placeholder_links') ?? false); + } +} diff --git a/tests/HtmlConverterTest.php b/tests/HtmlConverterTest.php index 816a491..e62247e 100644 --- a/tests/HtmlConverterTest.php +++ b/tests/HtmlConverterTest.php @@ -134,10 +134,6 @@ class HtmlConverterTest extends TestCase public function testImage(): void { $this->assertHtmlGivesMarkdown('alt text', '![alt text](/path/img.jpg "Title")'); - $this->assertHtmlGivesMarkdown("\n

A new header

", "![](a.png)\n\n### A new header"); - $this->assertHtmlGivesMarkdown('

Paragraph

', "![](a.png)\n\nParagraph"); - $this->assertHtmlGivesMarkdown('

A new header

', "[![](a.png)](b.html)\n\n### A new header"); - $this->assertHtmlGivesMarkdown('

Paragraph

', "> ![](a.png)\n> \n> Paragraph"); } public function testAnchor(): void