<?php
declare(strict_types=1);
namespace Zeobv\BundleProducts\Core\Subscriber;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsAnyFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityWriteResult;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
class OrderLineItemQuantitySubscriber implements EventSubscriberInterface
{
protected EntityRepositoryInterface $orderLineItemRepository;
public function __construct(
EntityRepositoryInterface $orderLineItemRepository
) {
$this->orderLineItemRepository = $orderLineItemRepository;
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_LINE_ITEM_WRITTEN_EVENT => 'onOrderLineItemWritten',
];
}
public function onOrderLineItemWritten(EntityWrittenEvent $event): void
{
/** @var EntityWriteResult $writeResult */
foreach ($event->getWriteResults() as $writeResult) {
if (
$writeResult->getOperation() !== EntityWriteResult::OPERATION_UPDATE
|| !$writeResult->hasPayload('quantity')
|| $writeResult->getProperty('quantity') <= 1
) {
continue;
}
/** @var array|string $id */
$id = $writeResult->getPrimaryKey();
$id = !is_array($id) ? [$id] : $id;
$criteria = new Criteria();
$criteria->addFilter(new EqualsAnyFilter('parentId', $id));
$result = $this->orderLineItemRepository->search($criteria, $event->getContext());
if ($result->getTotal() <= 0) {
continue;
}
$orderLineItemPatchData = [];
/** @var OrderLineItemEntity $item */
foreach ($result as $item) {
$payload = $item->getPayload();
if (!is_array($payload) || !key_exists('quantity', $payload)) {
continue 2;
}
$orderLineItemPatchData[] = [
'id' => $item->getId(),
'quantity' => $payload['quantity'] * $writeResult->getProperty('quantity')
];
}
if (empty($orderLineItemPatchData)) {
continue;
}
$this->orderLineItemRepository->update($orderLineItemPatchData, $event->getContext());
}
}
}