You are here

public function ContentEntityFallback::loadMultiple in Entity Language Fallback 8

Loads multiple items.

Parameters

array $ids: An array of datasource-specific item IDs.

Return value

\Drupal\Core\TypedData\ComplexDataInterface[] An associative array of loaded items, keyed by their (datasource-specific) IDs.

Overrides ContentEntity::loadMultiple

File

src/Plugin/search_api/datasource/ContentEntityFallback.php, line 48

Class

ContentEntityFallback
Represents a datasource which exposes the content entities.

Namespace

Drupal\entity_language_fallback\Plugin\search_api\datasource

Code

public function loadMultiple(array $ids) {
  $allowed_languages = $this
    ->getLanguages();
  $entity_ids = [];
  foreach ($ids as $item_id) {
    $pos = strrpos($item_id, ':');

    // This can only happen if someone passes an invalid ID, since we always
    // include a language code. Still, no harm in guarding against bad input.
    if ($pos === FALSE) {
      continue;
    }
    $entity_id = substr($item_id, 0, $pos);
    $langcode = substr($item_id, $pos + 1);
    if (isset($allowed_languages[$langcode])) {
      $entity_ids[$entity_id][$item_id] = $langcode;
    }
  }

  /** @var \Drupal\Core\Entity\ContentEntityInterface[] $entities */
  $entities = $this
    ->getEntityStorage()
    ->loadMultiple(array_keys($entity_ids));
  $items = [];
  $allowed_bundles = $this
    ->getBundles();
  foreach ($entity_ids as $entity_id => $langcodes) {
    if (empty($entities[$entity_id]) || !isset($allowed_bundles[$entities[$entity_id]
      ->bundle()])) {
      continue;
    }
    foreach ($this->languages as $langcode => $language) {
      $item_id = $entity_id . ':' . $langcode;
      if (!in_array($item_id, $ids)) {
        continue;
      }
      if ($entities[$entity_id]
        ->hasTranslation($langcode)) {
        $items[$item_id] = $entities[$entity_id]
          ->getTranslation($langcode)
          ->getTypedData();
        $items[$item_id]->language = $langcode;
      }
      else {
        $source = $this->fallbackController
          ->getTranslation($langcode, $entities[$entity_id]);
        if (!$source) {
          continue;
        }
        $translation = $entities[$entity_id]
          ->addTranslation($langcode, $source
          ->toArray());
        $items[$item_id] = $translation
          ->getTypedData();
        $items[$item_id]->language = $langcode;
      }
    }
  }
  return $items;
}