You are here

public function ServiceAuditFilesMergeFileReferences::auditfilesMergeFileReferencesUpdateFileFields in Audit Files 8.3

Same name and namespace in other branches
  1. 8.2 src/ServiceAuditFilesMergeFileReferences.php \Drupal\auditfiles\ServiceAuditFilesMergeFileReferences::auditfilesMergeFileReferencesUpdateFileFields()

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::auditfilesMergeFileReferencesUpdateFileFields()
ServiceAuditFilesMergeFileReferences::auditfilesMergeFileReferencesBatchMergeProcessFile in src/ServiceAuditFilesMergeFileReferences.php
Deletes the specified file from the file_managed table.

File

src/ServiceAuditFilesMergeFileReferences.php, line 303

Class

ServiceAuditFilesMergeFileReferences
Define all methods that used in merge file references functionality.

Namespace

Drupal\auditfiles

Code

public function auditfilesMergeFileReferencesUpdateFileFields($file_being_kept, $file_being_merged) {
  $file_being_merged_fields = file_get_file_references($this->entityTypeManager
    ->getStorage('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 = $this->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) {
            if ($item['target_id'] == $file_being_merged) {
              $file_object_being_kept = $this->entityTypeManager
                ->getStorage('file')
                ->load($file_being_kept);
              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;
            }
          }
        }
      }
    }
  }
}