You are here

public function OrderItemMatcher::matchAll in Commerce Core 8.2

Finds all matching order items for the given order item.

Parameters

\Drupal\commerce_order\Entity\OrderItemInterface $order_item: The order item.

\Drupal\commerce_order\Entity\OrderItemInterface[] $order_items: The order items to match against.

Return value

\Drupal\commerce_order\Entity\OrderItemInterface[] The matching order items.

Overrides OrderItemMatcherInterface::matchAll

1 call to OrderItemMatcher::matchAll()
OrderItemMatcher::match in modules/cart/src/OrderItemMatcher.php
Finds the first matching order item for the given order item.

File

modules/cart/src/OrderItemMatcher.php, line 54

Class

OrderItemMatcher
Default implementation of the order item matcher.

Namespace

Drupal\commerce_cart

Code

public function matchAll(OrderItemInterface $order_item, array $order_items) {
  $purchased_entity = $order_item
    ->getPurchasedEntity();
  if (empty($purchased_entity)) {

    // Don't support combining order items without a purchased entity.
    return [];
  }
  $comparison_fields = [
    'type',
    'purchased_entity',
  ];
  $comparison_fields = array_merge($comparison_fields, $this
    ->getCustomFields($order_item));
  $event = new OrderItemComparisonFieldsEvent($comparison_fields, $order_item);
  $this->eventDispatcher
    ->dispatch(CartEvents::ORDER_ITEM_COMPARISON_FIELDS, $event);
  $comparison_fields = $event
    ->getComparisonFields();
  $comparison_fields = array_unique($comparison_fields);
  $matched_order_items = [];

  /** @var \Drupal\commerce_order\Entity\OrderItemInterface $existing_order_item */
  foreach ($order_items as $existing_order_item) {
    foreach ($comparison_fields as $field_name) {
      if (!$existing_order_item
        ->hasField($field_name) || !$order_item
        ->hasField($field_name)) {

        // The field is missing on one of the order items.
        continue 2;
      }
      $existing_order_item_field = $existing_order_item
        ->get($field_name);
      $order_item_field = $order_item
        ->get($field_name);

      // Two empty fields should be considered identical, but an empty item
      // can affect the comparison and cause a false mismatch.
      $existing_order_item_field = $existing_order_item_field
        ->filterEmptyItems();
      $order_item_field = $order_item_field
        ->filterEmptyItems();
      if (!$existing_order_item_field
        ->equals($order_item_field)) {

        // Order item doesn't match.
        continue 2;
      }
    }
    $matched_order_items[] = $existing_order_item;
  }
  return $matched_order_items;
}