To improve code readability.
Signed-off-by: Faraz Samapoor <f.samapoor@gmail.com>
Co-authored-by: Côme Chilliet <91878298+come-nc@users.noreply.github.com>
$this->service->handleCreatedGroups([$gid]);
}
}
- return 0;
- } elseif ($wasMapped) {
+ return self::SUCCESS;
+ }
+
+ if ($wasMapped) {
$output->writeln('The group does not exist on LDAP anymore.');
if ($input->getOption('update')) {
$this->backend->getLDAPAccess($gid)->connection->clearCache();
$this->service->handleRemovedGroups([$gid]);
}
- return 0;
- } else {
- throw new \Exception('The given group is not a recognized LDAP group.');
+ return self::SUCCESS;
}
+
+ throw new \Exception('The given group is not a recognized LDAP group.');
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage(). '</error>');
- return 1;
+ return self::FAILURE;
}
}
use Symfony\Component\Console\Output\OutputInterface;
class CheckUser extends Command {
- /** @var User_Proxy */
- protected $backend;
+ protected User_Proxy $backend;
- /** @var Helper */
- protected $helper;
-
- /** @var DeletedUsersIndex */
- protected $dui;
-
- /** @var UserMapping */
- protected $mapping;
-
- public function __construct(User_Proxy $uBackend, Helper $helper, DeletedUsersIndex $dui, UserMapping $mapping) {
+ public function __construct(
+ User_Proxy $uBackend,
+ protected Helper $helper,
+ protected DeletedUsersIndex $dui,
+ protected UserMapping $mapping,
+ ) {
$this->backend = $uBackend;
- $this->helper = $helper;
- $this->dui = $dui;
- $this->mapping = $mapping;
parent::__construct();
}
if ($input->getOption('update')) {
$this->updateUser($uid, $output);
}
- return 0;
- } elseif ($wasMapped) {
+ return self::SUCCESS;
+ }
+
+ if ($wasMapped) {
$this->dui->markUser($uid);
$output->writeln('The user does not exists on LDAP anymore.');
$output->writeln('Clean up the user\'s remnants by: ./occ user:delete "'
. $uid . '"');
- return 0;
- } else {
- throw new \Exception('The given user is not a recognized LDAP user.');
+ return self::SUCCESS;
}
+
+ throw new \Exception('The given user is not a recognized LDAP user.');
} catch (\Exception $e) {
$output->writeln('<error>' . $e->getMessage(). '</error>');
- return 1;
+ return self::FAILURE;
}
}
use Symfony\Component\Console\Output\OutputInterface;
class CreateEmptyConfig extends Command {
- /** @var \OCA\User_LDAP\Helper */
- protected $helper;
-
- /**
- * @param Helper $helper
- */
- public function __construct(Helper $helper) {
- $this->helper = $helper;
+ public function __construct(
+ protected Helper $helper,
+ ) {
parent::__construct();
}
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:create-empty-config')
->setDescription('creates an empty LDAP configuration')
$prose = 'Created new configuration with configID ';
}
$output->writeln($prose . "{$configPrefix}");
- return 0;
+ return self::SUCCESS;
}
}
use Symfony\Component\Console\Output\OutputInterface;
class DeleteConfig extends Command {
- /** @var \OCA\User_LDAP\Helper */
- protected $helper;
-
- /**
- * @param Helper $helper
- */
- public function __construct(Helper $helper) {
- $this->helper = $helper;
+ public function __construct(
+ protected Helper $helper,
+ ) {
parent::__construct();
}
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:delete-config')
->setDescription('deletes an existing LDAP configuration')
;
}
-
protected function execute(InputInterface $input, OutputInterface $output): int {
$configPrefix = $input->getArgument('configID');
$success = $this->helper->deleteServerConfiguration($configPrefix);
- if ($success) {
- $output->writeln("Deleted configuration with configID '{$configPrefix}'");
- return 0;
- } else {
+ if (!$success) {
$output->writeln("Cannot delete configuration with configID '{$configPrefix}'");
- return 1;
+ return self::FAILURE;
}
+
+ $output->writeln("Deleted configuration with configID '{$configPrefix}'");
+ return self::SUCCESS;
}
}
use Symfony\Component\Console\Question\Question;
class ResetGroup extends Command {
- private IGroupManager $groupManager;
- private GroupPluginManager $pluginManager;
- private Group_Proxy $backend;
-
public function __construct(
- IGroupManager $groupManager,
- GroupPluginManager $pluginManager,
- Group_Proxy $backend
+ private IGroupManager $groupManager,
+ private GroupPluginManager $pluginManager,
+ private Group_Proxy $backend,
) {
- $this->groupManager = $groupManager;
- $this->pluginManager = $pluginManager;
- $this->backend = $backend;
parent::__construct();
}
echo "calling delete $gid\n";
if ($group->delete()) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
- return 0;
+ return self::SUCCESS;
}
} catch (\Throwable $e) {
if (isset($pluginManagerSuppressed)) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
}
$output->writeln('<error>' . $e->getMessage() . '</error>');
- return 1;
+ return self::FAILURE;
}
$output->writeln('<error>Error while resetting group</error>');
- return 2;
+ return self::INVALID;
}
}
use Symfony\Component\Console\Question\Question;
class ResetUser extends Command {
- /** @var DeletedUsersIndex */
- protected $dui;
- /** @var IUserManager */
- private $userManager;
- /** @var UserPluginManager */
- private $pluginManager;
-
public function __construct(
- DeletedUsersIndex $dui,
- IUserManager $userManager,
- UserPluginManager $pluginManager
+ protected DeletedUsersIndex $dui,
+ private IUserManager $userManager,
+ private UserPluginManager $pluginManager,
) {
- $this->dui = $dui;
- $this->userManager = $userManager;
- $this->pluginManager = $pluginManager;
parent::__construct();
}
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:reset-user')
->setDescription('deletes an LDAP user independent of the user state')
$pluginManagerSuppressed = $this->pluginManager->setSuppressDeletion(true);
if ($user->delete()) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
- return 0;
+ return self::SUCCESS;
}
} catch (\Throwable $e) {
if (isset($pluginManagerSuppressed)) {
$this->pluginManager->setSuppressDeletion($pluginManagerSuppressed);
}
$output->writeln('<error>' . $e->getMessage() . '</error>');
- return 1;
+ return self::FAILURE;
}
$output->writeln('<error>Error while resetting user</error>');
- return 2;
+ return self::INVALID;
}
}
use Symfony\Component\Console\Output\OutputInterface;
class Search extends Command {
- /** @var \OCP\IConfig */
- protected $ocConfig;
- /** @var User_Proxy */
- private $userProxy;
- /** @var Group_Proxy */
- private $groupProxy;
-
- public function __construct(IConfig $ocConfig, User_Proxy $userProxy, Group_Proxy $groupProxy) {
+ public function __construct(
+ protected IConfig $ocConfig,
+ private User_Proxy $userProxy,
+ private Group_Proxy $groupProxy,
+ ) {
parent::__construct();
- $this->ocConfig = $ocConfig;
- $this->userProxy = $userProxy;
- $this->groupProxy = $groupProxy;
}
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:search')
->setDescription('executes a user or group search')
/**
* Tests whether the offset and limit options are valid
- * @param int $offset
- * @param int $limit
+ *
* @throws \InvalidArgumentException
*/
- protected function validateOffsetAndLimit($offset, $limit) {
+ protected function validateOffsetAndLimit($offset, $limit): void {
if ($limit < 0) {
throw new \InvalidArgumentException('limit must be 0 or greater');
}
$line = $name . ($printID ? ' ('.$id.')' : '');
$output->writeln($line);
}
- return 0;
+ return self::SUCCESS;
}
}
use Symfony\Component\Console\Output\OutputInterface;
class SetConfig extends Command {
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:set-config')
->setDescription('modifies an LDAP configuration')
$configID = $input->getArgument('configID');
if (!in_array($configID, $availableConfigs)) {
$output->writeln("Invalid configID");
- return 1;
+ return self::FAILURE;
}
$this->setValue(
$input->getArgument('configKey'),
$input->getArgument('configValue')
);
- return 0;
+ return self::SUCCESS;
}
/**
* save the configuration value as provided
- * @param string $configID
- * @param string $configKey
- * @param string $configValue
*/
- protected function setValue($configID, $key, $value) {
+ protected function setValue(string $configID, string $key, string $value): void {
$configHolder = new Configuration($configID);
$configHolder->$key = $value;
$configHolder->saveConfiguration();
use Symfony\Component\Console\Output\OutputInterface;
class ShowConfig extends Base {
- /** @var \OCA\User_LDAP\Helper */
- protected $helper;
-
- /**
- * @param Helper $helper
- */
- public function __construct(Helper $helper) {
- $this->helper = $helper;
+ public function __construct(
+ protected Helper $helper,
+ ) {
parent::__construct();
}
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:show-config')
->setDescription('shows the LDAP configuration')
$configIDs[] = $configID;
if (!in_array($configIDs[0], $availableConfigs)) {
$output->writeln("Invalid configID");
- return 1;
+ return self::FAILURE;
}
} else {
$configIDs = $availableConfigs;
}
$this->renderConfigs($configIDs, $input, $output);
- return 0;
+ return self::SUCCESS;
}
/**
* prints the LDAP configuration(s)
- * @param string[] configID(s)
- * @param InputInterface $input
- * @param OutputInterface $output
+ *
+ * @param string[] $configIDs
*/
- protected function renderConfigs($configIDs, $input, $output) {
+ protected function renderConfigs(
+ array $configIDs,
+ InputInterface $input,
+ OutputInterface $output,
+ ): void {
$renderTable = $input->getOption('output') === 'table' or $input->getOption('output') === null;
$showPassword = $input->getOption('show-password');
$table->setHeaders(['Configuration', $id]);
$table->setRows($rows);
$table->render();
- } else {
- foreach ($configuration as $key => $value) {
- if ($key === 'ldapAgentPassword' && !$showPassword) {
- $rows[$key] = '***';
- } else {
- $rows[$key] = $value;
- }
+ continue;
+ }
+
+ foreach ($configuration as $key => $value) {
+ if ($key === 'ldapAgentPassword' && !$showPassword) {
+ $rows[$key] = '***';
+ } else {
+ $rows[$key] = $value;
}
- $configs[$id] = $rows;
}
+ $configs[$id] = $rows;
}
if (!$renderTable) {
$this->writeArrayInOutputFormat($input, $output, $configs);
use Symfony\Component\Console\Output\OutputInterface;
class ShowRemnants extends Command {
- /** @var \OCA\User_LDAP\User\DeletedUsersIndex */
- protected $dui;
-
- /** @var \OCP\IDateTimeFormatter */
- protected $dateFormatter;
-
- /**
- * @param DeletedUsersIndex $dui
- * @param IDateTimeFormatter $dateFormatter
- */
- public function __construct(DeletedUsersIndex $dui, IDateTimeFormatter $dateFormatter) {
- $this->dui = $dui;
- $this->dateFormatter = $dateFormatter;
+ public function __construct(
+ protected DeletedUsersIndex $dui,
+ protected IDateTimeFormatter $dateFormatter,
+ ) {
parent::__construct();
}
- protected function configure() {
+ protected function configure(): void {
$this
->setName('ldap:show-remnants')
->setDescription('shows which users are not available on LDAP anymore, but have remnants in Nextcloud.')
->addOption('short-date', null, InputOption::VALUE_NONE, 'show dates in Y-m-d format');
}
- protected function formatDate(int $timestamp, string $default, bool $showShortDate) {
+ protected function formatDate(int $timestamp, string $default, bool $showShortDate): string {
if (!($timestamp > 0)) {
return $default;
}
$table->setRows($rows);
$table->render();
}
- return 0;
+ return self::SUCCESS;
}
}
protected const BINDFAILURE = 2;
protected const SEARCHFAILURE = 3;
- protected AccessFactory $accessFactory;
- protected Helper $helper;
- protected ILDAPWrapper $ldap;
-
public function __construct(
- AccessFactory $accessFactory,
- Helper $helper,
- ILDAPWrapper $ldap
+ protected AccessFactory $accessFactory,
+ protected Helper $helper,
+ protected ILDAPWrapper $ldap,
) {
- $this->accessFactory = $accessFactory;
- $this->helper = $helper;
- $this->ldap = $ldap;
parent::__construct();
}
$configID = $input->getArgument('configID');
if (!in_array($configID, $availableConfigs)) {
$output->writeln('Invalid configID');
- return 1;
+ return self::FAILURE;
}
$result = $this->testConfig($configID);
- switch ($result) {
- case static::ESTABLISHED:
- $output->writeln('The configuration is valid and the connection could be established!');
- return 0;
- case static::CONF_INVALID:
- $output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
- break;
- case static::BINDFAILURE:
- $output->writeln('The configuration is valid, but the bind failed. Please check the server settings and credentials.');
- break;
- case static::SEARCHFAILURE:
- $output->writeln('The configuration is valid and the bind passed, but a simple search on the base fails. Please check the server base setting.');
- break;
- default:
- $output->writeln('Your LDAP server was kidnapped by aliens.');
- break;
- }
- return 1;
+
+ $message = match ($result) {
+ static::ESTABLISHED => 'The configuration is valid and the connection could be established!',
+ static::CONF_INVALID => 'The configuration is invalid. Please have a look at the logs for further details.',
+ static::BINDFAILURE => 'The configuration is valid, but the bind failed. Please check the server settings and credentials.',
+ static::SEARCHFAILURE => 'The configuration is valid and the bind passed, but a simple search on the base fails. Please check the server base setting.',
+ default => 'Your LDAP server was kidnapped by aliens.',
+ };
+
+ $output->writeln($message);
+
+ return $result === static::ESTABLISHED
+ ? self::SUCCESS
+ : self::FAILURE;
}
/**
public const UNWRITABLE = 4;
public const UNMAPPED = 5;
- public $id = '';
- public $dn = '';
- public $isUser = true;
- public $state = self::UNCHANGED;
- public $oldUuid = '';
- public $newUuid = '';
-
- public function __construct(string $id, string $dn, bool $isUser, int $state, string $oldUuid = '', string $newUuid = '') {
- $this->id = $id;
- $this->dn = $dn;
- $this->isUser = $isUser;
- $this->state = $state;
- $this->oldUuid = $oldUuid;
- $this->newUuid = $newUuid;
+ public function __construct(
+ public string $id,
+ public string $dn,
+ public bool $isUser,
+ public int $state,
+ public string $oldUuid = '',
+ public string $newUuid = '',
+ ) {
}
}
class UpdateUUID extends Command {
- /** @var UserMapping */
- private $userMapping;
- /** @var GroupMapping */
- private $groupMapping;
- /** @var User_Proxy */
- private $userProxy;
- /** @var Group_Proxy */
- private $groupProxy;
/** @var array<UuidUpdateReport[]> */
- protected $reports = [];
- /** @var LoggerInterface */
- private $logger;
- /** @var bool */
- private $dryRun = false;
+ protected array $reports = [];
+ private bool $dryRun = false;
- public function __construct(UserMapping $userMapping, GroupMapping $groupMapping, User_Proxy $userProxy, Group_Proxy $groupProxy, LoggerInterface $logger) {
- $this->userMapping = $userMapping;
- $this->groupMapping = $groupMapping;
- $this->userProxy = $userProxy;
- $this->groupProxy = $groupProxy;
- $this->logger = $logger;
+ public function __construct(
+ private UserMapping $userMapping,
+ private GroupMapping $groupMapping,
+ private User_Proxy $userProxy,
+ private Group_Proxy $groupProxy,
+ private LoggerInterface $logger,
+ ) {
$this->reports = [
UuidUpdateReport::UPDATED => [],
UuidUpdateReport::UNKNOWN => [],
$entriesToUpdate = $this->estimateNumberOfUpdates($input);
$progress = new ProgressBar($output);
$progress->start($entriesToUpdate);
- foreach($this->handleUpdates($input) as $_) {
+ foreach ($this->handleUpdates($input) as $_) {
$progress->advance();
}
$progress->finish();
return count($this->reports[UuidUpdateReport::UNMAPPED]) === 0
&& count($this->reports[UuidUpdateReport::UNREADABLE]) === 0
&& count($this->reports[UuidUpdateReport::UNWRITABLE]) === 0
- ? 0
- : 1;
+ ? self::SUCCESS
+ : self::FAILURE;
}
protected function printReport(OutputInterface $output): void {
protected function handleUpdates(InputInterface $input): \Generator {
if ($input->getOption('all')) {
- foreach($this->handleMappingBasedUpdates(false) as $_) {
+ foreach ($this->handleMappingBasedUpdates(false) as $_) {
yield;
}
} elseif ($input->getOption('userId')
|| $input->getOption('groupId')
|| $input->getOption('dn')
) {
- foreach($this->handleUpdatesByUserId($input->getOption('userId')) as $_) {
+ foreach ($this->handleUpdatesByUserId($input->getOption('userId')) as $_) {
yield;
}
- foreach($this->handleUpdatesByGroupId($input->getOption('groupId')) as $_) {
+ foreach ($this->handleUpdatesByGroupId($input->getOption('groupId')) as $_) {
yield;
}
- foreach($this->handleUpdatesByDN($input->getOption('dn')) as $_) {
+ foreach ($this->handleUpdatesByDN($input->getOption('dn')) as $_) {
yield;
}
} else {
- foreach($this->handleMappingBasedUpdates(true) as $_) {
+ foreach ($this->handleMappingBasedUpdates(true) as $_) {
yield;
}
}
}
protected function handleUpdatesByUserId(array $userIds): \Generator {
- foreach($this->handleUpdatesByEntryId($userIds, $this->userMapping) as $_) {
+ foreach ($this->handleUpdatesByEntryId($userIds, $this->userMapping) as $_) {
yield;
}
}
protected function handleUpdatesByGroupId(array $groupIds): \Generator {
- foreach($this->handleUpdatesByEntryId($groupIds, $this->groupMapping) as $_) {
+ foreach ($this->handleUpdatesByEntryId($groupIds, $this->groupMapping) as $_) {
yield;
}
}
$this->reports[UuidUpdateReport::UNMAPPED][] = new UuidUpdateReport('', $dn, true, UuidUpdateReport::UNMAPPED);
yield;
}
- foreach($this->handleUpdatesByList($this->userMapping, $userList) as $_) {
+ foreach ($this->handleUpdatesByList($this->userMapping, $userList) as $_) {
yield;
}
- foreach($this->handleUpdatesByList($this->groupMapping, $groupList) as $_) {
+ foreach ($this->handleUpdatesByList($this->groupMapping, $groupList) as $_) {
yield;
}
}
$isUser = $mapping instanceof UserMapping;
$list = [];
while ($id = array_pop($ids)) {
- if(!$dn = $mapping->getDNByName($id)) {
+ if (!$dn = $mapping->getDNByName($id)) {
$this->reports[UuidUpdateReport::UNMAPPED][] = new UuidUpdateReport($id, '', $isUser, UuidUpdateReport::UNMAPPED);
yield;
continue;
$uuid = $mapping->getUUIDByDN($dn);
$list[] = ['name' => $id, 'uuid' => $uuid];
}
- foreach($this->handleUpdatesByList($mapping, $list) as $_) {
+ foreach ($this->handleUpdatesByList($mapping, $list) as $_) {
yield;
}
}
protected function handleMappingBasedUpdates(bool $invalidatedOnly): \Generator {
$limit = 1000;
/** @var AbstractMapping $mapping*/
- foreach([$this->userMapping, $this->groupMapping] as $mapping) {
+ foreach ([$this->userMapping, $this->groupMapping] as $mapping) {
$offset = 0;
do {
$list = $mapping->getList($offset, $limit, $invalidatedOnly);
$offset += $limit;
- foreach($this->handleUpdatesByList($mapping, $list) as $tick) {
+ foreach ($this->handleUpdatesByList($mapping, $list) as $tick) {
yield; // null, for it only advances progress counter
}
} while (count($list) === $limit);
return $this->userMapping->countInvalidated() + $this->groupMapping->countInvalidated();
}
}
-
}