/**
* Method to add a user to a group.
*
* @param integer $userId The id of the user.
* @param integer $groupId The id of the group.
*
* @return boolean True on success
*
* @since 1.7.0
* @throws \RuntimeException
*/
public static function addUserToGroup($userId, $groupId)
{
// Cast as integer until method is typehinted.
$userId = (int) $userId;
$groupId = (int) $groupId;
// Get the user object.
$user = new User($userId);
// Add the user to the group if necessary.
if (!\in_array($groupId, $user->groups)) {
// Check whether the group exists.
$db = Factory::getDbo();
$query = $db->getQuery(true)->select($db->quoteName('id'))->from($db->quoteName('#__usergroups'))->where($db->quoteName('id') . ' = :groupId')->bind(':groupId', $groupId, ParameterType::INTEGER);
$db->setQuery($query);
// If the group does not exist, return an exception.
if ($db->loadResult() === null) {
throw new \RuntimeException('Access Usergroup Invalid');
}
// Add the group data to the user object.
$user->groups[$groupId] = $groupId;
// Reindex the array for prepared statements binding
$user->groups = array_values($user->groups);
// Store the user object.
$user->save();
}
// Set the group data for any preloaded user objects.
$temp = User::getInstance($userId);
$temp->groups = $user->groups;
if (Factory::getSession()->getId()) {
// Set the group data for the user object in the session.
$temp = Factory::getUser();
if ($temp->id == $userId) {
$temp->groups = $user->groups;
}
}
return true;
}