commerce_amws-8.x-1.x-dev/modules/shipping/src/EventSubscriber/OrderShipment.php
modules/shipping/src/EventSubscriber/OrderShipment.php
<?php
namespace Drupal\commerce_amws_shipping\EventSubscriber;
use Drupal\commerce_amws_shipping\ShipmentService;
use Drupal\entity_sync\Event\TerminateOperationEvent;
use Drupal\entity_sync\Import\Event\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Generates the shipment for Amazon MWS orders.
*/
class OrderShipment implements EventSubscriberInterface {
/**
* The Amazon MWS shipment service.
*
* @var \Drupal\commerce_amws_shipping\ShipmentService
*/
protected $shipmentService;
/**
* Constructs a new OrderShipmentSubscriber object.
*
* @param \Drupal\commerce_amws_shipping\ShipmentService $shipment_service
* The Amazon MWS shipment service.
*/
public function __construct(ShipmentService $shipment_service) {
$this->shipmentService = $shipment_service;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
// We need this to be called after the order items are set in the order.
Events::REMOTE_LIST_TERMINATE => ['setShipment', 80],
];
return $events;
}
/**
* Generates the shipments for the order, if not already set.
*
* @param \Drupal\entity_sync\Event\TerminateOperationEvent $event
* The terminate operation event.
*/
public function setShipment(TerminateOperationEvent $event) {
if (!$this->isApplicable($event)) {
return;
}
$context = $event->getContext();
$order = $context['commerce_order'];
$shipments_field = $order->get('shipments');
if (!$shipments_field->isEmpty()) {
return;
}
$this->shipmentService->createShipment(
$order,
// The remote order.
$context['remote_entity'],
// The remote order items. we have an API Iterator here; get the flat item
// array.
$event->getData()['remote_entities']->getAllItems(),
ShipmentService::DEFAULT_SHIPPING_PROFILE_TYPE
);
// We have set the shipments, save the order.
$order->save();
}
/**
* Returns whether our changes apply to the given sync, operation and action.
*
* The order shipments is created after we have imported the order items.
*
* @param \Drupal\entity_sync\Event\TerminateOperationEvent $event
* The terminate operation event.
*
* @return bool
* Whether the changes in this subscriber should be applied.
*/
protected function isApplicable(TerminateOperationEvent $event) {
if ($event->getOperation() !== 'import_list') {
return FALSE;
}
$sync = $event->getSync();
if ($sync->get('id') !== 'commerce_amws__order_item') {
return FALSE;
}
return TRUE;
}
}
