You are here

public function BulkVariationsCreator::createProductVariation in Commerce Bulk 8

Creates a variation for commerce_product.

Parameters

\Drupal\commerce_product\Entity\Product $product: A commerce product, whether new or having some variations saved on it.

array $variation_custom_values: (optional) An associative array of a variation property values which will be used to auto create sample variation.

array $not_all: (optional) Additional settings to pass, such as the maximum number of variation combinations to create.

Return value

\Drupal\commerce_product\Entity\ProductVariation A commerce_product variation.

Overrides BulkVariationsCreatorInterface::createProductVariation

See also

\Drupal\commerce_product\Entity\ProductVariation->create()

self->createAllProductVariations()

1 call to BulkVariationsCreator::createProductVariation()
BulkVariationsCreator::createAllProductVariations in src/BulkVariationsCreator.php
Creates all possible variations for commerce_product.

File

src/BulkVariationsCreator.php, line 129

Class

BulkVariationsCreator
Default implementation of the BulkVariationsCreatorInterface.

Namespace

Drupal\commerce_bulk

Code

public function createProductVariation(Product $product, array $variation_custom_values = [], array $not_all = [
  'not_all' => TRUE,
]) {
  $combination = [];
  $variation = $this
    ->getProductVariation($product);
  if (($all = $this
    ->getAttributesCombinations([
    $variation,
  ], $not_all)) && $all['not_used_combinations']) {
    $combination = reset($all['not_used_combinations']);
    foreach ($combination as $field_name => $id) {
      $variation
        ->get($field_name)
        ->setValue([
        'target_id' => $id == '_none' ? NULL : $id,
      ]);
    }
  }
  $sku = static::getAutoSku($variation);
  $settings = static::getSkuSettings($variation);
  $clone = clone $variation;
  $sku = empty($sku) ? \uniqid() : $sku;
  $settings['combination'] = $combination;
  \Drupal::moduleHandler()
    ->alter("bulk_creator_sku", $sku, $settings, $clone);
  $variation
    ->setSku($sku);
  foreach ($variation_custom_values as $name => $value) {
    $variation
      ->set($name, $value);
  }
  if (!$variation
    ->getPrice() instanceof Price) {
    $currency_storage = $this->entityTypeManager
      ->getStorage('commerce_currency');
    $currencies = array_keys($currency_storage
      ->loadMultiple());
    $currency = empty($currencies) ? 'USD' : $currencies[0];

    // Decimals are omitted intentionally as $currency format is unknown here.
    // The prices still will have valid format after saving.
    $variation
      ->setPrice(new Price('1', $currency));
  }
  $variation
    ->updateOriginalValues();
  return $variation;
}