commerce_amws-8.x-1.x-dev/modules/order/src/EventSubscriber/OrderSetItems.php

modules/order/src/EventSubscriber/OrderSetItems.php
<?php

namespace Drupal\commerce_amws_order\EventSubscriber;

use Drupal\entity_sync\Import\Event\Events;
use Drupal\entity_sync\Event\TerminateOperationEvent;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

/**
 * Sets the items in the corresponding order field they have been imported.
 */
class OrderSetItems implements EventSubscriberInterface {

  /**
   * The entity type manager.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new OrderSetItems object.
   *
   * @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
   *   The entity type manager.
   */
  public function __construct(EntityTypeManagerInterface $entity_type_manager) {
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events = [
      // We need the order's store to be set before setting the order items
      // because setting the items triggers recalculating the order total and
      // which at some point during order processing requires the store for
      // getting the calculation date.
      Events::REMOTE_LIST_TERMINATE => ['setItems', 90],
    ];
    return $events;
  }

  /**
   * Trigger dependent synchronizations for the order import.
   *
   * @param \Drupal\entity_sync\Event\TerminateOperationEvent $event
   *   The terminate operation event.
   */
  public function setItems(TerminateOperationEvent $event) {
    if (!$this->isApplicable($event)) {
      return;
    }

    $context = $event->getContext();
    $order = $context['commerce_order'];

    $order_items = $this->entityTypeManager
      ->getStorage('commerce_order_item')
      ->loadByProperties([
        'order_id' => $order->id(),
      ]);
    $order->setItems($order_items ?? []);
    $order->save();
  }

  /**
   * Returns whether our changes apply to the given sync, operation and action.
   *
   * The order items are stored in the corresponding order field 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;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc