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

113 lines
3.6 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\CmsTranslationRepository;
use Esun\MultiLocaleTranslation\Model\BlogPostFields;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Mageplaza\Blog\Model\Post;
use Mageplaza\Blog\Model\PostFactory;
class BlogPostEntity implements TranslatableEntityInterface
{
public function __construct(
private readonly PostFactory $postFactory,
private readonly CmsTranslationRepository $translationRepository,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$post = $this->loadPost($entityId);
$baseValues = $this->getBaseValues($post);
$sourceValues = $sourceStoreId > 0
? array_replace($baseValues, $this->getTranslations($entityId, $sourceStoreId))
: $baseValues;
$targetTranslations = $this->getTranslations($entityId, $targetStoreId);
$fields = [];
foreach (BlogPostFields::FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('blog_post', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($sourceValues[$field] ?? ''),
'target_value' => (string)($targetTranslations[$field] ?? $baseValues[$field] ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => !array_key_exists($field, $targetTranslations),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$this->loadPost($entityId);
$defaultFields = [];
$translations = [];
foreach (BlogPostFields::codes() as $field) {
if ($this->skippedFields->isSkipped('blog_post', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$defaultFields[] = $field;
continue;
}
if (array_key_exists($field, $fields)) {
$translations[$field] = (string)$fields[$field];
}
}
$this->translationRepository->deleteTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOG_POST,
$defaultFields
);
$this->translationRepository->saveTranslations(
$entityId,
$targetStoreId,
CmsTranslationRepository::ENTITY_BLOG_POST,
$translations
);
}
private function loadPost(int $entityId): Post
{
$post = $this->postFactory->create()->load($entityId);
if (!$post->getId()) {
throw NoSuchEntityException::singleField('post_id', $entityId);
}
return $post;
}
private function getBaseValues(Post $post): array
{
$values = [];
foreach (BlogPostFields::codes() as $field) {
$values[$field] = BlogPostFields::baseValue($field, $post->getData($field));
}
return $values;
}
private function getTranslations(int $entityId, int $storeId): array
{
return $this->translationRepository->getTranslations(
$entityId,
$storeId,
CmsTranslationRepository::ENTITY_BLOG_POST,
BlogPostFields::codes()
);
}
}