You are here

public function QueryStringWebformSourceEntity::getSourceEntity in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Plugin/WebformSourceEntity/QueryStringWebformSourceEntity.php \Drupal\webform\Plugin\WebformSourceEntity\QueryStringWebformSourceEntity::getSourceEntity()

Detect and return a source entity from current context.

Parameters

string[] $ignored_types: Entity types that may not be used as a source entity.

Return value

\Drupal\Core\Entity\EntityInterface|null Source entity or NULL when no source entity is found.

Overrides WebformSourceEntityInterface::getSourceEntity

File

src/Plugin/WebformSourceEntity/QueryStringWebformSourceEntity.php, line 112

Class

QueryStringWebformSourceEntity
Detect source entity by examining query string.

Namespace

Drupal\webform\Plugin\WebformSourceEntity

Code

public function getSourceEntity(array $ignored_types) {

  // Note: We deliberately discard $ignored_types because through query string
  // any arbitrary entity can be injected as a source.
  $webform = $this->routeMatch
    ->getParameter('webform');
  if (!$webform) {
    return NULL;
  }

  // Get and check source entity type.
  $source_entity_type = $this->request->query
    ->get('source_entity_type');
  if (!$source_entity_type || !$this->entityTypeManager
    ->hasDefinition($source_entity_type)) {
    return NULL;
  }

  // Get and check source entity id.
  $source_entity_id = $this->request->query
    ->get('source_entity_id');
  if (!$source_entity_id) {
    return NULL;
  }

  // Get and check source entity.
  $source_entity = $this->entityTypeManager
    ->getStorage($source_entity_type)
    ->load($source_entity_id);
  if (!$source_entity) {
    return NULL;
  }

  // Get translated source entity.
  if ($source_entity instanceof TranslatableInterface && $source_entity
    ->hasTranslation($this->languageManager
    ->getCurrentLanguage()
    ->getId())) {
    $source_entity = $source_entity
      ->getTranslation($this->languageManager
      ->getCurrentLanguage()
      ->getId());
  }

  // Check source entity access.
  if (!$source_entity
    ->access('view')) {
    return NULL;
  }

  // Check that the webform is referenced by the source entity.
  if (!$webform
    ->getSetting('form_prepopulate_source_entity')) {

    // Get source entity's webform field.
    $webform_field_names = $this->webformEntityReferenceManager
      ->getFieldNames($source_entity);
    foreach ($webform_field_names as $webform_field_name) {

      // Check that source entity's reference webform is the
      // current webform.
      foreach ($source_entity->{$webform_field_name} as $item) {
        if ($item->target_id === $webform
          ->id()) {
          return $source_entity;
        }
      }
    }
    return NULL;
  }
  return $source_entity;
}