You are here

public static function GenerateProducts::populateFields in Commerce Bulk 8

Populate the fields on a given entity with sample values.

Parameters

\Drupal\Core\Entity\EntityInterface $entity: The entity to be enriched with sample field values.

1 call to GenerateProducts::populateFields()
GenerateProducts::generateSaveProduct in modules/commerce_generate/src/Plugin/DevelGenerate/GenerateProducts.php
Create one product. Used by both batch and non-batch code branches.

File

modules/commerce_generate/src/Plugin/DevelGenerate/GenerateProducts.php, line 626

Class

GenerateProducts
Provides a GenerateProducts plugin.

Namespace

Drupal\commerce_generate\Plugin\DevelGenerate

Code

public static function populateFields(EntityInterface $entity) {

  /** @var \Drupal\field\FieldConfigInterface[] $instances */
  $instances = \Drupal::entityTypeManager()
    ->getStorage('field_config')
    ->loadByProperties([
    'entity_type' => $entity
      ->getEntityType()
      ->id(),
    'bundle' => $entity
      ->bundle(),
  ]);
  if ($skips = function_exists('drush_get_option') ? drush_get_option('skip-fields', '') : @$_REQUEST['skip-fields']) {
    foreach (explode(',', $skips) as $skip) {
      unset($instances[$skip]);
    }
  }
  foreach ($instances as $instance) {
    $field_storage = $instance
      ->getFieldStorageDefinition();
    $field_name = $field_storage
      ->getName();
    $type = $field_storage
      ->getSetting('target_type');

    // These fields are populated in the ::generateSaveProduct() method.
    if ($type == 'commerce_product_attribute_value' || $field_name == 'stores' || $field_name == 'variations' || $field_name == 'body') {
      continue;
    }
    $max = $cardinality = $field_storage
      ->getCardinality();
    if ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {

      // Just an arbitrary number for 'unlimited'.
      $max = rand(1, 3);
    }
    $entity->{$field_name}
      ->generateSampleItems($max);
  }
}