You are here

protected function PriceListRepository::selectPriceListItem in Commerce Pricelist 8.2

Selects the best matching price list item, based on quantity and weight.

Assumes that price list items are ordered by quantity, and that price list IDs are ordered by weight.

Parameters

\Drupal\commerce_pricelist\Entity\PriceListItemInterface[] $price_list_items: The price list items.

int[] $price_list_ids: The price list IDs.

Return value

\Drupal\commerce_pricelist\Entity\PriceListItemInterface The selected price list item.

1 call to PriceListRepository::selectPriceListItem()
PriceListRepository::loadItem in src/PriceListRepository.php
Loads the price list item for the given purchasable entity.

File

src/PriceListRepository.php, line 120

Class

PriceListRepository

Namespace

Drupal\commerce_pricelist

Code

protected function selectPriceListItem(array $price_list_items, array $price_list_ids) {
  if (count($price_list_items) > 1) {

    // Multiple matching price list items found.
    // First, reduce to one per price list, by selecting the quantity tier.
    $grouped_price_list_items = [];
    foreach ($price_list_items as $price_list_item) {
      $price_list_id = $price_list_item
        ->getPriceListId();
      $grouped_price_list_items[$price_list_id] = $price_list_item;
    }

    // Then, select the one whose price list has the smallest weight.
    $price_list_weights = [];
    foreach ($grouped_price_list_items as $price_list_id => $price_list_item) {
      $price_list_weight = array_search($price_list_id, $price_list_ids);
      $price_list_weights[$price_list_id] = $price_list_weight;
    }
    asort($price_list_weights);
    $sorted_price_list_ids = array_keys($price_list_weights);
    $price_list_id = reset($sorted_price_list_ids);
    $price_list_item = $grouped_price_list_items[$price_list_id];
  }
  else {
    $price_list_item = reset($price_list_items);
  }
  return $price_list_item;
}