Files
2026-09-15 10:35:56 +08:00

70 lines
1.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\Translation\Model\Html;
use DOMDocument;
use DOMElement;
use DOMText;
class HtmlFragment
{
/**
* @param array<string, DOMText> $textNodes
* @param array<string, string> $texts
*/
public function __construct(
private readonly DOMDocument $document,
private readonly DOMElement $root,
private readonly array $textNodes,
private readonly array $texts,
private readonly array $directivePlaceholders = []
) {
}
/**
* @return array<string, string>
*/
public function getTexts(): array
{
return $this->texts;
}
/**
* @param array<string, string> $translations
*/
public function applyTranslations(array $translations): string
{
foreach ($this->textNodes as $id => $node) {
if (array_key_exists($id, $translations)) {
$node->nodeValue = $translations[$id];
}
}
$html = '';
foreach ($this->root->childNodes as $childNode) {
$html .= $this->document->saveHTML($childNode);
}
$restored = $this->directivePlaceholders === [] ? $html : strtr($html, $this->directivePlaceholders);
return $this->normalizeMagentoDirectiveQuotes($restored);
}
private function normalizeMagentoDirectiveQuotes(string $html): string
{
return preg_replace_callback(
'/\{\{.*?\}\}/s',
static function (array $matches): string {
return str_ireplace(
['&quot;', '&#34;', '&#x22;', '&apos;', '&#39;', '&#x27;'],
['"', '"', '"', "'", "'", "'"],
$matches[0]
);
},
$html
) ?? $html;
}
}