Skip to content

Instantly share code, notes, and snippets.

@ohvitorino
Created September 2, 2018 15:12
Show Gist options
  • Save ohvitorino/affc659c0d9274360940a4089e514243 to your computer and use it in GitHub Desktop.
Save ohvitorino/affc659c0d9274360940a4089e514243 to your computer and use it in GitHub Desktop.
<?php
// Pre-load all locale files to have a cache
function loadOtherTranslations() {
$existingTranslations = [];
$iterator = new RecursiveDirectoryIterator('src');
/** @var \SplFileInfo $file */
foreach(new RecursiveIteratorIterator($iterator) as $file){
if(strpos($file->getPathname(), 'locale.xml') !== false){
$document = new DOMDocument();
$document->load($file->getPathname());
foreach ($document->getElementsByTagName('item') as $item) {
/** @var \DOMElement $translation */
foreach ($item->getElementsByTagName('translation') as $translation) {
if ($translation->getAttribute('language') === 'pt') {
$existingTranslations[$item->getAttribute(
'name'
)] = $translation->textContent;
break;
}
}
}
}
}
return $existingTranslations;
}
$existingTranslations = loadOtherTranslations();
$document = new DOMDocument();
$document->load($argv[1]);
function getUserInput() {
return readline("\nTranslation PT: ");
}
/** @var \DOMElement $item */
/**
* @param \DOMElement $item
* @param $document
*/
function printCurrentItem($item, $document): void
{
echo sprintf(
"Type: %s\n",
$item->attributes->getNamedItem('type')->textContent
);
echo sprintf(
"Name: %s\n",
$item->attributes->getNamedItem('name')->textContent
);
echo $document->saveXML($item);
}
foreach ($document->getElementsByTagName('item') as $item) {
$hasPtTranslation = false;
/** @var \DOMElement $translation */
foreach ($item->getElementsByTagName('translation') as $translation) {
if ($translation->getAttribute('language') === 'pt') {
$hasPtTranslation = true;
$existingTranslations[
$item->getAttribute('name')
] = $translation->textContent;
break;
}
}
if ($hasPtTranslation) {
continue;
}
printCurrentItem($item, $document);
if (isset($existingTranslations[$item->getAttribute('name')])) {
$translationValue = $existingTranslations[$item->getAttribute('name')];
echo "\n\nRepeated value " . $item->getAttribute('name') . ". Using: $translationValue\n";
} else {
$translationValue = getUserInput();
}
if (empty($translationValue)) {
continue;
}
$cdata = $document->createCDATASection($translationValue);
$translation = $document->createElement('translation');
$translation->setAttribute('language', 'pt');
$translation->appendChild($cdata);
$item->appendChild($translation);
$response = readline("\nContinue? ");
if ($response === 'n' || $response === 'no') {
break;
}
}
$document->preserveWhiteSpace = false;
$document->formatOutput = true;
$document->save($argv[1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment