59 lines
1.8 KiB
PHP
59 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Utils;
|
|
|
|
class TextFormatter
|
|
{
|
|
/**
|
|
* Formata conteúdo de texto para exibição HTML segura.
|
|
* - Escapa caracteres especiais HTML (segurança XSS)
|
|
* - Converte URLs em links clicáveis
|
|
* - Converte quebras de linha em <br>
|
|
*
|
|
* @param string|null $text Texto a ser formatado
|
|
* @return string Texto formatado para HTML
|
|
*/
|
|
public static function formatContent(?string $text): string
|
|
{
|
|
if (empty($text)) {
|
|
return '';
|
|
}
|
|
|
|
// 1. Escapa caracteres especiais HTML (segurança contra XSS)
|
|
$text = htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
|
|
|
|
// 2. Converte URLs em links clicáveis
|
|
// Padrão para URLs HTTP/HTTPS
|
|
$urlPattern = '/(https?:\/\/[^\s\)\]]+)/i';
|
|
$text = preg_replace_callback($urlPattern, function ($matches) {
|
|
$url = rtrim($matches[1], '.,;:!?)\'\"'); // Remove pontuação final
|
|
$displayUrl = strlen($url) > 60 ? substr($url, 0, 57) . '...' : $url;
|
|
return '<a href="' . $url . '" target="_blank" rel="noopener noreferrer" class="text-blue-600 hover:text-blue-800 underline">' . $displayUrl . '</a>';
|
|
}, $text);
|
|
|
|
// 3. Converte quebras de linha em <br>
|
|
$text = nl2br($text);
|
|
|
|
return $text;
|
|
}
|
|
|
|
/**
|
|
* Limpa e normaliza quebras de linha no texto.
|
|
* Útil para normalizar dados antes de salvar no banco.
|
|
*
|
|
* @param string|null $text Texto a ser normalizado
|
|
* @return string Texto com quebras de linha normalizadas
|
|
*/
|
|
public static function normalizeLineBreaks(?string $text): string
|
|
{
|
|
if (empty($text)) {
|
|
return '';
|
|
}
|
|
|
|
// Normaliza todas as variações de quebra de linha para \n
|
|
$text = str_replace(["\r\n", "\r"], "\n", $text);
|
|
|
|
return $text;
|
|
}
|
|
}
|