<?php declare(strict_types=1);
namespace Wexo\ExtendedCustomerList\Subscriber\Customer\Checkout;
use Wexo\ExtendedCustomerList\Helpers\Helper;
use Shopware\Core\Checkout\Customer\CustomerEntity;
use Shopware\Core\Checkout\Order\OrderDefinition;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\Context;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
class CustomerOrderAmountSubscriber implements EventSubscriberInterface
{
private Helper $helper;
/**
* @param EntityRepositoryInterface $orderRepository
* @param EntityRepositoryInterface $customerRepository
*/
public function __construct(
protected EntityRepositoryInterface $orderRepository,
protected EntityRepositoryInterface $customerRepository
) {
$this->helper = new Helper($customerRepository, Context::createDefaultContext());
}
/**
* @return array|string[]
*/
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_WRITTEN_EVENT => 'fillCustomerMetaDataFields',
];
}
/**
* @param EntityWrittenEvent $event
*/
public function fillCustomerMetaDataFields(EntityWrittenEvent $event): void
{
if ($event->getEntityName() !== OrderDefinition::ENTITY_NAME) {
return;
}
$context = $event->getContext();
foreach ($event->getWriteResults() as $writeResult) {
if ($writeResult->getExistence() !== null && $writeResult->getExistence()->exists()) {
break;
}
$payload = $writeResult->getPayload();
if (empty($payload)) {
continue;
}
$orderResult = $this->orderRepository->search(
(new Criteria([$payload['id']]))->addAssociation('orderCustomer'),
$context
);
/** @var OrderEntity|null $order */
$order = $orderResult->first();
if (!($order instanceof OrderEntity)) {
continue;
}
$customerId = $order->getOrderCustomer()->getCustomerId();
// happens if the customer was deleted
if (!$customerId) {
continue;
}
$this->helper->calculate($customerId);
}
}
}