You are here

function image_replace_field_attach_presave in Image Replace 7

Implements hook_field_attach_presave().

Insert image mappings into the image replace table when entities are saved.

1 call to image_replace_field_attach_presave()
image_replace_rebuild_mapping_action in ./image_replace.rules.inc
Rules action callback: Rebuild image replacement mapping for a given entity.

File

./image_replace.module, line 160
Provides an image style effect replacing the whole image with another one.

Code

function image_replace_field_attach_presave($entity_type, $entity) {
  list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity);

  // Collect involved image fields and target mapping from image instance
  // settings.
  $involved_fields = array();
  $target_map = array();
  foreach (_image_replace_image_instances($entity_type, $bundle) as $target_field => $instance) {
    $source_map = _image_replace_instance_setting($instance, 'source_field');
    if (!empty($source_map)) {
      $involved_fields[$target_field] = $target_field;
      foreach ($source_map as $target_style => $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 = array();
  foreach ($involved_fields as $field_name) {
    $uri_map[$field_name] = array();
    $items = field_get_items($entity_type, $entity, $field_name);
    if ($items) {
      foreach ($items as $item) {
        $file = file_load($item['fid']);
        $uri_map[$field_name][] = $file->uri;
      }
    }
  }

  // Synchronize image replacement entries.
  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) {
        image_replace_remove($target_style, $target_uri);
        if (isset($uri_map[$source_field][$delta])) {
          image_replace_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);
    }
  }
}