ContentEntityStorageBase::invokeFieldMethod

protected ContentEntityStorageBase::invokeFieldMethod($method, ContentEntityInterface $entity)

Invokes a method on the Field objects within an entity.

Any argument passed will be forwarded to the invoked method.

Parameters

string $method: The name of the method to be invoked.

\Drupal\Core\Entity\ContentEntityInterface $entity: The entity object.

Return value

array A multidimensional associative array of results, keyed by entity translation language code and field name.

File

core/lib/Drupal/Core/Entity/ContentEntityStorageBase.php, line 435

Class

ContentEntityStorageBase
Base class for content entity storage handlers.

Namespace

Drupal\Core\Entity

Code

protected function invokeFieldMethod($method, ContentEntityInterface $entity) {
  $result = [];
  $args = array_slice(func_get_args(), 2);
  $langcodes = array_keys($entity->getTranslationLanguages());
  // Ensure that the field method is invoked as first on the current entity
  // translation and then on all other translations.
  $current_entity_langcode = $entity->language()->getId();
  if (reset($langcodes) != $current_entity_langcode) {
    $langcodes = array_diff($langcodes, [$current_entity_langcode]);
    array_unshift($langcodes, $current_entity_langcode);
  }
  foreach ($langcodes as $langcode) {
    $translation = $entity->getTranslation($langcode);
    // For non translatable fields, there is only one field object instance
    // across all translations and it has as parent entity the entity in the
    // default entity translation. Therefore field methods on non translatable
    // fields should be invoked only on the default entity translation.
    $fields = $translation->isDefaultTranslation() ? $translation->getFields() : $translation->getTranslatableFields();
    foreach ($fields as $name => $items) {
      // call_user_func_array() is way slower than a direct call so we avoid
      // using it if have no parameters.
      $result[$langcode][$name] = $args ? call_user_func_array([$items, $method], $args) : $items->{$method}();
    }
  }

  // We need to call the delete method for field items of removed
  // translations.
  if ($method == 'postSave' && !empty($entity->original)) {
    $original_langcodes = array_keys($entity->original->getTranslationLanguages());
    foreach (array_diff($original_langcodes, $langcodes) as $removed_langcode) {
      $translation = $entity->original->getTranslation($removed_langcode);
      $fields = $translation->getTranslatableFields();
      foreach ($fields as $name => $items) {
        $items->delete();
      }
    }
  }

  return $result;
}
doc_Drupal
2016-10-29 08:57:34
Comments
Leave a Comment

Please login to continue.