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

88 lines
3.2 KiB
PHP

<?php
declare(strict_types=1);
namespace Esun\MultiLocaleTranslation\Model\Entity;
use Esun\MultiLocaleTranslation\Model\Config\SkippedFields;
use Esun\MultiLocaleTranslation\Model\TranslatableEntityInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Catalog\Api\Data\ProductInterface;
use Magento\Catalog\Model\Attribute\ScopeOverriddenValue;
class ProductEntity implements TranslatableEntityInterface
{
private const TRANSLATABLE_FIELDS = [
'name' => ['label' => 'Name', 'is_html' => false],
'description' => ['label' => 'Description', 'is_html' => true],
'short_description' => ['label' => 'Short Description', 'is_html' => true],
'meta_title' => ['label' => 'Meta Title', 'is_html' => false],
'meta_keyword' => ['label' => 'Meta Keywords', 'is_html' => false],
'meta_description' => ['label' => 'Meta Description', 'is_html' => false],
];
public function __construct(
private readonly ProductRepositoryInterface $productRepository,
private readonly ScopeOverriddenValue $scopeOverriddenValue,
private readonly SkippedFields $skippedFields
) {
}
public function getFields(int $entityId, int $sourceStoreId, int $targetStoreId): array
{
$source = $this->getProduct($entityId, $sourceStoreId);
$target = $this->getProduct($entityId, $targetStoreId);
$fields = [];
foreach (self::TRANSLATABLE_FIELDS as $field => $meta) {
if ($this->skippedFields->isSkipped('product', $field)) {
continue;
}
$fields[] = [
'code' => $field,
'label' => $meta['label'],
'source_value' => (string)($source->getData($field) ?? ''),
'target_value' => (string)($target->getData($field) ?? ''),
'is_html' => (bool)$meta['is_html'],
'use_default' => $targetStoreId > 0 && !$this->scopeOverriddenValue->containsValue(
ProductInterface::class,
$target,
$field,
$targetStoreId
),
];
}
return $fields;
}
public function apply(int $entityId, int $targetStoreId, array $fields, array $useDefault = []): void
{
$product = $this->getProduct($entityId, $targetStoreId, true);
foreach (array_keys(self::TRANSLATABLE_FIELDS) as $field) {
if ($this->skippedFields->isSkipped('product', $field)) {
continue;
}
if (!empty($useDefault[$field])) {
$product->setData($field, null);
continue;
}
if (!array_key_exists($field, $fields)) {
continue;
}
$product->setData($field, (string)$fields[$field]);
}
$this->productRepository->save($product);
}
private function getProduct(int $entityId, int $storeId, bool $forceReload = false): ProductInterface
{
$storeId = $storeId > 0 ? $storeId : null;
$product = $this->productRepository->getById($entityId, true, $storeId, $forceReload);
return $product;
}
}