dcco-8.x-3.x-dev/modules/dcco_store/inc/dcco_store.inc

modules/dcco_store/inc/dcco_store.inc
<?php

/**
 * @file
 * Helper functions for product creation.
 */

use Drupal\commerce_price\Price;
use Drupal\commerce_product\Entity\ProductVariation;
use Drupal\commerce_product\Entity\Product;
use Drupal\commerce_product\Entity\ProductAttributeValue;

/**
 * Create a product from supplied info.
 *
 * @param array $product
 *   An array of product info.
 * @param array[] $variants
 *   An array of product variant array info.
 *
 * @return \Drupal\commerce_product\Entity\Product
 *   The created product.
 */
function dcco_store_create_product($product, $variants = []) {
  $variations = array_map('dcco_store_create_product_variation', $variants);

  $prod = Product::create([
    'type' => $product['type'],
    'title' => $product['title'],
    'variations' => $variations,
  ]);

  $prod->save();
  return $prod;
}

/**
 * Create a product variation.
 *
 * @param array $variant
 *   An array of product variant info.
 *
 * @return \Drupal\commerce_product\Entity\ProductVariation
 *   The created product variation.
 */
function dcco_store_create_product_variation($variant) {
  $variation = ProductVariation::create([
    'title' => $variant['title'] ?? '',
    'type' => $variant['type'],
    'sku' => $variant['sku'],
    'price' => new Price($variant['price'] ?? '0.00', 'USD'),
  ]);

  $variation->save();
  return $variation;
}

/**
 * Create product attribute values.
 *
 * @param string $attribute_id
 *   The ID of the attribute to add values to.
 * @param string[] $values
 *   An array of value strings.
 *
 * @return \Drupal\commerce_product\Entity\ProductAttributeValue[]
 *   An array of product attribute values.
 */
function dcco_store_create_attribute_values($attribute_id, $values = []) {
  return array_map(function ($value) use ($attribute_id) {
    $attr = ProductAttributeValue::create([
      'attribute' => $attribute_id,
      'name' => $value,
    ]);

    $attr->save();
    return $attr;
  }, $values);
}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc