<?php
/**
* @copyright Copyright (C) Ibexa AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace Ibexa\Bundle\Shipping\EventSubscriber;
use Ibexa\Contracts\OrderManagement\Event\BeforeCancelOrderEvent;
use Ibexa\Contracts\OrderManagement\Value\Order\OrderInterface;
use Ibexa\Contracts\Shipping\Shipment\Query\Criterion\Order as ShipmentOrderCriterion;
use Ibexa\Contracts\Shipping\Shipment\ShipmentInterface;
use Ibexa\Contracts\Shipping\Shipment\ShipmentQuery;
use Ibexa\Contracts\Shipping\Shipment\ShipmentUpdateStruct;
use Ibexa\Contracts\Shipping\ShipmentServiceInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
final class ShipmentCancellingSubscriber implements EventSubscriberInterface
{
private ShipmentServiceInterface $shipmentService;
public function __construct(ShipmentServiceInterface $shipmentService)
{
$this->shipmentService = $shipmentService;
}
public static function getSubscribedEvents(): array
{
return [
BeforeCancelOrderEvent::class => 'cancelShipment',
];
}
/**
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\UnauthorizedException
* @throws \Ibexa\Contracts\Core\Repository\Exceptions\BadStateException
*/
public function cancelShipment(BeforeCancelOrderEvent $event): void
{
$shipment = $this->getOrderShipment($event->getOrder());
if ($shipment === null || $shipment->getStatus() === 'cancelled') {
return;
}
$this->shipmentService->updateShipment($shipment, new ShipmentUpdateStruct('cancel'));
}
private function getOrderShipment(OrderInterface $order): ?ShipmentInterface
{
$shipments = $this->shipmentService->findShipments(
new ShipmentQuery(new ShipmentOrderCriterion($order))
)->getShipments();
return $shipments[0] ?? null;
}
}