Skip to content

Commit

Permalink
refactor: Move to PHP 8.1 language features
Browse files Browse the repository at this point in the history
Signed-off-by: provokateurin <[email protected]>
  • Loading branch information
provokateurin committed Sep 19, 2024
1 parent 2453391 commit 216e7dc
Show file tree
Hide file tree
Showing 29 changed files with 171 additions and 293 deletions.
8 changes: 2 additions & 6 deletions lib/ACL/ACLCacheWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -89,9 +87,7 @@ public function searchQuery(ISearchQuery $query): array {
* @return array<string, Rule[]>
*/
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);
}
Expand Down
8 changes: 2 additions & 6 deletions lib/ACL/ACLManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
8 changes: 4 additions & 4 deletions lib/ACL/ACLStorageWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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;
Expand Down
8 changes: 2 additions & 6 deletions lib/ACL/Rule.php
Original file line number Diff line number Diff line change
Expand Up @@ -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', ''),
Expand Down
48 changes: 18 additions & 30 deletions lib/ACL/RuleManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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) {
Expand All @@ -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());
}
Expand Down Expand Up @@ -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)
)
);

Expand Down Expand Up @@ -176,9 +168,7 @@ private function getId(int $storageId, string $path): int {
* @return array<string, Rule[]>
*/
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')
Expand Down Expand Up @@ -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();

Expand Down
4 changes: 1 addition & 3 deletions lib/ACL/UserMapping/UserMappingManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()),
Expand Down
30 changes: 12 additions & 18 deletions lib/AppInfo/Application.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');
}
}, [
Expand All @@ -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';
Expand Down Expand Up @@ -142,17 +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(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
Expand Down Expand Up @@ -215,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),
Expand Down
4 changes: 1 addition & 3 deletions lib/BackgroundJob/ExpireGroupVersions.php
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Expand Down
18 changes: 6 additions & 12 deletions lib/Command/ACL.php
Original file line number Diff line number Diff line change
Expand Up @@ -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('<error><path> argument has to be set when not using --enable or --disable</error>');
Expand All @@ -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');
Expand Down Expand Up @@ -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 [
Expand All @@ -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']);
Expand Down
16 changes: 4 additions & 12 deletions lib/Command/ListCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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);
Expand All @@ -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;
Expand All @@ -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));
}
}
4 changes: 2 additions & 2 deletions lib/Command/Scan.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<info>/$path</info>", OutputInterface::VERBOSITY_VERBOSE);
$statsRow[2]++;
// abortIfInterrupted doesn't exist in nc14
Expand All @@ -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<info>/$path</info>", OutputInterface::VERBOSITY_VERBOSE);
$statsRow[1]++;
// abortIfInterrupted doesn't exist in nc14
Expand Down
2 changes: 1 addition & 1 deletion lib/Controller/DelegationController.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ public function getAllCircles(): DataResponse {

try {
$circlesManager = Server::get(CirclesManager::class);
} catch (ContainerExceptionInterface $e) {
} catch (ContainerExceptionInterface) {
return new DataResponse([]);
}

Expand Down
Loading

0 comments on commit 216e7dc

Please sign in to comment.