<?php
declare(strict_types=1);
namespace Orcamultimedia\OciPunchout\Subscriber;
use Orcamultimedia\OciPunchout\Service\OciService;
use Orcamultimedia\OciPunchout\Struct\OciCartData;
use Shopware\Core\Checkout\Cart\Event\BeforeLineItemAddedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\System\SalesChannel\Entity\SalesChannelRepository;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class LineItemAddedSubscriber implements EventSubscriberInterface
{
/**
* @var SalesChannelRepository
*/
private SalesChannelRepository $productRepository;
/**
* @var OciService
*/
private OciService $ociService;
/**
* @var SystemConfigService
*/
private SystemConfigService $systemConfigService;
public function __construct(
SalesChannelRepository $productRepository,
OciService $ociService,
SystemConfigService $systemConfigService
)
{
$this->productRepository = $productRepository;
$this->ociService = $ociService;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
return [
BeforeLineItemAddedEvent::class => 'addPayloadValues',
];
}
public function addPayloadValues(BeforeLineItemAddedEvent $event): void
{
if (!$this->ociService->isPunchout()) {
return;
}
$lineItem = $event->getLineItem();
$context = $event->getSalesChannelContext();
$config = $this->systemConfigService->get('OciPunchout.config', $context->getSalesChannel()->getId());
$product = $this->productRepository->search(new Criteria([$lineItem->getReferencedId()]), $context)->first();
$extensionData = new OciCartData();
if ($product) {
$cartDataArray = $this->getCartDataArray($config, $product);
$extensionData->assign($cartDataArray);
}
$lineItem->addExtension(OciCartData::EXTENSION_NAME, $extensionData);
}
private function getCartDataArray(array $config, $product): array
{
$cartDataArray = [];
foreach (CheckoutCartSubscriber::CONFIG_KEYS as $key) {
$configValue = $config[$key] ?? '';
if (!$configValue || strpos($configValue, '@') === false) {
continue;
}
$configValue = str_replace('@', '', $configValue);
if(
($data = $product->getCustomFields()[$configValue] ?? null)
|| ($data = $product->getVars()[$configValue] ?? null)
) {
$cartDataArray[$configValue] = $data;
}
}
$cartDataArray['description'] = $product->getDescription();
return $cartDataArray;
}
}