<?php
// Act on content entities when loaded from the storage.
// The results of this hook will be cached.
// It makes possible to add necessary data to the fields wich will be available in preprocess or for render
// Or add data to entity object.
/**
* Implements hook_entity_storage_load().
*/
function hook_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) {
/** @var \Drupal\Core\Entity\ContentEntityInterface $entity */
// Examine every image field instance attached to this entity's bundle.
foreach ($entity->getFieldDefinitions() as $field_definition) {
$field_name = $field_definition->getName();
$types[] = $field_definition->getType();
if ($field_definition->getType() == 'image') {
if (!empty($entity->{$field_name})) {
/** @var \Drupal\image\Plugin\Field\FieldType\ImageItem $item */
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 entity type.
$values = $item->getValue();
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();
$values[$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);
}
}
$item->setValue($values);
}
}
}
}
}
}
}