<?php
declare(strict_types=1);
namespace WbfkExtensions\Subscriber;
use DateTime;
use DateTimeZone;
use Exception;
use Shopware\Core\Checkout\Order\Aggregate\OrderLineItem\OrderLineItemEntity;
use Shopware\Core\Checkout\Order\OrderEntity;
use Shopware\Core\Checkout\Order\OrderEvents;
use Shopware\Core\Defaults;
use Shopware\Core\Framework\DataAbstractionLayer\EntityRepository;
use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityLoadedEvent;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use WbfkExtensions\Core\Checkout\Cart\Delivery\DeliveryMode;
use WbfkExtensions\Core\Checkout\Cart\Delivery\ExpectedProductDeliveryTimeByQuantity\ExpectedProductDeliveryTimeByQuantityCollection;
use WbfkExtensions\Core\Checkout\Cart\Delivery\ExpectedProductDeliveryTimeByQuantity\ExpectedProductDeliveryTimeByQuantityEntity;
use WbfkExtensions\Core\Checkout\Cart\Delivery\PossibleDeliveryModes;
class RestoreDeliveryTimeDataInOrder implements EventSubscriberInterface
{
public function __construct(
private readonly EntityRepository $productRepository
)
{
}
public static function getSubscribedEvents(): array
{
return [
OrderEvents::ORDER_LOADED_EVENT => 'restoreDeliveryModeForOrder',
OrderEvents::ORDER_LINE_ITEM_LOADED_EVENT => 'onOrderLineItemLoadedEvent',
];
}
public function restoreDeliveryModeForOrder(EntityLoadedEvent $event): void
{
foreach ($event->getEntities() as $order) {
/** @var OrderEntity $order */
$deliveryModeData = $order->getCustomFields()['deliveryMode'] ?? false;
if (!$deliveryModeData || !isset($deliveryModeData['selectedDeliveryMode'])) {
continue;
}
$deliveryMode = new DeliveryMode(
PossibleDeliveryModes::from($deliveryModeData['selectedDeliveryMode']),
$deliveryModeData['cartRequiresPartialDelivery']
);
/** @noinspection PhpDeprecationInspection */
$order->addExtension(DeliveryMode::CART_EXTENSION_KEY, $deliveryMode);
}
}
public function onOrderLineItemLoadedEvent(EntityLoadedEvent $event)
{
$this->assignLineItemCoverImage($event);
}
/**
* @throws Exception
*/
private function assignLineItemCoverImage(EntityLoadedEvent $event): void
{
/** @var OrderLineItemEntity $lineItem */
foreach ($event->getEntities() as $lineItem) {
$productId = $lineItem->getProductId();
if ($productId) {
$productCriteria = new Criteria([$productId]);
$productCriteria->addAssociation('cover');
$productCriteria->setLimit(1);
$product = $this->productRepository->search($productCriteria, $event->getContext())->first();
if ($product) {
$lineItem->assign([
'coverImage' => $product->getCover(),
]);
}
}
}
}
}