You are here

private function ReferenceMigrator::updateReferencingEntity in Term reference change 8

Changes the reference of an entity from the source term to the target term.

Parameters

\Drupal\taxonomy\TermInterface $sourceTerm: The term to migrate from.

\Drupal\taxonomy\TermInterface $targetTerm: The term to migrate to.

string[] $referenceFieldNames: Names of possible entityReference fields.

\Drupal\Core\Entity\FieldableEntityInterface $entity: The entity to update.

Throws

\Drupal\Core\Entity\EntityStorageException

1 call to ReferenceMigrator::updateReferencingEntity()
ReferenceMigrator::migrateReference in src/ReferenceMigrator.php
Updates the term reference on all entities from the source to the target.

File

src/ReferenceMigrator.php, line 151

Class

ReferenceMigrator
Migrates references from one taxonomy term to the other.

Namespace

Drupal\term_reference_change

Code

private function updateReferencingEntity(TermInterface $sourceTerm, TermInterface $targetTerm, array $referenceFieldNames, FieldableEntityInterface $entity) {
  foreach ($referenceFieldNames as $fieldName) {
    $value = [];
    if (!$entity
      ->hasField($fieldName)) {
      continue;
    }
    $values = $entity->{$fieldName}
      ->getValue();
    if (empty($values)) {
      continue;
    }
    $referenceUpdated = FALSE;
    foreach ($values as &$value) {
      if ($value['target_id'] !== $sourceTerm
        ->id()) {
        continue;
      }
      $referenceUpdated = TRUE;
      $value['target_id'] = $targetTerm
        ->id();
    }
    if (!$referenceUpdated) {
      continue;
    }
    $entity->{$fieldName}
      ->setValue($this
      ->removeDuplicates($values));
    $entity
      ->save();
  }
}