<?php
namespace Twigel\BonusProgram\Subscriber;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Shopware\Storefront\Page\GenericPageLoadedEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Twigel\BonusProgram\Core\Content\TwigelOrderStatus\TwigelOrderStatusEntity;
class GenericPageLoading implements EventSubscriberInterface
{
/** @var EntityRepository */
private $orderStatusRepository;
public function __construct(EntityRepository $orderStatusRepository)
{
$this->orderStatusRepository = $orderStatusRepository;
}
/**
* @inheritDoc
*/
public static function getSubscribedEvents()
{
return [
GenericPageLoadedEvent::class => 'onLoad'
];
}
public function onLoad(GenericPageLoadedEvent $event)
{
if (!$event->getSalesChannelContext()->getCustomerId()) {
return;
}
$customerId = $event->getSalesChannelContext()->getCustomerId();
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('customerId', $customerId));
$orders = $this->orderStatusRepository->search($criteria, $event->getContext())->getElements();
$bonusAmount = 0;
/** @var TwigelOrderStatusEntity $order */
foreach ($orders as $order) {
if ($order->getOrder()->getStateMachineState()->getTechnicalName() !== 'cancelled'){
$bonusAmount += $order->getBonusAmount();
}
}
$event->getPage()->assign(['customerBonus' => $bonusAmount]);
}
}