function image_replace_entity_presave in Image Replace 8
Implements hook_field_attach_presave().
Insert image mappings into the image replace table when entities are saved.
File
- ./
image_replace.module, line 93 - Provides an image style effect replacing the whole image with another one.
Code
function image_replace_entity_presave(EntityInterface $entity) {
if (!$entity instanceof ContentEntityInterface) {
return;
}
// Collect involved image fields and target mapping from image instance
// settings.
$involved_fields = [];
$target_map = [];
foreach (_image_replace_image_fields($entity
->getEntityTypeId(), $entity
->bundle()) as $target_field => $field) {
if ($field && ($source_map = $field
->getThirdPartySetting('image_replace', 'image_style_map', []))) {
$involved_fields[$target_field] = $target_field;
foreach ($source_map as $target_style => $record) {
$source_field = $record['source_field'];
$target_map[$target_field][$target_style] = $source_field;
$involved_fields[$source_field] = $source_field;
}
}
}
// Extract all uris from all involved image fields.
$uri_map = [];
foreach ($involved_fields as $field_name) {
$uri_map[$field_name] = [];
if (!empty($entity->{$field_name})) {
foreach ($entity->{$field_name} as $image) {
$uri_map[$field_name][] = $image->entity
->getFileUri();
}
}
}
// Synchronize image replacement entries.
$storage_service = \Drupal::service('image_replace.storage');
foreach ($target_map as $target_field => $source_map) {
foreach ($source_map as $target_style => $source_field) {
foreach ($uri_map[$target_field] as $delta => $target_uri) {
$storage_service
->remove($target_style, $target_uri);
if (isset($uri_map[$source_field][$delta])) {
$storage_service
->add($target_style, $target_uri, $uri_map[$source_field][$delta]);
}
}
}
}
// Flush derived images.
foreach ($uri_map as $uris) {
foreach ($uris as $uri) {
image_path_flush($uri);
}
}
}