protected function GenerateProducts::generateSaveProduct in Commerce Bulk 8
Create one product. Used by both batch and non-batch code branches.
2 calls to GenerateProducts::generateSaveProduct()
- GenerateProducts::batchGenerateSaveProduct in modules/
commerce_generate/ src/ Plugin/ DevelGenerate/ GenerateProducts.php - GenerateProducts::generateProducts in modules/
commerce_generate/ src/ Plugin/ DevelGenerate/ GenerateProducts.php
File
- modules/
commerce_generate/ src/ Plugin/ DevelGenerate/ GenerateProducts.php, line 566
Class
- GenerateProducts
- Provides a GenerateProducts plugin.
Namespace
Drupal\commerce_generate\Plugin\DevelGenerateCode
protected function generateSaveProduct(&$results) {
if (!isset($results['time_range'])) {
$results['time_range'] = 0;
}
$users = $results['users'];
$title = empty($results['title_length']) ? '' : ' ' . $this
->getRandom()
->sentences(mt_rand(1, $results['title_length']), TRUE);
$store = $this->storeStorage
->load(array_rand(array_filter($results['stores'])));
$code = $store
->getDefaultCurrencyCode();
$values = [
'price' => new Price($this
->getRandomPrice($results), $code),
];
if ($list_price = !empty($results['list_price_min']) && !empty($results['list_price_max'])) {
$values['list_price'] = new Price($this
->getRandomPrice($results, 'list_'), $code);
}
$product_type = array_rand(array_filter($results['product_types']));
// Anonymous user (uid = 0) cannot be assigned as product owner.
$uid = $users[array_rand($users)] ?: $users[array_rand($users)];
$product = $this->productStorage
->create([
'type' => $product_type,
'title' => "{$results['title_prefix']}{$title}",
'uid' => $uid,
'created' => REQUEST_TIME - mt_rand(0, $results['time_range']),
'langcode' => $this
->getLangcode($results),
]);
// See example usage of the commerce_generate property.
// @see devel_generate_entity_insert()
// @see commerce_generate_commerce_product_insert()
$product->commerce_generate = $results;
$all = [
'shuffle_variations' => $results['shuffle_variations'],
'max_nb_skus' => $results['max_nb_skus'],
];
$variations = $this->creator
->createAllProductVariations($product, $values, $all);
foreach ($variations as $variation) {
// Generate custom field's sample value, such as variation image.
$this
->populateFields($variation);
if ($results['price_per_variation']) {
$variation
->setPrice(new Price($this
->getRandomPrice($results), $code));
if ($list_price) {
$variation
->setListPrice(new Price($this
->getRandomPrice($results, 'list_'), $code));
}
}
}
// Populate all the rest fields with sample values.
$this
->populateFields($product);
// The populateFields() generates too much paragraphs, so do it here.
$product
->get('body')
->setvalue($this
->getRandom()
->paragraphs(2));
$product
->setStores([
$store,
]);
$product
->setVariations($variations);
$product
->save();
}