diff --git a/lib/ACL/ACLCacheWrapper.php b/lib/ACL/ACLCacheWrapper.php index 1c32a05a9..ba75c2b80 100644 --- a/lib/ACL/ACLCacheWrapper.php +++ b/lib/ACL/ACLCacheWrapper.php @@ -58,9 +58,7 @@ public function getFolderContentsById($fileId): array { $results = $this->getCache()->getFolderContentsById($fileId); $rules = $this->preloadEntries($results); - return array_filter(array_map(function (ICacheEntry $entry) use ($rules): ICacheEntry|false { - return $this->formatCacheEntry($entry, $rules); - }, $results)); + return array_filter(array_map(fn (ICacheEntry $entry): ICacheEntry|false => $this->formatCacheEntry($entry, $rules), $results)); } public function search($pattern): array { @@ -89,9 +87,7 @@ public function searchQuery(ISearchQuery $query): array { * @return array */ private function preloadEntries(array $entries): array { - $paths = array_map(function (ICacheEntry $entry): string { - return $entry->getPath(); - }, $entries); + $paths = array_map(fn (ICacheEntry $entry): string => $entry->getPath(), $entries); return $this->aclManager->getRelevantRulesForPath($paths, false); } diff --git a/lib/ACL/ACLManager.php b/lib/ACL/ACLManager.php index 167aa2efe..b6a5fa3b0 100644 --- a/lib/ACL/ACLManager.php +++ b/lib/ACL/ACLManager.php @@ -52,13 +52,9 @@ private function getRules(array $paths, bool $cache = true): array { // beware: adding new rules to the cache besides the cap // might discard former cached entries, so we can't assume they'll stay // cached, so we read everything out initially to be able to return it - $rules = array_combine($paths, array_map(function (string $path): ?array { - return $this->ruleCache->get($path); - }, $paths)); + $rules = array_combine($paths, array_map(fn (string $path): ?array => $this->ruleCache->get($path), $paths)); - $nonCachedPaths = array_filter($paths, function (string $path) use ($rules): bool { - return !isset($rules[$path]); - }); + $nonCachedPaths = array_filter($paths, fn (string $path): bool => !isset($rules[$path])); if (!empty($nonCachedPaths)) { $newRules = $this->ruleManager->getRulesForFilesByPath($this->user, $this->getRootStorageId(), $nonCachedPaths); diff --git a/lib/ACL/ACLStorageWrapper.php b/lib/ACL/ACLStorageWrapper.php index 3f71c7b95..66a0d45e5 100644 --- a/lib/ACL/ACLStorageWrapper.php +++ b/lib/ACL/ACLStorageWrapper.php @@ -69,10 +69,10 @@ public function getPermissions($path): int { } public function rename($source, $target): bool { - if (strpos($source, $target) === 0) { + if (str_starts_with($source, $target)) { $part = substr($source, strlen($target)); //This is a rename of the transfer file to the original file - if (strpos($part, '.ocTransferId') === 0) { + if (str_starts_with($part, '.ocTransferId')) { return $this->checkPermissions($target, Constants::PERMISSION_CREATE) && parent::rename($source, $target); } } @@ -188,7 +188,7 @@ public function getMetaData($path): ?array { $data = parent::getMetaData($path); if ($data && isset($data['permissions'])) { - $data['scan_permissions'] = isset($data['scan_permissions']) ? $data['scan_permissions'] : $data['permissions']; + $data['scan_permissions'] ??= $data['permissions']; $data['permissions'] &= $this->getACLPermissionsForPath($path); } @@ -297,7 +297,7 @@ public function getDirectDownload($path): array|bool { public function getDirectoryContent($directory): \Traversable { foreach ($this->getWrapperStorage()->getDirectoryContent($directory) as $data) { - $data['scan_permissions'] = isset($data['scan_permissions']) ? $data['scan_permissions'] : $data['permissions']; + $data['scan_permissions'] ??= $data['permissions']; $data['permissions'] &= $this->getACLPermissionsForPath(rtrim($directory, '/') . '/' . $data['name']); yield $data; diff --git a/lib/ACL/Rule.php b/lib/ACL/Rule.php index 6c18b4c72..123fa0013 100644 --- a/lib/ACL/Rule.php +++ b/lib/ACL/Rule.php @@ -125,13 +125,9 @@ public static function xmlDeserialize(Reader $reader): Rule { */ public static function mergeRules(array $rules): Rule { // or'ing the masks to get a new mask that masks all set permissions - $mask = array_reduce($rules, function (int $mask, Rule $rule): int { - return $mask | $rule->getMask(); - }, 0); + $mask = array_reduce($rules, fn (int $mask, Rule $rule): int => $mask | $rule->getMask(), 0); // or'ing the permissions combines them with allow overwriting deny - $permissions = array_reduce($rules, function (int $permissions, Rule $rule): int { - return $permissions | $rule->getPermissions(); - }, 0); + $permissions = array_reduce($rules, fn (int $permissions, Rule $rule): int => $permissions | $rule->getPermissions(), 0); return new Rule( new UserMapping('dummy', ''), diff --git a/lib/ACL/RuleManager.php b/lib/ACL/RuleManager.php index a4b1369b4..19b08179a 100644 --- a/lib/ACL/RuleManager.php +++ b/lib/ACL/RuleManager.php @@ -50,12 +50,10 @@ public function getRulesForFilesById(IUser $user, array $fileIds): array { $query->select(['fileid', 'mapping_type', 'mapping_id', 'mask', 'permissions']) ->from('group_folders_acl') ->where($query->expr()->in('fileid', $query->createNamedParameter($fileIds, IQueryBuilder::PARAM_INT_ARRAY))) - ->andWhere($query->expr()->orX(...array_map(function (IUserMapping $userMapping) use ($query): ICompositeExpression { - return $query->expr()->andX( - $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), - $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) - ); - }, $userMappings))); + ->andWhere($query->expr()->orX(...array_map(fn (IUserMapping $userMapping): ICompositeExpression => $query->expr()->andX( + $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), + $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) + ), $userMappings))); $rows = $query->executeQuery()->fetchAll(); @@ -81,9 +79,7 @@ public function getRulesForFilesById(IUser $user, array $fileIds): array { public function getRulesForFilesByPath(IUser $user, int $storageId, array $filePaths): array { $userMappings = $this->userMappingManager->getMappingsForUser($user); - $hashes = array_map(function (string $path): string { - return md5(trim($path, '/')); - }, $filePaths); + $hashes = array_map(fn (string $path): string => md5(trim($path, '/')), $filePaths); $rows = []; foreach (array_chunk($hashes, 1000) as $chunk) { @@ -93,12 +89,10 @@ public function getRulesForFilesByPath(IUser $user, int $storageId, array $fileP ->innerJoin('a', 'filecache', 'f', $query->expr()->eq('f.fileid', 'a.fileid')) ->where($query->expr()->in('path_hash', $query->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY))) ->andWhere($query->expr()->eq('storage', $query->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))) - ->andWhere($query->expr()->orX(...array_map(function (IUserMapping $userMapping) use ($query): ICompositeExpression { - return $query->expr()->andX( - $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), - $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) - ); - }, $userMappings))); + ->andWhere($query->expr()->orX(...array_map(fn (IUserMapping $userMapping): ICompositeExpression => $query->expr()->andX( + $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), + $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) + ), $userMappings))); $rows = array_merge($rows, $query->executeQuery()->fetchAll()); } @@ -133,12 +127,10 @@ public function getRulesForFilesByParent(IUser $user, int $storageId, string $pa $query->expr()->isNull('mapping_type'), $query->expr()->isNull('mapping_id') ), - ...array_map(function (IUserMapping $userMapping) use ($query): ICompositeExpression { - return $query->expr()->andX( - $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), - $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) - ); - }, $userMappings) + ...array_map(fn (IUserMapping $userMapping): ICompositeExpression => $query->expr()->andX( + $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), + $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) + ), $userMappings) ) ); @@ -176,9 +168,7 @@ private function getId(int $storageId, string $path): int { * @return array */ public function getAllRulesForPaths(int $storageId, array $filePaths): array { - $hashes = array_map(function (string $path): string { - return md5(trim($path, '/')); - }, $filePaths); + $hashes = array_map(fn (string $path): string => md5(trim($path, '/')), $filePaths); $query = $this->connection->getQueryBuilder(); $query->select(['f.fileid', 'mapping_type', 'mapping_id', 'mask', 'a.permissions', 'path']) ->from('group_folders_acl', 'a') @@ -240,12 +230,10 @@ public function getRulesForPrefix(IUser $user, int $storageId, string $prefix): $query->expr()->eq('path_hash', $query->createNamedParameter(md5($prefix))) )) ->andWhere($query->expr()->eq('storage', $query->createNamedParameter($storageId, IQueryBuilder::PARAM_INT))) - ->andWhere($query->expr()->orX(...array_map(function (IUserMapping $userMapping) use ($query): ICompositeExpression { - return $query->expr()->andX( - $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), - $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) - ); - }, $userMappings))); + ->andWhere($query->expr()->orX(...array_map(fn (IUserMapping $userMapping): ICompositeExpression => $query->expr()->andX( + $query->expr()->eq('mapping_type', $query->createNamedParameter($userMapping->getType())), + $query->expr()->eq('mapping_id', $query->createNamedParameter($userMapping->getId())) + ), $userMappings))); $rows = $query->executeQuery()->fetchAll(); diff --git a/lib/ACL/UserMapping/UserMappingManager.php b/lib/ACL/UserMapping/UserMappingManager.php index 3a767a013..ef74e4732 100644 --- a/lib/ACL/UserMapping/UserMappingManager.php +++ b/lib/ACL/UserMapping/UserMappingManager.php @@ -21,9 +21,7 @@ public function __construct( } public function getMappingsForUser(IUser $user, bool $userAssignable = true): array { - $groupMappings = array_values(array_map(function (IGroup $group): UserMapping { - return new UserMapping('group', $group->getGID(), $group->getDisplayName()); - }, $this->groupManager->getUserGroups($user))); + $groupMappings = array_values(array_map(fn (IGroup $group): UserMapping => new UserMapping('group', $group->getGID(), $group->getDisplayName()), $this->groupManager->getUserGroups($user))); return array_merge([ new UserMapping('user', $user->getUID(), $user->getDisplayName()), diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 52d556233..5ca54e458 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -91,7 +91,7 @@ public function register(IRegistrationContext $context): void { $folder = $rootFolder->get('__groupfolders'); return $folder; - } catch (NotFoundException $e) { + } catch (NotFoundException) { return $rootFolder->newFolder('__groupfolders'); } }, [ @@ -100,9 +100,7 @@ public function register(IRegistrationContext $context): void { }); $context->registerService(MountProvider::class, function (ContainerInterface $c): MountProvider { - $rootProvider = function () use ($c): Folder { - return $c->get('GroupAppFolder'); - }; + $rootProvider = fn (): Folder => $c->get('GroupAppFolder'); /** @var IAppConfig $config */ $config = $c->get(IAppConfig::class); $allowRootShare = $config->getValueString('groupfolders', 'allow_root_share', 'true') === 'true'; @@ -142,18 +140,15 @@ public function register(IRegistrationContext $context): void { return $trashBackend; }); - $context->registerService(VersionsBackend::class, function (ContainerInterface $c): VersionsBackend { - return new VersionsBackend( - $c->get(IRootFolder::class), - $c->get('GroupAppFolder'), - $c->get(MountProvider::class), - $c->get(ITimeFactory::class), - $c->get(LoggerInterface::class), - $c->get(GroupVersionsMapper::class), - $c->get(IMimeTypeLoader::class), - $c->get(IUserSession::class), - ); - }); + $context->registerService(VersionsBackend::class, fn (ContainerInterface $c): VersionsBackend => new VersionsBackend( + $c->get(IRootFolder::class), + $c->get('GroupAppFolder'), + $c->get(MountProvider::class), + $c->get(LoggerInterface::class), + $c->get(GroupVersionsMapper::class), + $c->get(IMimeTypeLoader::class), + $c->get(IUserSession::class), + )); $context->registerService(ExpireGroupBase::class, function (ContainerInterface $c): ExpireGroupBase { // Multiple implementation of this class exists depending on if the trash and versions @@ -216,9 +211,7 @@ public function register(IRegistrationContext $context): void { }); $context->registerService(ACLManagerFactory::class, function (ContainerInterface $c): ACLManagerFactory { - $rootFolderProvider = function () use ($c): \OCP\Files\IRootFolder { - return $c->get(IRootFolder::class); - }; + $rootFolderProvider = fn (): \OCP\Files\IRootFolder => $c->get(IRootFolder::class); return new ACLManagerFactory( $c->get(RuleManager::class), diff --git a/lib/BackgroundJob/ExpireGroupVersions.php b/lib/BackgroundJob/ExpireGroupVersions.php index d1b07519b..96c7461f1 100644 --- a/lib/BackgroundJob/ExpireGroupVersions.php +++ b/lib/BackgroundJob/ExpireGroupVersions.php @@ -63,9 +63,7 @@ protected function run(mixed $argument): void { // Determine the set of folders to process $folderSet = array_slice($folders, $lastFolder, $toDo); - $folderIDs = array_map(function (array $folder): int { - return $folder['id']; - }, $folderSet); + $folderIDs = array_map(fn (array $folder): int => $folder['id'], $folderSet); // Log and start the expiration process $this->logger->debug('Expiring versions for ' . count($folderSet) . ' folders', ['app' => 'cron', 'folders' => $folderIDs]); diff --git a/lib/Command/ACL.php b/lib/Command/ACL.php index e6b69f65f..995844d03 100644 --- a/lib/Command/ACL.php +++ b/lib/Command/ACL.php @@ -95,11 +95,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int $this->printPermissions($input, $output, $folder); } elseif ($input->getOption('manage-add') && ($input->getOption('user') || $input->getOption('group'))) { $mappingType = $input->getOption('user') ? 'user' : 'group'; - $mappingId = $input->getOption('user') ? $input->getOption('user') : $input->getOption('group'); + $mappingId = $input->getOption('user') ?: $input->getOption('group'); $this->folderManager->setManageACL($folder['id'], $mappingType, $mappingId, true); } elseif ($input->getOption('manage-remove') && ($input->getOption('user') || $input->getOption('group'))) { $mappingType = $input->getOption('user') ? 'user' : 'group'; - $mappingId = $input->getOption('user') ? $input->getOption('user') : $input->getOption('group'); + $mappingId = $input->getOption('user') ?: $input->getOption('group'); $this->folderManager->setManageACL($folder['id'], $mappingType, $mappingId, false); } elseif (!$input->getArgument('path')) { $output->writeln(' argument has to be set when not using --enable or --disable'); @@ -115,7 +115,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return -3; } else { $mappingType = $input->getOption('user') ? 'user' : 'group'; - $mappingId = $input->getOption('user') ? $input->getOption('user') : $input->getOption('group'); + $mappingId = $input->getOption('user') ?: $input->getOption('group'); $path = $input->getArgument('path'); $path = trim($path, '/'); $permissionStrings = $input->getArgument('permissions'); @@ -196,12 +196,8 @@ private function printPermissions(InputInterface $input, OutputInterface $output default: $items = array_map(function (array $rulesForPath, string $path) use ($jailPathLength): array { /** @var Rule[] $rulesForPath */ - $mappings = array_map(function (Rule $rule): string { - return $rule->getUserMapping()->getType() . ': ' . $rule->getUserMapping()->getId(); - }, $rulesForPath); - $permissions = array_map(function (Rule $rule): string { - return $rule->formatPermissions(); - }, $rulesForPath); + $mappings = array_map(fn (Rule $rule): string => $rule->getUserMapping()->getType() . ': ' . $rule->getUserMapping()->getId(), $rulesForPath); + $permissions = array_map(fn (Rule $rule): string => $rule->formatPermissions(), $rulesForPath); $formattedPath = substr($path, $jailPathLength); return [ @@ -210,9 +206,7 @@ private function printPermissions(InputInterface $input, OutputInterface $output 'permissions' => implode("\n", $permissions), ]; }, $rules, array_keys($rules)); - usort($items, function (array $a, array $b): int { - return $a['path'] <=> $b['path']; - }); + usort($items, fn (array $a, array $b): int => $a['path'] <=> $b['path']); $table = new Table($output); $table->setHeaders(['Path', 'User/Group', 'Permissions']); diff --git a/lib/Command/ListCommand.php b/lib/Command/ListCommand.php index 86229f9f6..8381e3142 100644 --- a/lib/Command/ListCommand.php +++ b/lib/Command/ListCommand.php @@ -67,9 +67,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $folders = $this->folderManager->getAllFoldersWithSize($rootStorageId); } - usort($folders, function (array $a, array $b): int { - return $a['id'] - $b['id']; - }); + usort($folders, fn (array $a, array $b): int => $a['id'] - $b['id']); $outputType = $input->getOption('output'); if (count($folders) === 0) { @@ -85,9 +83,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int if ($outputType === self::OUTPUT_FORMAT_JSON || $outputType === self::OUTPUT_FORMAT_JSON_PRETTY) { foreach ($folders as &$folder) { $folder['group_details'] = $folder['groups']; - $folder['groups'] = array_map(function (array $group): int { - return $group['permissions']; - }, $folder['groups']); + $folder['groups'] = array_map(fn (array $group): int => $group['permissions'], $folder['groups']); } $this->writeArrayInOutputFormat($input, $output, $folders); @@ -105,9 +101,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int }, array_keys($folder['groups']), array_values($folder['groups'])); $folder['groups'] = implode("\n", $groupStrings); $folder['acl'] = $folder['acl'] ? 'Enabled' : 'Disabled'; - $manageStrings = array_map(function (array $manage): string { - return $manage['id'] . ' (' . $manage['type'] . ')'; - }, $folder['manage']); + $manageStrings = array_map(fn (array $manage): string => $manage['id'] . ' (' . $manage['type'] . ')', $folder['manage']); $folder['manage'] = implode("\n", $manageStrings); return $folder; @@ -123,8 +117,6 @@ private function permissionsToString(int $permissions): string { return 'none'; } - return implode(', ', array_filter(self::PERMISSION_NAMES, function (int $possiblePermission) use ($permissions): int { - return $possiblePermission & $permissions; - }, ARRAY_FILTER_USE_KEY)); + return implode(', ', array_filter(self::PERMISSION_NAMES, fn (int $possiblePermission): int => $possiblePermission & $permissions, ARRAY_FILTER_USE_KEY)); } } diff --git a/lib/Command/Scan.php b/lib/Command/Scan.php index e1bbb938e..5c0703a8e 100644 --- a/lib/Command/Scan.php +++ b/lib/Command/Scan.php @@ -93,7 +93,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return -1; } - $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function (string $path) use ($output, &$statsRow): void { + $scanner->listen(\OC\Files\Cache\Scanner::class, 'scanFile', function (string $path) use ($output, &$statsRow): void { $output->writeln("\tFile\t/$path", OutputInterface::VERBOSITY_VERBOSE); $statsRow[2]++; // abortIfInterrupted doesn't exist in nc14 @@ -102,7 +102,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int } }); - $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function (string $path) use ($output, &$statsRow): void { + $scanner->listen(\OC\Files\Cache\Scanner::class, 'scanFolder', function (string $path) use ($output, &$statsRow): void { $output->writeln("\tFolder\t/$path", OutputInterface::VERBOSITY_VERBOSE); $statsRow[1]++; // abortIfInterrupted doesn't exist in nc14 diff --git a/lib/Controller/DelegationController.php b/lib/Controller/DelegationController.php index 99daf6dbd..642daeb5f 100644 --- a/lib/Controller/DelegationController.php +++ b/lib/Controller/DelegationController.php @@ -73,7 +73,7 @@ public function getAllCircles(): DataResponse { try { $circlesManager = Server::get(CirclesManager::class); - } catch (ContainerExceptionInterface $e) { + } catch (ContainerExceptionInterface) { return new DataResponse([]); } diff --git a/lib/Controller/FolderController.php b/lib/Controller/FolderController.php index 3e70bcd74..3139705f2 100644 --- a/lib/Controller/FolderController.php +++ b/lib/Controller/FolderController.php @@ -42,9 +42,7 @@ public function __construct( parent::__construct($AppName, $request); $this->user = $userSession->getUser(); - $this->registerResponder('xml', function (DataResponse $data): V1Response { - return $this->buildOCSResponseXML('xml', $data); - }); + $this->registerResponder('xml', fn (DataResponse $data): V1Response => $this->buildOCSResponseXML('xml', $data)); } /** @@ -52,9 +50,7 @@ public function __construct( */ private function filterNonAdminFolder(array $folder): ?array { $userGroups = $this->groupManager->getUserGroupIds($this->user); - $folder['groups'] = array_filter($folder['groups'], function (string $group) use ($userGroups): bool { - return in_array($group, $userGroups); - }, ARRAY_FILTER_USE_KEY); + $folder['groups'] = array_filter($folder['groups'], fn (string $group): bool => in_array($group, $userGroups), ARRAY_FILTER_USE_KEY); if ($folder['groups']) { return $folder; } else { @@ -69,9 +65,7 @@ private function filterNonAdminFolder(array $folder): ?array { private function formatFolder(array $folder): array { // keep compatibility with the old 'groups' field $folder['group_details'] = $folder['groups']; - $folder['groups'] = array_map(function (array $group): int { - return $group['permissions']; - }, $folder['groups']); + $folder['groups'] = array_map(fn (array $group): int => $group['permissions'], $folder['groups']); return $folder; } diff --git a/lib/DAV/ACLPlugin.php b/lib/DAV/ACLPlugin.php index 18a154d52..95479173b 100644 --- a/lib/DAV/ACLPlugin.php +++ b/lib/DAV/ACLPlugin.php @@ -33,8 +33,8 @@ class ACLPlugin extends ServerPlugin { public const INHERITED_ACL_LIST = '{http://nextcloud.org/ns}inherited-acl-list'; public const GROUP_FOLDER_ID = '{http://nextcloud.org/ns}group-folder-id'; - private ?Server $server; - private ?IUser $user; + private ?Server $server = null; + private ?IUser $user = null; public function __construct( private RuleManager $ruleManager, @@ -62,9 +62,7 @@ public function initialize(Server $server): void { $this->server->on('propPatch', $this->propPatch(...)); $this->server->xml->elementMap[Rule::ACL] = Rule::class; - $this->server->xml->elementMap[self::ACL_LIST] = function (Reader $reader): array { - return \Sabre\Xml\Deserializer\repeatingElements($reader, Rule::ACL); - }; + $this->server->xml->elementMap[self::ACL_LIST] = fn (Reader $reader): array => \Sabre\Xml\Deserializer\repeatingElements($reader, Rule::ACL); } /** @@ -108,9 +106,7 @@ public function propFind(PropFind $propFind, INode $node): void { $propFind->handle(self::INHERITED_ACL_LIST, function () use ($fileInfo, $mount): array { $parentInternalPaths = $this->getParents($fileInfo->getInternalPath()); - $parentPaths = array_map(function (string $internalPath) use ($mount): string { - return trim($mount->getSourcePath() . '/' . $internalPath, '/'); - }, $parentInternalPaths); + $parentPaths = array_map(fn (string $internalPath): string => trim($mount->getSourcePath() . '/' . $internalPath, '/'), $parentInternalPaths); if ($this->isAdmin($fileInfo->getPath())) { $rulesByPath = $this->ruleManager->getAllRulesForPaths($mount->getNumericStorageId(), $parentPaths); } else { @@ -141,28 +137,22 @@ public function propFind(PropFind $propFind, INode $node): void { } } - return array_map(function (UserMapping $mapping, int $permissions, int $mask) use ($fileInfo): Rule { - return new Rule( - $mapping, - $fileInfo->getId(), - $mask, - $permissions - ); - }, $mappings, $inheritedPermissionsByMapping, $inheritedMaskByMapping); + return array_map(fn (UserMapping $mapping, int $permissions, int $mask): Rule => new Rule( + $mapping, + $fileInfo->getId(), + $mask, + $permissions + ), $mappings, $inheritedPermissionsByMapping, $inheritedMaskByMapping); }); - $propFind->handle(self::GROUP_FOLDER_ID, function () use ($fileInfo): int { - return $this->folderManager->getFolderByPath($fileInfo->getPath()); - }); + $propFind->handle(self::GROUP_FOLDER_ID, fn (): int => $this->folderManager->getFolderByPath($fileInfo->getPath())); $propFind->handle(self::ACL_ENABLED, function () use ($fileInfo): bool { $folderId = $this->folderManager->getFolderByPath($fileInfo->getPath()); return $this->folderManager->getFolderAclEnabled($folderId); }); - $propFind->handle(self::ACL_CAN_MANAGE, function () use ($fileInfo): bool { - return $this->isAdmin($fileInfo->getPath()); - }); + $propFind->handle(self::ACL_CAN_MANAGE, fn (): bool => $this->isAdmin($fileInfo->getPath())); } public function propPatch(string $path, PropPatch $propPatch): void { @@ -193,18 +183,14 @@ public function propPatch(string $path, PropPatch $propPatch): void { $path = trim($mount->getSourcePath() . '/' . $fileInfo->getInternalPath(), '/'); // populate fileid in rules - $rules = array_map(function (Rule $rule) use ($fileInfo): Rule { - return new Rule( - $rule->getUserMapping(), - $fileInfo->getId(), - $rule->getMask(), - $rule->getPermissions() - ); - }, $rawRules); - - $formattedRules = array_map(function (Rule $rule): string { - return $rule->getUserMapping()->getType() . ' ' . $rule->getUserMapping()->getDisplayName() . ': ' . $rule->formatPermissions(); - }, $rules); + $rules = array_map(fn (Rule $rule): Rule => new Rule( + $rule->getUserMapping(), + $fileInfo->getId(), + $rule->getMask(), + $rule->getPermissions() + ), $rawRules); + + $formattedRules = array_map(fn (Rule $rule): string => $rule->getUserMapping()->getType() . ' ' . $rule->getUserMapping()->getDisplayName() . ': ' . $rule->formatPermissions(), $rules); if (count($formattedRules)) { $formattedRules = implode(', ', $formattedRules); $this->eventDispatcher->dispatchTyped(new CriticalActionPerformedEvent('The advanced permissions for "%s" in groupfolder with id %d was set to "%s"', [ @@ -221,19 +207,15 @@ public function propPatch(string $path, PropPatch $propPatch): void { $existingRules = array_reduce( $this->ruleManager->getAllRulesForPaths($mount->getNumericStorageId(), [$path]), - function (array $rules, array $rulesForPath): array { - return array_merge($rules, $rulesForPath); - }, + fn (array $rules, array $rulesForPath): array => array_merge($rules, $rulesForPath), [] ); - $deletedRules = array_udiff($existingRules, $rules, function (Rule $obj_a, Rule $obj_b): int { - return ( - $obj_a->getUserMapping()->getType() === $obj_b->getUserMapping()->getType() && - $obj_a->getUserMapping()->getId() === $obj_b->getUserMapping()->getId() - ) ? 0 : -1; - }); + $deletedRules = array_udiff($existingRules, $rules, fn (Rule $obj_a, Rule $obj_b): int => ( + $obj_a->getUserMapping()->getType() === $obj_b->getUserMapping()->getType() && + $obj_a->getUserMapping()->getId() === $obj_b->getUserMapping()->getId() + ) ? 0 : -1); foreach ($deletedRules as $deletedRule) { $this->ruleManager->deleteRule($deletedRule); } diff --git a/lib/DAV/PropFindPlugin.php b/lib/DAV/PropFindPlugin.php index b605de4b3..5556a57de 100644 --- a/lib/DAV/PropFindPlugin.php +++ b/lib/DAV/PropFindPlugin.php @@ -52,7 +52,7 @@ public function propFind(PropFind $propFind, INode $node): void { ); $propFind->handle( self::GROUP_FOLDER_ID_PROPERTYNAME, - fn () => $node->getFolderId() + fn (): int => $node->getFolderId() ); } } diff --git a/lib/Folder/FolderManager.php b/lib/Folder/FolderManager.php index 3b4831504..6213efaea 100644 --- a/lib/Folder/FolderManager.php +++ b/lib/Folder/FolderManager.php @@ -240,9 +240,7 @@ private function getManageAcl(array $mappings): array { 'id' => $group->getGID(), 'displayname' => $group->getDisplayName() ]; - }, $mappings), function (?array $element): bool { - return $element !== null; - }); + }, $mappings), fn (?array $element): bool => $element !== null); } /** @@ -358,7 +356,7 @@ private function generateApplicableMapEntry( $entityId = $row['circle_id']; try { $circle = $queryHelper?->extractCircle($row); - } catch (CircleNotFoundException $e) { + } catch (CircleNotFoundException) { $circle = null; } @@ -377,16 +375,12 @@ private function generateApplicableMapEntry( */ private function getGroups(int $id): array { $groups = $this->getAllApplicable()[$id] ?? []; - $groups = array_map(function (string $gid): ?IGroup { - return $this->groupManager->get($gid); - }, array_keys($groups)); + $groups = array_map(fn (string $gid): ?IGroup => $this->groupManager->get($gid), array_keys($groups)); - return array_map(function (IGroup $group): array { - return [ - 'gid' => $group->getGID(), - 'displayname' => $group->getDisplayName() - ]; - }, array_filter($groups)); + return array_map(fn (IGroup $group): array => [ + 'gid' => $group->getGID(), + 'displayname' => $group->getDisplayName() + ], array_filter($groups)); } /** @@ -402,10 +396,10 @@ public function canManageACL(int $folderId, IUser $user): bool { } // Call private server api - if (class_exists('\OC\Settings\AuthorizedGroupMapper')) { - $authorizedGroupMapper = Server::get('\OC\Settings\AuthorizedGroupMapper'); + if (class_exists(\OC\Settings\AuthorizedGroupMapper::class)) { + $authorizedGroupMapper = Server::get(\OC\Settings\AuthorizedGroupMapper::class); $settingClasses = $authorizedGroupMapper->findAllClassesForUser($user); - if (in_array('OCA\GroupFolders\Settings\Admin', $settingClasses, true)) { + if (in_array(\OCA\GroupFolders\Settings\Admin::class, $settingClasses, true)) { return true; } } @@ -444,9 +438,7 @@ public function searchGroups(int $id, string $search = ''): array { return $groups; } - return array_filter($groups, function (array $group) use ($search): bool { - return (stripos($group['gid'], $search) !== false) || (stripos($group['displayname'], $search) !== false); - }); + return array_filter($groups, fn (array $group): bool => (stripos($group['gid'], $search) !== false) || (stripos($group['displayname'], $search) !== false)); } /** @@ -512,16 +504,14 @@ public function getFoldersForGroup(string $groupId, int $rootStorageId = 0): arr $result = $query->executeQuery()->fetchAll(); - return array_values(array_map(function (array $folder): array { - return [ - 'folder_id' => (int)$folder['folder_id'], - 'mount_point' => (string)$folder['mount_point'], - 'permissions' => (int)$folder['group_permissions'], - 'quota' => (int)$folder['quota'], - 'acl' => (bool)$folder['acl'], - 'rootCacheEntry' => (isset($folder['fileid'])) ? Cache::cacheEntryFromData($folder, $this->mimeTypeLoader) : null - ]; - }, $result)); + return array_values(array_map(fn (array $folder): array => [ + 'folder_id' => (int)$folder['folder_id'], + 'mount_point' => (string)$folder['mount_point'], + 'permissions' => (int)$folder['group_permissions'], + 'quota' => (int)$folder['quota'], + 'acl' => (bool)$folder['acl'], + 'rootCacheEntry' => (isset($folder['fileid'])) ? Cache::cacheEntryFromData($folder, $this->mimeTypeLoader) : null + ], $result)); } /** @@ -569,16 +559,14 @@ public function getFoldersForGroups(array $groupIds, int $rootStorageId = 0): ar $result = array_merge($result, $query->executeQuery()->fetchAll()); } - return array_map(function (array $folder): array { - return [ - 'folder_id' => (int)$folder['folder_id'], - 'mount_point' => (string)$folder['mount_point'], - 'permissions' => (int)$folder['group_permissions'], - 'quota' => (int)$folder['quota'], - 'acl' => (bool)$folder['acl'], - 'rootCacheEntry' => (isset($folder['fileid'])) ? Cache::cacheEntryFromData($folder, $this->mimeTypeLoader) : null - ]; - }, $result); + return array_map(fn (array $folder): array => [ + 'folder_id' => (int)$folder['folder_id'], + 'mount_point' => (string)$folder['mount_point'], + 'permissions' => (int)$folder['group_permissions'], + 'quota' => (int)$folder['quota'], + 'acl' => (bool)$folder['acl'], + 'rootCacheEntry' => (isset($folder['fileid'])) ? Cache::cacheEntryFromData($folder, $this->mimeTypeLoader) : null + ], $result); } /** @@ -593,7 +581,7 @@ public function getFoldersFromCircleMemberships(IUser $user, int $rootStorageId try { $federatedUser = $circlesManager->getLocalFederatedUser($user->getUID()); - } catch (\Exception $e) { + } catch (\Exception) { return []; } @@ -631,16 +619,14 @@ public function getFoldersFromCircleMemberships(IUser $user, int $rootStorageId $queryHelper->limitToInheritedMembers('a', 'circle_id', $federatedUser); $this->joinQueryWithFileCache($query, $rootStorageId); - return array_map(function (array $folder): array { - return [ - 'folder_id' => (int)$folder['folder_id'], - 'mount_point' => (string)$folder['mount_point'], - 'permissions' => (int)$folder['group_permissions'], - 'quota' => (int)$folder['quota'], - 'acl' => (bool)$folder['acl'], - 'rootCacheEntry' => (isset($folder['fileid'])) ? Cache::cacheEntryFromData($folder, $this->mimeTypeLoader) : null - ]; - }, $query->executeQuery()->fetchAll()); + return array_map(fn (array $folder): array => [ + 'folder_id' => (int)$folder['folder_id'], + 'mount_point' => (string)$folder['mount_point'], + 'permissions' => (int)$folder['group_permissions'], + 'quota' => (int)$folder['quota'], + 'acl' => (bool)$folder['acl'], + 'rootCacheEntry' => (isset($folder['fileid'])) ? Cache::cacheEntryFromData($folder, $this->mimeTypeLoader) : null + ], $query->executeQuery()->fetchAll()); } @@ -927,7 +913,7 @@ public function isACircle(string $groupId): bool { $circlesManager->getCircle($groupId, $probe); return true; - } catch (CircleNotFoundException $e) { + } catch (CircleNotFoundException) { } catch (\Exception $e) { $this->logger->warning('', ['exception' => $e]); } finally { @@ -940,7 +926,7 @@ public function isACircle(string $groupId): bool { public function getCirclesManager(): ?CirclesManager { try { return Server::get(CirclesManager::class); - } catch (ContainerExceptionInterface|AutoloadNotAllowedException $e) { + } catch (ContainerExceptionInterface|AutoloadNotAllowedException) { return null; } } diff --git a/lib/Listeners/NodeRenamedListener.php b/lib/Listeners/NodeRenamedListener.php index 86354b934..84b12c135 100644 --- a/lib/Listeners/NodeRenamedListener.php +++ b/lib/Listeners/NodeRenamedListener.php @@ -15,7 +15,6 @@ use OCP\EventDispatcher\IEventListener; use OCP\Files\Events\Node\NodeRenamedEvent; use OCP\Files\Folder; -use Psr\Log\LoggerInterface; /** * @template-implements IEventListener @@ -23,7 +22,6 @@ class NodeRenamedListener implements IEventListener { public function __construct( private TrashManager $trashManager, - private LoggerInterface $logger, ) { } diff --git a/lib/Mount/CacheRootPermissionsMask.php b/lib/Mount/CacheRootPermissionsMask.php index ec281edca..9ea66dda4 100644 --- a/lib/Mount/CacheRootPermissionsMask.php +++ b/lib/Mount/CacheRootPermissionsMask.php @@ -22,7 +22,7 @@ public function __construct( protected function formatCacheEntry($entry): ICacheEntry|false { $path = $entry['path']; - $isRoot = $path === '' || (strpos($path, '__groupfolders') === 0 && count(explode('/', $path)) === 2); + $isRoot = $path === '' || (str_starts_with($path, '__groupfolders') && count(explode('/', $path)) === 2); if (isset($entry['permissions']) && $isRoot) { $entry['scan_permissions'] = $entry['permissions']; $entry['permissions'] &= $this->mask; diff --git a/lib/Mount/MountProvider.php b/lib/Mount/MountProvider.php index 3536703f9..cd3bd4d58 100644 --- a/lib/Mount/MountProvider.php +++ b/lib/Mount/MountProvider.php @@ -73,17 +73,11 @@ public function getFoldersForUser(IUser $user): array { public function getMountsForUser(IUser $user, IStorageFactory $loader): array { $folders = $this->getFoldersForUser($user); - $mountPoints = array_map(function (array $folder): string { - return 'files/' . $folder['mount_point']; - }, $folders); + $mountPoints = array_map(fn (array $folder): string => 'files/' . $folder['mount_point'], $folders); $conflicts = $this->findConflictsForUser($user, $mountPoints); - $foldersWithAcl = array_filter($folders, function (array $folder): bool { - return $folder['acl']; - }); - $aclRootPaths = array_map(function (array $folder): string { - return $this->getJailPath($folder['folder_id']); - }, $foldersWithAcl); + $foldersWithAcl = array_filter($folders, fn (array $folder): bool => $folder['acl']); + $aclRootPaths = array_map(fn (array $folder): string => $this->getJailPath($folder['folder_id']), $foldersWithAcl); $aclManager = $this->aclManagerFactory->getACLManager($user, $this->getRootStorageId()); $rootRules = $aclManager->getRelevantRulesForPath($aclRootPaths); @@ -132,7 +126,7 @@ private function getCurrentUID(): ?string { return $wopi->getEditorUid(); } } - } catch (\Exception $e) { + } catch (\Exception) { } $user = $this->userSession->getUser(); @@ -246,7 +240,7 @@ private function getRootFolder(): Folder { public function getFolder(int $id, bool $create = true): ?Node { try { return $this->getRootFolder()->get((string)$id); - } catch (NotFoundException $e) { + } catch (NotFoundException) { if ($create) { return $this->getRootFolder()->newFolder((string)$id); } else { diff --git a/lib/Mount/RootPermissionsMask.php b/lib/Mount/RootPermissionsMask.php index 2ca862352..62e19e474 100644 --- a/lib/Mount/RootPermissionsMask.php +++ b/lib/Mount/RootPermissionsMask.php @@ -81,7 +81,7 @@ public function getMetaData($path): ?array { $data = parent::getMetaData($path); if ($data && $path === '' && isset($data['permissions'])) { - $data['scan_permissions'] = $data['scan_permissions'] ?? $data['permissions']; + $data['scan_permissions'] ??= $data['permissions']; $data['permissions'] &= $this->mask; } diff --git a/lib/Service/FoldersFilter.php b/lib/Service/FoldersFilter.php index 584942b65..22324b36f 100644 --- a/lib/Service/FoldersFilter.php +++ b/lib/Service/FoldersFilter.php @@ -23,7 +23,8 @@ public function __construct( */ public function getForApiUser(array $folders): array { $user = $this->userSession->getUser(); - $folders = array_filter($folders, function (array $folder) use ($user): bool { + + return array_filter($folders, function (array $folder) use ($user): bool { foreach ($folder['manage'] as $manager) { if ($manager['type'] === 'group') { if ($this->groupManager->isInGroup($user->getUid(), $manager['id'])) { @@ -36,7 +37,5 @@ public function getForApiUser(array $folders): array { return false; }); - - return $folders; } } diff --git a/lib/Trash/TrashBackend.php b/lib/Trash/TrashBackend.php index 478a548d4..cf847253d 100644 --- a/lib/Trash/TrashBackend.php +++ b/lib/Trash/TrashBackend.php @@ -200,7 +200,6 @@ public function removeItem(ITrashItem $item): void { public function moveToTrash(IStorage $storage, string $internalPath): bool { if ($storage->instanceOfStorage(GroupFolderStorage::class) && $storage->isDeletable($internalPath)) { - /** @var GroupFolderStorage|Jail $storage */ $name = basename($internalPath); $fileEntry = $storage->getCache()->get($internalPath); $folderId = $storage->getFolderId(); @@ -240,9 +239,7 @@ private function unwrapJails(IStorage $storage, string $internalPath): array { private function userHasAccessToFolder(IUser $user, int $folderId): bool { $folders = $this->folderManager->getFoldersForUser($user); - $folderIds = array_map(function (array $folder): int { - return $folder['folder_id']; - }, $folders); + $folderIds = array_map(fn (array $folder): int => $folder['folder_id'], $folders); return in_array($folderId, $folderIds); } @@ -271,7 +268,7 @@ private function getNodeForTrashItem(IUser $user, ITrashItem $trashItem): ?Node } return $node; - } catch (NotFoundException $e) { + } catch (NotFoundException) { return null; } } @@ -286,7 +283,7 @@ private function getTrashRoot(): Folder { $folder = $this->appFolder->get('trash'); return $folder; - } catch (NotFoundException $e) { + } catch (NotFoundException) { return $this->appFolder->newFolder('trash'); } } @@ -297,7 +294,7 @@ private function getTrashFolder(int $folderId): Folder { $folder = $this->appFolder->get('trash/' . $folderId); return $folder; - } catch (NotFoundException $e) { + } catch (NotFoundException) { /** @var Folder $trashRoot */ $trashRoot = $this->appFolder->nodeExists('trash') ? $this->appFolder->get('trash') : $this->appFolder->newFolder('trash'); @@ -310,9 +307,7 @@ private function getTrashFolder(int $folderId): Folder { * @return list */ private function getTrashForFolders(IUser $user, array $folders): array { - $folderIds = array_map(function (array $folder): int { - return $folder['folder_id']; - }, $folders); + $folderIds = array_map(fn (array $folder): int => $folder['folder_id'], $folders); $rows = $this->trashManager->listTrashForFolders($folderIds); $indexedRows = []; $trashItemsByOriginalLocation = []; @@ -414,7 +409,7 @@ public function getTrashNodeById(IUser $user, int $fileId): ?Node { } else { return null; } - } catch (NotFoundException $e) { + } catch (NotFoundException) { return null; } } @@ -422,10 +417,6 @@ public function getTrashNodeById(IUser $user, int $fileId): ?Node { public function cleanTrashFolder(int $folderid): void { $trashFolder = $this->getTrashFolder($folderid); - if (!($trashFolder instanceof Folder)) { - return; - } - foreach ($trashFolder->getDirectoryListing() as $node) { $node->delete(); } @@ -449,7 +440,7 @@ public function expire(Expiration $expiration): array { $nodeName = $groupTrashItem['name'] . '.d' . $groupTrashItem['deleted_time']; try { $nodes[$nodeName] = $node = $trashFolder->get($nodeName); - } catch (NotFoundException $e) { + } catch (NotFoundException) { $this->trashManager->removeItem($folderId, $groupTrashItem['name'], $groupTrashItem['deleted_time']); continue; } diff --git a/lib/Versions/ExpireManager.php b/lib/Versions/ExpireManager.php index 02e0328e8..e4f63bb29 100644 --- a/lib/Versions/ExpireManager.php +++ b/lib/Versions/ExpireManager.php @@ -50,9 +50,7 @@ protected function getAutoExpireList(int $time, array $versions): array { $toDelete = []; // versions we want to delete // ensure the versions are sorted newest first - usort($versions, function (IVersion $a, IVersion $b): int { - return $b->getTimestamp() <=> $a->getTimestamp(); - }); + usort($versions, fn (IVersion $a, IVersion $b): int => $b->getTimestamp() <=> $a->getTimestamp()); $interval = 1; $step = self::MAX_VERSIONS_PER_INTERVAL[$interval]['step']; @@ -106,10 +104,8 @@ public function getExpiredVersion(array $versions, int $time, bool $quotaExceede $autoExpire = []; } - $versionsLeft = array_udiff($versions, $autoExpire, function (IVersion $a, IVersion $b): int { - return ($a->getRevisionId() <=> $b->getRevisionId()) * - ($a->getSourceFile()->getId() <=> $b->getSourceFile()->getId()); - }); + $versionsLeft = array_udiff($versions, $autoExpire, fn (IVersion $a, IVersion $b): int => ($a->getRevisionId() <=> $b->getRevisionId()) * + ($a->getSourceFile()->getId() <=> $b->getSourceFile()->getId())); $expired = array_filter($versionsLeft, function (IVersion $version) use ($quotaExceeded): bool { // Do not expire current version. diff --git a/lib/Versions/VersionsBackend.php b/lib/Versions/VersionsBackend.php index d2737dccd..471f5f968 100644 --- a/lib/Versions/VersionsBackend.php +++ b/lib/Versions/VersionsBackend.php @@ -19,7 +19,6 @@ use OCA\GroupFolders\Mount\GroupFolderStorage; use OCA\GroupFolders\Mount\GroupMountPoint; use OCA\GroupFolders\Mount\MountProvider; -use OCP\AppFramework\Utility\ITimeFactory; use OCP\Constants; use OCP\Files\File; use OCP\Files\FileInfo; @@ -38,7 +37,6 @@ public function __construct( private IRootFolder $rootFolder, private Folder $appFolder, private MountProvider $mountProvider, - private ITimeFactory $timeFactory, private LoggerInterface $logger, private GroupVersionsMapper $groupVersionsMapper, private IMimeTypeLoader $mimeTypeLoader, @@ -60,9 +58,8 @@ private function getFolderIdForFile(FileInfo $file): int { } elseif ($storage->instanceOfStorage(GroupFolderStorage::class)) { /** @var GroupFolderStorage $storage */ return $storage->getFolderId(); - } else { - throw new \LogicException('groupfolder version backend called for non groupfolder file'); } + throw new \LogicException('groupfolder version backend called for non groupfolder file'); } public function getVersionFolderForFile(FileInfo $file): Folder { @@ -74,7 +71,7 @@ public function getVersionFolderForFile(FileInfo $file): Folder { $versionsFolder = $groupfoldersVersionsFolder->get((string)$file->getId()); return $versionsFolder; - } catch (NotFoundException $e) { + } catch (NotFoundException) { // The folder for the file's versions might not exists if no versions has been create yet. return $groupfoldersVersionsFolder->newFolder((string)$file->getId()); } @@ -129,7 +126,7 @@ public function getVersionsForFile(IUser $user, FileInfo $file): array { } return $this->getVersionsForFileFromDB($file, $user); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return []; } } @@ -156,7 +153,7 @@ function (GroupVersionEntity $versionEntity) use ($versionsFolder, $mountPoint, } else { try { $versionFile = $versionsFolder->get((string)$versionEntity->getTimestamp()); - } catch (NotFoundException $e) { + } catch (NotFoundException) { // The version does not exists on disk anymore, so we can delete its entity in the DB. // The reality is that the disk version might have been lost during a move operation between storages, // and its not possible to recover it, so removing the entity makes sense. @@ -256,13 +253,11 @@ public function getAllVersionedFiles(array $folder): array { try { $contents = $versionsFolder->getDirectoryListing(); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return []; } - $fileIds = array_map(function (Node $node) use ($mount): int { - return (int)$node->getName(); - }, $contents); + $fileIds = array_map(fn (Node $node): int => (int)$node->getName(), $contents); $files = array_map(function (int $fileId) use ($mount): ?FileInfo { $cacheEntry = $mount->getStorage()->getCache()->get($fileId); if ($cacheEntry) { @@ -280,7 +275,7 @@ public function deleteAllVersionsForFile(int $folderId, int $fileId): void { try { $versionsFolder->get((string)$fileId)->delete(); $this->groupVersionsMapper->deleteAllVersionsForFileId($fileId); - } catch (NotFoundException $e) { + } catch (NotFoundException) { } } @@ -290,7 +285,7 @@ private function getVersionsFolder(int $folderId): Folder { $folder = $this->appFolder->get('versions/' . $folderId); return $folder; - } catch (NotFoundException $e) { + } catch (NotFoundException) { /** @var Folder $trashRoot */ $trashRoot = $this->appFolder->nodeExists('versions') ? $this->appFolder->get('versions') : $this->appFolder->newFolder('versions'); diff --git a/rector.php b/rector.php index 47c5b5d7d..993341e5f 100644 --- a/rector.php +++ b/rector.php @@ -15,4 +15,9 @@ ->withSkip([ __DIR__ . '/tests/stubs', ]) - ->withTypeCoverageLevel(0); + ->withPreparedSets( + deadCode: true, + typeDeclarations: true, + )->withPhpSets( + php81: true, + ); diff --git a/tests/ACL/ACLCacheWrapperTest.php b/tests/ACL/ACLCacheWrapperTest.php index 415203e6e..562700196 100644 --- a/tests/ACL/ACLCacheWrapperTest.php +++ b/tests/ACL/ACLCacheWrapperTest.php @@ -23,23 +23,20 @@ class ACLCacheWrapperTest extends TestCase { private $aclManager; /** @var ICache|\PHPUnit_Framework_MockObject_MockObject */ private $source; - /** @var ACLCacheWrapper */ - private $cache; - private $aclPermissions = []; + private ?ACLCacheWrapper $cache = null; + private array $aclPermissions = []; protected function setUp(): void { parent::setUp(); $this->aclManager = $this->createMock(ACLManager::class); $this->aclManager->method('getACLPermissionsForPath') - ->willReturnCallback(function (string $path) { - return isset($this->aclPermissions[$path]) ? $this->aclPermissions[$path] : Constants::PERMISSION_ALL; - }); + ->willReturnCallback(fn (string $path) => $this->aclPermissions[$path] ?? Constants::PERMISSION_ALL); $this->source = $this->createMock(ICache::class); $this->cache = new ACLCacheWrapper($this->source, $this->aclManager, false); } - public function testHideNonRead() { + public function testHideNonRead(): void { $this->source->method('getFolderContentsById') ->willReturn([ new CacheEntry([ diff --git a/tests/ACL/ACLManagerTest.php b/tests/ACL/ACLManagerTest.php index 349c9987a..188d13fba 100644 --- a/tests/ACL/ACLManagerTest.php +++ b/tests/ACL/ACLManagerTest.php @@ -41,12 +41,10 @@ protected function setUp(): void { $this->dummyMapping = $this->createMapping('dummy'); $this->ruleManager->method('getRulesForFilesByPath') - ->willReturnCallback(function (IUser $user, int $storageId, array $paths) { + ->willReturnCallback(function (IUser $user, int $storageId, array $paths): array { // fill with empty in case no rule was found $rules = array_fill_keys($paths, []); - $actualRules = array_filter($this->rules, function (string $path) use ($paths) { - return array_search($path, $paths) !== false; - }, ARRAY_FILTER_USE_KEY); + $actualRules = array_filter($this->rules, fn (string $path): bool => array_search($path, $paths) !== false, ARRAY_FILTER_USE_KEY); return array_merge($rules, $actualRules); }); @@ -69,9 +67,7 @@ private function getAclManager(bool $perUserMerge = false): ACLManager { $rootFolder->method('getMountPoint') ->willReturn($rootMountPoint); - return new ACLManager($this->ruleManager, $this->trashManager, $this->logger, $this->user, function () use ($rootFolder) { - return $rootFolder; - }, null, $perUserMerge); + return new ACLManager($this->ruleManager, $this->trashManager, $this->logger, $this->user, fn () => $rootFolder, null, $perUserMerge); } public function testGetACLPermissionsForPathNoRules(): void { diff --git a/tests/ACL/ACLScannerTest.php b/tests/ACL/ACLScannerTest.php index dba331836..222b07bb8 100644 --- a/tests/ACL/ACLScannerTest.php +++ b/tests/ACL/ACLScannerTest.php @@ -22,14 +22,12 @@ private function getAclManager(array $rules): ACLManager { ->disableOriginalConstructor() ->getMock(); $manager->method('getACLPermissionsForPath') - ->willReturnCallback(function ($path) use ($rules) { - return $rules[$path] ?? Constants::PERMISSION_ALL; - }); + ->willReturnCallback(fn ($path) => $rules[$path] ?? Constants::PERMISSION_ALL); return $manager; } - public function testScanAclStorage() { + public function testScanAclStorage(): void { $baseStorage = new Temporary([]); $baseStorage->mkdir('foo'); $baseStorage->mkdir('foo/bar'); diff --git a/tests/ACL/ACLStorageWrapperTest.php b/tests/ACL/ACLStorageWrapperTest.php index 35b63fe89..7b2f993ff 100644 --- a/tests/ACL/ACLStorageWrapperTest.php +++ b/tests/ACL/ACLStorageWrapperTest.php @@ -12,26 +12,21 @@ use OCA\GroupFolders\ACL\ACLManager; use OCA\GroupFolders\ACL\ACLStorageWrapper; use OCP\Constants; -use OCP\Files\Storage\IStorage; use Test\TestCase; class ACLStorageWrapperTest extends TestCase { /** @var ACLManager|\PHPUnit_Framework_MockObject_MockObject */ private $aclManager; - /** @var IStorage */ - private $source; - /** @var ACLStorageWrapper */ - private $storage; - private $aclPermissions = []; + private ?Temporary $source = null; + private ?ACLStorageWrapper $storage = null; + private array $aclPermissions = []; protected function setUp(): void { parent::setUp(); $this->aclManager = $this->createMock(ACLManager::class); $this->aclManager->method('getACLPermissionsForPath') - ->willReturnCallback(function (string $path) { - return isset($this->aclPermissions[$path]) ? $this->aclPermissions[$path] : Constants::PERMISSION_ALL; - }); + ->willReturnCallback(fn (string $path) => $this->aclPermissions[$path] ?? Constants::PERMISSION_ALL); $this->source = new Temporary([]); $this->storage = new ACLStorageWrapper([ 'storage' => $this->source, @@ -40,7 +35,7 @@ protected function setUp(): void { ]); } - public function testNoReadImpliesNothing() { + public function testNoReadImpliesNothing(): void { $this->source->mkdir('foo'); $this->aclPermissions['foo'] = Constants::PERMISSION_ALL - Constants::PERMISSION_READ; @@ -50,7 +45,7 @@ public function testNoReadImpliesNothing() { $this->assertEquals(false, $this->storage->isSharable('foo')); } - public function testOpenDir() { + public function testOpenDir(): void { $this->source->mkdir('foo'); $this->source->touch('foo/file1'); $this->source->touch('foo/file2'); @@ -73,7 +68,7 @@ public function testOpenDir() { $this->assertEquals($expected, $result); } - public function testMove() { + public function testMove(): void { $this->source->mkdir('foo'); $this->source->touch('file1'); diff --git a/tests/ACL/RuleManagerTest.php b/tests/ACL/RuleManagerTest.php index 36a9b43ae..0d50f91b3 100644 --- a/tests/ACL/RuleManagerTest.php +++ b/tests/ACL/RuleManagerTest.php @@ -24,8 +24,7 @@ class RuleManagerTest extends TestCase { /** @var \PHPUnit_Framework_MockObject_MockObject | IUserMappingManager */ private $userMappingManager; - /** @var RuleManager */ - private $ruleManager; + private ?RuleManager $ruleManager = null; /** @var \PHPUnit_Framework_MockObject_MockObject | IUser */ private $user; @@ -42,7 +41,7 @@ protected function setUp(): void { $this->userMappingManager = $this->createMock(IUserMappingManager::class); $this->userMappingManager->expects($this->any()) ->method('mappingFromId') - ->willReturnCallback(function ($type, $id) { + ->willReturnCallback(function ($type, $id): UserMapping { if ($type === 'user') { return new UserMapping($type, $id, 'The User'); } else { @@ -54,7 +53,7 @@ protected function setUp(): void { $this->ruleManager = new RuleManager(\OC::$server->getDatabaseConnection(), $this->userMappingManager, $this->eventDispatcher); } - public function testGetSetRule() { + public function testGetSetRule(): void { $mapping = new UserMapping('user', '1', 'The User'); $this->userMappingManager->expects($this->any()) ->method('getMappingsForUser') @@ -64,28 +63,22 @@ public function testGetSetRule() { $this->eventDispatcher->expects($this->any()) ->method('dispatchTyped') ->withConsecutive( - [$this->callback(function (CriticalActionPerformedEvent $event): bool { - return $event->getParameters() === [ - 'permissions' => 0b00001001, - 'mask' => 0b00001111, - 'fileId' => 10, - 'user' => 'The User (1)', - ]; - })], - [$this->callback(function (CriticalActionPerformedEvent $event): bool { - return $event->getParameters() === [ - 'permissions' => 0b00001000, - 'mask' => 0b00001111, - 'fileId' => 10, - 'user' => 'The User (1)', - ]; - })], - [$this->callback(function (CriticalActionPerformedEvent $event): bool { - return $event->getParameters() === [ - 'fileId' => 10, - 'user' => 'The User (1)', - ]; - })], + [$this->callback(fn (CriticalActionPerformedEvent $event): bool => $event->getParameters() === [ + 'permissions' => 0b00001001, + 'mask' => 0b00001111, + 'fileId' => 10, + 'user' => 'The User (1)', + ])], + [$this->callback(fn (CriticalActionPerformedEvent $event): bool => $event->getParameters() === [ + 'permissions' => 0b00001000, + 'mask' => 0b00001111, + 'fileId' => 10, + 'user' => 'The User (1)', + ])], + [$this->callback(fn (CriticalActionPerformedEvent $event): bool => $event->getParameters() === [ + 'fileId' => 10, + 'user' => 'The User (1)', + ])], ); $rule = new Rule($mapping, 10, 0b00001111, 0b00001001); @@ -104,7 +97,7 @@ public function testGetSetRule() { $this->ruleManager->deleteRule($rule); } - public function testGetMultiple() { + public function testGetMultiple(): void { $mapping1 = new UserMapping('test', '1'); $mapping2 = new UserMapping('test', '2'); $this->userMappingManager->expects($this->any()) @@ -131,7 +124,7 @@ public function testGetMultiple() { $this->ruleManager->deleteRule($rule3); } - public function testGetByPath() { + public function testGetByPath(): void { $storage = new Temporary([]); $storage->mkdir('foo'); $storage->mkdir('foo/bar'); @@ -166,7 +159,7 @@ public function testGetByPath() { $this->ruleManager->deleteRule($rule2); } - public function testGetByPathMore() { + public function testGetByPathMore(): void { $storage = new Temporary([]); $storage->mkdir('foo'); $paths = []; @@ -207,7 +200,7 @@ public function testGetByPathMore() { $this->ruleManager->deleteRule($rule); } - public function testGetByParent() { + public function testGetByParent(): void { $storage = new Temporary([]); $storage->mkdir('foo'); $storage->mkdir('foo/bar'); diff --git a/tests/ACL/RuleTest.php b/tests/ACL/RuleTest.php index 9f549e7c5..fe2f146d0 100644 --- a/tests/ACL/RuleTest.php +++ b/tests/ACL/RuleTest.php @@ -26,7 +26,7 @@ public function permissionsProvider() { /** * @dataProvider permissionsProvider */ - public function testApplyPermissions($input, $mask, $permissions, $expected) { + public function testApplyPermissions($input, $mask, $permissions, $expected): void { $rule = new Rule($this->createMock(IUserMapping::class), 0, $mask, $permissions); $this->assertEquals($expected, $rule->applyPermissions($input)); } @@ -56,10 +56,8 @@ public function mergeRulesProvider() { /** * @dataProvider mergeRulesProvider */ - public function testMergeRules($inputs, $expectedMask, $expectedPermissions) { - $inputRules = array_map(function (array $input) { - return new Rule($this->createMock(IUserMapping::class), 0, $input[0], $input[1]); - }, $inputs); + public function testMergeRules($inputs, $expectedMask, $expectedPermissions): void { + $inputRules = array_map(fn (array $input): Rule => new Rule($this->createMock(IUserMapping::class), 0, $input[0], $input[1]), $inputs); $result = Rule::mergeRules($inputRules); $this->assertEquals($expectedMask, $result->getMask()); diff --git a/tests/Folder/FolderManagerTest.php b/tests/Folder/FolderManagerTest.php index 89ca8fc1b..4cd515e1f 100644 --- a/tests/Folder/FolderManagerTest.php +++ b/tests/Folder/FolderManagerTest.php @@ -51,7 +51,7 @@ protected function setUp(): void { $this->clean(); } - private function clean() { + private function clean(): void { $query = \OC::$server->getDatabaseConnection()->getQueryBuilder(); $query->delete('group_folders')->execute(); @@ -59,14 +59,10 @@ private function clean() { $query->delete('group_folders_groups')->execute(); } - private function assertHasFolders($folders) { + private function assertHasFolders(array $folders): void { $existingFolders = array_values($this->manager->getAllFolders()); - usort($existingFolders, function ($a, $b) { - return strcmp($a['mount_point'], $b['mount_point']); - }); - usort($folders, function ($a, $b) { - return strcmp($a['mount_point'], $b['mount_point']); - }); + usort($existingFolders, fn (array $a, array $b): int => strcmp($a['mount_point'], $b['mount_point'])); + usort($folders, fn (array $a, array $b): int => strcmp($a['mount_point'], $b['mount_point'])); foreach ($folders as &$folder) { if (!isset($folder['size'])) { @@ -89,7 +85,7 @@ private function assertHasFolders($folders) { $this->assertEquals($folders, $existingFolders); } - public function testCreateFolder() { + public function testCreateFolder(): void { $this->manager->createFolder('foo'); $this->assertHasFolders([ @@ -97,7 +93,7 @@ public function testCreateFolder() { ]); } - public function testSetMountpoint() { + public function testSetMountpoint(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->createFolder('bar'); @@ -109,7 +105,7 @@ public function testSetMountpoint() { ]); } - public function testAddApplicable() { + public function testAddApplicable(): void { $folderId1 = $this->manager->createFolder('foo'); $folderId2 = $this->manager->createFolder('bar'); $this->manager->addApplicableGroup($folderId1, 'g1'); @@ -154,7 +150,7 @@ public function testAddApplicable() { ); } - public function testSetPermissions() { + public function testSetPermissions(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->addApplicableGroup($folderId1, 'g1'); $this->manager->addApplicableGroup($folderId1, 'g2'); @@ -182,7 +178,7 @@ public function testSetPermissions() { ); } - public function testRemoveApplicable() { + public function testRemoveApplicable(): void { $folderId1 = $this->manager->createFolder('foo'); $folderId2 = $this->manager->createFolder('bar'); $this->manager->addApplicableGroup($folderId1, 'g1'); @@ -225,7 +221,7 @@ public function testRemoveApplicable() { ); } - public function testRemoveFolder() { + public function testRemoveFolder(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->createFolder('bar'); @@ -236,7 +232,7 @@ public function testRemoveFolder() { ]); } - public function testRenameFolder() { + public function testRenameFolder(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->createFolder('other'); @@ -248,7 +244,7 @@ public function testRenameFolder() { ]); } - public function testSetACL() { + public function testSetACL(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->createFolder('other'); @@ -267,7 +263,7 @@ public function testSetACL() { ]); } - public function testGetFoldersForGroup() { + public function testGetFoldersForGroup(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->addApplicableGroup($folderId1, 'g1'); $this->manager->addApplicableGroup($folderId1, 'g2'); @@ -280,7 +276,7 @@ public function testGetFoldersForGroup() { $this->assertEquals(2, $folder['permissions']); } - public function testGetFoldersForGroups() { + public function testGetFoldersForGroups(): void { $folderId1 = $this->manager->createFolder('foo'); $this->manager->addApplicableGroup($folderId1, 'g1'); $this->manager->addApplicableGroup($folderId1, 'g2'); @@ -309,13 +305,13 @@ protected function getUser($groups = []) { return $user; } - public function testGetFoldersForUserEmpty() { + public function testGetFoldersForUserEmpty(): void { $folders = $this->manager->getFoldersForUser($this->getUser()); $this->assertEquals([], $folders); } - public function testGetFoldersForUserSimple() { + public function testGetFoldersForUserSimple(): void { $db = $this->createMock(IDBConnection::class); /** @var FolderManager|\PHPUnit_Framework_MockObject_MockObject $manager */ $manager = $this->getMockBuilder(FolderManager::class) @@ -338,7 +334,7 @@ public function testGetFoldersForUserSimple() { $this->assertEquals([$folder], $folders); } - public function testGetFoldersForUserMerge() { + public function testGetFoldersForUserMerge(): void { $db = $this->createMock(IDBConnection::class); /** @var FolderManager|\PHPUnit_Framework_MockObject_MockObject $manager */ $manager = $this->getMockBuilder(FolderManager::class) @@ -374,7 +370,7 @@ public function testGetFoldersForUserMerge() { ], $folders); } - public function testGetFolderPermissionsForUserMerge() { + public function testGetFolderPermissionsForUserMerge(): void { $db = $this->createMock(IDBConnection::class); /** @var FolderManager|\PHPUnit_Framework_MockObject_MockObject $manager */ $manager = $this->getMockBuilder(FolderManager::class) diff --git a/tests/Trash/TrashBackendTest.php b/tests/Trash/TrashBackendTest.php index 9c45ea428..119065783 100644 --- a/tests/Trash/TrashBackendTest.php +++ b/tests/Trash/TrashBackendTest.php @@ -105,7 +105,7 @@ private function createNoReadRule(string $userId, int $fileId): Rule { ); } - public function testHideTrashItemAcl() { + public function testHideTrashItemAcl(): void { $this->loginAsUser('manager'); $restricted = $this->managerUserFolder->newFile("{$this->folderName}/restricted.txt", 'content'); @@ -126,7 +126,7 @@ public function testHideTrashItemAcl() { $this->logout(); } - public function testHideItemInDeletedFolderAcl() { + public function testHideItemInDeletedFolderAcl(): void { $this->loginAsUser('manager'); $folder = $this->managerUserFolder->newFolder("{$this->folderName}/folder"); @@ -155,7 +155,7 @@ public function testHideItemInDeletedFolderAcl() { $this->logout(); } - public function testHideDeletedTrashItemInDeletedFolderAcl() { + public function testHideDeletedTrashItemInDeletedFolderAcl(): void { $this->loginAsUser('manager'); $folder = $this->managerUserFolder->newFolder("{$this->folderName}/restricted"); @@ -183,7 +183,7 @@ public function testHideDeletedTrashItemInDeletedFolderAcl() { $this->logout(); } - public function testHideDeletedTrashItemInDeletedParentFolderAcl() { + public function testHideDeletedTrashItemInDeletedParentFolderAcl(): void { $this->loginAsUser('manager'); $parent = $this->managerUserFolder->newFolder("{$this->folderName}/parent");