<?php declare(strict_types=1);
namespace Cogi\Affiliate\Subscriber;
use Cogi\Affiliate\Core\Service\AffiliateService;
use Shopware\Core\Checkout\Cart\Event\CheckoutOrderPlacedEvent;
use Shopware\Storefront\Page\PageLoadedEvent;
use Shopware\Storefront\Page\Product\ProductPageCriteriaEvent;
use Shopware\Storefront\Pagelet\Header\HeaderPageletLoadedEvent;
use Shopware\Storefront\Page\Checkout\Confirm\CheckoutConfirmPageLoadedEvent;
use Shopware\Core\System\SystemConfig\SystemConfigService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Session\Session;
class StorefrontSubscriber implements EventSubscriberInterface
{
protected $affiliateService;
protected $systemConfigService;
public function __construct(
AffiliateService $affiliateService,
SystemConfigService $systemConfigService
)
{
$this->affiliateService = $affiliateService;
$this->systemConfigService = $systemConfigService;
}
public static function getSubscribedEvents(): array
{
return [
CheckoutOrderPlacedEvent::class => 'onCheckoutOrderPlaced',
ProductPageCriteriaEvent::class => 'onProductCriteriaLoaded',
PageLoadedEvent::class => 'onPageLoaded',
HeaderPageletLoadedEvent::class => 'onPageLoaded',
CheckoutConfirmPageLoadedEvent::class => 'onCheckoutConfirmPageLoaded'
];
}
public function onPageLoaded($event): void
{
$urlParameter = empty($this->systemConfigService->get('CogiAffiliate.config.urlParameter')) ? 'affiliateCode' : $this->systemConfigService->get('CogiAffiliate.config.urlParameter');
$affiliateCode = $event->getRequest()->query->get($urlParameter);
if ($affiliateCode) {
$session = new Session();
$session->set('cogi-affiliate-code', $affiliateCode);
}
}
public function onCheckoutOrderPlaced(CheckoutOrderPlacedEvent $event): void
{
$order = $event->getOrder();
$context = $event->getContext();
try {
$this->affiliateService->calculateAffiliateProvision($context, $order);
} catch (\Exception $e) {}
}
public function onProductCriteriaLoaded(ProductPageCriteriaEvent $event): void
{
// If current user is affiliate, add productGroups association
try {
if ($event->getSalesChannelContext()->getCustomer() && $event->getSalesChannelContext()->getCustomer()->getCustomFields() && $event->getSalesChannelContext()->getCustomer()->getCustomFields()['ca_active']) {
$event->getCriteria()->addAssociation('productGroups');
}
} catch (\Exception $e) {}
}
public function onCheckoutConfirmPageLoaded(CheckoutConfirmPageLoadedEvent $event): void
{
if ($this->systemConfigService->get('CogiAffiliate.config.enableCheckoutAffiliateSelection', $event->getSalesChannelContext()->getSalesChannelId())) {
$event->getContext()->addExtension('cogi-affiliate-affiliates', $this->affiliateService->getAffiliates($event->getContext()));
}
}
}