<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use Shopware\Core\Checkout\Order\SalesChannel\OrderService;
use Shopware\Core\Framework\Struct\ArrayStruct;
use Shopware\Core\System\SalesChannel\Event\SalesChannelContextCreatedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class AddAffiliateInformationToSalesChannelContext implements EventSubscriberInterface
{
public function __construct(private readonly RequestStack $requestStack)
{
}
public static function getSubscribedEvents(): array
{
return [
SalesChannelContextCreatedEvent::class => 'addAffiliateInformation',
];
}
public function addAffiliateInformation(SalesChannelContextCreatedEvent $event): void
{
$salesChannelContext = $event->getSalesChannelContext();
$affiliateInformation = new ArrayStruct([], 'affiliateInformation');
try {
$session = $this->requestStack->getSession();
$request = $this->requestStack->getCurrentRequest();
$affiliateCode = $request->get(OrderService::AFFILIATE_CODE_KEY, $session->get(OrderService::AFFILIATE_CODE_KEY));
if ($affiliateCode) {
$affiliateInformation->set(OrderService::AFFILIATE_CODE_KEY, $affiliateCode);
}
$campaignCode = $request->get(OrderService::CAMPAIGN_CODE_KEY, $session->get(OrderService::CAMPAIGN_CODE_KEY));
if ($campaignCode) {
$affiliateInformation->set(OrderService::CAMPAIGN_CODE_KEY, $campaignCode);
}
} catch (\Symfony\Component\HttpFoundation\Exception\SessionNotFoundException $exception) {
// If this is run in CLI context, there is no session
}
/** @noinspection PhpDeprecationInspection */
$salesChannelContext->addExtension('affiliateInformation', $affiliateInformation);
}
}