You are here

class ContentEntityFallback in Entity Language Fallback 8

Represents a datasource which exposes the content entities.

In addition to default ContentEntity behavior, indexes content in languages that don't have translations, but have translations in fallback language(s).

Plugin annotation


@SearchApiDatasource(
  id = "entity_language_fallback",
  deriver = "Drupal\entity_language_fallback\Plugin\search_api\datasource\ContentEntityFallbackDeriver"
)

Hierarchy

Expanded class hierarchy of ContentEntityFallback

1 file declares its use of ContentEntityFallback
entity_language_fallback.module in ./entity_language_fallback.module
Add fallback languages to entities.

File

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

Namespace

Drupal\entity_language_fallback\Plugin\search_api\datasource
View source
class ContentEntityFallback extends ContentEntity {

  /**
   * Fallback controller
   *
   * @var \Drupal\entity_language_fallback\FallbackControllerInterface
   *
   */
  protected $fallbackController;

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {

    /** @var static $datasource */
    $datasource = parent::create($container, $configuration, $plugin_id, $plugin_definition);
    $datasource
      ->setFallbackController($container
      ->get('language_fallback.controller'));
    return $datasource;
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function getPartialItemIds($page = NULL, array $bundles = NULL, array $languages = NULL) {
    $parent_items = parent::getPartialItemIds($page, $bundles, $languages);
    if (empty($parent_items)) {
      return $parent_items;
    }
    $entity_ids = [];
    foreach ($parent_items as $parent_item) {
      list($id, ) = Utility::splitPropertyPath($parent_item);
      $entity_ids[$id] = 1;
    }

    /** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
    foreach ($this
      ->getEntityStorage()
      ->loadMultiple(array_keys($entity_ids)) as $entity_id => $entity) {
      foreach ($this->languages as $langcode => $language) {
        if ($entity
          ->hasTranslation($langcode)) {
          $item_ids[] = "{$entity_id}:{$langcode}";
        }
        else {
          $fallback_found = FALSE;
          foreach ($this->fallback_chain[$langcode] as $candidate) {
            if ($entity
              ->hasTranslation($candidate)) {
              $fallback_found = TRUE;
              break;
            }
          }
          if ($fallback_found) {
            $item_ids[] = "{$entity_id}:{$langcode}";
          }
        }
      }
    }
    return $item_ids;
  }

  /**
   * {@inheritdoc}
   */
  protected function getLanguages() {
    $parent_languages = parent::getLanguages();
    if (!isset($this->languages)) {
      $this->languages = ConfigurableLanguage::loadMultiple(array_keys($parent_languages));
      foreach ($this->languages as $langcode => $language) {
        $this->fallback_chain[$langcode] = $language
          ->getThirdPartySetting('entity_language_fallback', 'fallback_langcodes', []);
      }
    }
    return $parent_languages;
  }

  /**
   * {@inheritdoc}
   */
  public static function getIndexesForEntity(ContentEntityInterface $entity) {
    $datasource_id = 'entity_language_fallback:' . $entity
      ->getEntityTypeId();
    $entity_bundle = $entity
      ->bundle();
    $has_bundles = $entity
      ->getEntityType()
      ->hasKey('bundle');
    $indexes = Index::loadMultiple();
    foreach ($indexes as $index_id => $index) {

      // Filter our indexes that don't contain the datasource in question.
      if (!$index
        ->isValidDatasource($datasource_id)) {
        unset($indexes[$index_id]);
      }
      elseif ($has_bundles) {

        // If the entity type supports bundles, we also have to filter out
        // indexes that exclude the entity's bundle.
        $config = $index
          ->getDatasource($datasource_id)
          ->getConfiguration();
        $default = !empty($config['bundles']['default']);
        $bundle_set = in_array($entity_bundle, $config['bundles']['selected']);
        if ($default == $bundle_set) {
          unset($indexes[$index_id]);
        }
      }
    }
    return $indexes;
  }

  /**
   * Set fallback controller instance.
   *
   * @param \Drupal\entity_language_fallback\FallbackControllerInterface $controller
   */
  public function setFallbackController(FallbackControllerInterface $controller) {
    $this->fallbackController = $controller;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConfigurablePluginBase::calculatePluginDependencies Deprecated protected function Calculates and adds dependencies of a specific plugin instance.
ConfigurablePluginBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
ConfigurablePluginBase::getDescription public function Returns the plugin's description. Overrides ConfigurablePluginInterface::getDescription
ConfigurablePluginBase::getPluginDependencies Deprecated protected function Calculates and returns dependencies of a specific plugin instance.
ConfigurablePluginBase::label public function Returns the label for use on the administration pages. Overrides ConfigurablePluginInterface::label
ConfigurablePluginBase::moduleHandler Deprecated protected function Wraps the module handler.
ConfigurablePluginBase::onDependencyRemoval public function Informs the plugin that some of its dependencies are being removed. Overrides ConfigurablePluginInterface::onDependencyRemoval 5
ConfigurablePluginBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration 3
ConfigurablePluginBase::themeHandler Deprecated protected function Wraps the theme handler.
ContentEntity::$configFactory protected property The config factory.
ContentEntity::$database protected property The database connection.
ContentEntity::$entityDisplayRepository protected property The entity display repository manager.
ContentEntity::$entityFieldManager protected property The entity field manager.
ContentEntity::$entityTypeBundleInfo protected property The entity type bundle info.
ContentEntity::$entityTypeManager protected property The entity type manager.
ContentEntity::$fieldsHelper protected property The fields helper.
ContentEntity::$languageManager protected property The language manager.
ContentEntity::$memoryCache protected property The entity memory cache.
ContentEntity::$state protected property The state service.
ContentEntity::$typedDataManager protected property The typed data manager.
ContentEntity::buildConfigurationForm public function Form constructor. Overrides PluginFormInterface::buildConfigurationForm
ContentEntity::calculateDependencies public function Calculates dependencies for the configured plugin. Overrides ConfigurablePluginBase::calculateDependencies
ContentEntity::canContainEntityReferences public function Determines whether this datasource can contain entity references. Overrides DatasourcePluginBase::canContainEntityReferences
ContentEntity::defaultConfiguration public function Gets default configuration for this plugin. Overrides ConfigurablePluginBase::defaultConfiguration
ContentEntity::getAffectedItemsForEntityChange public function Identifies items affected by a change to a referenced entity. Overrides DatasourcePluginBase::getAffectedItemsForEntityChange
ContentEntity::getBundles public function Retrieves the bundles associated to this datasource. Overrides DatasourcePluginBase::getBundles
ContentEntity::getConfigFactory public function Retrieves the config factory.
ContentEntity::getConfigValue protected function Retrieves the config value for a certain key in the Search API settings.
ContentEntity::getDatabaseConnection public function Retrieves the database connection.
ContentEntity::getEntity protected function Retrieves the entity from a search item.
ContentEntity::getEntityBundleOptions protected function Retrieves the available bundles of this entity type as an options list.
ContentEntity::getEntityBundles protected function Retrieves all bundles of this datasource's entity type.
ContentEntity::getEntityDisplayRepository public function Retrieves the entity display repository.
ContentEntity::getEntityFieldManager public function Retrieves the entity field manager.
ContentEntity::getEntityMemoryCache public function Retrieves the entity memory cache service.
ContentEntity::getEntityStorage protected function Retrieves the entity storage.
ContentEntity::getEntityType protected function Returns the definition of this datasource's entity type.
ContentEntity::getEntityTypeBundleInfo public function Retrieves the entity display repository.
ContentEntity::getEntityTypeId public function Retrieves the entity type ID of items from this datasource, if any. Overrides DatasourcePluginBase::getEntityTypeId
ContentEntity::getEntityTypeManager public function Retrieves the entity type manager.
ContentEntity::getFieldDependencies public function Retrieves any dependencies of the given fields. Overrides DatasourcePluginBase::getFieldDependencies
ContentEntity::getFieldsHelper public function Retrieves the fields helper.
ContentEntity::getItemAccessResult public function Checks whether a user has permission to view the given item. Overrides DatasourcePluginBase::getItemAccessResult
ContentEntity::getItemBundle public function Retrieves the item's bundle. Overrides DatasourcePluginBase::getItemBundle
ContentEntity::getItemId public function Retrieves the unique ID of an object from this datasource. Overrides DatasourceInterface::getItemId
ContentEntity::getItemIds public function Returns a list of IDs of items from this datasource. Overrides DatasourcePluginBase::getItemIds
ContentEntity::getItemLabel public function Retrieves a human-readable label for an item. Overrides DatasourcePluginBase::getItemLabel
ContentEntity::getItemUrl public function Retrieves a URL at which the item can be viewed on the web. Overrides DatasourcePluginBase::getItemUrl
ContentEntity::getLanguageManager public function Retrieves the language manager.
ContentEntity::getListCacheContexts public function Returns the list cache contexts associated with this datasource. Overrides DatasourcePluginBase::getListCacheContexts
ContentEntity::getPropertyDefinitions public function Retrieves the properties exposed by the underlying complex data type. Overrides DatasourcePluginBase::getPropertyDefinitions
ContentEntity::getPropertyPathDependencies protected function Computes all dependencies of the given property path.
ContentEntity::getState public function Retrieves the state service.
ContentEntity::getTranslationOptions protected function Retrieves the available languages of this entity type as an options list.
ContentEntity::getTypedDataManager public function Retrieves the typed data manager.
ContentEntity::getViewModes public function Returns the available view modes for this datasource. Overrides DatasourcePluginBase::getViewModes
ContentEntity::hasBundles protected function Determines whether the entity type supports bundles.
ContentEntity::isTranslatable protected function Determines whether the entity type supports translations.
ContentEntity::setConfigFactory public function Sets the config factory.
ContentEntity::setDatabaseConnection public function Sets the database connection.
ContentEntity::setEntityDisplayRepository public function Sets the entity display repository.
ContentEntity::setEntityFieldManager public function Sets the entity field manager.
ContentEntity::setEntityMemoryCache public function Sets the entity memory cache service.
ContentEntity::setEntityTypeBundleInfo public function Sets the entity type bundle info.
ContentEntity::setEntityTypeManager public function Sets the entity type manager.
ContentEntity::setFieldsHelper public function Sets the fields helper.
ContentEntity::setLanguageManager public function Sets the language manager.
ContentEntity::setState public function Sets the state service.
ContentEntity::setTypedDataManager public function Sets the typed data manager.
ContentEntity::submitConfigurationForm public function Form submission handler. Overrides PluginFormTrait::submitConfigurationForm
ContentEntity::TRACKING_PAGE_STATE_KEY constant The key for accessing last tracked ID information in site state.
ContentEntity::viewItem public function Returns the render array for the provided item and view mode. Overrides DatasourcePluginBase::viewItem
ContentEntity::viewMultipleItems public function Returns the render array for the provided items and view mode. Overrides DatasourcePluginBase::viewMultipleItems
ContentEntity::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides IndexPluginBase::__construct
ContentEntityFallback::$fallbackController protected property Fallback controller
ContentEntityFallback::create public static function Creates an instance of the plugin. Overrides ContentEntity::create
ContentEntityFallback::getIndexesForEntity public static function Overrides ContentEntity::getIndexesForEntity
ContentEntityFallback::getLanguages protected function Retrieves the enabled languages. Overrides ContentEntity::getLanguages
ContentEntityFallback::getPartialItemIds public function Overrides ContentEntity::getPartialItemIds
ContentEntityFallback::loadMultiple public function Loads multiple items. Overrides ContentEntity::loadMultiple
ContentEntityFallback::setFallbackController public function Set fallback controller instance.
DatasourcePluginBase::checkItemAccess public function Checks whether a user has permission to view the given item. Overrides DatasourceInterface::checkItemAccess
DatasourcePluginBase::getItemLanguage public function Retrieves the item's language. Overrides DatasourceInterface::getItemLanguage 1
DatasourcePluginBase::load public function Loads an item. Overrides DatasourceInterface::load
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DependencyTrait::$dependencies protected property The object's dependencies.
DependencyTrait::addDependencies protected function Adds multiple dependencies.
DependencyTrait::addDependency protected function Adds a dependency.
HideablePluginBase::isHidden public function Determines whether this plugin should be hidden in the UI. Overrides HideablePluginInterface::isHidden 1
IndexPluginBase::$index protected property The index this processor is configured for.
IndexPluginBase::getIndex public function Retrieves the index this plugin is configured for. Overrides IndexPluginInterface::getIndex
IndexPluginBase::setIndex public function Sets the index this plugin is configured for. Overrides IndexPluginInterface::setIndex
LoggerTrait::$logger protected property The logging channel to use.
LoggerTrait::getLogger public function Retrieves the logger.
LoggerTrait::logException protected function Logs an exception.
LoggerTrait::setLogger public function Sets the logger.
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 3
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
PluginDependencyTrait::calculatePluginDependencies protected function Calculates and adds dependencies of a specific plugin instance. Aliased as: traitCalculatePluginDependencies 1
PluginDependencyTrait::getPluginDependencies protected function Calculates and returns dependencies of a specific plugin instance. Aliased as: traitGetPluginDependencies
PluginDependencyTrait::moduleHandler protected function Wraps the module handler. Aliased as: traitModuleHandler 1
PluginDependencyTrait::themeHandler protected function Wraps the theme handler. Aliased as: traitThemeHandler 1
PluginFormTrait::validateConfigurationForm public function Form validation handler. 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.