You are here

public function UserRole::setTarget in Feeds 8.3

Sets the values on an object.

Parameters

\Drupal\feeds\FeedInterface $feed: The feed object.

\Drupal\Core\Entity\EntityInterface $entity: The target object.

string $target: The name of the target to set.

array $values: A list of values to set on the target.

Overrides ConfigEntityReference::setTarget

File

src/Feeds/Target/UserRole.php, line 48

Class

UserRole
Defines a user role mapper.

Namespace

Drupal\feeds\Feeds\Target

Code

public function setTarget(FeedInterface $feed, EntityInterface $entity, $field_name, array $values) {

  // Check if values list is currently empty.
  $entity_target = $this
    ->getEntityTarget($feed, $entity);
  $is_empty = empty($entity_target
    ->get($field_name)
    ->getValue());
  if (empty($entity_target)) {
    return;
  }
  parent::setTarget($feed, $entity, $field_name, $values);
  $item_list = $entity_target
    ->get($field_name);

  // Append roles from unsaved entity, if there is one.
  if ($entity_target
    ->id() && $is_empty) {
    $original = $this->entityTypeManager
      ->getStorage($entity_target
      ->getEntityTypeId())
      ->loadUnchanged($entity
      ->id());
    if ($original) {
      $original_values = $original
        ->get($field_name)
        ->getValue();

      // Revoke roles, when that option is enabled. But do not touch roles
      // that are not allowed to set by the source.
      if ($this->configuration['revoke_roles']) {
        foreach ($original_values as $key => $value) {
          $rid = $value['target_id'];
          if (!empty($this->configuration['allowed_roles'][$rid])) {
            unset($original_values[$key]);
          }
        }
      }

      // Merge the remaining values.
      $values = array_merge($item_list
        ->getValue(), $original_values);
      $item_list
        ->setValue($values);
    }
  }
}