commerce_amws-8.x-1.x-dev/modules/order/src/EventSubscriber/OrderSetAmwsStore.php
modules/order/src/EventSubscriber/OrderSetAmwsStore.php
<?php
namespace Drupal\commerce_amws_order\EventSubscriber;
use Drupal\commerce_amws\MachineName\Field\Order as OrderField;
use Drupal\entity_sync\Import\Event\Events;
use Drupal\entity_sync\Import\ManagerInterface;
use Drupal\entity_sync\Event\TerminateOperationEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Sets the Amazon MWS store in the order.
*/
class OrderSetAmwsStore implements EventSubscriberInterface {
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
$events = [
Events::REMOTE_ENTITY_TERMINATE => ['setAmwsStore', 0],
];
return $events;
}
/**
* Sets the Amazon MWS store that the order belongs to.
*
* We wouldn't have it available in a field mapping callback.
*
* @param \Drupal\entity_sync\Event\TerminateOperationEvent $event
* The terminate operation event.
*/
public function setAmwsStore(TerminateOperationEvent $event) {
if (!$this->isApplicable($event)) {
return;
}
$data = $event->getData();
// We only need to set the store the first time that the order is
// created. No need to reset it on updates, and nothing to do on skips. If
// the action was a skip, the `local_entity` wouldn't be available in the
// data and we would be getting an error anyways.
if ($data['action'] !== ManagerInterface::ACTION_CREATE) {
return;
}
$data['local_entity']->set(
OrderField::AMWS_STORE,
['target_id' => $event->getContext()['amws_store_id']]
);
$event->setSaveLocalEntity(TRUE);
}
/**
* Returns whether our changes apply to the given sync, operation and action.
*
* @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_entity') {
return FALSE;
}
$sync = $event->getSync();
if ($sync->get('id') !== 'commerce_amws__order') {
return FALSE;
}
return TRUE;
}
}
