/**
* Internal function to execute the command.
*
* @param InputInterface $input The input to inject into the command.
* @param OutputInterface $output The output to inject into the command.
*
* @return integer The command exit code
*
* @since 4.0.0
*/
protected function doExecute(InputInterface $input, OutputInterface $output) : int
{
$this->configureIO($input, $output);
$this->username = $this->getStringFromOption('username', 'Please enter a username');
$this->ioStyle->title('Add user to group');
$userId = $this->getUserId($this->username);
if (empty($userId)) {
$this->ioStyle->error("The user " . $this->username . " does not exist!");
return Command::FAILURE;
}
// Fetch user
$user = User::getInstance($userId);
$this->userGroups = $this->getGroups($user);
$db = Factory::getDbo();
$query = $db->getQuery(true)->select($db->quoteName('title'))->from($db->quoteName('#__usergroups'))->where($db->quoteName('id') . ' = :userGroup');
foreach ($this->userGroups as $userGroup) {
$query->bind(':userGroup', $userGroup);
$db->setQuery($query);
$result = $db->loadResult();
if (UserHelper::addUserToGroup($user->id, $userGroup)) {
$this->ioStyle->success("Added '" . $user->username . "' to group '" . $result . "'!");
} else {
$this->ioStyle->error("Can't add '" . $user->username . "' to group '" . $result . "'!");
return Command::FAILURE;
}
}
return Command::SUCCESS;
}