You are here

public function BulkVariationsCreator::getAttributeFieldOptionIds in Commerce Bulk 8

Gets the IDs of the variation's attribute fields.

Parameters

\Drupal\commerce_product\Entity\ProductVariation $variation: The commerce product variation.

Return value

array An array of IDs arrays keyed by field name.

Overrides BulkVariationsCreatorInterface::getAttributeFieldOptionIds

1 call to BulkVariationsCreator::getAttributeFieldOptionIds()
BulkVariationsCreator::getUsedAttributesCombinations in src/BulkVariationsCreator.php
Gets used combinations on a product.

File

src/BulkVariationsCreator.php, line 437

Class

BulkVariationsCreator
Default implementation of the BulkVariationsCreatorInterface.

Namespace

Drupal\commerce_bulk

Code

public function getAttributeFieldOptionIds(ProductVariation $variation) {
  $count = 1;
  $field_options = $ids = $options = $attributeopt = [];
  if (($product = $variation
    ->getProduct()) && $product->attributeopt) {
    $attributeopt = $product->attributeopt->value;
  }
  foreach ($this
    ->getAttributeFieldNames($variation) as $field_name => $values) {
    if ($attributeopt) {
      $values = array_filter($values, function ($k) use ($attributeopt, $field_name) {
        return isset($attributeopt[$field_name][$k]);
      }, ARRAY_FILTER_USE_KEY);
    }
    $definition = $variation
      ->get($field_name)
      ->getFieldDefinition();
    $ids[$field_name] = $options[$field_name] = [];
    foreach ($values as $value) {
      if (is_array($value) && ($keys = array_keys($value))) {
        $ids[$field_name] = array_unique(array_merge($ids[$field_name], $keys));
        $options[$field_name] += $value;
      }
      elseif ($keys = array_keys($values)) {
        $ids[$field_name] = array_unique(array_merge($ids[$field_name], $keys));
        $options[$field_name] += $values;
      }

      // Optional fields need '_none' id as a possible choice.
      !$definition
        ->isRequired() && !in_array('_none', $ids[$field_name]) && array_unshift($ids[$field_name], '_none');
      array_walk($ids[$field_name], function (&$id) {
        $id = (string) $id;
      });
    }
    $count *= count($ids[$field_name]);
  }
  $field_options['ids'] = $ids;
  $field_options['options'] = $options;
  $field_options['count'] = $count;
  return $field_options;
}