Files
esun3d/app/code/Esun/Translation/Model/Ai/ProtectedTextProcessor.php
T
2026-09-15 10:35:56 +08:00

44 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\Translation\Model\Ai;
class ProtectedTextProcessor
{
/**
* @return array{0: string, 1: array<string, string>}
*/
public function protect(string $text): array
{
$placeholders = [];
$index = 0;
$protected = preg_replace_callback(
'/\{\{.*?\}\}|https?:\/\/[^\s<>"\']+|%[0-9]*\$?[a-zA-Z]|\{[A-Za-z0-9_.-]+\}/',
function (array $matches) use (&$placeholders, &$index): string {
$token = '__ESUN_TRANSLATION_PRESERVE_' . $index++ . '__';
$placeholders[$token] = $matches[0];
return $token;
},
$text
);
return [$protected ?? $text, $placeholders];
}
/**
* @param array<string, string> $placeholders
*/
public function restore(string $text, array $placeholders): string
{
foreach ($placeholders as $token => $original) {
if (!str_contains($text, $token)) {
throw new \RuntimeException(sprintf('Protected token "%s" was not preserved by AI response.', $token));
}
}
return strtr($text, $placeholders);
}
}