init
This commit is contained in:
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user