eZ\Publish\Core\Repository\UserService::assignUserToUserGroup PHP Method

assignUserToUserGroup() public method

Assigns a new user group to the user.
public assignUserToUserGroup ( eZ\Publish\API\Repository\Values\User\User $user, eZ\Publish\API\Repository\Values\User\UserGroup $userGroup )
$user eZ\Publish\API\Repository\Values\User\User
$userGroup eZ\Publish\API\Repository\Values\User\UserGroup
    public function assignUserToUserGroup(APIUser $user, APIUserGroup $userGroup)
    {
        $loadedUser = $this->loadUser($user->id);
        $loadedGroup = $this->loadUserGroup($userGroup->id);
        $locationService = $this->repository->getLocationService();
        $existingGroupIds = array();
        $userLocations = $locationService->loadLocations($loadedUser->getVersionInfo()->getContentInfo());
        foreach ($userLocations as $userLocation) {
            $existingGroupIds[] = $userLocation->parentLocationId;
        }
        if ($loadedGroup->getVersionInfo()->getContentInfo()->mainLocationId === null) {
            throw new BadStateException('userGroup', 'user group has no main location or no locations');
        }
        if (in_array($loadedGroup->getVersionInfo()->getContentInfo()->mainLocationId, $existingGroupIds)) {
            // user is already assigned to the user group
            throw new InvalidArgumentException('user', 'user is already in the given user group');
        }
        $locationCreateStruct = $locationService->newLocationCreateStruct($loadedGroup->getVersionInfo()->getContentInfo()->mainLocationId);
        $this->repository->beginTransaction();
        try {
            $locationService->createLocation($loadedUser->getVersionInfo()->getContentInfo(), $locationCreateStruct);
            $this->repository->commit();
        } catch (Exception $e) {
            $this->repository->rollback();
            throw $e;
        }
    }