Files
server/app/Utils/TextFormatter.php

108 lines
3.7 KiB
PHP

<?php
namespace App\Utils;
class TextFormatter
{
/**
* Formata conteúdo de texto para exibição HTML segura.
* - Detecta se o conteúdo já é HTML (do Quill editor) ou texto puro
* - Para HTML: aplica purificação básica mantendo tags permitidas
* - Para texto puro: escapa e converte URLs/quebras de linha
*
* @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 '';
}
// Detecta se o conteúdo já é HTML (contém tags HTML comuns do Quill)
if (self::isHtmlContent($text)) {
// Conteúdo HTML do Quill - purificar e retornar
return self::purifyHtml($text);
}
// Conteúdo texto puro (dados antigos) - aplicar formatação completa
// 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;
}
/**
* Verifica se o conteúdo parece ser HTML (do Quill editor)
*
* @param string $text Texto a verificar
* @return bool True se parece ser HTML
*/
private static function isHtmlContent(string $text): bool
{
// Verifica se contém tags HTML comuns do Quill
return preg_match('/<(p|div|br|strong|em|u|a|ul|ol|li|h[1-6]|span|blockquote)[^>]*>/i', $text) === 1;
}
/**
* Purifica HTML mantendo apenas tags seguras
*
* @param string $html HTML a ser purificado
* @return string HTML purificado
*/
private static function purifyHtml(string $html): string
{
// Tags permitidas do Quill editor
$allowedTags = '<p><br><strong><b><em><i><u><s><a><ul><ol><li><h1><h2><h3><h4><h5><h6><span><blockquote><pre><code>';
// Remove tags não permitidas
$html = strip_tags($html, $allowedTags);
// Adiciona target="_blank" e rel="noopener" em links para segurança
$html = preg_replace_callback(
'/<a\s+([^>]*href=["\'][^"\']+["\'][^>]*)>/i',
function ($matches) {
$attrs = $matches[1];
// Remove atributos target e rel existentes
$attrs = preg_replace('/\s*(target|rel)=["\'][^"\']*["\']/i', '', $attrs);
return '<a ' . $attrs . ' target="_blank" rel="noopener noreferrer">';
},
$html
);
return $html;
}
/**
* 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;
}
}