89 lines
2.4 KiB
PHP
89 lines
2.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\MultiLocaleTranslation\Model;
|
|
|
|
use Magento\Framework\App\State;
|
|
use Magento\Framework\Exception\LocalizedException;
|
|
use Magento\Store\Model\StoreManagerInterface;
|
|
use Mageplaza\Blog\Model\Post;
|
|
|
|
class BlogPostTranslationApplier
|
|
{
|
|
public function __construct(
|
|
private readonly CmsTranslationRepository $translationRepository,
|
|
private readonly StoreManagerInterface $storeManager,
|
|
private readonly State $appState
|
|
) {
|
|
}
|
|
|
|
public function apply(Post $post): void
|
|
{
|
|
if (!$this->isFrontend() || !$post->getId()) {
|
|
return;
|
|
}
|
|
$storeId = (int)$this->storeManager->getStore()->getId();
|
|
if ($storeId <= 0) {
|
|
return;
|
|
}
|
|
|
|
$translations = $this->translationRepository->getTranslations(
|
|
(int)$post->getId(),
|
|
$storeId,
|
|
CmsTranslationRepository::ENTITY_BLOG_POST,
|
|
BlogPostFields::codes()
|
|
);
|
|
$this->applyValues($post, $translations);
|
|
}
|
|
|
|
/** @param Post[] $posts */
|
|
public function applyMany(array $posts): void
|
|
{
|
|
if (!$this->isFrontend() || $posts === []) {
|
|
return;
|
|
}
|
|
$storeId = (int)$this->storeManager->getStore()->getId();
|
|
if ($storeId <= 0) {
|
|
return;
|
|
}
|
|
|
|
$postIds = [];
|
|
foreach ($posts as $post) {
|
|
if ($post instanceof Post && $post->getId()) {
|
|
$postIds[] = (int)$post->getId();
|
|
}
|
|
}
|
|
$translations = $this->translationRepository->getTranslationsForEntities(
|
|
$postIds,
|
|
$storeId,
|
|
CmsTranslationRepository::ENTITY_BLOG_POST,
|
|
BlogPostFields::codes()
|
|
);
|
|
foreach ($posts as $post) {
|
|
if (!$post instanceof Post || !$post->getId()) {
|
|
continue;
|
|
}
|
|
$this->applyValues($post, $translations[(int)$post->getId()] ?? []);
|
|
}
|
|
}
|
|
|
|
private function applyValues(Post $post, array $translations): void
|
|
{
|
|
foreach (BlogPostFields::codes() as $field) {
|
|
if (array_key_exists($field, $translations)) {
|
|
$post->setData($field, $translations[$field]);
|
|
}
|
|
}
|
|
}
|
|
|
|
private function isFrontend(): bool
|
|
{
|
|
try {
|
|
return $this->appState->getAreaCode() === 'frontend';
|
|
} catch (LocalizedException) {
|
|
return false;
|
|
}
|
|
}
|
|
}
|