You are here

public function UserSectionStorage::addUser in Workbench Access 8

Adds a set of sections to a user.

Parameters

\Drupal\workbench_access\Entity\AccessSchemeInterface $scheme: Access scheme.

\Drupal\Core\Session\AccountInterface $account: User to add to the section.

array $sections: An array of section ids to assign to this user.

Return value

\Drupal\Core\Session\AccountInterface The saved user entity.

Overrides UserSectionStorageInterface::addUser

File

src/UserSectionStorage.php, line 105

Class

UserSectionStorage
Defines a class for storing and retrieving sections assigned to a user.

Namespace

Drupal\workbench_access

Code

public function addUser(AccessSchemeInterface $scheme, AccountInterface $account, array $sections = []) {
  foreach ($sections as $id) {
    if ($section_association = $this
      ->sectionStorage()
      ->loadSection($scheme
      ->id(), $id)) {
      if ($new_values = $section_association
        ->getCurrentUserIds()) {
        $new_values[] = $account
          ->id();
        $section_association
          ->set('user_id', array_unique($new_values));
      }
      else {
        $section_association
          ->set('user_id', [
          $account
            ->id(),
        ]);
      }
      $section_association
        ->setNewRevision();
    }
    else {
      $values = [
        'access_scheme' => $scheme
          ->id(),
        'section_id' => $id,
        'user_id' => [
          $account
            ->id(),
        ],
      ];
      $new_values[] = $account
        ->id();
      $section_association = $this
        ->sectionStorage()
        ->create($values);
    }
    $section_association
      ->save();
    $this
      ->resetCache($scheme, $account
      ->id());
  }

  // Return the user object.
  return $this
    ->userStorage()
    ->load($account
    ->id());
}