AddUser.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Core\Command\Group;
  7. use OC\Core\Command\Base;
  8. use OCP\IGroup;
  9. use OCP\IGroupManager;
  10. use OCP\IUser;
  11. use OCP\IUserManager;
  12. use Stecman\Component\Symfony\Console\BashCompletion\CompletionContext;
  13. use Symfony\Component\Console\Input\InputArgument;
  14. use Symfony\Component\Console\Input\InputInterface;
  15. use Symfony\Component\Console\Output\OutputInterface;
  16. class AddUser extends Base {
  17. public function __construct(
  18. protected IUserManager $userManager,
  19. protected IGroupManager $groupManager,
  20. ) {
  21. parent::__construct();
  22. }
  23. protected function configure() {
  24. $this
  25. ->setName('group:adduser')
  26. ->setDescription('add a user to a group')
  27. ->addArgument(
  28. 'group',
  29. InputArgument::REQUIRED,
  30. 'group to add the user to'
  31. )->addArgument(
  32. 'user',
  33. InputArgument::REQUIRED,
  34. 'user to add to the group'
  35. );
  36. }
  37. protected function execute(InputInterface $input, OutputInterface $output): int {
  38. $group = $this->groupManager->get($input->getArgument('group'));
  39. if (is_null($group)) {
  40. $output->writeln('<error>group not found</error>');
  41. return 1;
  42. }
  43. $user = $this->userManager->get($input->getArgument('user'));
  44. if (is_null($user)) {
  45. $output->writeln('<error>user not found</error>');
  46. return 1;
  47. }
  48. $group->addUser($user);
  49. return 0;
  50. }
  51. /**
  52. * @param string $argumentName
  53. * @param CompletionContext $context
  54. * @return string[]
  55. */
  56. public function completeArgumentValues($argumentName, CompletionContext $context) {
  57. if ($argumentName === 'group') {
  58. return array_map(static fn (IGroup $group) => $group->getGID(), $this->groupManager->search($context->getCurrentWord()));
  59. }
  60. if ($argumentName === 'user') {
  61. $groupId = $context->getWordAtIndex($context->getWordIndex() - 1);
  62. $group = $this->groupManager->get($groupId);
  63. if ($group === null) {
  64. return [];
  65. }
  66. $members = array_map(static fn (IUser $user) => $user->getUID(), $group->searchUsers($context->getCurrentWord()));
  67. $users = array_map(static fn (IUser $user) => $user->getUID(), $this->userManager->search($context->getCurrentWord()));
  68. return array_diff($users, $members);
  69. }
  70. return [];
  71. }
  72. }