This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,43 @@
<?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);
}
}