<?php
namespace App\EventListener;
use Exception;
use Pimcore\Event\Model\TranslationEvent;
use Pimcore\Model\Translation;
use Pimcore\Tool;
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;
class CreateTranslationJsonEventlisterner
{
public function onPostSave(TranslationEvent $event)
{
$domain = Translation::DOMAIN_DEFAULT;
$list = new Translation\Listing();
$list->setDomain($domain);
$translations = $list->load();
if ($translations) {
$languages = Tool::getValidLanguages();
if ($languages) {
foreach ($languages as $language) {
$content = $this->getContent($translations, $language);
$this->createLocaleFile($language, $content);
}
}
}
}
/**
* @param array $translations
* @return string
*/
private function getContent(array $translations, $locale): string
{
$output = [];
foreach ($translations as $translation) {
try {
$this->assignArrayByPath($output, $translation->getKey(), $translation->getTranslation($locale));
} catch (Exception $exception) {
$msg = $exception->getMessage();
}
}
$output = json_encode($output);
return $output;
}
public function assignArrayByPath(&$arr, $path, $value, $separator = '.')
{
if (preg_match("/^[\w-]+?(?:\.?[\w-]+?)*$/m", $path)) {
$keys = explode($separator, $path);
foreach ($keys as $key) {
$arr = &$arr[$key];
}
$arr = $value;
}
}
public function createLocaleFile($locale, $content)
{
$path = PIMCORE_WEB_ROOT . '/locales';
$file = $path . '/' . $locale . '.json';
$filesystem = new Filesystem();
try {
$filesystem->mkdir(
Path::normalize($path),
);
$filesystem->dumpFile($file, $content);
} catch (IOExceptionInterface $exception) {
echo "An error occurred while creating your directory at " . $exception->getPath();
}
}
}