init
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
<?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(
|
||||
['"', '"', '"', ''', ''', '''],
|
||||
['"', '"', '"', "'", "'", "'"],
|
||||
$matches[0]
|
||||
);
|
||||
},
|
||||
$html
|
||||
) ?? $html;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user