You are here

public function ProductVariationAttributeMapper::selectVariation in Commerce Core 8.2

Selects the best matching variation for the given attribute values.

Takes the first variation that matches the most attribute values. Partial matches are considered when a full match cannot be made. For example, when given [Red, Small, Cotton], the search priority is: 1) [Red, Small, Cotton] 2) [Red, Small] 3) [Red]

Parameters

\Drupal\commerce_product\Entity\ProductVariationInterface[] $variations: The variations.

array $attribute_values: Attribute value IDs, keyed by the field name.

Return value

\Drupal\commerce_product\Entity\ProductVariationInterface|null The selected variation, or NULL if none could be selected.

Overrides ProductVariationAttributeMapperInterface::selectVariation

File

modules/product/src/ProductVariationAttributeMapper.php, line 51

Class

ProductVariationAttributeMapper

Namespace

Drupal\commerce_product

Code

public function selectVariation(array $variations, array $attribute_values = []) {
  $selected_variation = NULL;

  // Select the first variation that matches the most attribute values.
  // Start with all attribute values, reduce them by 1 until a match is found.
  while (!empty($attribute_values)) {
    foreach ($variations as $variation) {
      $match = TRUE;
      foreach ($attribute_values as $field_name => $attribute_value_id) {
        if ($variation
          ->getAttributeValueId($field_name) != $attribute_value_id) {
          $match = FALSE;
        }
      }
      if ($match) {
        $selected_variation = $variation;
        break 2;
      }
    }
    array_pop($attribute_values);
  }
  return $selected_variation;
}