Skip to content

Commit a321f3c

Browse files
committed
feat: Collapse multiple newlines to a maximum of two in Telegram HTML conversion and add a corresponding test.
1 parent 1909927 commit a321f3c

File tree

2 files changed

+16
-1
lines changed

2 files changed

+16
-1
lines changed

app/Services/Telegram/TelegramMessageService.php

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,9 @@ private function convertMarkdownToHtml(string $markdown): string
181181
// Strip unsupported tags
182182
// Telegram supports: <b>, <strong>, <i>, <em>, <u>, <ins>, <s>, <strike>, <del>,
183183
// <span class="tg-spoiler">, <a>, <code>, <pre>, <blockquote>
184-
return trim(strip_tags($html, '<b><strong><i><em><u><ins><s><strike><del><a><code><pre><blockquote>'));
184+
$html = strip_tags($html, '<b><strong><i><em><u><ins><s><strike><del><a><code><pre><blockquote>');
185+
186+
// Collapse multiple newlines into max 2
187+
return trim(preg_replace('/\n{3,}/', "\n\n", $html));
185188
}
186189
}

tests/Unit/Services/Telegram/TelegramHtmlConversionTest.php

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,18 @@
3939
->toContain('• Item 2');
4040
});
4141

42+
test('handles complex structure without excessive whitespace', function (): void {
43+
$service = new TelegramMessageService();
44+
$reflection = new ReflectionClass(TelegramMessageService::class);
45+
$method = $reflection->getMethod('convertMarkdownToHtml');
46+
47+
$markdown = "Paragraph 1\n\n- Item 1\n- Item 2\n\nParagraph 2";
48+
$html = $method->invoke($service, $markdown);
49+
50+
// We expect max 2 newlines ideally
51+
expect($html)->not->toContain("\n\n\n");
52+
});
53+
4254
test('safe message length is respected', function (): void {
4355
$reflection = new ReflectionClass(TelegramMessageService::class);
4456
$constant = $reflection->getReflectionConstant('SAFE_MESSAGE_LENGTH');

0 commit comments

Comments
 (0)