You are here

public function ProductVariationStorage::loadEnabled in Commerce Core 8.2

Loads the enabled product variations for the given product.

Enabled variations are active variations that have been filtered through the FILTER_VARIATIONS event.

Parameters

\Drupal\commerce_product\Entity\ProductInterface $product: The product.

Return value

\Drupal\commerce_product\Entity\ProductVariationInterface[] The enabled product variations.

Overrides ProductVariationStorageInterface::loadEnabled

File

modules/product/src/ProductVariationStorage.php, line 111

Class

ProductVariationStorage
Defines the product variation storage.

Namespace

Drupal\commerce_product

Code

public function loadEnabled(ProductInterface $product) {
  $ids = [];
  foreach ($product->variations as $variation) {
    $ids[$variation->target_id] = $variation->target_id;
  }

  // Speed up loading by filtering out the IDs of disabled variations.
  $query = $this
    ->getQuery()
    ->accessCheck(TRUE)
    ->addTag('entity_access')
    ->condition('status', TRUE)
    ->condition('variation_id', $ids, 'IN');
  $result = $query
    ->execute();
  if (empty($result)) {
    return [];
  }

  // Restore the original sort order.
  $result = array_intersect_key($ids, $result);

  /** @var \Drupal\commerce_product\Entity\ProductVariationInterface $enabled_variation */
  $enabled_variations = $this
    ->loadMultiple($result);

  // Allow modules to apply own filtering (based on date, stock, etc).
  $event = new FilterVariationsEvent($product, $enabled_variations);
  $this->eventDispatcher
    ->dispatch(ProductEvents::FILTER_VARIATIONS, $event);
  $enabled_variations = $event
    ->getVariations();

  // Filter out variations that can't be accessed.
  foreach ($enabled_variations as $variation_id => $enabled_variation) {
    if (!$enabled_variation
      ->access('view')) {
      unset($enabled_variations[$variation_id]);
    }
  }
  return $enabled_variations;
}