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

92 lines
2.8 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model;
use Esun\Wiki\Model\Category;
use Esun\Wiki\Model\Homepage;
use Magento\Framework\App\State;
use Magento\Framework\Exception\LocalizedException;
use Magento\Store\Model\StoreManagerInterface;
class WikiTranslationApplier
{
public function __construct(
private readonly CmsTranslationRepository $translationRepository,
private readonly StoreManagerInterface $storeManager,
private readonly State $appState
) {
}
public function apply(Category $entity): void
{
if (!$this->isFrontend() || !$entity->getId()) {
return;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0) {
return;
}
$isHomepage = $entity instanceof Homepage;
$translations = $this->translationRepository->getTranslations(
(int)$entity->getId(),
$storeId,
$isHomepage
? CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE
: CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
$isHomepage ? WikiFields::homepageCodes() : WikiFields::categoryCodes()
);
$this->applyValues($entity, $translations);
}
/** @param Category[] $entities */
public function applyMany(array $entities, bool $homepage = false): void
{
if (!$this->isFrontend() || $entities === []) {
return;
}
$storeId = (int)$this->storeManager->getStore()->getId();
if ($storeId <= 0) {
return;
}
$entityIds = [];
foreach ($entities as $entity) {
if ($entity instanceof Category && $entity->getId()) {
$entityIds[] = (int)$entity->getId();
}
}
$translations = $this->translationRepository->getTranslationsForEntities(
$entityIds,
$storeId,
$homepage
? CmsTranslationRepository::ENTITY_WIKI_HOMEPAGE
: CmsTranslationRepository::ENTITY_WIKI_CATEGORY,
$homepage ? WikiFields::homepageCodes() : WikiFields::categoryCodes()
);
foreach ($entities as $entity) {
if ($entity instanceof Category && $entity->getId()) {
$this->applyValues($entity, $translations[(int)$entity->getId()] ?? []);
}
}
}
private function applyValues(Category $entity, array $translations): void
{
foreach ($translations as $field => $value) {
$entity->setData($field, $value);
}
}
private function isFrontend(): bool
{
try {
return $this->appState->getAreaCode() === 'frontend';
} catch (LocalizedException) {
return false;
}
}
}