You are here

function ServiceAuditFilesMergeFileReferences::_auditfiles_merge_file_references_update_file_fields in Audit Files 8

Updates any fields that might be pointing to the file being merged.

Parameters

int $file_being_kept: The file ID of the file to merge the other into.

int $file_being_merged: The file ID of the file to merge.

1 call to ServiceAuditFilesMergeFileReferences::_auditfiles_merge_file_references_update_file_fields()
ServiceAuditFilesMergeFileReferences::_auditfiles_merge_file_references_batch_merge_process_file in src/ServiceAuditFilesMergeFileReferences.php
Deletes the specified file from the file_managed table.

File

src/ServiceAuditFilesMergeFileReferences.php, line 246
providing the service that used in 'managed not used' functionality.

Class

ServiceAuditFilesMergeFileReferences

Namespace

Drupal\auditfiles

Code

function _auditfiles_merge_file_references_update_file_fields($file_being_kept, $file_being_merged) {
  $connection = Database::getConnection();

  // Get any fields that might be referencing this file being merged.
  $file_being_merged_fields = file_get_file_references(File::load($file_being_merged), NULL, EntityStorageInterface::FIELD_LOAD_REVISION, NULL);
  if (empty($file_being_merged_fields)) {
    return;
  }
  foreach ($file_being_merged_fields as $field_name => $field_references) {
    foreach ($field_references as $entity_type => $type_references) {
      foreach ($type_references as $id => $reference) {
        $entity = \Drupal::entityTypeManager()
          ->getStorage($entity_type)
          ->load($id);
        if ($entity) {
          $field_items = $entity
            ->get($field_name)
            ->getValue();
          $alt = $field_items[0]['alt'];
          $title = $field_items[0]['title'] ? $field_items[0]['title'] : '';
          foreach ($field_items as $item_id => $item) {
            if ($item['target_id'] == $file_being_merged) {
              $file_object_being_kept = File::load($file_being_kept);
              foreach ($entity
                ->get($field_name)
                ->getValue() as $key => $value) {
                if (!empty($file_object_being_kept) && $entity
                  ->get($field_name)
                  ->getValue() != $file_being_kept) {
                  $entity->{$field_name} = [
                    'target_id' => $file_object_being_kept
                      ->id(),
                    'alt' => $alt,
                    'title' => $title,
                  ];
                }
              }
              $entity
                ->save();
              break;
            }
          }
        }
      }
    }
  }
}