<?php
declare(strict_types=1);
namespace Orcamultimedia\OciPunchout\Subscriber;
use Orcamultimedia\OciPunchout\Service\OciService;
use Orcamultimedia\OciPunchout\Struct\OciCartData;
use Orcamultimedia\OciPunchout\Struct\OciPunchoutData;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Shopware\Storefront\Page\Checkout\Cart\CheckoutCartPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CheckoutCartSubscriber implements EventSubscriberInterface
{
public const CONFIG_KEYS = [
'extcategoryid', 'leadtime', 'manufactmat', 'matgroup', 'matnr', 'unit', 'vendor',
'customfield1', 'customfield2', 'customfield3', 'customfield4', 'customfield5'
];
/**
* @var OciService
*/
private OciService $ociService;
/**
* @var SystemConfigService
*/
private SystemConfigService $systemConfigService;
public function __construct(
OciService $ociService,
SystemConfigService $systemConfigService
)
{
$this->ociService = $ociService;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutCartPageLoadedEvent::class => 'addOciPunchoutPageData',
];
}
public function addOciPunchoutPageData(CheckoutCartPageLoadedEvent $event): void
{
if (!$this->ociService->isPunchout()) {
return;
}
$page = $event->getPage();
$request = $event->getRequest();
$context = $event->getSalesChannelContext();
$config = $this->systemConfigService->get('OciPunchout.config', $context->getSalesChannel()->getId());
$punchoutData = new OciPunchoutData();
$oci = $request->getSession()->get('oci');
$lineItems = $page->getCart()->getLineItems();
foreach ($lineItems as $lineItem) {
$cartDataArray = [];
foreach (self::CONFIG_KEYS as $key) {
$cartDataArray[$key] = $this->getLineItemData($config[$key] ?? null, $lineItem);
}
$cartDataArray['description'] = $this->getLineItemData('@description' ?? null, $lineItem);
$cartData = new OciCartData();
$cartData->assign($cartDataArray);
$lineItem->addExtension(OciCartData::EXTENSION_NAME, $cartData);
}
$punchoutData->assign([
'hookUrl' => $oci['hookUrl'],
'returnTarget' => $oci['returnTarget'],
'currencyIsoCode' => $page->getHeader()->getActiveCurrency()->getIsoCode(),
'lineItems' => $page->getCart()->getLineItems()
]);
$page->addExtension(OciPunchoutData::EXTENSION_NAME, $punchoutData);
}
private function getLineItemData($config, $lineItem)
{
if (!$config || strpos($config, '@') === false) {
return $config;
}
$config = str_replace('@', '', $config);
if (
($lineItemData = $lineItem->getVars()[$config] ?? null)
|| ($lineItemData = $lineItem->getPayloadValue($config) ?? null)
|| ($lineItem->hasExtension(OciCartData::EXTENSION_NAME)
&& $lineItemData = $lineItem->getExtension(OciCartData::EXTENSION_NAME)->getVars()[$config] ?? null
)
) {
return $lineItemData;
}
return null;
}
}