vendor/ibexa/shipping/src/bundle/EventSubscriber/ShipmentCancellingSubscriber.php line 40

Open in your IDE?
  1. <?php
  2. /**
  3. * @copyright Copyright (C) Ibexa AS. All rights reserved.
  4. * @license For full copyright and license information view LICENSE file distributed with this source code.
  5. */
  6. declare(strict_types=1);
  7. namespace Ibexa\Bundle\Shipping\EventSubscriber;
  8. use Ibexa\Contracts\OrderManagement\Event\BeforeCancelOrderEvent;
  9. use Ibexa\Contracts\OrderManagement\Value\Order\OrderInterface;
  10. use Ibexa\Contracts\Shipping\Shipment\Query\Criterion\Order as ShipmentOrderCriterion;
  11. use Ibexa\Contracts\Shipping\Shipment\ShipmentInterface;
  12. use Ibexa\Contracts\Shipping\Shipment\ShipmentQuery;
  13. use Ibexa\Contracts\Shipping\Shipment\ShipmentUpdateStruct;
  14. use Ibexa\Contracts\Shipping\ShipmentServiceInterface;
  15. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  16. final class ShipmentCancellingSubscriber implements EventSubscriberInterface
  17. {
  18. private ShipmentServiceInterface $shipmentService;
  19. public function __construct(ShipmentServiceInterface $shipmentService)
  20. {
  21. $this->shipmentService = $shipmentService;
  22. }
  23. public static function getSubscribedEvents(): array
  24. {
  25. return [
  26. BeforeCancelOrderEvent::class => 'cancelShipment',
  27. ];
  28. }
  29. /**
  30. * @throws \Ibexa\Contracts\Core\Repository\Exceptions\UnauthorizedException
  31. * @throws \Ibexa\Contracts\Core\Repository\Exceptions\BadStateException
  32. */
  33. public function cancelShipment(BeforeCancelOrderEvent $event): void
  34. {
  35. $shipment = $this->getOrderShipment($event->getOrder());
  36. if ($shipment === null || $shipment->getStatus() === 'cancelled') {
  37. return;
  38. }
  39. $this->shipmentService->updateShipment($shipment, new ShipmentUpdateStruct('cancel'));
  40. }
  41. private function getOrderShipment(OrderInterface $order): ?ShipmentInterface
  42. {
  43. $shipments = $this->shipmentService->findShipments(
  44. new ShipmentQuery(new ShipmentOrderCriterion($order))
  45. )->getShipments();
  46. return $shipments[0] ?? null;
  47. }
  48. }