commerce_amws-8.x-1.x-dev/modules/shipping/src/EventSubscriber/ShipmentQueueExportValidate.php
modules/shipping/src/EventSubscriber/ShipmentQueueExportValidate.php
<?php
namespace Drupal\commerce_amws_shipping\EventSubscriber;
use Drupal\commerce_amws\MachineName\Bundle\Order as OrderBundle;
use Drupal\commerce_amws\MachineName\Field\Order as OrderField;
use Drupal\commerce_amws_shipping\Plugin\EntitySync\OperationConfigurator\FeedPostOrderFulfillmentData;
use Drupal\entity_sync\Entity\OperationTypeInterface;
use Drupal\entity_sync\Event\QueueOperationEvent;
use Drupal\entity_sync\Export\Event\Events;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Validates that the shipment has been shipped.
*/
class ShipmentQueueExportValidate implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
Events::LOCAL_ENTITY_QUEUE => ['validate', 0],
];
return $events;
}
/**
* Validates that the shipment should be queued.
*
* The Entity Synchronization state manager takes care of triggering the
* export when a shipment is created and when any of the exportable fields
* (state and tracking codes) change.
*
* The purpose of the export is to send fulfillment data i.e. carrier
* information and tracking codes to Amazon MWS. If the item has not been
* shipped there's no information to send and, in fact, the feed submissions
* will be rejected.
*
* We therefore cancel queueing the export if the item is not in shipped
* state.
*
* We also cancel if the order is not an Amazon MWS order.
*
* @param \Drupal\entity_sync\Event\QueueOperationEvent $event
* The queue operation event.
*/
public function validate(QueueOperationEvent $event) {
$operation_type = $event->getSync();
if (!$operation_type instanceof OperationTypeInterface) {
return;
}
$plugin = $operation_type->getPlugin();
if (!$plugin instanceof FeedPostOrderFulfillmentData) {
return;
}
$shipment = $event->getContext()['local_entity'];
// Only export shipped shipments.
// We don't log a message as we would spam the logs unnecessarily.
if ($shipment->get('state')->first()->getId() !== 'shipped') {
$event->cancel();
return;
}
$order = $shipment->getOrder();
if (!$order) {
$event->cancel(sprintf(
'No order found for shipment with ID "%s"',
$shipment->id()
));
return;
}
// We only export Amazon MWS orders.
// We don't log a message as we would spam the logs unnecessarily.
if ($order->bundle() !== OrderBundle::AMWS) {
$event->cancel();
return;
}
// Lastly, do not queue if we don't have the Amazon MWS store. That must be
// by error, log a message.
if ($order->get(OrderField::AMWS_STORE)->isEmpty()) {
$event->cancel(sprintf(
'No Amazon MWS store found for shipment with ID "%s"',
$shipment->id()
));
return;
}
}
}
