diff --git a/lib/AppConfig.php b/lib/AppConfig.php index c77fc032c1..18949b5345 100644 --- a/lib/AppConfig.php +++ b/lib/AppConfig.php @@ -112,7 +112,7 @@ public function getAppSettings() { $keys = $this->config->getAppKeys(self::WATERMARK_APP_NAMESPACE); foreach ($keys as $key) { - if (strpos($key, 'watermark_') === 0) { + if (str_starts_with($key, 'watermark_')) { $value = $this->getAppValueArray($key); $value = $value === 'yes' ? true : $value; $result[$key] = $value === 'no' ? false : $value; @@ -209,22 +209,18 @@ private function getFederationDomains(): array { } $federationService = \OCP\Server::get(FederationService::class); - $trustedNextcloudDomains = array_filter(array_map(function ($server) use ($federationService) { - return $federationService->isTrustedRemote($server) ? $server : null; - }, $federationService->getTrustedServers())); + $trustedNextcloudDomains = array_filter(array_map(fn ($server) => $federationService->isTrustedRemote($server) ? $server : null, $federationService->getTrustedServers())); $trustedCollaboraDomains = array_filter(array_map(function ($server) use ($federationService) { try { return $federationService->getRemoteCollaboraURL($server); - } catch (\Exception $e) { + } catch (\Exception) { // If there is no remote collabora server we can just skip that return null; } }, $trustedNextcloudDomains)); - return array_map(function ($url) { - return $this->domainOnly($url); - }, array_merge($trustedNextcloudDomains, $trustedCollaboraDomains)); + return array_map(fn ($url) => $this->domainOnly($url), array_merge($trustedNextcloudDomains, $trustedCollaboraDomains)); } private function getGSDomains(): array { diff --git a/lib/Backgroundjobs/Cleanup.php b/lib/Backgroundjobs/Cleanup.php index 71e0348ad2..b20abd3d74 100644 --- a/lib/Backgroundjobs/Cleanup.php +++ b/lib/Backgroundjobs/Cleanup.php @@ -13,15 +13,8 @@ use OCP\IDBConnection; class Cleanup extends TimedJob { - /** @var IDBConnection */ - private $db; - /** @var WopiMapper $wopiMapper */ - private $wopiMapper; - - public function __construct(ITimeFactory $time, IDBConnection $db, WopiMapper $wopiMapper) { + public function __construct(ITimeFactory $time, private IDBConnection $db, private WopiMapper $wopiMapper) { parent::__construct($time); - $this->db = $db; - $this->wopiMapper = $wopiMapper; $this->setInterval(60 * 60); } diff --git a/lib/Command/UpdateEmptyTemplates.php b/lib/Command/UpdateEmptyTemplates.php index a32a1d0552..41996375d9 100644 --- a/lib/Command/UpdateEmptyTemplates.php +++ b/lib/Command/UpdateEmptyTemplates.php @@ -13,11 +13,7 @@ use Symfony\Component\Console\Output\OutputInterface; class UpdateEmptyTemplates extends Command { - /** @var TemplateManager */ - private $templateManager; - - public function __construct(TemplateManager $templateManager) { - $this->templateManager = $templateManager; + public function __construct(private TemplateManager $templateManager) { parent::__construct(); } diff --git a/lib/Controller/AssetsController.php b/lib/Controller/AssetsController.php index d7792a6017..1d8ae346c4 100644 --- a/lib/Controller/AssetsController.php +++ b/lib/Controller/AssetsController.php @@ -22,26 +22,14 @@ use OCP\IURLGenerator; class AssetsController extends Controller { - private AssetMapper $assetMapper; - private IRootFolder $rootFolder; - private ?string $userId; - private UserScopeService $userScopeService; - private IURLGenerator $urlGenerator; - public function __construct($appName, IRequest $request, - AssetMapper $assetMapper, - IRootFolder $rootFolder, - $userId, - UserScopeService $userScopeService, - IURLGenerator $urlGenerator) { + private AssetMapper $assetMapper, + private IRootFolder $rootFolder, + private ?string $userId, + private UserScopeService $userScopeService, + private IURLGenerator $urlGenerator) { parent::__construct($appName, $request); - - $this->assetMapper = $assetMapper; - $this->rootFolder = $rootFolder; - $this->userId = $userId; - $this->userScopeService = $userScopeService; - $this->urlGenerator = $urlGenerator; } /** @@ -56,7 +44,7 @@ public function create($path) { try { $node = $userFolder->get($path); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new JSONResponse([], Http::STATUS_NOT_FOUND); } @@ -80,7 +68,7 @@ public function create($path) { public function get($token) { try { $asset = $this->assetMapper->getAssetByToken($token); - } catch (DoesNotExistException $e) { + } catch (DoesNotExistException) { return new DataResponse([], Http::STATUS_NOT_FOUND); } diff --git a/lib/Controller/DocumentAPIController.php b/lib/Controller/DocumentAPIController.php index 3aa7edab3e..b5143c6409 100644 --- a/lib/Controller/DocumentAPIController.php +++ b/lib/Controller/DocumentAPIController.php @@ -29,23 +29,8 @@ use Throwable; class DocumentAPIController extends \OCP\AppFramework\OCSController { - private $rootFolder; - private $shareManager; - private $templateManager; - private $l10n; - private $logger; - private $lockManager; - private $userId; - - public function __construct(IRequest $request, IRootFolder $rootFolder, IManager $shareManager, TemplateManager $templateManager, IL10N $l10n, LoggerInterface $logger, ILockManager $lockManager, $userId) { + public function __construct(IRequest $request, private IRootFolder $rootFolder, private IManager $shareManager, private TemplateManager $templateManager, private IL10N $l10n, private LoggerInterface $logger, private ILockManager $lockManager, private $userId) { parent::__construct(Application::APPNAME, $request); - $this->rootFolder = $rootFolder; - $this->shareManager = $shareManager; - $this->templateManager = $templateManager; - $this->l10n = $l10n; - $this->logger = $logger; - $this->lockManager = $lockManager; - $this->userId = $userId; } /** @@ -153,9 +138,9 @@ public function openLocal(int $fileId): DataResponse { Application::APPNAME )); return new DataResponse([]); - } catch (NoLockProviderException|PreConditionNotMetException $e) { + } catch (NoLockProviderException|PreConditionNotMetException) { return new DataResponse([], Http::STATUS_BAD_REQUEST); - } catch (\Exception $e) { + } catch (\Exception) { return new DataResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); } diff --git a/lib/Controller/DocumentController.php b/lib/Controller/DocumentController.php index e5759751f7..dd2bd77c9e 100644 --- a/lib/Controller/DocumentController.php +++ b/lib/Controller/DocumentController.php @@ -169,7 +169,7 @@ public function createFromTemplate(int $templateId, string $fileName, string $di $userFolder = $this->rootFolder->getUserFolder($this->userId); try { $folder = $userFolder->get($dir); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new TemplateResponse('core', '403', [], 'guest'); } @@ -286,7 +286,7 @@ public function remote(string $shareToken, string $remoteServer, string $remoteS $response->addHeader('X-Frame-Options', 'ALLOW'); return $response; } - } catch (ShareNotFound $e) { + } catch (ShareNotFound) { return new TemplateResponse('core', '404', [], 'guest'); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); diff --git a/lib/Controller/DocumentTrait.php b/lib/Controller/DocumentTrait.php index 7971478555..99520dc7a8 100644 --- a/lib/Controller/DocumentTrait.php +++ b/lib/Controller/DocumentTrait.php @@ -46,7 +46,7 @@ private function applyPolicies($response) { private function domainOnly(string $url): string { $parsed_url = parse_url($url); $scheme = isset($parsed_url['scheme']) ? $parsed_url['scheme'] . '://' : ''; - $host = isset($parsed_url['host']) ? $parsed_url['host'] : ''; + $host = $parsed_url['host'] ?? ''; $port = isset($parsed_url['port']) ? ':' . $parsed_url['port'] : ''; return "$scheme$host$port"; } diff --git a/lib/Controller/FederationController.php b/lib/Controller/FederationController.php index fc97e4bdff..646c5204da 100644 --- a/lib/Controller/FederationController.php +++ b/lib/Controller/FederationController.php @@ -19,36 +19,16 @@ use Psr\Log\LoggerInterface; class FederationController extends OCSController { - /** @var IConfig */ - private $config; - - /** @var LoggerInterface */ - private $logger; - - /** @var WopiMapper */ - private $wopiMapper; - - /** @var IUserManager */ - private $userManager; - - /** @var IURLGenerator */ - private $urlGenerator; - public function __construct( string $appName, IRequest $request, - IConfig $config, - LoggerInterface $logger, - WopiMapper $wopiMapper, - IUserManager $userManager, - IURLGenerator $urlGenerator + private IConfig $config, + private LoggerInterface $logger, + private WopiMapper $wopiMapper, + private IUserManager $userManager, + private IURLGenerator $urlGenerator ) { parent::__construct($appName, $request); - $this->config = $config; - $this->logger = $logger; - $this->wopiMapper = $wopiMapper; - $this->userManager = $userManager; - $this->urlGenerator = $urlGenerator; } /** @@ -97,10 +77,10 @@ public function remoteWopiToken($token): DataResponse { } $this->logger->debug('COOL-Federation-Initiator: Token ' . $token . ' returned'); return new DataResponse($initiatorWopi); - } catch (UnknownTokenException $e) { + } catch (UnknownTokenException) { $this->logger->debug('COOL-Federation-Initiator: Token ' . $token . 'not found'); throw new OCSNotFoundException(); - } catch (ExpiredTokenException $e) { + } catch (ExpiredTokenException) { $this->logger->debug('COOL-Federation-Initiator: Token ' . $token . ' is expired'); throw new OCSNotFoundException(); } @@ -132,10 +112,10 @@ public function initiatorUser($token): DataResponse { 'displayName' => $user->getDisplayName(), 'avatar' => $this->urlGenerator->linkToRouteAbsolute('core.avatar.getAvatar', ['userId' => $wopi->getEditorUid(), 'size' => WopiController::WOPI_AVATAR_SIZE]) ]); - } catch (UnknownTokenException $e) { + } catch (UnknownTokenException) { $this->logger->debug('COOL-Federation-Initiator-User: Token ' . $token . 'not found'); throw new OCSNotFoundException(); - } catch (ExpiredTokenException $e) { + } catch (ExpiredTokenException) { $this->logger->debug('COOL-Federation-Initiator-User: Token ' . $token . ' is expired.'); throw new OCSNotFoundException(); } diff --git a/lib/Controller/OCSController.php b/lib/Controller/OCSController.php index b9d15d6008..6329f87a59 100644 --- a/lib/Controller/OCSController.php +++ b/lib/Controller/OCSController.php @@ -30,56 +30,22 @@ use Psr\Log\LoggerInterface; class OCSController extends \OCP\AppFramework\OCSController { - /** @var IRootFolder */ - private $rootFolder; - - /** @var string */ - private $userId; - - /** @var DirectMapper */ - private $directMapper; - - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var TemplateManager */ - private $manager; - - /** @var TokenManager */ - private $tokenManager; - - /** @var IManager */ - private $shareManager; - - /** @var FederationService */ - private $federationService; - - /** @var LoggerInterface */ - private $logger; - + /** + * @param string $userId + */ public function __construct(string $appName, IRequest $request, - IRootFolder $rootFolder, - $userId, - DirectMapper $directMapper, - IURLGenerator $urlGenerator, - TemplateManager $manager, - TokenManager $tokenManager, - IManager $shareManager, - FederationService $federationService, - LoggerInterface $logger + private IRootFolder $rootFolder, + private $userId, + private DirectMapper $directMapper, + private IURLGenerator $urlGenerator, + private TemplateManager $manager, + private TokenManager $tokenManager, + private IManager $shareManager, + private FederationService $federationService, + private LoggerInterface $logger ) { parent::__construct($appName, $request); - - $this->rootFolder = $rootFolder; - $this->userId = $userId; - $this->directMapper = $directMapper; - $this->urlGenerator = $urlGenerator; - $this->manager = $manager; - $this->tokenManager = $tokenManager; - $this->shareManager = $shareManager; - $this->federationService = $federationService; - $this->logger = $logger; } /** @@ -111,7 +77,7 @@ public function createDirect($fileId) { 'token' => $direct->getToken() ]) ]); - } catch (NotFoundException $e) { + } catch (NotFoundException) { throw new OCSNotFoundException(); } } @@ -174,7 +140,7 @@ public function createPublic( try { $share = $this->shareManager->getShareByToken($shareToken); - } catch (ShareNotFound $ex) { + } catch (ShareNotFound) { $response = new DataResponse([], HTTP::STATUS_NOT_FOUND); $response->throttle(); return $response; @@ -220,7 +186,7 @@ public function createPublicFromInitiator( ): DataResponse { try { $share = $this->shareManager->getShareByToken($shareToken); - } catch (ShareNotFound $ex) { + } catch (ShareNotFound) { $response = new DataResponse([], HTTP::STATUS_NOT_FOUND); $response->throttle(); return $response; @@ -261,11 +227,11 @@ public function updateGuestName(string $access_token, string $guestName): DataRe try { $this->tokenManager->updateGuestName($access_token, $guestName); return new DataResponse([], Http::STATUS_OK); - } catch (UnknownTokenException $e) { + } catch (UnknownTokenException) { $response = new DataResponse([], Http::STATUS_FORBIDDEN); $response->throttle(); return $response; - } catch (ExpiredTokenException $e) { + } catch (ExpiredTokenException) { $response = new DataResponse([], Http::STATUS_UNAUTHORIZED); $response->throttle(); return $response; @@ -318,7 +284,7 @@ public function createFromTemplate($path, $template) { 'token' => $direct->getToken() ]) ]); - } catch (NotFoundException $e) { + } catch (NotFoundException) { throw new OCSNotFoundException(); } catch (\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); diff --git a/lib/Controller/SettingsController.php b/lib/Controller/SettingsController.php index d2eebe3a57..2c40b60131 100644 --- a/lib/Controller/SettingsController.php +++ b/lib/Controller/SettingsController.php @@ -242,7 +242,7 @@ public function setPersonalSettings($templateFolder, if ($templateFolder !== null) { try { $this->config->setUserValue($this->userId, 'richdocuments', 'templateFolder', $templateFolder); - } catch (PreConditionNotMetException $e) { + } catch (PreConditionNotMetException) { $message = $this->l10n->t('Error when saving'); $status = 'error'; } @@ -250,7 +250,7 @@ public function setPersonalSettings($templateFolder, if ($zoteroAPIKeyInput !== null) { try { $this->config->setUserValue($this->userId, 'richdocuments', 'zoteroAPIKey', $zoteroAPIKeyInput); - } catch (PreConditionNotMetException $e) { + } catch (PreConditionNotMetException) { $message = $this->l10n->t('Error when saving'); $status = 'error'; } @@ -295,9 +295,7 @@ public function getFontNames() { public function getJsonFontList() { $files = $this->fontService->getFontFiles(); $etags = array_map( - static function (ISimpleFile $f) { - return $f->getETag(); - }, + static fn (ISimpleFile $f) => $f->getETag(), $files ); $etag = md5(implode(',', $etags)); @@ -335,7 +333,7 @@ public function getFontFile(string $name) { Http::STATUS_OK, ['Content-Type' => $fontFile->getMimeType(), 'Etag' => $etag] ); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new DataDisplayResponse('', Http::STATUS_NOT_FOUND); } } @@ -357,7 +355,7 @@ public function getFontFileOverview(string $name): DataDisplayResponse { Http::STATUS_OK, ['Content-Type' => 'image/png'] ); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new DataDisplayResponse('', Http::STATUS_NOT_FOUND); } } diff --git a/lib/Controller/TargetController.php b/lib/Controller/TargetController.php index 72e067d4d4..281ab1552d 100644 --- a/lib/Controller/TargetController.php +++ b/lib/Controller/TargetController.php @@ -36,7 +36,7 @@ public function getTargets(string $path): DataResponse { try { $file = $this->getFile($path); return new DataResponse($this->fileTargetService->getFileTargets($file)); - } catch (NotFoundException $e) { + } catch (NotFoundException) { } return new DataResponse('File not found', Http::STATUS_NOT_FOUND); @@ -54,7 +54,7 @@ public function getPreview(string $path, string $target): Response { Http::STATUS_OK, ['Content-Type' => 'image/png'] ); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new DataResponse('File not found', Http::STATUS_NOT_FOUND); } } @@ -71,7 +71,7 @@ private function getFile(string $path): File { } return $file; - } catch (NotFoundException|NotPermittedException|NoUserException $e) { + } catch (NotFoundException|NotPermittedException|NoUserException) { throw new NotFoundException(); } } diff --git a/lib/Controller/TemplateFieldController.php b/lib/Controller/TemplateFieldController.php index 0f604b82b8..69945d3153 100644 --- a/lib/Controller/TemplateFieldController.php +++ b/lib/Controller/TemplateFieldController.php @@ -33,7 +33,7 @@ public function extractFields(int $fileId): DataResponse { $fields = $this->templateFieldService->extractFields($fileId); return new DataResponse($fields, Http::STATUS_OK); - } catch (\Exception $e) { + } catch (\Exception) { return new DataResponse(['Unable to extract fields from given file'], Http::STATUS_INTERNAL_SERVER_ERROR); } } @@ -54,7 +54,7 @@ public function fillFields(int $fileId, array $fields = [], ?string $destination } return new DataResponse([], Http::STATUS_OK); - } catch (\Exception $e) { + } catch (\Exception) { return new DataResponse(['Unable to fill fields into the given file'], Http::STATUS_INTERNAL_SERVER_ERROR); } } diff --git a/lib/Controller/TemplatesController.php b/lib/Controller/TemplatesController.php index e05343e84a..78415e0a3f 100644 --- a/lib/Controller/TemplatesController.php +++ b/lib/Controller/TemplatesController.php @@ -26,12 +26,6 @@ use Psr\Log\LoggerInterface; class TemplatesController extends Controller { - private IL10N $l10n; - private TemplateManager $manager; - private IPreview $preview; - private IMimeTypeDetector $mimeTypeDetector; - private LoggerInterface $logger; - /** @var int Max template size */ private $maxSize = 20 * 1024 * 1024; @@ -46,21 +40,16 @@ class TemplatesController extends Controller { */ public function __construct($appName, IRequest $request, - IL10N $l10n, - TemplateManager $manager, - IPreview $preview, - IMimeTypeDetector $mimeTypeDetector, - LoggerInterface $logger + private IL10N $l10n, + private TemplateManager $manager, + private IPreview $preview, + private IMimeTypeDetector $mimeTypeDetector, + private LoggerInterface $logger ) { parent::__construct($appName, $request); $this->appName = $appName; $this->request = $request; - $this->l10n = $l10n; - $this->manager = $manager; - $this->preview = $preview; - $this->mimeTypeDetector = $mimeTypeDetector; - $this->logger = $logger; } /** @@ -91,7 +80,7 @@ public function getPreview($fileId, try { $template = $this->manager->get($fileId); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new DataResponse([], Http::STATUS_NOT_FOUND); } @@ -171,7 +160,7 @@ public function delete($fileId) { ['data' => ['status' => 'success']], Http::STATUS_NO_CONTENT ); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new JSONResponse( ['data' => ['message' => $this->l10n->t('Template not found')]], Http::STATUS_NOT_FOUND @@ -208,9 +197,9 @@ private function fetchPreview( $response->cacheFor(3600 * 24); return $response; - } catch (NotFoundException $e) { + } catch (NotFoundException) { return new DataResponse([], Http::STATUS_NOT_FOUND); - } catch (\InvalidArgumentException $e) { + } catch (\InvalidArgumentException) { return new DataResponse([], Http::STATUS_BAD_REQUEST); } } diff --git a/lib/Controller/WopiController.php b/lib/Controller/WopiController.php index a075a2bc83..f7441a96b2 100644 --- a/lib/Controller/WopiController.php +++ b/lib/Controller/WopiController.php @@ -109,10 +109,7 @@ public function checkFileInfo($fileId, $access_token) { if (!($file instanceof File)) { throw new NotFoundException('No valid file found for ' . $fileId); } - } catch (NotFoundException $e) { - $this->logger->debug($e->getMessage(), ['exception' => $e]); - return new JSONResponse([], Http::STATUS_FORBIDDEN); - } catch (UnknownTokenException $e) { + } catch (NotFoundException|UnknownTokenException $e) { $this->logger->debug($e->getMessage(), ['exception' => $e]); return new JSONResponse([], Http::STATUS_FORBIDDEN); } catch (ExpiredTokenException $e) { @@ -188,9 +185,7 @@ public function checkFileInfo($fileId, $access_token) { 'email' => $email, ]; $watermarkTemplate = $this->appConfig->getAppValue('watermark_text'); - $response['WatermarkText'] = preg_replace_callback('/{(.+?)}/', function ($matches) use ($replacements) { - return $replacements[$matches[1]]; - }, $watermarkTemplate); + $response['WatermarkText'] = preg_replace_callback('/{(.+?)}/', fn ($matches) => $replacements[$matches[1]], $watermarkTemplate); } $user = $this->userManager->get($wopi->getEditorUid()); @@ -463,9 +458,7 @@ public function putFile($fileId, if ($freespace >= 0 && $contentLength > $freespace) { throw new \Exception('Not enough storage'); } - $this->wrappedFilesystemOperation($wopi, function () use ($file, $content) { - return $file->putContent($content); - }); + $this->wrappedFilesystemOperation($wopi, fn () => $file->putContent($content)); } catch (LockedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); return new JSONResponse(['message' => 'File locked'], Http::STATUS_INTERNAL_SERVER_ERROR); @@ -566,9 +559,9 @@ public function postFile(string $fileId, string $access_token): JSONResponse { $suggested = mb_convert_encoding($suggested, 'utf-8', 'utf-7') . '.' . $file->getExtension(); - if (strpos($suggested, '.') === 0) { + if (str_starts_with($suggested, '.')) { $path = dirname($file->getPath()) . '/New File' . $suggested; - } elseif (strpos($suggested, '/') !== 0) { + } elseif (!str_starts_with($suggested, '/')) { $path = dirname($file->getPath()) . '/' . $suggested; } else { $path = $userFolder->getPath() . $suggested; @@ -592,7 +585,7 @@ public function postFile(string $fileId, string $access_token): JSONResponse { $this->getFileForWopiToken($wopi), ILock::TYPE_APP, Application::APPNAME - ), function () use (&$file, $path) { + ), function () use (&$file, $path): void { $file = $file->move($path); }); } else { @@ -632,10 +625,8 @@ public function postFile(string $fileId, string $access_token): JSONResponse { $this->userScopeService->setFilesystemScope($wopi->getEditorUid()); try { - $this->wrappedFilesystemOperation($wopi, function () use ($file, $content) { - return $file->putContent($content); - }); - } catch (LockedException $e) { + $this->wrappedFilesystemOperation($wopi, fn () => $file->putContent($content)); + } catch (LockedException) { return new JSONResponse(['message' => 'File locked'], Http::STATUS_INTERNAL_SERVER_ERROR); } @@ -666,7 +657,7 @@ private function lock(Wopi $wopi, string $lock): JSONResponse { Application::APPNAME )); return new JSONResponse(); - } catch (NoLockProviderException|PreConditionNotMetException $e) { + } catch (NoLockProviderException|PreConditionNotMetException) { return new JSONResponse([], Http::STATUS_BAD_REQUEST); } catch (OwnerLockedException $e) { // If a file is manually locked by a user we want to all this user to still perform a WOPI lock and write @@ -675,7 +666,7 @@ private function lock(Wopi $wopi, string $lock): JSONResponse { } return new JSONResponse([], Http::STATUS_LOCKED); - } catch (\Exception $e) { + } catch (\Exception) { return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); } } @@ -688,14 +679,14 @@ private function unlock(Wopi $wopi, string $lock): JSONResponse { Application::APPNAME )); return new JSONResponse(); - } catch (NoLockProviderException|PreConditionNotMetException $e) { + } catch (NoLockProviderException|PreConditionNotMetException) { $locks = $this->lockManager->getLocks($wopi->getFileid()); $canWriteThroughLock = count($locks) > 0 && $locks[0]->getType() === ILock::TYPE_USER && $locks[0]->getOwner() !== $wopi->getEditorUid() ? false : true; if ($canWriteThroughLock) { return new JSONResponse(); } return new JSONResponse([], Http::STATUS_BAD_REQUEST); - } catch (\Exception $e) { + } catch (\Exception) { return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); } } @@ -708,11 +699,11 @@ private function refreshLock(Wopi $wopi, string $lock): JSONResponse { Application::APPNAME )); return new JSONResponse(); - } catch (NoLockProviderException|PreConditionNotMetException $e) { + } catch (NoLockProviderException|PreConditionNotMetException) { return new JSONResponse([], Http::STATUS_BAD_REQUEST); - } catch (OwnerLockedException $e) { + } catch (OwnerLockedException) { return new JSONResponse([], Http::STATUS_LOCKED); - } catch (\Exception $e) { + } catch (\Exception) { return new JSONResponse([], Http::STATUS_INTERNAL_SERVER_ERROR); } } @@ -729,7 +720,7 @@ private function getLock(Wopi $wopi, string $lock): JSONResponse { * @throws ShareNotFound */ protected function wrappedFilesystemOperation(Wopi $wopi, callable $filesystemOperation): void { - $retryOperation = function () use ($filesystemOperation) { + $retryOperation = function () use ($filesystemOperation): void { $this->retryOperation($filesystemOperation); }; try { @@ -738,7 +729,7 @@ protected function wrappedFilesystemOperation(Wopi $wopi, callable $filesystemOp ILock::TYPE_APP, Application::APPNAME ), $retryOperation); - } catch (NoLockProviderException $e) { + } catch (NoLockProviderException) { $retryOperation(); } } @@ -798,9 +789,7 @@ private function getFileForWopiToken(Wopi $wopi) { // Workaround to always open files with edit permissions if multiple occurrences of // the same file id are in the user home, ideally we should also track the path of the file when opening - usort($files, function (Node $a, Node $b) { - return ($b->getPermissions() & Constants::PERMISSION_UPDATE) <=> ($a->getPermissions() & Constants::PERMISSION_UPDATE); - }); + usort($files, fn (Node $a, Node $b) => ($b->getPermissions() & Constants::PERMISSION_UPDATE) <=> ($a->getPermissions() & Constants::PERMISSION_UPDATE)); return array_shift($files); } @@ -808,7 +797,7 @@ private function getFileForWopiToken(Wopi $wopi) { private function getShareForWopiToken(Wopi $wopi): ?IShare { try { return $wopi->getShare() ? $this->shareManager->getShareByToken($wopi->getShare()) : null; - } catch (ShareNotFound $e) { + } catch (ShareNotFound) { } return null; @@ -857,7 +846,7 @@ private function isMasterKeyEnabled(): bool { try { $util = \OC::$server->query(\OCA\Encryption\Util::class); return $util->isMasterKeyEnabled(); - } catch (QueryException $e) { + } catch (QueryException) { // No encryption module enabled return false; } diff --git a/lib/Db/AssetMapper.php b/lib/Db/AssetMapper.php index 928c3b0470..147bb8a73b 100644 --- a/lib/Db/AssetMapper.php +++ b/lib/Db/AssetMapper.php @@ -17,14 +17,8 @@ class AssetMapper extends QBMapper { /** @var int Lifetime of a token is 10 minutes */ public const TOKEN_TTL = 600; - private ISecureRandom $random; - private ITimeFactory $time; - - public function __construct(IDBConnection $db, ISecureRandom $random, ITimeFactory $timeFactory) { + public function __construct(IDBConnection $db, private ISecureRandom $random, private ITimeFactory $time) { parent::__construct($db, 'richdocuments_assets', Asset::class); - - $this->random = $random; - $this->time = $timeFactory; } /** @@ -61,7 +55,7 @@ public function getAssetByToken(string $token): Asset { } return $asset; - } catch (\Exception $e) { + } catch (\Exception) { } throw new DoesNotExistException('No asset for token found'); diff --git a/lib/Db/DirectMapper.php b/lib/Db/DirectMapper.php index c3347fe7a0..471c9724d3 100644 --- a/lib/Db/DirectMapper.php +++ b/lib/Db/DirectMapper.php @@ -17,16 +17,10 @@ class DirectMapper extends QBMapper { /** @var int Lifetime of a token is 10 minutes */ public const TOKEN_TTL = 600; - protected ISecureRandom $random; - protected ITimeFactory $timeFactory; - public function __construct(IDBConnection $db, - ISecureRandom $random, - ITimeFactory $timeFactory) { + protected ISecureRandom $random, + protected ITimeFactory $timeFactory) { parent::__construct($db, 'richdocuments_direct', Direct::class); - - $this->random = $random; - $this->timeFactory = $timeFactory; } /** @@ -66,7 +60,7 @@ public function getByToken(string $token): Direct { } return $direct; - } catch (\Exception $e) { + } catch (\Exception) { } throw new DoesNotExistException('No asset for token found'); diff --git a/lib/Db/Wopi.php b/lib/Db/Wopi.php index d97ea1b78e..14d12f3071 100644 --- a/lib/Db/Wopi.php +++ b/lib/Db/Wopi.php @@ -168,7 +168,7 @@ public function jsonSerialize() { $reflection = new \ReflectionClass($this); $json = []; foreach ($properties as $property => $value) { - if (strpos($property, '_') !== 0 && $reflection->hasProperty($property)) { + if (!str_starts_with($property, '_') && $reflection->hasProperty($property)) { $propertyReflection = $reflection->getProperty($property); if (!$propertyReflection->isPrivate()) { $json[$property] = $this->getter($property); diff --git a/lib/Db/WopiMapper.php b/lib/Db/WopiMapper.php index de1f640c58..89bf3d1d41 100644 --- a/lib/Db/WopiMapper.php +++ b/lib/Db/WopiMapper.php @@ -17,29 +17,12 @@ /** @template-extends QBMapper */ class WopiMapper extends QBMapper { - /** @var ISecureRandom */ - private $random; - - /** @var LoggerInterface */ - private $logger; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var AppConfig */ - private $appConfig; - public function __construct(IDBConnection $db, - ISecureRandom $random, - LoggerInterface $logger, - ITimeFactory $timeFactory, - AppConfig $appConfig) { + private ISecureRandom $random, + private LoggerInterface $logger, + private ITimeFactory $timeFactory, + private AppConfig $appConfig) { parent::__construct($db, 'richdocuments_wopi', Wopi::class); - - $this->random = $random; - $this->logger = $logger; - $this->timeFactory = $timeFactory; - $this->appConfig = $appConfig; } /** diff --git a/lib/Events/BeforeFederationRedirectEvent.php b/lib/Events/BeforeFederationRedirectEvent.php index c40e6c3373..11a548b8a3 100644 --- a/lib/Events/BeforeFederationRedirectEvent.php +++ b/lib/Events/BeforeFederationRedirectEvent.php @@ -9,20 +9,16 @@ use OCP\Files\Node; class BeforeFederationRedirectEvent extends Event { - /** @var Node */ - private $node; - /** @var string */ - private $relativePath; /** @var string|null */ private $redirectUrl = null; - /** @var string */ - private $remote; - public function __construct($node, $relativePath, $remote) { + /** + * @param Node $node + * @param string $relativePath + * @param string $remote + */ + public function __construct(private $node, private $relativePath, private $remote) { parent::__construct(); - $this->node = $node; - $this->relativePath = $relativePath; - $this->remote = $remote; } public function getRelativePath() { diff --git a/lib/Events/DocumentOpenedEvent.php b/lib/Events/DocumentOpenedEvent.php index 554cc0c0bc..df72b99c7a 100644 --- a/lib/Events/DocumentOpenedEvent.php +++ b/lib/Events/DocumentOpenedEvent.php @@ -11,12 +11,7 @@ use OCP\Files\Node; class DocumentOpenedEvent extends \OCP\EventDispatcher\Event { - private ?string $userId; - private Node $node; - - public function __construct(?string $userId, Node $node) { - $this->userId = $userId; - $this->node = $node; + public function __construct(private ?string $userId, private Node $node) { } public function getUserId(): ?string { diff --git a/lib/Helper.php b/lib/Helper.php index 50ba5dc5b1..45fd144784 100644 --- a/lib/Helper.php +++ b/lib/Helper.php @@ -10,11 +10,10 @@ use OCP\Files\Folder; class Helper { - /** @var string|null */ - private $userId; - - public function __construct($userId) { - $this->userId = $userId; + /** + * @param string|null $userId + */ + public function __construct(private $userId) { } /** @@ -38,7 +37,7 @@ public static function parseFileId(string $fileId) { throw new \Exception('$fileId has not the expected format'); } - if (strpos($fileId, '-') !== false) { + if (str_contains($fileId, '-')) { [$fileId, $templateId] = explode('/', $fileId); } diff --git a/lib/Listener/BeforeFetchPreviewListener.php b/lib/Listener/BeforeFetchPreviewListener.php index 0adf48053c..ac63e89e15 100644 --- a/lib/Listener/BeforeFetchPreviewListener.php +++ b/lib/Listener/BeforeFetchPreviewListener.php @@ -24,16 +24,7 @@ /** @template-implements IEventListener */ class BeforeFetchPreviewListener implements IEventListener { - private PermissionManager $permissionManager; - private IUserSession $userSession; - private IRequest $request; - private IManager $shareManager; - - public function __construct(PermissionManager $permissionManager, IUserSession $userSession, IRequest $request, IManager $shareManager) { - $this->permissionManager = $permissionManager; - $this->userSession = $userSession; - $this->request = $request; - $this->shareManager = $shareManager; + public function __construct(private PermissionManager $permissionManager, private IUserSession $userSession, private IRequest $request, private IManager $shareManager) { } public function handle(Event $event): void { @@ -56,7 +47,7 @@ public function handle(Event $event): void { // Get different share for public previews as the share from the node is only set for mounted shares try { $share = $shareToken ? $this->shareManager->getShareByToken($shareToken) : $share; - } catch (ShareNotFound $e) { + } catch (ShareNotFound) { } $userId = $this->userSession->getUser() ? $this->userSession->getUser()->getUID() : null; diff --git a/lib/Listener/BeforeTemplateRenderedListener.php b/lib/Listener/BeforeTemplateRenderedListener.php index 7b4ff3a050..c00bb9ad5f 100644 --- a/lib/Listener/BeforeTemplateRenderedListener.php +++ b/lib/Listener/BeforeTemplateRenderedListener.php @@ -14,10 +14,7 @@ /** @template-implements IEventListener */ class BeforeTemplateRenderedListener implements IEventListener { - private CapabilitiesService $capabilitiesService; - - public function __construct(CapabilitiesService $capabilitiesService) { - $this->capabilitiesService = $capabilitiesService; + public function __construct(private CapabilitiesService $capabilitiesService) { } public function handle(Event $event): void { diff --git a/lib/Listener/LoadViewerListener.php b/lib/Listener/LoadViewerListener.php index ae79dd8a05..2d9de9335e 100644 --- a/lib/Listener/LoadViewerListener.php +++ b/lib/Listener/LoadViewerListener.php @@ -20,17 +20,7 @@ /** @template-implements IEventListener */ class LoadViewerListener implements IEventListener { - /** @var PermissionManager */ - private $permissionManager; - /** @var InitialStateService */ - private $initialStateService; - - private ?string $userId = null; - - public function __construct(PermissionManager $permissionManager, InitialStateService $initialStateService, ?string $userId) { - $this->permissionManager = $permissionManager; - $this->initialStateService = $initialStateService; - $this->userId = $userId; + public function __construct(private PermissionManager $permissionManager, private InitialStateService $initialStateService, private ?string $userId) { } public function handle(Event $event): void { diff --git a/lib/Listener/ShareLinkListener.php b/lib/Listener/ShareLinkListener.php index 4b8b9c23fc..7fb71a1020 100644 --- a/lib/Listener/ShareLinkListener.php +++ b/lib/Listener/ShareLinkListener.php @@ -21,14 +21,7 @@ /** @template-implements IEventListener */ class ShareLinkListener implements \OCP\EventDispatcher\IEventListener { - /** @var PermissionManager */ - private $permissionManager; - /** @var InitialStateService */ - private $initialStateService; - - public function __construct(PermissionManager $permissionManager, InitialStateService $initialStateService) { - $this->permissionManager = $permissionManager; - $this->initialStateService = $initialStateService; + public function __construct(private PermissionManager $permissionManager, private InitialStateService $initialStateService) { } public function handle(Event $event): void { diff --git a/lib/PermissionManager.php b/lib/PermissionManager.php index 3beb9baa85..a1fe764eed 100644 --- a/lib/PermissionManager.php +++ b/lib/PermissionManager.php @@ -19,27 +19,14 @@ use OCP\SystemTag\ISystemTagObjectMapper; class PermissionManager { - private AppConfig $appConfig; - private IConfig $config; - private IGroupManager $groupManager; - private IUserManager $userManager; - private IUserSession $userSession; - private ISystemTagObjectMapper $systemTagObjectMapper; - public function __construct( - AppConfig $appConfig, - IConfig $config, - IGroupManager $groupManager, - IUserManager $userManager, - IUserSession $userSession, - ISystemTagObjectMapper $systemTagObjectMapper + private AppConfig $appConfig, + private IConfig $config, + private IGroupManager $groupManager, + private IUserManager $userManager, + private IUserSession $userSession, + private ISystemTagObjectMapper $systemTagObjectMapper ) { - $this->appConfig = $appConfig; - $this->config = $config; - $this->groupManager = $groupManager; - $this->userManager = $userManager; - $this->userSession = $userSession; - $this->systemTagObjectMapper = $systemTagObjectMapper; } private function userMatchesGroupList(?string $userId = null, ?array $groupList = []): bool { diff --git a/lib/Service/CachedRequestService.php b/lib/Service/CachedRequestService.php index 9c71247ac9..14610241d1 100644 --- a/lib/Service/CachedRequestService.php +++ b/lib/Service/CachedRequestService.php @@ -107,7 +107,7 @@ private function getAppDataFolder(): ISimpleFolder { $appData = $this->appDataFactory->get(Application::APPNAME); try { $folder = $appData->getFolder('remoteData'); - } catch (NotFoundException $e) { + } catch (NotFoundException) { $folder = $appData->newFolder('remoteData'); } return $folder; @@ -147,7 +147,7 @@ private function isProxyStarting(): bool { return true; } } - } catch (\Exception $e) { + } catch (\Exception) { // ignore } } diff --git a/lib/Service/DemoService.php b/lib/Service/DemoService.php index bf6511f17c..5606956fc8 100644 --- a/lib/Service/DemoService.php +++ b/lib/Service/DemoService.php @@ -10,18 +10,7 @@ use OCP\ICache; class DemoService { - /** - * @var ICache - */ - private $cache; - /** - * @var IClientService - */ - private $clientService; - - public function __construct(ICache $cache, IClientService $clientService) { - $this->cache = $cache; - $this->clientService = $clientService; + public function __construct(private ICache $cache, private IClientService $clientService) { } public function fetchDemoServers($refresh = false) { @@ -34,7 +23,7 @@ public function fetchDemoServers($refresh = false) { try { $response = $client->get($demoServerList); $servers = json_decode($response->getBody(), true)['servers'] ?? []; - } catch (\Exception $e) { + } catch (\Exception) { $servers = []; } $this->cache->set('richdocuments-demo', json_encode($servers)); diff --git a/lib/Service/FederationService.php b/lib/Service/FederationService.php index 617d64dec3..bc7af4c2a3 100644 --- a/lib/Service/FederationService.php +++ b/lib/Service/FederationService.php @@ -32,34 +32,14 @@ class FederationService { /** @var ICache */ private $cache; - /** @var IClientService */ - private $clientService; - /** @var LoggerInterface */ - private $logger; /** @var TrustedServers */ private $trustedServers; - /** @var AppConfig */ - private $appConfig; - /** @var TokenManager */ - private $tokenManager; - /** @var IRequest */ - private $request; - /** @var IURLGenerator */ - private $urlGenerator; - - public function __construct(ICacheFactory $cacheFactory, IClientService $clientService, LoggerInterface $logger, TokenManager $tokenManager, AppConfig $appConfig, IRequest $request, IURLGenerator $urlGenerator) { + + public function __construct(ICacheFactory $cacheFactory, private IClientService $clientService, private LoggerInterface $logger, private TokenManager $tokenManager, private AppConfig $appConfig, private IRequest $request, private IURLGenerator $urlGenerator) { $this->cache = $cacheFactory->createDistributed('richdocuments_remote/'); - $this->clientService = $clientService; - $this->logger = $logger; - $this->tokenManager = $tokenManager; - $this->appConfig = $appConfig; - $this->request = $request; - $this->urlGenerator = $urlGenerator; try { $this->trustedServers = \OC::$server->get(\OCA\Federation\TrustedServers::class); - } catch (NotFoundExceptionInterface $e) { - } catch (ContainerExceptionInterface $e) { - } catch (AutoloadNotAllowedException $e) { + } catch (NotFoundExceptionInterface|ContainerExceptionInterface|AutoloadNotAllowedException) { } } @@ -68,9 +48,7 @@ public function getTrustedServers(): array { return []; } - return array_map(function (array $server) { - return $server['url']; - }, $this->trustedServers->getServers()); + return array_map(fn (array $server) => $server['url'], $this->trustedServers->getServers()); } /** @@ -80,7 +58,7 @@ public function getTrustedServers(): array { */ public function getRemoteCollaboraURL($remote) { // If no protocol is provided we default to https - if (strpos($remote, 'http://') !== 0 && strpos($remote, 'https://') !== 0) { + if (!str_starts_with($remote, 'http://') && !str_starts_with($remote, 'https://')) { $remote = 'https://' . $remote; } @@ -106,7 +84,7 @@ public function getRemoteCollaboraURL($remote) { } public function isTrustedRemote($domainWithPort) { - if (strpos($domainWithPort, 'http://') === 0 || strpos($domainWithPort, 'https://') === 0) { + if (str_starts_with($domainWithPort, 'http://') || str_starts_with($domainWithPort, 'https://')) { $port = parse_url($domainWithPort, PHP_URL_PORT); $domainWithPort = parse_url($domainWithPort, PHP_URL_HOST) . ($port ? ':' . $port : ''); } @@ -126,9 +104,7 @@ public function isTrustedRemote($domainWithPort) { if (!is_string($trusted)) { break; } - $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(function ($v) { - return preg_quote($v, '/'); - }, explode('*', $trusted))) . '$/i'; + $regex = '/^' . implode('[-\.a-zA-Z0-9]*', array_map(fn ($v) => preg_quote($v, '/'), explode('*', $trusted))) . '$/i'; if (preg_match($regex, $domain) || preg_match($regex, $domainWithPort)) { return true; } diff --git a/lib/Service/FontService.php b/lib/Service/FontService.php index 5122235adf..28e554b6c2 100644 --- a/lib/Service/FontService.php +++ b/lib/Service/FontService.php @@ -18,32 +18,16 @@ class FontService { private const INVALIDATE_FONT_LIST_CACHE_AFTER_SECONDS = 3600; - - /** - * @var IAppData - */ - private $appData; /** * @var \OCP\ICache */ private $cache; - /** - * @var IURLGenerator - */ - private $url; - /** - * @var IConfig - */ - private $config; - public function __construct(IAppData $appData, + public function __construct(private IAppData $appData, ICacheFactory $cacheFactory, - IURLGenerator $url, - IConfig $config) { - $this->appData = $appData; + private IURLGenerator $url, + private IConfig $config) { $this->cache = $cacheFactory->createDistributed(Application::APPNAME); - $this->url = $url; - $this->config = $config; } /** @@ -53,7 +37,7 @@ public function __construct(IAppData $appData, private function getFontAppDataDir(): ISimpleFolder { try { return $this->appData->getFolder('fonts'); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return $this->appData->newFolder('fonts'); } } @@ -65,7 +49,7 @@ private function getFontAppDataDir(): ISimpleFolder { private function getFontOverviewAppDataDir(): ISimpleFolder { try { return $this->appData->getFolder('font-overviews'); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return $this->appData->newFolder('font-overviews'); } } @@ -93,9 +77,7 @@ public function getFontFileNames(): array { if ($cachedNames === null) { $files = $this->getFontFiles(); $cachedNames = array_map( - static function (ISimpleFile $f) { - return $f->getName(); - }, + static fn (ISimpleFile $f) => $f->getName(), $files ); $this->cache->set($cacheKey, $cachedNames, self::INVALIDATE_FONT_LIST_CACHE_AFTER_SECONDS); @@ -113,12 +95,10 @@ static function (ISimpleFile $f) { public function getFontList(array $fontFiles): array { $url = $this->url; $list = array_map( - static function (ISimpleFile $f) use ($url) { - return [ - 'uri' => $url->linkToRouteAbsolute(Application::APPNAME . '.settings.getFontFile', ['name' => $f->getName()]), - 'stamp' => $f->getETag(), - ]; - }, + static fn (ISimpleFile $f) => [ + 'uri' => $url->linkToRouteAbsolute(Application::APPNAME . '.settings.getFontFile', ['name' => $f->getName()]), + 'stamp' => $f->getETag(), + ], $fontFiles ); @@ -220,7 +200,7 @@ private function generateFontOverview(ISimpleFile $fontFile): void { imagepng($im, $imageFileResource); imagedestroy($im); } - } catch (\Exception|\Throwable $e) { + } catch (\Exception|\Throwable) { // do nothing if there was any kind of error during overview generation // the /apps/richdocuments/settings/fonts/FILE_NAME/overview request will fail with 404 // in the UI and display a fallback message diff --git a/lib/Settings/Personal.php b/lib/Settings/Personal.php index 03c544597c..ed98e36ece 100644 --- a/lib/Settings/Personal.php +++ b/lib/Settings/Personal.php @@ -13,23 +13,12 @@ use OCP\Settings\ISettings; class Personal implements ISettings { - /** @var IConfig Config */ - private $config; - - /** @var CapabilitiesService */ - private $capabilitiesService; - - /** @var InitialStateService */ - private $initialState; - - /** @var string */ - private $userId; - - public function __construct(IConfig $config, CapabilitiesService $capabilitiesService, InitialStateService $initialStateService, $userId) { - $this->config = $config; - $this->capabilitiesService = $capabilitiesService; - $this->initialState = $initialStateService; - $this->userId = $userId; + public function __construct( + private IConfig $config, + private CapabilitiesService $capabilitiesService, + private InitialStateService $initialState, + private ?string $userId + ) { } /** @psalm-suppress InvalidNullableReturnType */ diff --git a/lib/Settings/Section.php b/lib/Settings/Section.php index d48a7b2e5d..e59f3c9eb5 100644 --- a/lib/Settings/Section.php +++ b/lib/Settings/Section.php @@ -12,17 +12,7 @@ use OCP\Settings\IIconSection; class Section implements IIconSection { - /** @var IURLGenerator */ - private $url; - /** @var CapabilitiesService */ - private $capabilitites; - /** @var IL10N */ - private $l10n; - - public function __construct(IURLGenerator $url, CapabilitiesService $capabilities, IL10N $l10n) { - $this->url = $url; - $this->capabilitites = $capabilities; - $this->l10n = $l10n; + public function __construct(private IURLGenerator $url, private CapabilitiesService $capabilitites, private IL10N $l10n) { } public function getID() { diff --git a/lib/Template/CollaboraTemplateProvider.php b/lib/Template/CollaboraTemplateProvider.php index b889d3a4ca..13813fa377 100644 --- a/lib/Template/CollaboraTemplateProvider.php +++ b/lib/Template/CollaboraTemplateProvider.php @@ -57,7 +57,7 @@ private function isSameUserTemplateFolder(): bool { $internalPath = $userTemplatesFolder->getInternalPath(); $userTemplatePath = mb_strpos($internalPath, 'files/') === 0 ? mb_substr($internalPath, 5): $internalPath; return $this->coreTemplateManager->getTemplatePath() === $userTemplatePath; - } catch (NotFoundException $e) { + } catch (NotFoundException) { } return false; } diff --git a/lib/TemplateManager.php b/lib/TemplateManager.php index bc6b578a96..363d3ded44 100644 --- a/lib/TemplateManager.php +++ b/lib/TemplateManager.php @@ -27,27 +27,6 @@ class TemplateManager { /** @var string */ protected $userId; - /** @var IConfig */ - private $config; - - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var IRootFolder */ - private $rootFolder; - - /** @var IL10N */ - private $l; - - /** @var IDBConnection */ - private $db; - - /** @var IAppData */ - private $appData; - - /** @var LoggerInterface */ - private $logger; - /** Accepted templates mime types */ public const MIMES_DOCUMENTS = [ 'application/vnd.oasis.opendocument.text-template', @@ -91,22 +70,15 @@ class TemplateManager { public function __construct( ?string $userId, - IConfig $config, - IAppData $appData, - IURLGenerator $urlGenerator, - IRootFolder $rootFolder, - IL10N $l, - IDBConnection $connection, - LoggerInterface $logger + private IConfig $config, + private IAppData $appData, + private IURLGenerator $urlGenerator, + private IRootFolder $rootFolder, + private IL10N $l, + private IDBConnection $db, + private LoggerInterface $logger ) { $this->userId = $userId; - $this->config = $config; - $this->rootFolder = $rootFolder; - $this->urlGenerator = $urlGenerator; - $this->db = $connection; - $this->logger = $logger; - $this->appData = $appData; - $this->l = $l; } private function ensureAppDataFolders() { @@ -117,12 +89,12 @@ private function ensureAppDataFolders() { */ try { $this->appData->getFolder('templates'); - } catch (NotFoundException $e) { + } catch (NotFoundException) { $this->appData->newFolder('templates'); } try { $this->appData->getFolder('empty_templates'); - } catch (NotFoundException $e) { + } catch (NotFoundException) { $this->appData->newFolder('empty_templates'); } } @@ -185,21 +157,13 @@ private function filterTemplates($templates, $type = null) { } public function getTemplateTypeForExtension(string $extension): ?string { - switch ($extension) { - case 'odt': - case 'docx': - return 'document'; - case 'ods': - case 'xlsx': - return 'spreadsheet'; - case 'odp': - case 'pptx': - return 'presentation'; - case 'odg': - return 'drawing'; - } - - return null; + return match ($extension) { + 'odt', 'docx' => 'document', + 'ods', 'xlsx' => 'spreadsheet', + 'odp', 'pptx' => 'presentation', + 'odg' => 'drawing', + default => null, + }; } public function getEmpty($type = null) { @@ -234,7 +198,7 @@ public function updateEmptyTemplates() { try { $folder = $this->getEmptyTemplateDir(); $folder->delete(); - } catch (NotFoundException $e) { + } catch (NotFoundException) { } $this->appData->newFolder('empty_templates'); $this->getEmpty(); @@ -262,13 +226,9 @@ public function getSystemFormatted($type = null) { $empty = $this->getEmpty($type); $system = $this->getSystem($type); - $emptyFormatted = array_map(function (File $file) { - return $this->formatEmpty($file); - }, $empty); + $emptyFormatted = array_map(fn (File $file) => $this->formatEmpty($file), $empty); - $systemFormatted = array_map(function (File $file) { - return $this->formatNodeReturn($file); - }, $system); + $systemFormatted = array_map(fn (File $file) => $this->formatNodeReturn($file), $system); return array_merge($emptyFormatted, $systemFormatted); } @@ -288,7 +248,7 @@ public function getUser($type = null) { $templateFiles = $templateDir->getDirectoryListing(); return $this->filterTemplates($templateFiles, $type); - } catch (NotFoundException $e) { + } catch (NotFoundException) { return []; } } @@ -303,9 +263,7 @@ public function getUserFormatted($type) { $templates = $this->getUser($type); - return array_map(function (File $file) { - return $this->formatNodeReturn($file); - }, $templates); + return array_map(fn (File $file) => $this->formatNodeReturn($file), $templates); } /** @@ -354,7 +312,7 @@ public function add($templateName, $templateFile) { try { $template = $folder->get($templateName); - } catch (NotFoundException $e) { + } catch (NotFoundException) { $template = $folder->newFile($templateName); } $template->putContent($templateFile); @@ -416,7 +374,7 @@ public function getUserTemplateDir() { // fallback to default template dir try { $templateDir = $userFolder->get('Templates'); - } catch (NotFoundException $e) { + } catch (NotFoundException) { throw new NotFoundException('Template directory not found'); } } diff --git a/tests/OCA/Richdocuments/Listener/AddFeaturePolicyListenerTest.php b/tests/OCA/Richdocuments/Listener/AddFeaturePolicyListenerTest.php index c358558b06..b7be8fccbd 100644 --- a/tests/OCA/Richdocuments/Listener/AddFeaturePolicyListenerTest.php +++ b/tests/OCA/Richdocuments/Listener/AddFeaturePolicyListenerTest.php @@ -51,7 +51,7 @@ private function getMergedPolicy(): \OC\Security\FeaturePolicy\FeaturePolicy { $eventDispatcher = $this->createMock(IEventDispatcher::class); $eventDispatcher->expects(self::once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { $this->featurePolicyListener->handle($event); }); $manager = new FeaturePolicyManager($eventDispatcher); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 738e1e2e01..6ec12295f7 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -10,7 +10,7 @@ require_once __DIR__.'/../../../lib/base.php'; -if (!class_exists('\PHPUnit\Framework\TestCase')) { +if (!class_exists(\PHPUnit\Framework\TestCase::class)) { require_once('PHPUnit/Autoload.php'); } \OC_App::loadApp('richdocuments'); diff --git a/tests/features/bootstrap/DirectContext.php b/tests/features/bootstrap/DirectContext.php index 47d9995ac4..bd4350522c 100644 --- a/tests/features/bootstrap/DirectContext.php +++ b/tests/features/bootstrap/DirectContext.php @@ -128,7 +128,7 @@ private function handleDirectEditingLink() { Assert::assertNotEmpty($initialState['document']['fileId']); Assert::assertNotEmpty($initialState['document']['token']); - $currentServer = $currentServer ?? $this->serverContext->getBaseUrl(); + $currentServer ??= $this->serverContext->getBaseUrl(); $this->wopiContext->setWopiParameters($currentServer, $initialState['document']['fileId'], $initialState['document']['token']); Assert::assertEquals(200, $response->getStatusCode()); diff --git a/tests/lib/Listener/AddContentSecurityPolicyListenerTest.php b/tests/lib/Listener/AddContentSecurityPolicyListenerTest.php index f9787882c7..67577ef83f 100644 --- a/tests/lib/Listener/AddContentSecurityPolicyListenerTest.php +++ b/tests/lib/Listener/AddContentSecurityPolicyListenerTest.php @@ -72,7 +72,7 @@ private function getMergedPolicy(): ContentSecurityPolicy { $eventDispatcher = $this->createMock(IEventDispatcher::class); $eventDispatcher->expects(self::once()) ->method('dispatchTyped') - ->willReturnCallback(function ($event) { + ->willReturnCallback(function ($event): void { $this->listener->handle($event); }); $manager = new ContentSecurityPolicyManager($eventDispatcher); @@ -191,7 +191,7 @@ public function testHandleMerged() { $eventDispatcher = $this->createMock(IEventDispatcher::class); $eventDispatcher->expects(self::once()) ->method('dispatchTyped') - ->willReturnCallback(function (AddContentSecurityPolicyEvent $event) { + ->willReturnCallback(function (AddContentSecurityPolicyEvent $event): void { $otherPolicy = new EmptyContentSecurityPolicy(); $otherPolicy->addAllowedFrameDomain('external.example.com'); $otherPolicy->addAllowedFormActionDomain('external.example.com'); @@ -203,7 +203,7 @@ public function testHandleMerged() { $policy = $manager->getDefaultPolicy(); - self::assertArrayUnordered(["'self'", 'external.example.com', 'http://public', 'nc:'], $policy->getAllowedFrameDomains(), 'Domains are equal', 0.0, 10, true); + self::assertArrayUnordered(["'self'", 'external.example.com', 'http://public', 'nc:'], $policy->getAllowedFrameDomains(), 'Domains are equal'); self::assertArrayUnordered(["'self'", 'external.example.com', 'http://public'], $policy->getAllowedFormActionDomains()); }