<?php declare(strict_types=1);
namespace MetalementsTheme\Subscriber;
use Shopware\Core\Checkout\Order\OrderEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Shopware\Core\Checkout\Order\Event\OrderStateMachineStateChangeEvent;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
class OrderCompletedSubscriber implements EventSubscriberInterface
{
/**
* @var EntityRepositoryInterface
*/
private $productRepository;
public function __construct(EntityRepositoryInterface $productRepository) {
$this->productRepository = $productRepository;
}
public static function getSubscribedEvents(): array
{
return [
OrderStateMachineStateChangeEvent::class => 'onOrderCompleted'
];
}
public function onOrderCompleted(OrderStateMachineStateChangeEvent $event): void
{
if ($event->getToPlace()->getTechnicalName() !== 'completed') {
return;
}
$order = $event->getOrder();
$context = $event->getContext();
foreach ($order->getLineItems() as $lineItem) {
$customFields = $lineItem->getCustomFields();
if ($customFields && isset($customFields['wct_custom_field_single_parts'])) {
$singleParts = explode(';', $customFields['wct_custom_field_single_parts']);
foreach ($singleParts as $singlePart) {
if (strlen($singlePart) > 0 && substr_count($singlePart, ':') == 2) {
$singlePartParts = explode(':', $singlePart);
$singlePartProductNumber = $singlePartParts[0];
$singlePartRequired = intval($singlePartParts[1]);
$singlePartAmount = intval($singlePartParts[2]);
if ($singlePartRequired == 1) {
$criteria = new Criteria();
$criteria->addFilter(new EqualsFilter('productNumber', $singlePartProductNumber));
$product = $this->productRepository->search($criteria, $context)->first();
if ($product !== null) {
$currentStock = $product->getStock();
$newStock = max($currentStock - $singlePartAmount, 0);
$updateData = [
'id' => $product->getId(),
'stock' => $newStock
];
$this->productRepository->update([$updateData], $context);
}
}
}
}
}
}
}
}