<?php
namespace Harmonizely\Service\CustomTranslation\EventListener;
use Exception;
use Harmonizely\Service\CustomTranslation\Contract\IGetCustomTranslationCatalogService;
use Harmonizely\Service\CustomTranslation\Event\SetCustomTranslationEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Translation\MessageCatalogue;
use Symfony\Contracts\Translation\TranslatorInterface;
class SetCustomTranslationListener implements EventSubscriberInterface
{
/**
* @var TranslatorInterface
*/
private TranslatorInterface $translator;
/**
* @var IGetCustomTranslationCatalogService
*/
private IGetCustomTranslationCatalogService $getCustomTranslationCatalogService;
/**
* @param TranslatorInterface $translator
* @param IGetCustomTranslationCatalogService $getCustomTranslationCatalogService
*/
public function __construct(
TranslatorInterface $translator,
IGetCustomTranslationCatalogService $getCustomTranslationCatalogService
)
{
$this->translator = $translator;
$this->getCustomTranslationCatalogService = $getCustomTranslationCatalogService;
}
/**
* @return array
*/
public static function getSubscribedEvents(): array
{
return [
SetCustomTranslationEvent::NAME => 'onSetCustomTranslation',
];
}
/**
* @param SetCustomTranslationEvent $event
* @throws Exception
*/
public function onSetCustomTranslation(SetCustomTranslationEvent $event): void
{
$customTranslationCatalog = $this->getCustomTranslationCatalogService->perform(
$event->getUserId(),
$event->getOrganizationId()
);
/** @var MessageCatalogue $catalogue */
$catalogue = $this->translator->getCatalogue();
$domains = $catalogue->getDomains();
foreach ($customTranslationCatalog->getEntries() as $entry) {
foreach ($domains as $domain) {
$catalogue->set($entry->getMsgId(), $entry->getMsgStr(), $domain);
}
}
}
}