You are here

public static function StateItem::generateSampleValue in State Machine 8

Generates placeholder field values.

Useful when populating site with placeholder content during site building or profiling.

Parameters

\Drupal\Core\Field\FieldDefinitionInterface $field_definition: The field definition.

Return value

array An associative array of values.

Overrides FieldItemBase::generateSampleValue

File

src/Plugin/Field/FieldType/StateItem.php, line 407

Class

StateItem
Plugin implementation of the 'state' field type.

Namespace

Drupal\state_machine\Plugin\Field\FieldType

Code

public static function generateSampleValue(FieldDefinitionInterface $field_definition) {

  // Attempt to determine the right workflow to use.
  if ($callback = $field_definition
    ->getSetting('workflow_callback')) {
    $entity_type_id = $field_definition
      ->getTargetEntityTypeId();
    $entity_storage = \Drupal::entityTypeManager()
      ->getStorage($entity_type_id);
    if (!$entity_storage instanceof ContentEntityStorageInterface) {
      return [];
    }
    $values = [];

    // Attempt to create a sample entity with at least the bundle set.
    if ($bundle_key = $entity_storage
      ->getEntityType()
      ->getKey('bundle')) {
      if ($field_definition
        ->getTargetBundle()) {
        $bundle = $field_definition
          ->getTargetBundle();
      }
      else {
        $bundle_ids = \Drupal::service('entity_type.bundle.info')
          ->getBundleInfo($entity_type_id);
        $bundle = array_rand($bundle_ids);
      }
      $values[$bundle_key] = $bundle;
    }
    $entity = $entity_storage
      ->create($values);
    $workflow_id = call_user_func($callback, $entity);
  }
  else {
    $workflow_id = $field_definition
      ->getSetting('workflow');
  }

  // The workflow could not be determined, cannot generate a sample value.
  if (empty($workflow_id)) {
    return [];
  }

  /** @var \Drupal\state_machine\WorkflowManagerInterface $workflow_manager */
  $workflow_manager = \Drupal::service('plugin.manager.workflow');

  /** @var \Drupal\state_machine\Plugin\Workflow\WorkflowInterface $workflow */
  $workflow = $workflow_manager
    ->createInstance($workflow_id);

  // Select states that allow at least one transition.
  $candidate_states = $states = $workflow
    ->getStates();
  foreach ($candidate_states as $key => $candidate) {
    if (empty($workflow
      ->getPossibleTransitions($candidate
      ->getId()))) {
      unset($states[$key]);
    }
  }
  $random_state = array_rand($states);
  $values = [
    'value' => $states[$random_state]
      ->getId(),
  ];
  return $values;
}