You are here

function file_entity_entity_storage_load in File Entity (fieldable files) 8.2

Implements hook_entity_storage_load().

File

./file_entity.module, line 390
Extends Drupal file entities to be fieldable and viewable.

Code

function file_entity_entity_storage_load($entities, $entity_type) {
  $token_service = \Drupal::token();
  $replace_options = [
    'clear' => TRUE,
    'sanitize' => FALSE,
  ];
  $config = \Drupal::config('file_entity.settings');

  // Loop over all the entities looking for entities with attached images.
  foreach ($entities as $entity) {

    // Skip non-fieldable entities.
    if (!$entity instanceof FieldableEntityInterface) {
      continue;
    }

    /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */

    // Examine every image field instance attached to this entity's bundle.
    foreach ($entity
      ->getFieldDefinitions() as $field_definition) {
      if ($field_definition
        ->getSetting('target_type') == 'file' && $field_definition
        ->getType() != 'image') {
        $field_name = $field_definition
          ->getName();
        if (!empty($entity->{$field_name})) {
          foreach ($entity->{$field_name} as $delta => $item) {

            // If alt and title text is not specified, fall back to alt and
            // title text on the file.
            if (!empty($item->target_id) && (empty($item->alt) || empty($item->title))) {
              foreach ([
                'alt',
                'title',
              ] as $key) {
                if (empty($item->{$key})) {
                  $token_bubbleable_metadata = new BubbleableMetadata();
                  $item->{$key} = $token_service
                    ->replace($config
                    ->get($key), [
                    'file' => $item->entity,
                  ], $replace_options, $token_bubbleable_metadata);

                  // Add the cacheability metadata of the token to the entity.
                  // This means attachments are discarded, but it does not ever
                  // make sense to have attachments for an image's "alt" and
                  // "title"attribute anyway, so this is acceptable.
                  $entity
                    ->addCacheableDependency($token_bubbleable_metadata);
                }
              }
            }
          }
        }
      }
    }
  }
}