52 lines
1.7 KiB
PHP
52 lines
1.7 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Esun\Catalog\Observer\Adminhtml;
|
|
|
|
use Esun\Catalog\Setup\Patch\Data\AddMixStepPricesAttribute;
|
|
use Magento\Catalog\Model\Product;
|
|
use Magento\ConfigurableProduct\Model\Product\Type\Configurable;
|
|
use Magento\Framework\Event\Observer;
|
|
use Magento\Framework\Event\ObserverInterface;
|
|
|
|
class SaveMixStepPrices implements ObserverInterface
|
|
{
|
|
public function execute(Observer $observer): void
|
|
{
|
|
$product = $observer->getEvent()->getProduct();
|
|
$controller = $observer->getEvent()->getController();
|
|
if (!$product instanceof Product
|
|
|| $product->getTypeId() !== Configurable::TYPE_CODE
|
|
|| !$controller
|
|
) {
|
|
return;
|
|
}
|
|
|
|
$post = $controller->getRequest()->getPostValue();
|
|
$productData = is_array($post['product'] ?? null) ? $post['product'] : [];
|
|
$attributeCode = AddMixStepPricesAttribute::ATTRIBUTE_CODE;
|
|
if (!array_key_exists($attributeCode, $productData)) {
|
|
return;
|
|
}
|
|
|
|
$value = $this->unwrapNestedValue($productData[$attributeCode], $attributeCode);
|
|
$attribute = $product->getResource()->getAttribute($attributeCode);
|
|
if (!$attribute) {
|
|
return;
|
|
}
|
|
|
|
$product->setData($attributeCode, is_array($value) ? $value : []);
|
|
$attribute->getBackend()->beforeSave($product);
|
|
$product->getResource()->saveAttribute($product, $attributeCode);
|
|
}
|
|
|
|
private function unwrapNestedValue(mixed $value, string $attributeCode): mixed
|
|
{
|
|
if (is_array($value) && isset($value[$attributeCode]) && is_array($value[$attributeCode])) {
|
|
return $value[$attributeCode];
|
|
}
|
|
|
|
return $value;
|
|
}
|
|
}
|