diff --git a/composer.json b/composer.json index 8b429bd31c..fece82cf3d 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,7 @@ "nextcloud/ocp": "dev-stable29", "staabm/annotate-pull-request-from-checkstyle": "^1.8.5", "phpunit/phpunit": "^9", - "psalm/phar": "^5.26.1", + "psalm/phar": "6.7.*", "bamarni/composer-bin-plugin": "^1.8.2" }, "config": { @@ -35,11 +35,13 @@ "lint": "find . -name \\*.php -not -path './vendor/*' -not -path './build/*' -print0 | xargs -0 -n1 php -l", "cs:check": "php-cs-fixer fix --dry-run --diff", "cs:fix": "php-cs-fixer fix", - "psalm": "./vendor/bin/psalm.phar --show-info=false --no-cache", + "psalm": "./vendor/bin/psalm.phar --no-cache", "psalm:update-baseline": "./vendor/bin/psalm.phar --update-baseline", "psalm:fix": "./vendor/bin/psalm.phar --no-cache --alter --issues=InvalidReturnType,InvalidNullableReturnType,MismatchingDocblockParamType,MismatchingDocblockReturnType,MissingParamType,InvalidFalsableReturnType", "psalm:fix:dry": "./vendor/bin/psalm.phar --no-cache --alter --issues=InvalidReturnType,InvalidNullableReturnType,MismatchingDocblockParamType,MismatchingDocblockReturnType,MissingParamType,InvalidFalsableReturnType --dry-run", "openapi": "generate-spec --verbose && (npm run typescript:generate || echo 'Please manually regenerate the typescript OpenAPI models')", + "rector:check": "rector --dry-run", + "rector:fix": "rector", "post-install-cmd": [ "[ $COMPOSER_DEV_MODE -eq 0 ] || composer bin all install --ansi" ], diff --git a/composer.lock b/composer.lock index 103e4e3160..8300035f20 100644 --- a/composer.lock +++ b/composer.lock @@ -4,7 +4,7 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "5448a8284eb94597f43c52bb76c6c04b", + "content-hash": "28bdd1710fd0068ecfa819b339c5c42e", "packages": [ { "name": "composer/pcre", @@ -1684,16 +1684,16 @@ }, { "name": "psalm/phar", - "version": "5.26.1", + "version": "6.7.1", "source": { "type": "git", "url": "https://github.com/psalm/phar.git", - "reference": "8a38e7ad04499a0ccd2c506fd1da6fc01fff4547" + "reference": "a7112d33cfd48d857c2eb730ea642046d21bbdf5" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/psalm/phar/zipball/8a38e7ad04499a0ccd2c506fd1da6fc01fff4547", - "reference": "8a38e7ad04499a0ccd2c506fd1da6fc01fff4547", + "url": "https://api.github.com/repos/psalm/phar/zipball/a7112d33cfd48d857c2eb730ea642046d21bbdf5", + "reference": "a7112d33cfd48d857c2eb730ea642046d21bbdf5", "shasum": "" }, "require": { @@ -1713,9 +1713,9 @@ "description": "Composer-based Psalm Phar", "support": { "issues": "https://github.com/psalm/phar/issues", - "source": "https://github.com/psalm/phar/tree/5.26.1" + "source": "https://github.com/psalm/phar/tree/6.7.1" }, - "time": "2024-09-09T16:22:43+00:00" + "time": "2025-02-17T10:54:35+00:00" }, { "name": "psr/clock", diff --git a/lib/Analytics/AnalyticsDatasource.php b/lib/Analytics/AnalyticsDatasource.php index 4a92580a0c..a8937aa94c 100644 --- a/lib/Analytics/AnalyticsDatasource.php +++ b/lib/Analytics/AnalyticsDatasource.php @@ -21,36 +21,24 @@ use Psr\Log\LoggerInterface; class AnalyticsDatasource implements IDatasource { - private LoggerInterface $logger; private IL10N $l10n; - private TableService $tableService; - private ViewService $viewService; - private RowService $rowService; - private ColumnService $columnService; - - protected ?string $userId; public function __construct( IL10N $l10n, - LoggerInterface $logger, - TableService $tableService, - ViewService $viewService, - ColumnService $columnService, - RowService $rowService, - ?string $userId, + private LoggerInterface $logger, + private TableService $tableService, + private ViewService $viewService, + private ColumnService $columnService, + private RowService $rowService, + protected ?string $userId, ) { $this->l10n = $l10n; - $this->logger = $logger; - $this->tableService = $tableService; - $this->viewService = $viewService; - $this->columnService = $columnService; - $this->rowService = $rowService; - $this->userId = $userId; } /** * @return string Display Name of the datasource */ + #[\Override] public function getName(): string { return $this->l10n->t('Nextcloud Tables'); } @@ -58,6 +46,7 @@ public function getName(): string { /** * @return int 2 digit unique datasource id */ + #[\Override] public function getId(): int { return 55; } @@ -88,6 +77,7 @@ public function getId(): int { * @throws NotFoundError * @throws PermissionError */ + #[\Override] public function getTemplate(): array { $tableString = ''; $template = []; @@ -108,7 +98,7 @@ public function getTemplate(): array { // concatenate the option-string. The format is tableId:viewId-title $tableString = $tableString . $table->getId() . ':' . $view->getId() . '-' . $view->getTitle() . '/'; } - } catch (PermissionError $e) { + } catch (PermissionError) { // this is a shared table without shared views; continue; } @@ -145,6 +135,7 @@ public function getTemplate(): array { * @throws DoesNotExistException * @throws MultipleObjectsReturnedException */ + #[\Override] public function readData($option): array { // get the ids which come in the format tableId:viewId $ids = explode(':', $option['tableId']); diff --git a/lib/Api/V1Api.php b/lib/Api/V1Api.php index e76f8e4307..b3889eaf87 100644 --- a/lib/Api/V1Api.php +++ b/lib/Api/V1Api.php @@ -15,15 +15,9 @@ use OCP\AppFramework\Db\MultipleObjectsReturnedException; class V1Api { - private RowService $rowService; - private ColumnService $columnService; - private ?string $userId; - - public function __construct(ColumnService $columnService, RowService $rowService, ?string $userId) { - $this->columnService = $columnService; - $this->rowService = $rowService; - $this->userId = $userId; - } + public function __construct(private ColumnService $columnService, private RowService $rowService, private ?string $userId) + { + } /** * @param int $nodeId diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 938ae00bcc..4738321e7a 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -66,6 +66,7 @@ public function __construct() { /** * @throws Exception */ + #[\Override] public function register(IRegistrationContext $context): void { if ((@include_once __DIR__ . '/../../vendor/autoload.php') === false) { throw new Exception('Cannot include autoload. Did you run install dependencies using composer?'); @@ -94,6 +95,7 @@ public function register(IRegistrationContext $context): void { $context->registerMiddleware(PermissionMiddleware::class); } + #[\Override] public function boot(IBootContext $context): void { } } diff --git a/lib/Capabilities.php b/lib/Capabilities.php index 2ecebb72f6..365ea396ac 100644 --- a/lib/Capabilities.php +++ b/lib/Capabilities.php @@ -21,17 +21,11 @@ class Capabilities implements ICapability { private IAppManager $appManager; - private LoggerInterface $logger; - private IConfig $config; - private CircleHelper $circleHelper; - - public function __construct(IAppManager $appManager, LoggerInterface $logger, IConfig $config, CircleHelper $circleHelper) { + public function __construct(IAppManager $appManager, private LoggerInterface $logger, IConfig $config, private CircleHelper $circleHelper) { $this->appManager = $appManager; - $this->logger = $logger; $this->config = $config; - $this->circleHelper = $circleHelper; } /** @@ -40,6 +34,7 @@ public function __construct(IAppManager $appManager, LoggerInterface $logger, IC * * @inheritDoc */ + #[\Override] public function getCapabilities(): array { $textColumnVariant = 'text-rich'; if (version_compare($this->config->getSystemValueString('version', '0.0.0'), '26.0.0', '<')) { diff --git a/lib/Command/AddTable.php b/lib/Command/AddTable.php index 0a3a2d12c1..90959f46d4 100644 --- a/lib/Command/AddTable.php +++ b/lib/Command/AddTable.php @@ -19,13 +19,8 @@ use Symfony\Component\Console\Output\OutputInterface; class AddTable extends Command { - protected TableService $tableService; - protected LoggerInterface $logger; - - public function __construct(TableService $tableService, LoggerInterface $logger) { + public function __construct(protected TableService $tableService, protected LoggerInterface $logger) { parent::__construct(); - $this->tableService = $tableService; - $this->logger = $logger; } protected function configure(): void { diff --git a/lib/Command/ChangeOwnershipTable.php b/lib/Command/ChangeOwnershipTable.php index de412aa53a..7739ebca21 100644 --- a/lib/Command/ChangeOwnershipTable.php +++ b/lib/Command/ChangeOwnershipTable.php @@ -18,13 +18,8 @@ use Symfony\Component\Console\Output\OutputInterface; class ChangeOwnershipTable extends Command { - protected TableService $tableService; - protected LoggerInterface $logger; - - public function __construct(TableService $tableService, LoggerInterface $logger) { + public function __construct(protected TableService $tableService, protected LoggerInterface $logger) { parent::__construct(); - $this->tableService = $tableService; - $this->logger = $logger; } protected function configure(): void { diff --git a/lib/Command/Clean.php b/lib/Command/Clean.php index e145ac9078..eaef4f4e61 100644 --- a/lib/Command/Clean.php +++ b/lib/Command/Clean.php @@ -28,12 +28,6 @@ class Clean extends Command { public const PRINT_LEVEL_WARNING = 3; public const PRINT_LEVEL_ERROR = 4; - protected ColumnService $columnService; - protected RowService $rowService; - protected TableService $tableService; - protected LoggerInterface $logger; - protected Row2Mapper $rowMapper; - private bool $dry = false; private int $truncateLength = 20; @@ -42,13 +36,8 @@ class Clean extends Command { private OutputInterface $output; - public function __construct(LoggerInterface $logger, ColumnService $columnService, RowService $rowService, TableService $tableService, Row2Mapper $rowMapper) { + public function __construct(protected LoggerInterface $logger, protected ColumnService $columnService, protected RowService $rowService, protected TableService $tableService, protected Row2Mapper $rowMapper) { parent::__construct(); - $this->logger = $logger; - $this->columnService = $columnService; - $this->rowService = $rowService; - $this->tableService = $tableService; - $this->rowMapper = $rowMapper; } protected function configure(): void { @@ -142,7 +131,7 @@ private function checkColumns(): void { } catch (InternalError $e) { $this->print('😱️ internal error while looking for column', self::PRINT_LEVEL_ERROR); $this->logger->error('Following error occurred during executing occ command "' . self::class . '"', ['exception' => $e]); - } catch (NotFoundError $e) { + } catch (NotFoundError) { if ($this->output->isVerbose()) { $this->print('corresponding column not found.', self::PRINT_LEVEL_ERROR); } else { diff --git a/lib/Command/CleanLegacy.php b/lib/Command/CleanLegacy.php index ce3563b8e2..9af7d4de30 100644 --- a/lib/Command/CleanLegacy.php +++ b/lib/Command/CleanLegacy.php @@ -30,12 +30,6 @@ class CleanLegacy extends Command { public const PRINT_LEVEL_WARNING = 3; public const PRINT_LEVEL_ERROR = 4; - protected ColumnService $columnService; - protected RowService $rowService; - protected TableService $tableService; - protected LoggerInterface $logger; - protected LegacyRowMapper $rowMapper; - private bool $dry = false; private int $truncateLength = 20; @@ -44,13 +38,8 @@ class CleanLegacy extends Command { private OutputInterface $output; - public function __construct(LoggerInterface $logger, ColumnService $columnService, RowService $rowService, TableService $tableService, LegacyRowMapper $rowMapper) { + public function __construct(protected LoggerInterface $logger, protected ColumnService $columnService, protected RowService $rowService, protected TableService $tableService, protected LegacyRowMapper $rowMapper) { parent::__construct(); - $this->logger = $logger; - $this->columnService = $columnService; - $this->rowService = $rowService; - $this->tableService = $tableService; - $this->rowMapper = $rowMapper; } protected function configure(): void { @@ -95,7 +84,7 @@ private function getNextRow():void { } catch (MultipleObjectsReturnedException|Exception $e) { $this->print('Error while fetching row', self::PRINT_LEVEL_ERROR); $this->logger->error('Following error occurred during executing occ command "' . self::class . '"', ['exception' => $e]); - } catch (DoesNotExistException $e) { + } catch (DoesNotExistException) { $this->print(''); $this->print('No more rows found.', self::PRINT_LEVEL_INFO); $this->print(''); @@ -143,7 +132,7 @@ private function checkColumns(): void { } catch (InternalError $e) { $this->print('😱️ internal error while looking for column', self::PRINT_LEVEL_ERROR); $this->logger->error('Following error occurred during executing occ command "' . self::class . '"', ['exception' => $e]); - } catch (NotFoundError $e) { + } catch (NotFoundError) { if ($this->output->isVerbose()) { $this->print('corresponding column not found.', self::PRINT_LEVEL_ERROR); } else { diff --git a/lib/Command/ListContexts.php b/lib/Command/ListContexts.php index e04f206f99..4d8b49927d 100644 --- a/lib/Command/ListContexts.php +++ b/lib/Command/ListContexts.php @@ -20,18 +20,14 @@ use function json_encode; class ListContexts extends Base { - protected ContextService $contextService; - protected LoggerInterface $logger; private IConfig $config; public function __construct( - ContextService $contextService, - LoggerInterface $logger, + protected ContextService $contextService, + protected LoggerInterface $logger, IConfig $config, ) { parent::__construct(); - $this->contextService = $contextService; - $this->logger = $logger; $this->config = $config; } diff --git a/lib/Command/ListTables.php b/lib/Command/ListTables.php index a9af050476..7ec84511c1 100644 --- a/lib/Command/ListTables.php +++ b/lib/Command/ListTables.php @@ -17,13 +17,8 @@ use Symfony\Component\Console\Output\OutputInterface; class ListTables extends Command { - protected TableService $tableService; - protected LoggerInterface $logger; - - public function __construct(TableService $tableService, LoggerInterface $logger) { + public function __construct(protected TableService $tableService, protected LoggerInterface $logger) { parent::__construct(); - $this->tableService = $tableService; - $this->logger = $logger; } protected function configure(): void { diff --git a/lib/Command/RemoveTable.php b/lib/Command/RemoveTable.php index f743d28733..62ff3528c2 100644 --- a/lib/Command/RemoveTable.php +++ b/lib/Command/RemoveTable.php @@ -18,13 +18,8 @@ use Symfony\Component\Console\Output\OutputInterface; class RemoveTable extends Command { - protected TableService $tableService; - protected LoggerInterface $logger; - - public function __construct(TableService $tableService, LoggerInterface $logger) { + public function __construct(protected TableService $tableService, protected LoggerInterface $logger) { parent::__construct(); - $this->tableService = $tableService; - $this->logger = $logger; } protected function configure(): void { diff --git a/lib/Command/RenameTable.php b/lib/Command/RenameTable.php index 8f656cd86f..419996828b 100644 --- a/lib/Command/RenameTable.php +++ b/lib/Command/RenameTable.php @@ -17,13 +17,8 @@ use Symfony\Component\Console\Output\OutputInterface; class RenameTable extends Command { - protected TableService $tableService; - protected LoggerInterface $logger; - - public function __construct(TableService $tableService, LoggerInterface $logger) { + public function __construct(protected TableService $tableService, protected LoggerInterface $logger) { parent::__construct(); - $this->tableService = $tableService; - $this->logger = $logger; } protected function configure(): void { diff --git a/lib/Command/ShowContext.php b/lib/Command/ShowContext.php index ec3dbcc848..8983a8ca5a 100644 --- a/lib/Command/ShowContext.php +++ b/lib/Command/ShowContext.php @@ -20,18 +20,14 @@ use function json_encode; class ShowContext extends Base { - protected ContextService $contextService; - protected LoggerInterface $logger; private IConfig $config; public function __construct( - ContextService $contextService, - LoggerInterface $logger, + protected ContextService $contextService, + protected LoggerInterface $logger, IConfig $config, ) { parent::__construct(); - $this->contextService = $contextService; - $this->logger = $logger; $this->config = $config; } diff --git a/lib/Command/TransferLegacyRows.php b/lib/Command/TransferLegacyRows.php index fce75e008e..175203c335 100644 --- a/lib/Command/TransferLegacyRows.php +++ b/lib/Command/TransferLegacyRows.php @@ -24,19 +24,8 @@ use Symfony\Component\Console\Output\OutputInterface; class TransferLegacyRows extends Command { - protected TableService $tableService; - protected LoggerInterface $logger; - protected LegacyRowMapper $legacyRowMapper; - protected Row2Mapper $rowMapper; - protected ColumnService $columnService; - - public function __construct(TableService $tableService, LoggerInterface $logger, LegacyRowMapper $legacyRowMapper, Row2Mapper $rowMapper, ColumnService $columnService) { + public function __construct(protected TableService $tableService, protected LoggerInterface $logger, protected LegacyRowMapper $legacyRowMapper, protected Row2Mapper $rowMapper, protected ColumnService $columnService) { parent::__construct(); - $this->tableService = $tableService; - $this->logger = $logger; - $this->legacyRowMapper = $legacyRowMapper; - $this->rowMapper = $rowMapper; - $this->columnService = $columnService; } protected function configure(): void { @@ -78,7 +67,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int try { $tables = $this->tableService->findAll('', true, true, false); $output->writeln('Found ' . count($tables) . ' table(s)'); - } catch (InternalError $e) { + } catch (InternalError) { $output->writeln('Error while fetching tables. Will aboard.'); return 1; } @@ -89,7 +78,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int foreach ($tableIds as $tableId) { try { $tables[] = $this->tableService->find((int)ltrim($tableId), true, ''); - } catch (InternalError|NotFoundError|PermissionError $e) { + } catch (InternalError|NotFoundError|PermissionError) { $output->writeln('Could not load table id ' . $tableId . '. Will continue.'); } } @@ -156,7 +145,7 @@ private function deleteDataForTables(array $tables, OutputInterface $output): vo foreach ($tables as $table) { try { $columns = $this->columnService->findAllByTable($table->getId(), null, ''); - } catch (InternalError|PermissionError $e) { + } catch (InternalError|PermissionError) { $output->writeln('Could not delete data for table ' . $table->getId()); break; } diff --git a/lib/Controller/AEnvironmentAwareOCSController.php b/lib/Controller/AEnvironmentAwareOCSController.php new file mode 100644 index 0000000000..75a367ffda --- /dev/null +++ b/lib/Controller/AEnvironmentAwareOCSController.php @@ -0,0 +1,43 @@ +table; + } + + public function setTable(?Table $table): void { + $this->table = $table; + } + + public function getView(): ?View { + return $this->view; + } + + public function setView(?View $view): void { + $this->view = $view; + } + + public function getContext(): ?Context { + return $this->context; + } + + public function setContext(?Context $context): void { + $this->context = $context; + } +} diff --git a/lib/Controller/AOCSController.php b/lib/Controller/AOCSController.php index 1d5d6d3188..fe0222ea43 100644 --- a/lib/Controller/AOCSController.php +++ b/lib/Controller/AOCSController.php @@ -21,19 +21,15 @@ abstract class AOCSController extends OCSController { - protected LoggerInterface $logger; - protected string $userId; protected IL10N $n; public function __construct( IRequest $request, - LoggerInterface $logger, + protected LoggerInterface $logger, IL10N $n, - string $userId, + protected string $userId, ) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->userId = $userId; $this->n = $n; } diff --git a/lib/Controller/Api1Controller.php b/lib/Controller/Api1Controller.php index bc5076a381..be22727140 100644 --- a/lib/Controller/Api1Controller.php +++ b/lib/Controller/Api1Controller.php @@ -48,49 +48,26 @@ * @psalm-import-type TablesContextNavigation from ResponseDefinitions */ class Api1Controller extends ApiController { - private TableService $tableService; - private ShareService $shareService; - private ColumnService $columnService; - private RowService $rowService; - private ImportService $importService; - private ViewService $viewService; - private ViewMapper $viewMapper; private IL10N $l10N; - private V1Api $v1Api; - - private ?string $userId; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - TableService $service, - ShareService $shareService, - ColumnService $columnService, - RowService $rowService, - ImportService $importService, - ViewService $viewService, - ViewMapper $viewMapper, - V1Api $v1Api, - LoggerInterface $logger, + private TableService $tableService, + private ShareService $shareService, + private ColumnService $columnService, + private RowService $rowService, + private ImportService $importService, + private ViewService $viewService, + private ViewMapper $viewMapper, + private V1Api $v1Api, + protected LoggerInterface $logger, IL10N $l10N, - ?string $userId, + private ?string $userId, ) { parent::__construct(Application::APP_ID, $request); - $this->tableService = $service; - $this->shareService = $shareService; - $this->columnService = $columnService; - $this->rowService = $rowService; - $this->importService = $importService; - $this->viewService = $viewService; - $this->viewMapper = $viewMapper; - $this->userId = $userId; - $this->v1Api = $v1Api; - $this->logger = $logger; $this->l10N = $l10N; } diff --git a/lib/Controller/ApiColumnsController.php b/lib/Controller/ApiColumnsController.php index e48ff0c3aa..04bf682580 100644 --- a/lib/Controller/ApiColumnsController.php +++ b/lib/Controller/ApiColumnsController.php @@ -25,16 +25,13 @@ * @psalm-import-type TablesColumn from ResponseDefinitions */ class ApiColumnsController extends AOCSController { - private ColumnService $service; - public function __construct( IRequest $request, LoggerInterface $logger, - ColumnService $service, + private ColumnService $service, IL10N $n, string $userId) { parent::__construct($request, $logger, $n, $userId); - $this->service = $service; } /** diff --git a/lib/Controller/ApiFavoriteController.php b/lib/Controller/ApiFavoriteController.php index 05271b4cb7..89d800bb32 100644 --- a/lib/Controller/ApiFavoriteController.php +++ b/lib/Controller/ApiFavoriteController.php @@ -27,16 +27,13 @@ * @psalm-import-type TablesTable from ResponseDefinitions */ class ApiFavoriteController extends AOCSController { - private FavoritesService $service; - public function __construct( IRequest $request, LoggerInterface $logger, - FavoritesService $service, + private FavoritesService $service, IL10N $n, string $userId) { parent::__construct($request, $logger, $n, $userId); - $this->service = $service; } /** diff --git a/lib/Controller/ApiGeneralController.php b/lib/Controller/ApiGeneralController.php index e376ea754c..4210535ef2 100644 --- a/lib/Controller/ApiGeneralController.php +++ b/lib/Controller/ApiGeneralController.php @@ -25,20 +25,15 @@ * @psalm-import-type TablesIndex from ResponseDefinitions */ class ApiGeneralController extends AOCSController { - private TableService $tableService; - private ViewService $viewService; - public function __construct( IRequest $request, - TableService $tableService, - ViewService $viewService, + private TableService $tableService, + private ViewService $viewService, LoggerInterface $logger, IL10N $n, ?string $userId, ) { parent::__construct($request, $logger, $n, $userId); - $this->tableService = $tableService; - $this->viewService = $viewService; } diff --git a/lib/Controller/ApiTablesController.php b/lib/Controller/ApiTablesController.php index 541d0d09e4..fb8ec305d0 100644 --- a/lib/Controller/ApiTablesController.php +++ b/lib/Controller/ApiTablesController.php @@ -33,27 +33,21 @@ * @psalm-import-type TablesColumn from ResponseDefinitions */ class ApiTablesController extends AOCSController { - private TableService $service; - private ColumnService $columnService; - private ViewService $viewService; private IAppManager $appManager; private IDBConnection $db; public function __construct( IRequest $request, LoggerInterface $logger, - TableService $service, - ColumnService $columnService, - ViewService $viewService, + private TableService $service, + private ColumnService $columnService, + private ViewService $viewService, IL10N $n, IAppManager $appManager, IDBConnection $db, string $userId) { parent::__construct($request, $logger, $n, $userId); - $this->service = $service; - $this->columnService = $columnService; $this->appManager = $appManager; - $this->viewService = $viewService; $this->db = $db; } diff --git a/lib/Controller/ColumnController.php b/lib/Controller/ColumnController.php index 0f1073ad37..9b9878a219 100644 --- a/lib/Controller/ColumnController.php +++ b/lib/Controller/ColumnController.php @@ -18,52 +18,35 @@ use Psr\Log\LoggerInterface; class ColumnController extends Controller { - private ColumnService $service; - - private string $userId; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - ColumnService $service, - string $userId) { + protected LoggerInterface $logger, + private ColumnService $service, + private string $userId) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; - $this->userId = $userId; } #[NoAdminRequired] public function index(int $tableId, ?int $viewId): DataResponse { - return $this->handleError(function () use ($tableId, $viewId) { - return $this->service->findAllByTable($tableId, $viewId); - }); + return $this->handleError(fn() => $this->service->findAllByTable($tableId, $viewId)); } #[NoAdminRequired] public function indexTableByView(int $tableId, ?int $viewId): DataResponse { - return $this->handleError(function () use ($tableId, $viewId) { - return $this->service->findAllByTable($tableId, $viewId); - }); + return $this->handleError(fn() => $this->service->findAllByTable($tableId, $viewId)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_VIEW, idParam: 'viewId')] public function indexView(int $viewId): DataResponse { - return $this->handleError(function () use ($viewId) { - return $this->service->findAllByView($viewId); - }); + return $this->handleError(fn() => $this->service->findAllByView($viewId)); } #[NoAdminRequired] public function show(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->find($id); - }); + return $this->handleError(fn() => $this->service->find($id)); } #[NoAdminRequired] @@ -101,40 +84,7 @@ public function create( ?array $selectedViewIds, ): DataResponse { - return $this->handleError(function () use ( - $tableId, - $viewId, - $type, - $subtype, - $title, - $mandatory, - $description, - - $textDefault, - $textAllowedPattern, - $textMaxLength, - - $numberPrefix, - $numberSuffix, - $numberDefault, - $numberMin, - $numberMax, - $numberDecimals, - - $selectionOptions, - $selectionDefault, - - $datetimeDefault, - - $usergroupDefault, - $usergroupMultipleItems, - $usergroupSelectUsers, - $usergroupSelectGroups, - $usergroupSelectTeams, - $showUserStatus, - - $selectedViewIds) { - return $this->service->create( + return $this->handleError(fn() => $this->service->create( $this->userId, $tableId, $viewId, @@ -164,8 +114,7 @@ public function create( showUserStatus: $showUserStatus ), $selectedViewIds - ); - }); + )); } #[NoAdminRequired] @@ -201,39 +150,7 @@ public function update( ?bool $usergroupSelectTeams, ?bool $showUserStatus, ): DataResponse { - return $this->handleError(function () use ( - $id, - $tableId, - $type, - $subtype, - $title, - $mandatory, - $description, - - $textDefault, - $textAllowedPattern, - $textMaxLength, - - $numberPrefix, - $numberSuffix, - $numberDefault, - $numberMin, - $numberMax, - $numberDecimals, - - $selectionOptions, - $selectionDefault, - - $datetimeDefault, - - $usergroupDefault, - $usergroupMultipleItems, - $usergroupSelectUsers, - $usergroupSelectGroups, - $usergroupSelectTeams, - $showUserStatus - ) { - return $this->service->update( + return $this->handleError(fn() => $this->service->update( $id, $tableId, $this->userId, @@ -262,14 +179,11 @@ public function update( usergroupSelectTeams: $usergroupSelectTeams, showUserStatus: $showUserStatus ) - ); - }); + )); } #[NoAdminRequired] public function destroy(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->delete($id, false, $this->userId); - }); + return $this->handleError(fn() => $this->service->delete($id, false, $this->userId)); } } diff --git a/lib/Controller/ContextController.php b/lib/Controller/ContextController.php index 1fbc799723..48c99917ee 100644 --- a/lib/Controller/ContextController.php +++ b/lib/Controller/ContextController.php @@ -30,17 +30,14 @@ */ class ContextController extends AOCSController { - private ContextService $contextService; - public function __construct( IRequest $request, LoggerInterface $logger, IL10N $n, string $userId, - ContextService $contextService, + private ContextService $contextService, ) { parent::__construct($request, $logger, $n, $userId); - $this->contextService = $contextService; $this->userId = $userId; } diff --git a/lib/Controller/ImportController.php b/lib/Controller/ImportController.php index 17fab1a3a0..25c1aa0f04 100644 --- a/lib/Controller/ImportController.php +++ b/lib/Controller/ImportController.php @@ -32,11 +32,6 @@ class ImportController extends Controller { 'application/vnd.oasis.opendocument.spreadsheet', ]; - private ImportService $service; - private string $userId; - - protected LoggerInterface $logger; - private IL10N $l10n; use Errors; @@ -44,49 +39,40 @@ class ImportController extends Controller { public function __construct( IRequest $request, - LoggerInterface $logger, - ImportService $service, - string $userId, + protected LoggerInterface $logger, + private ImportService $service, + private string $userId, IL10N $l10n) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; - $this->userId = $userId; $this->l10n = $l10n; } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')] public function previewImportTable(int $tableId, String $path): DataResponse { - return $this->handleError(function () use ($tableId, $path) { - return $this->service->previewImport($tableId, null, $path); - }); + return $this->handleError(fn() => $this->service->previewImport($tableId, null, $path)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_CREATE, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')] public function importInTable(int $tableId, String $path, bool $createMissingColumns = true, array $columnsConfig = []): DataResponse { - return $this->handleError(function () use ($tableId, $path, $createMissingColumns, $columnsConfig) { - // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer - return $this->service->import($tableId, null, $path, $createMissingColumns, $columnsConfig); - }); + return $this->handleError(fn() => + // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer + $this->service->import($tableId, null, $path, $createMissingColumns, $columnsConfig)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_CREATE, type: Application::NODE_TYPE_VIEW, idParam: 'viewId')] public function previewImportView(int $viewId, String $path): DataResponse { - return $this->handleError(function () use ($viewId, $path) { - return $this->service->previewImport(null, $viewId, $path); - }); + return $this->handleError(fn() => $this->service->previewImport(null, $viewId, $path)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_CREATE, type: Application::NODE_TYPE_VIEW, idParam: 'viewId')] public function importInView(int $viewId, String $path, bool $createMissingColumns = true, array $columnsConfig = []): DataResponse { - return $this->handleError(function () use ($viewId, $path, $createMissingColumns, $columnsConfig) { - // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer - return $this->service->import(null, $viewId, $path, $createMissingColumns, $columnsConfig); - }); + return $this->handleError(fn() => + // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer + $this->service->import(null, $viewId, $path, $createMissingColumns, $columnsConfig)); } #[NoAdminRequired] @@ -94,9 +80,7 @@ public function importInView(int $viewId, String $path, bool $createMissingColum public function previewUploadImportTable(int $tableId): DataResponse { try { $file = $this->getUploadedFile('uploadfile'); - return $this->handleError(function () use ($tableId, $file) { - return $this->service->previewImport($tableId, null, $file['tmp_name']); - }); + return $this->handleError(fn() => $this->service->previewImport($tableId, null, $file['tmp_name'])); } catch (UploadException|NotPermittedException $e) { $this->logger->error('Upload error', ['exception' => $e]); return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); @@ -109,10 +93,9 @@ public function importUploadInTable(int $tableId, bool $createMissingColumns = t try { $columnsConfigArray = json_decode($columnsConfig, true); $file = $this->getUploadedFile('uploadfile'); - return $this->handleError(function () use ($tableId, $file, $createMissingColumns, $columnsConfigArray) { - // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer - return $this->service->import($tableId, null, $file['tmp_name'], $createMissingColumns, $columnsConfigArray); - }); + return $this->handleError(fn() => + // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer + $this->service->import($tableId, null, $file['tmp_name'], $createMissingColumns, $columnsConfigArray)); } catch (UploadException|NotPermittedException $e) { $this->logger->error('Upload error', ['exception' => $e]); return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); @@ -124,9 +107,7 @@ public function importUploadInTable(int $tableId, bool $createMissingColumns = t public function previewUploadImportView(int $viewId): DataResponse { try { $file = $this->getUploadedFile('uploadfile'); - return $this->handleError(function () use ($viewId, $file) { - return $this->service->previewImport(null, $viewId, $file['tmp_name']); - }); + return $this->handleError(fn() => $this->service->previewImport(null, $viewId, $file['tmp_name'])); } catch (UploadException|NotPermittedException $e) { $this->logger->error('Upload error', ['exception' => $e]); return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); @@ -139,10 +120,9 @@ public function importUploadInView(int $viewId, bool $createMissingColumns = tru try { $columnsConfigArray = json_decode($columnsConfig, true); $file = $this->getUploadedFile('uploadfile'); - return $this->handleError(function () use ($viewId, $file, $createMissingColumns, $columnsConfigArray) { - // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer - return $this->service->import(null, $viewId, $file['tmp_name'], $createMissingColumns, $columnsConfigArray); - }); + return $this->handleError(fn() => + // minimal permission is checked, creating columns requires MANAGE permissions - currently tested on service layer + $this->service->import(null, $viewId, $file['tmp_name'], $createMissingColumns, $columnsConfigArray)); } catch (UploadException|NotPermittedException $e) { $this->logger->error('Upload error', ['exception' => $e]); return new DataResponse(['message' => $e->getMessage()], Http::STATUS_BAD_REQUEST); diff --git a/lib/Controller/RowController.php b/lib/Controller/RowController.php index c5c7ebb39c..190b77f3b9 100644 --- a/lib/Controller/RowController.php +++ b/lib/Controller/RowController.php @@ -17,48 +17,31 @@ use Psr\Log\LoggerInterface; class RowController extends Controller { - /** @var RowService */ - private RowService $service; - - /** @var string */ - private string $userId; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - RowService $service, - string $userId) { + protected LoggerInterface $logger, + private RowService $service, + private string $userId) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; - $this->userId = $userId; } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')] public function index(int $tableId): DataResponse { - return $this->handleError(function () use ($tableId) { - return $this->service->findAllByTable($tableId, $this->userId); - }); + return $this->handleError(fn() => $this->service->findAllByTable($tableId, $this->userId)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_VIEW, idParam: 'viewId')] public function indexView(int $viewId): DataResponse { - return $this->handleError(function () use ($viewId) { - return $this->service->findAllByView($viewId, $this->userId); - }); + return $this->handleError(fn() => $this->service->findAllByView($viewId, $this->userId)); } #[NoAdminRequired] public function show(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->find($id); - }); + return $this->handleError(fn() => $this->service->find($id)); } #[NoAdminRequired] @@ -69,15 +52,7 @@ public function update( ?int $viewId, string $data, ): DataResponse { - return $this->handleError(function () use ( - $id, - $tableId, - $viewId, - $columnId, - $data - ) { - return $this->service->updateSet($id, $viewId, ['columnId' => $columnId, 'value' => $data], $this->userId); - }); + return $this->handleError(fn() => $this->service->updateSet($id, $viewId, ['columnId' => $columnId, 'value' => $data], $this->userId)); } #[NoAdminRequired] @@ -87,29 +62,19 @@ public function updateSet( array $data, ): DataResponse { - return $this->handleError(function () use ( - $id, - $viewId, - $data - ) { - return $this->service->updateSet( + return $this->handleError(fn() => $this->service->updateSet( $id, $viewId, $data, - $this->userId); - }); + $this->userId)); } #[NoAdminRequired] public function destroy(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->delete($id, null, $this->userId); - }); + return $this->handleError(fn() => $this->service->delete($id, null, $this->userId)); } #[NoAdminRequired] public function destroyByView(int $id, int $viewId): DataResponse { - return $this->handleError(function () use ($id, $viewId) { - return $this->service->delete($id, $viewId, $this->userId); - }); + return $this->handleError(fn() => $this->service->delete($id, $viewId, $this->userId)); } } diff --git a/lib/Controller/SearchController.php b/lib/Controller/SearchController.php index 297e4d1334..252f3e3b6b 100644 --- a/lib/Controller/SearchController.php +++ b/lib/Controller/SearchController.php @@ -17,29 +17,20 @@ class SearchController extends Controller { - private SearchService $service; - private string $userId; - private LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - SearchService $service, - string $userId) { + private LoggerInterface $logger, + private SearchService $service, + private string $userId) { parent::__construct(Application::APP_ID, $request); - $this->userId = $userId; - $this->service = $service; - $this->logger = $logger; } #[NoAdminRequired] public function all(string $term = ''): DataResponse { - return $this->handleError(function () use ($term) { - return $this->service->all($term); - }); + return $this->handleError(fn() => $this->service->all($term)); } } diff --git a/lib/Controller/ShareController.php b/lib/Controller/ShareController.php index 8cef76afc0..d4e475b120 100644 --- a/lib/Controller/ShareController.php +++ b/lib/Controller/ShareController.php @@ -17,48 +17,33 @@ use Psr\Log\LoggerInterface; class ShareController extends Controller { - private ShareService $service; - - private string $userId; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - ShareService $service, - string $userId) { + protected LoggerInterface $logger, + private ShareService $service, + private string $userId) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; - $this->userId = $userId; } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')] public function index(int $tableId): DataResponse { - return $this->handleError(function () use ($tableId) { - return $this->service->findAll('table', $tableId); - }); + return $this->handleError(fn() => $this->service->findAll('table', $tableId)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_VIEW, idParam: 'viewId')] public function indexView(int $viewId): DataResponse { - return $this->handleError(function () use ($viewId) { - return $this->service->findAll('view', $viewId); - }); + return $this->handleError(fn() => $this->service->findAll('view', $viewId)); } #[NoAdminRequired] public function show(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->find($id); - }); + return $this->handleError(fn() => $this->service->find($id)); } #[NoAdminRequired] @@ -75,16 +60,12 @@ public function create( bool $permissionManage = false, int $displayMode = Application::NAV_ENTRY_MODE_ALL, ): DataResponse { - return $this->handleError(function () use ($nodeId, $nodeType, $receiver, $receiverType, $permissionRead, $permissionCreate, $permissionUpdate, $permissionDelete, $permissionManage, $displayMode) { - return $this->service->create($nodeId, $nodeType, $receiver, $receiverType, $permissionRead, $permissionCreate, $permissionUpdate, $permissionDelete, $permissionManage, $displayMode); - }); + return $this->handleError(fn() => $this->service->create($nodeId, $nodeType, $receiver, $receiverType, $permissionRead, $permissionCreate, $permissionUpdate, $permissionDelete, $permissionManage, $displayMode)); } #[NoAdminRequired] public function updatePermission(int $id, string $permission, bool $value): DataResponse { - return $this->handleError(function () use ($id, $permission, $value) { - return $this->service->updatePermission($id, $permission, $value); - }); + return $this->handleError(fn() => $this->service->updatePermission($id, $permission, $value)); } /** @@ -108,8 +89,6 @@ public function updateDisplayMode(int $id, int $displayMode, string $target = 'd #[NoAdminRequired] public function destroy(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->delete($id); - }); + return $this->handleError(fn() => $this->service->delete($id)); } } diff --git a/lib/Controller/TableController.php b/lib/Controller/TableController.php index e22057d658..64d3317ff3 100644 --- a/lib/Controller/TableController.php +++ b/lib/Controller/TableController.php @@ -17,62 +17,43 @@ use Psr\Log\LoggerInterface; class TableController extends Controller { - private TableService $service; - - private string $userId; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - TableService $service, - string $userId) { + protected LoggerInterface $logger, + private TableService $service, + private string $userId) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; - $this->userId = $userId; } #[NoAdminRequired] public function index(): DataResponse { - return $this->handleError(function () { - return $this->service->findAll($this->userId); - }); + return $this->handleError(fn() => $this->service->findAll($this->userId)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_TABLE, idParam: 'id')] public function show(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->find($id); - }); + return $this->handleError(fn() => $this->service->find($id)); } #[NoAdminRequired] public function create(string $title, string $template, string $emoji): DataResponse { - return $this->handleError(function () use ($title, $template, $emoji) { - return $this->service->create($title, $template, $emoji); - }); + return $this->handleError(fn() => $this->service->create($title, $template, $emoji)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_MANAGE, type: Application::NODE_TYPE_TABLE, idParam: 'id')] public function destroy(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->delete($id); - }); + return $this->handleError(fn() => $this->service->delete($id)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_MANAGE, type: Application::NODE_TYPE_TABLE, idParam: 'id')] public function update(int $id, ?string $title = null, ?string $emoji = null, ?bool $archived = null): DataResponse { - return $this->handleError(function () use ($id, $title, $emoji, $archived) { - return $this->service->update($id, $title, $emoji, null, $archived, $this->userId); - }); + return $this->handleError(fn() => $this->service->update($id, $title, $emoji, null, $archived, $this->userId)); } } diff --git a/lib/Controller/TableTemplateController.php b/lib/Controller/TableTemplateController.php index 52bfc295a9..652eb82081 100644 --- a/lib/Controller/TableTemplateController.php +++ b/lib/Controller/TableTemplateController.php @@ -16,25 +16,17 @@ use Psr\Log\LoggerInterface; class TableTemplateController extends Controller { - private TableTemplateService $service; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - TableTemplateService $service) { + protected LoggerInterface $logger, + private TableTemplateService $service) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; } #[NoAdminRequired] public function list(): DataResponse { - return $this->handleError(function () { - return $this->service->getTemplateList(); - }); + return $this->handleError(fn() => $this->service->getTemplateList()); } } diff --git a/lib/Controller/ViewController.php b/lib/Controller/ViewController.php index 65f460503e..ce07284266 100644 --- a/lib/Controller/ViewController.php +++ b/lib/Controller/ViewController.php @@ -23,80 +23,53 @@ use Psr\Log\LoggerInterface; class ViewController extends Controller { - private ViewService $service; - - private ViewMapper $mapper; - - private TableService $tableService; - - private string $userId; - - protected LoggerInterface $logger; - use Errors; public function __construct( IRequest $request, - LoggerInterface $logger, - ViewService $service, - ViewMapper $mapper, - TableService $tableService, - string $userId) { + protected LoggerInterface $logger, + private ViewService $service, + private ViewMapper $mapper, + private TableService $tableService, + private string $userId) { parent::__construct(Application::APP_ID, $request); - $this->logger = $logger; - $this->service = $service; - $this->mapper = $mapper; - $this->tableService = $tableService; - $this->userId = $userId; } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')] public function index(int $tableId): DataResponse { - return $this->handleError(function () use ($tableId) { - return $this->service->findAll($this->getTable($tableId), $this->userId); - }); + return $this->handleError(fn() => $this->service->findAll($this->getTable($tableId), $this->userId)); } #[NoAdminRequired] public function indexSharedWithMe(): DataResponse { - return $this->handleError(function () { - return $this->service->findSharedViewsWithMe($this->userId); - }); + return $this->handleError(fn() => $this->service->findSharedViewsWithMe($this->userId)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_READ, type: Application::NODE_TYPE_VIEW, idParam: 'id')] public function show(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->find($id); - }); + return $this->handleError(fn() => $this->service->find($id)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_MANAGE, type: Application::NODE_TYPE_TABLE, idParam: 'tableId')] public function create(int $tableId, string $title, ?string $emoji): DataResponse { - return $this->handleError(function () use ($tableId, $title, $emoji) { - return $this->service->create($title, $emoji, $this->getTable($tableId, true)); - }); + return $this->handleError(fn() => $this->service->create($title, $emoji, $this->getTable($tableId, true))); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_MANAGE, type: Application::NODE_TYPE_VIEW, idParam: 'id')] public function update(int $id, array $data): DataResponse { - return $this->handleError(function () use ($id, $data) { - return $this->service->update($id, $data, $this->userId); - }); + return $this->handleError(fn() => $this->service->update($id, $data, $this->userId)); } #[NoAdminRequired] #[RequirePermission(permission: Application::PERMISSION_MANAGE, type: Application::NODE_TYPE_VIEW, idParam: 'id')] public function destroy(int $id): DataResponse { - return $this->handleError(function () use ($id) { - return $this->service->delete($id); - }); + return $this->handleError(fn() => $this->service->delete($id)); } /** diff --git a/lib/Db/Column.php b/lib/Db/Column.php index fbd008066f..6ed12f34e3 100644 --- a/lib/Db/Column.php +++ b/lib/Db/Column.php @@ -235,6 +235,7 @@ public function setSelectionOptionsArray(array $array):void { /** * @psalm-return TablesColumn */ + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/ColumnMapper.php b/lib/Db/ColumnMapper.php index a72968cce6..16ed5f1321 100644 --- a/lib/Db/ColumnMapper.php +++ b/lib/Db/ColumnMapper.php @@ -18,11 +18,9 @@ /** @template-extends QBMapper */ class ColumnMapper extends QBMapper { protected string $table = 'tables_columns'; - private LoggerInterface $logger; - public function __construct(IDBConnection $db, LoggerInterface $logger) { + public function __construct(IDBConnection $db, private LoggerInterface $logger) { parent::__construct($db, $this->table, Column::class); - $this->logger = $logger; } /** diff --git a/lib/Db/ColumnTypes/DatetimeColumnQB.php b/lib/Db/ColumnTypes/DatetimeColumnQB.php index d031d5aa25..c9f71acd4b 100644 --- a/lib/Db/ColumnTypes/DatetimeColumnQB.php +++ b/lib/Db/ColumnTypes/DatetimeColumnQB.php @@ -11,6 +11,7 @@ class DatetimeColumnQB extends SuperColumnQB implements IColumnTypeQB { + #[\Override] public function passSearchValue(IQueryBuilder $qb, string $unformattedSearchValue, string $operator, string $searchValuePlaceHolder): void { $qb->setParameter($searchValuePlaceHolder, $unformattedSearchValue, IQueryBuilder::PARAM_STR); } diff --git a/lib/Db/ColumnTypes/NumberColumnQB.php b/lib/Db/ColumnTypes/NumberColumnQB.php index ca10aa3873..78bcf78456 100644 --- a/lib/Db/ColumnTypes/NumberColumnQB.php +++ b/lib/Db/ColumnTypes/NumberColumnQB.php @@ -11,6 +11,7 @@ class NumberColumnQB extends SuperColumnQB implements IColumnTypeQB { + #[\Override] public function passSearchValue(IQueryBuilder $qb, string $unformattedSearchValue, string $operator, string $searchValuePlaceHolder): void { // TODO can we filter for float values? $qb->setParameter($searchValuePlaceHolder, $unformattedSearchValue, IQueryBuilder::PARAM_INT); diff --git a/lib/Db/ColumnTypes/SelectionColumnQB.php b/lib/Db/ColumnTypes/SelectionColumnQB.php index 7b2f41c0c1..a7e11192a3 100644 --- a/lib/Db/ColumnTypes/SelectionColumnQB.php +++ b/lib/Db/ColumnTypes/SelectionColumnQB.php @@ -10,8 +10,9 @@ use OCP\DB\QueryBuilder\IQueryBuilder; class SelectionColumnQB extends SuperColumnQB implements IColumnTypeQB { + #[\Override] public function passSearchValue(IQueryBuilder $qb, string $unformattedSearchValue, string $operator, string $searchValuePlaceHolder): void { - if (substr($unformattedSearchValue, 0, 1) === '@') { + if (str_starts_with($unformattedSearchValue, '@')) { $parts = explode('-', $unformattedSearchValue); $selectedId = intval($parts[2]); $qb->setParameter($searchValuePlaceHolder, $selectedId, IQueryBuilder::PARAM_INT); diff --git a/lib/Db/ColumnTypes/SuperColumnQB.php b/lib/Db/ColumnTypes/SuperColumnQB.php index 6109f73c4c..84c2af6df4 100644 --- a/lib/Db/ColumnTypes/SuperColumnQB.php +++ b/lib/Db/ColumnTypes/SuperColumnQB.php @@ -14,17 +14,18 @@ use Psr\Log\LoggerInterface; class SuperColumnQB implements IColumnTypeQB { - protected LoggerInterface $logger; protected int $platform; - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; - } + public function __construct(protected LoggerInterface $logger) + { + } + #[\Override] public function setPlatform(int $platform): void { $this->platform = $platform; } + #[\Override] public function formatCellValue(string $unformattedValue): string { if ($this->platform === self::DB_PLATFORM_PGSQL) { return 'LOWER(' . $unformattedValue . ')'; @@ -35,6 +36,7 @@ public function formatCellValue(string $unformattedValue): string { } } + #[\Override] public function passSearchValue(IQueryBuilder $qb, string $unformattedSearchValue, string $operator, string $searchValuePlaceHolder): void { $lowerCaseSearchValue = strtolower($unformattedSearchValue); switch ($operator) { @@ -61,26 +63,16 @@ public function passSearchValue(IQueryBuilder $qb, string $unformattedSearchValu * @throws InternalError */ private function sqlFilterOperation(string $operator, string $formattedCellValue, string $searchValuePlaceHolder) : string { - switch ($operator) { - case 'begins-with': - case 'ends-with': - case 'contains': - return $formattedCellValue . ' LIKE :' . $searchValuePlaceHolder; - case 'is-equal': - return $formattedCellValue . ' = :' . $searchValuePlaceHolder; - case 'is-greater-than': - return $formattedCellValue . ' > :' . $searchValuePlaceHolder; - case 'is-greater-than-or-equal': - return $formattedCellValue . ' >= :' . $searchValuePlaceHolder; - case 'is-lower-than': - return $formattedCellValue . ' < :' . $searchValuePlaceHolder; - case 'is-lower-than-or-equal': - return $formattedCellValue . ' <= :' . $searchValuePlaceHolder; - case 'is-empty': - return $formattedCellValue . ' = \'\' OR ' . $formattedCellValue . ' IS NULL'; - default: - throw new InternalError('Operator ' . $operator . ' is not supported.'); - } + return match ($operator) { + 'begins-with', 'ends-with', 'contains' => $formattedCellValue . ' LIKE :' . $searchValuePlaceHolder, + 'is-equal' => $formattedCellValue . ' = :' . $searchValuePlaceHolder, + 'is-greater-than' => $formattedCellValue . ' > :' . $searchValuePlaceHolder, + 'is-greater-than-or-equal' => $formattedCellValue . ' >= :' . $searchValuePlaceHolder, + 'is-lower-than' => $formattedCellValue . ' < :' . $searchValuePlaceHolder, + 'is-lower-than-or-equal' => $formattedCellValue . ' <= :' . $searchValuePlaceHolder, + 'is-empty' => $formattedCellValue . ' = \'\' OR ' . $formattedCellValue . ' IS NULL', + default => throw new InternalError('Operator ' . $operator . ' is not supported.'), + }; } private function getFormattedDataCellValue(string $columnPlaceHolder, int $columnId): string { @@ -101,20 +93,14 @@ private function getFormattedDataCellValue(string $columnPlaceHolder, int $colum * @throws InternalError */ public static function getMetaColumnName(int $metaId): string { - switch ($metaId) { - case Column::TYPE_META_ID: - return 'id'; - case Column::TYPE_META_CREATED_BY: - return 'created_by'; - case Column::TYPE_META_UPDATED_BY: - return 'last_edit_by'; - case Column::TYPE_META_CREATED_AT: - return 'created_at'; - case Column::TYPE_META_UPDATED_AT: - return 'last_edit_at'; - default: - throw new InternalError('No meta data column exists with id ' . $metaId); - } + return match ($metaId) { + Column::TYPE_META_ID => 'id', + Column::TYPE_META_CREATED_BY => 'created_by', + Column::TYPE_META_UPDATED_BY => 'last_edit_by', + Column::TYPE_META_CREATED_AT => 'created_at', + Column::TYPE_META_UPDATED_AT => 'last_edit_at', + default => throw new InternalError('No meta data column exists with id ' . $metaId), + }; } /** @@ -124,12 +110,13 @@ public static function getMetaColumnName(int $metaId): string { * @return IQueryFunction * @throws InternalError */ + #[\Override] public function addWhereFilterExpression(IQueryBuilder $qb, array $filter, string $filterId): IQueryFunction { $searchValuePlaceHolder = 'searchValue' . $filterId; // qb parameter binding name $this->passSearchValue($qb, $filter['value'], $filter['operator'], $searchValuePlaceHolder); $columnPlaceHolder = 'column' . $filterId; // qb parameter binding name if ($filter['columnId'] < 0) { // negative ids for meta data columns - return $qb->createFunction($this->sqlFilterOperation($filter['operator'], $this->getMetaColumnName($filter['columnId']), $searchValuePlaceHolder)); + return $qb->createFunction($this->sqlFilterOperation($filter['operator'], static::getMetaColumnName($filter['columnId']), $searchValuePlaceHolder)); } $qb->setParameter($columnPlaceHolder, $filter['columnId'], IQueryBuilder::PARAM_INT); @@ -147,6 +134,7 @@ public function addWhereFilterExpression(IQueryBuilder $qb, array $filter, strin return $qb->createFunction($sqlFilterString); } + #[\Override] public function addWhereForFindAllWithColumn(IQueryBuilder $qb, int $columnId): void { if ($this->platform === self::DB_PLATFORM_PGSQL) { // due to errors using doctrine with json, I paste the columnId inline. diff --git a/lib/Db/ColumnTypes/UsergroupColumnQB.php b/lib/Db/ColumnTypes/UsergroupColumnQB.php index 5fdd093b13..874d508a4c 100644 --- a/lib/Db/ColumnTypes/UsergroupColumnQB.php +++ b/lib/Db/ColumnTypes/UsergroupColumnQB.php @@ -10,6 +10,7 @@ use OCP\DB\QueryBuilder\IQueryBuilder; class UsergroupColumnQB extends SuperColumnQB implements IColumnTypeQB { + #[\Override] public function passSearchValue(IQueryBuilder $qb, string $unformattedSearchValue, string $operator, string $searchValuePlaceHolder): void { // TODO how to handle searching for multiple users/groups? $qb->setParameter($searchValuePlaceHolder, $unformattedSearchValue, IQueryBuilder::PARAM_STR); diff --git a/lib/Db/Context.php b/lib/Db/Context.php index e7fbdea3df..2759afc539 100644 --- a/lib/Db/Context.php +++ b/lib/Db/Context.php @@ -44,6 +44,7 @@ public function __construct() { $this->addType('owner_type', 'integer'); } + #[\Override] public function jsonSerialize(): array { // basic information $data = [ diff --git a/lib/Db/ContextNavigation.php b/lib/Db/ContextNavigation.php index e39aecb4f3..d11d86d78d 100644 --- a/lib/Db/ContextNavigation.php +++ b/lib/Db/ContextNavigation.php @@ -27,6 +27,7 @@ public function __construct() { $this->addType('displayMode', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->getId(), diff --git a/lib/Db/ContextNavigationMapper.php b/lib/Db/ContextNavigationMapper.php index be304fb053..2c005bf6c5 100644 --- a/lib/Db/ContextNavigationMapper.php +++ b/lib/Db/ContextNavigationMapper.php @@ -45,6 +45,7 @@ public function setDisplayModeByShareId(int $shareId, int $displayMode, string $ // we have to overwrite QBMapper`s insert() because we do not have // an id column in this table. Sad. + #[\Override] public function insert(Entity $entity): Entity { // get updated fields to save, fields have to be set using a setter to // be saved @@ -70,6 +71,7 @@ public function insert(Entity $entity): Entity { // we have to overwrite QBMapper`s update() because we do not have // an id column in this table. Sad. + #[\Override] public function update(Entity $entity): ContextNavigation { if (!$entity instanceof ContextNavigation) { throw new \LogicException('Can only update context navigation entities'); diff --git a/lib/Db/ContextNodeRelation.php b/lib/Db/ContextNodeRelation.php index 70233bf2ef..61c8f01b54 100644 --- a/lib/Db/ContextNodeRelation.php +++ b/lib/Db/ContextNodeRelation.php @@ -34,6 +34,7 @@ public function __construct() { $this->addType('permissions', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->getId(), diff --git a/lib/Db/LegacyRow.php b/lib/Db/LegacyRow.php index 690fecba4b..f1a19f3623 100644 --- a/lib/Db/LegacyRow.php +++ b/lib/Db/LegacyRow.php @@ -40,6 +40,7 @@ public function __construct() { $this->addType('tableId', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/LegacyRowMapper.php b/lib/Db/LegacyRowMapper.php index a8e12dc9a7..fb7455beb9 100644 --- a/lib/Db/LegacyRowMapper.php +++ b/lib/Db/LegacyRowMapper.php @@ -52,9 +52,9 @@ public function __construct( } private function setPlatform() { - if (str_contains(strtolower(get_class($this->db->getDatabasePlatform())), 'postgres')) { + if (str_contains(strtolower($this->db->getDatabasePlatform()::class), 'postgres')) { $this->platform = IColumnTypeQB::DB_PLATFORM_PGSQL; - } elseif (str_contains(strtolower(get_class($this->db->getDatabasePlatform())), 'sqlite')) { + } elseif (str_contains(strtolower($this->db->getDatabasePlatform()::class), 'sqlite')) { $this->platform = IColumnTypeQB::DB_PLATFORM_SQLITE; } else { $this->platform = IColumnTypeQB::DB_PLATFORM_MYSQL; @@ -92,7 +92,7 @@ private function buildFilterByColumnType($qb, array $filter, string $filterId): /** @var IColumnTypeQB $columnQb */ $columnQb = Server::get($columnQbClassName); return $columnQb->addWhereFilterExpression($qb, $filter, $filterId); - } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) { + } catch (NotFoundExceptionInterface|ContainerExceptionInterface) { $this->logger->debug('Column type query builder class not found'); } return null; @@ -139,7 +139,7 @@ private function addOrderByRules(IQueryBuilder $qb, array $sortArray) { if ($sortRule['columnId'] < 0) { try { $orderString = SuperColumnQB::getMetaColumnName($sortRule['columnId']); - } catch (InternalError $e) { + } catch (InternalError) { return; } } else { @@ -300,9 +300,7 @@ public function findAllByView(View $view, string $userId, ?int $limit = null, ?i } $rows = $this->findEntities($qb); foreach ($rows as &$row) { - $row->setDataArray(array_filter($row->getDataArray(), function ($item) use ($view) { - return in_array($item['columnId'], $view->getColumnsArray()); - })); + $row->setDataArray(array_filter($row->getDataArray(), fn($item) => in_array($item['columnId'], $view->getColumnsArray()))); } return $rows; } @@ -410,9 +408,7 @@ public function findByView(int $id, View $view): LegacyRow { ->where($qb->expr()->eq('id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))); $row = $this->findEntity($qb); - $row->setDataArray(array_filter($row->getDataArray(), function ($item) use ($view) { - return in_array($item['columnId'], $view->getColumnsArray()); - })); + $row->setDataArray(array_filter($row->getDataArray(), fn($item) => in_array($item['columnId'], $view->getColumnsArray()))); return $row; } diff --git a/lib/Db/LogItem.php b/lib/Db/LogItem.php index 0a33fa652b..7140e12960 100644 --- a/lib/Db/LogItem.php +++ b/lib/Db/LogItem.php @@ -26,6 +26,7 @@ public function __construct() { $this->addType('id', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/Page.php b/lib/Db/Page.php index f56fceedae..132ac3fd50 100644 --- a/lib/Db/Page.php +++ b/lib/Db/Page.php @@ -25,6 +25,7 @@ public function __construct() { $this->addType('id', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->getId(), diff --git a/lib/Db/PageContent.php b/lib/Db/PageContent.php index a56147e54c..eda917a05c 100644 --- a/lib/Db/PageContent.php +++ b/lib/Db/PageContent.php @@ -29,6 +29,7 @@ public function __construct() { $this->addType('order', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->getId(), diff --git a/lib/Db/Row2.php b/lib/Db/Row2.php index dc24f7b335..6ca131cf73 100644 --- a/lib/Db/Row2.php +++ b/lib/Db/Row2.php @@ -127,15 +127,14 @@ public function insertOrUpdateCell(array $entry): string { * @param int[] $columns */ public function filterDataByColumns(array $columns): array { - $this->data = array_values(array_filter($this->data, function ($entry) use ($columns) { - return in_array($entry['columnId'], $columns); - })); + $this->data = array_values(array_filter($this->data, fn($entry) => in_array($entry['columnId'], $columns))); return $this->data; } /** * @psalm-return TablesRow */ + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/Row2Mapper.php b/lib/Db/Row2Mapper.php index eab663913e..6edffdf5ae 100644 --- a/lib/Db/Row2Mapper.php +++ b/lib/Db/Row2Mapper.php @@ -27,29 +27,15 @@ class Row2Mapper { use TTransactional; - - private RowSleeveMapper $rowSleeveMapper; - private ?string $userId = null; private IDBConnection $db; - private LoggerInterface $logger; - protected UserHelper $userHelper; - protected ColumnMapper $columnMapper; /* @var Column[] $columns */ private array $columns = []; /* @var Column[] $columns */ private array $allColumns = []; - private ColumnsHelper $columnsHelper; - - public function __construct(?string $userId, IDBConnection $db, LoggerInterface $logger, UserHelper $userHelper, RowSleeveMapper $rowSleeveMapper, ColumnsHelper $columnsHelper, ColumnMapper $columnMapper) { - $this->rowSleeveMapper = $rowSleeveMapper; - $this->userId = $userId; + public function __construct(private ?string $userId, IDBConnection $db, private LoggerInterface $logger, protected UserHelper $userHelper, private RowSleeveMapper $rowSleeveMapper, private ColumnsHelper $columnsHelper, protected ColumnMapper $columnMapper) { $this->db = $db; - $this->logger = $logger; - $this->userHelper = $userHelper; - $this->columnsHelper = $columnsHelper; - $this->columnMapper = $columnMapper; } /** @@ -68,7 +54,7 @@ public function delete(Row2 $row): Row2 { } catch (Throwable $e) { $this->db->rollBack(); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new Exception(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new Exception(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $row; @@ -90,11 +76,11 @@ public function find(int $id, array $columns): Row2 { } elseif (count($rows) === 0) { $e = new Exception('Wanted row not found.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } else { $e = new Exception('Too many results for one wanted row.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -106,8 +92,8 @@ public function findNextId(int $offsetId = -1): ?int { $rowSleeve = $this->rowSleeveMapper->findNext($offsetId); } catch (MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); - } catch (DoesNotExistException $e) { + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + } catch (DoesNotExistException) { return null; } return $rowSleeve->getId(); @@ -152,7 +138,7 @@ private function getWantedRowIds(string $userId, int $tableId, ?array $filter = $result = $this->db->executeQuery($qb->getSQL(), $qb->getParameters(), $qb->getParameterTypes()); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage(), ); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage(), ); } return array_map(fn (array $item) => $item['id'], $result->fetchAll()); @@ -225,23 +211,23 @@ private function getRows(array $rowIds, array $columnIds, array $sort = []): arr $result = $qb->executeQuery(); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage(), ); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage(), ); } try { - $sleeves = $this->rowSleeveMapper->findMultiple($rowIds, function (IQueryBuilder $qb, string $sleevesAlias) use ($sort) { + $sleeves = $this->rowSleeveMapper->findMultiple($rowIds, function (IQueryBuilder $qb, string $sleevesAlias) use ($sort): void { $this->addSortQueryForMultipleSleeveFinder($qb, $sleevesAlias, $sort); }); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $columnTypes = $this->columnMapper->getColumnTypes($columnIds); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $this->parseEntities($result, $sleeves, $columnTypes); @@ -319,7 +305,7 @@ private function addSortQueryForMultipleSleeveFinder(IQueryBuilder $qb, string $ private function replacePlaceholderValues(array &$filters, string $userId): void { foreach ($filters as &$filterGroup) { foreach ($filterGroup as &$filter) { - if (substr($filter['value'], 0, 1) === '@') { + if (str_starts_with($filter['value'], '@')) { $filter['value'] = $this->columnsHelper->resolveSearchValue($filter['value'], $userId); } } @@ -369,7 +355,7 @@ private function getFilter(IQueryBuilder &$qb, array $filterGroup): array { } else { $e = new Exception('Needed column (' . $columnId . ') not found.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $filterExpressions[] = $sql; } @@ -505,28 +491,18 @@ private function getMetaFilterExpression(IQueryBuilder $qb, int $columnId, strin * @throws InternalError */ private function getSqlOperator(string $operator, IQueryBuilder $qb, string $columnName, $value, $paramType): string { - switch ($operator) { - case 'begins-with': - return $qb->expr()->like($columnName, $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($value), $paramType)); - case 'ends-with': - return $qb->expr()->like($columnName, $qb->createNamedParameter($this->db->escapeLikeParameter($value) . '%', $paramType)); - case 'contains': - return $qb->expr()->like($columnName, $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%', $paramType)); - case 'is-equal': - return $qb->expr()->eq($columnName, $qb->createNamedParameter($value, $paramType)); - case 'is-greater-than': - return $qb->expr()->gt($columnName, $qb->createNamedParameter($value, $paramType)); - case 'is-greater-than-or-equal': - return $qb->expr()->gte($columnName, $qb->createNamedParameter($value, $paramType)); - case 'is-lower-than': - return $qb->expr()->lt($columnName, $qb->createNamedParameter($value, $paramType)); - case 'is-lower-than-or-equal': - return $qb->expr()->lte($columnName, $qb->createNamedParameter($value, $paramType)); - case 'is-empty': - return $qb->expr()->isNull($columnName); - default: - throw new InternalError('Operator ' . $operator . ' is not supported.'); - } + return match ($operator) { + 'begins-with' => $qb->expr()->like($columnName, $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($value), $paramType)), + 'ends-with' => $qb->expr()->like($columnName, $qb->createNamedParameter($this->db->escapeLikeParameter($value) . '%', $paramType)), + 'contains' => $qb->expr()->like($columnName, $qb->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%', $paramType)), + 'is-equal' => $qb->expr()->eq($columnName, $qb->createNamedParameter($value, $paramType)), + 'is-greater-than' => $qb->expr()->gt($columnName, $qb->createNamedParameter($value, $paramType)), + 'is-greater-than-or-equal' => $qb->expr()->gte($columnName, $qb->createNamedParameter($value, $paramType)), + 'is-lower-than' => $qb->expr()->lt($columnName, $qb->createNamedParameter($value, $paramType)), + 'is-lower-than-or-equal' => $qb->expr()->lte($columnName, $qb->createNamedParameter($value, $paramType)), + 'is-empty' => $qb->expr()->isNull($columnName), + default => throw new InternalError('Operator ' . $operator . ' is not supported.'), + }; } /** @@ -632,7 +608,7 @@ public function insert(Row2 $row, array $columns): Row2 { */ public function update(Row2 $row, array $columns): Row2 { if (!$columns) { - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': columns are missing'); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': columns are missing'); } $this->setColumns($columns); @@ -648,7 +624,7 @@ public function update(Row2 $row, array $columns): Row2 { $this->rowSleeveMapper->update($sleeve); } catch (DoesNotExistException|MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // write all changed cells to its db-table @@ -712,7 +688,7 @@ private function insertCell(int $rowId, int $columnId, $value, ?string $lastEdit if (!isset($this->columns[$columnId])) { $e = new Exception('Can not insert cell, because the given column-id is not known'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } @@ -769,7 +745,7 @@ private function insertOrUpdateCell(int $rowId, int $columnId, $value): void { $cellMapper = $this->getCellMapper($this->columns[$columnId]); try { if ($cellMapper->hasMultipleValues()) { - $this->atomic(function () use ($cellMapper, $rowId, $columnId, $value) { + $this->atomic(function () use ($cellMapper, $rowId, $columnId, $value): void { $cellMapper->deleteAllForRow($rowId); $this->insertCell($rowId, $columnId, $value); }, $this->db); @@ -781,7 +757,7 @@ private function insertOrUpdateCell(int $rowId, int $columnId, $value): void { $this->insertCell($rowId, $columnId, $value); } catch (MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -811,7 +787,7 @@ private function getCellMapperFromType(string $columnType): RowCellMapperSuper { return Server::get($cellMapperClassName); } catch (NotFoundExceptionInterface|ContainerExceptionInterface $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -830,7 +806,7 @@ public function deleteDataForColumn(Column $column): void { $this->getCellMapper($column)->deleteAllForColumn($column->getId()); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -879,23 +855,14 @@ public function countRowsForView(View $view, string $userId, array $columns): in private function getFormattedDefaultValue(Column $column) { $defaultValue = null; - switch ($column->getType()) { - case Column::TYPE_SELECTION: - $defaultValue = $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getSelectionDefault()); - break; - case Column::TYPE_DATETIME: - $defaultValue = $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getDatetimeDefault()); - break; - case Column::TYPE_NUMBER: - $defaultValue = $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getNumberDefault()); - break; - case Column::TYPE_TEXT: - $defaultValue = $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getTextDefault()); - break; - case Column::TYPE_USERGROUP: - $defaultValue = $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getUsergroupDefault()); - break; - } + $defaultValue = match ($column->getType()) { + Column::TYPE_SELECTION => $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getSelectionDefault()), + Column::TYPE_DATETIME => $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getDatetimeDefault()), + Column::TYPE_NUMBER => $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getNumberDefault()), + Column::TYPE_TEXT => $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getTextDefault()), + Column::TYPE_USERGROUP => $this->getCellMapper($column)->filterValueToQueryParam($column, $column->getUsergroupDefault()), + default => $defaultValue, + }; return $defaultValue; } } diff --git a/lib/Db/RowCellDatetime.php b/lib/Db/RowCellDatetime.php index 8843d3c404..99b970d33d 100644 --- a/lib/Db/RowCellDatetime.php +++ b/lib/Db/RowCellDatetime.php @@ -12,6 +12,7 @@ class RowCellDatetime extends RowCellSuper { protected ?string $value = null; protected ?int $valueType = null; + #[\Override] public function jsonSerialize(): array { return parent::jsonSerializePreparation($this->value, $this->valueType); } diff --git a/lib/Db/RowCellNumber.php b/lib/Db/RowCellNumber.php index 474f4519b3..453dead782 100644 --- a/lib/Db/RowCellNumber.php +++ b/lib/Db/RowCellNumber.php @@ -12,6 +12,7 @@ class RowCellNumber extends RowCellSuper { protected ?float $value = null; protected ?int $valueType = null; + #[\Override] public function jsonSerialize(): array { return parent::jsonSerializePreparation($this->value, $this->valueType); } diff --git a/lib/Db/RowCellNumberMapper.php b/lib/Db/RowCellNumberMapper.php index 45a02531f8..db00cc210c 100644 --- a/lib/Db/RowCellNumberMapper.php +++ b/lib/Db/RowCellNumberMapper.php @@ -18,6 +18,7 @@ public function __construct(IDBConnection $db) { parent::__construct($db, $this->table, RowCellNumber::class); } + #[\Override] public function formatEntity(Column $column, RowCellSuper $cell) { $value = $cell->getValue(); if ($value === '') { @@ -31,6 +32,7 @@ public function formatEntity(Column $column, RowCellSuper $cell) { } } + #[\Override] public function applyDataToEntity(Column $column, RowCellSuper $cell, $data): void { if (!is_numeric($data)) { $cell->setValueWrapper(null); @@ -38,6 +40,7 @@ public function applyDataToEntity(Column $column, RowCellSuper $cell, $data): vo $cell->setValueWrapper((float)$data); } + #[\Override] public function getDbParamType() { // seems to be a string for float/double values return IQueryBuilder::PARAM_STR; diff --git a/lib/Db/RowCellSelection.php b/lib/Db/RowCellSelection.php index b21ca4d0db..d63adb16b3 100644 --- a/lib/Db/RowCellSelection.php +++ b/lib/Db/RowCellSelection.php @@ -12,6 +12,7 @@ class RowCellSelection extends RowCellSuper { protected ?string $value = null; protected ?int $valueType = null; + #[\Override] public function jsonSerialize(): array { return parent::jsonSerializePreparation($this->value, $this->valueType); } diff --git a/lib/Db/RowCellSelectionMapper.php b/lib/Db/RowCellSelectionMapper.php index 53021e876f..ccaac1f97a 100644 --- a/lib/Db/RowCellSelectionMapper.php +++ b/lib/Db/RowCellSelectionMapper.php @@ -19,14 +19,17 @@ public function __construct(IDBConnection $db) { parent::__construct($db, $this->table, RowCellSelection::class); } + #[\Override] public function filterValueToQueryParam(Column $column, mixed $value): mixed { return $this->valueToJsonDbValue($column, $value); } + #[\Override] public function applyDataToEntity(Column $column, RowCellSuper $cell, $data): void { $cell->setValue($this->valueToJsonDbValue($column, $data)); } + #[\Override] public function formatEntity(Column $column, RowCellSuper $cell) { return json_decode($cell->getValue()); } diff --git a/lib/Db/RowCellText.php b/lib/Db/RowCellText.php index 6b5170691b..0abfd1f0ce 100644 --- a/lib/Db/RowCellText.php +++ b/lib/Db/RowCellText.php @@ -12,6 +12,7 @@ class RowCellText extends RowCellSuper { protected ?string $value = null; protected ?int $valueType = null; + #[\Override] public function jsonSerialize(): array { return parent::jsonSerializePreparation($this->value, $this->valueType); } diff --git a/lib/Db/RowCellUsergroup.php b/lib/Db/RowCellUsergroup.php index 4e9fb7ebef..0c6a41b2c8 100644 --- a/lib/Db/RowCellUsergroup.php +++ b/lib/Db/RowCellUsergroup.php @@ -16,10 +16,12 @@ class RowCellUsergroup extends RowCellSuper { protected ?string $value = null; protected ?int $valueType = null; + #[\Override] public function jsonSerialize(): array { return parent::jsonSerializePreparation($this->value, $this->valueType); } + #[\Override] public function setValueWrapper($value) { $this->setValue((string)$value['id']); $this->setValueType((int)$value['type']); diff --git a/lib/Db/RowCellUsergroupMapper.php b/lib/Db/RowCellUsergroupMapper.php index 956b1b78e9..da5bcc87b2 100644 --- a/lib/Db/RowCellUsergroupMapper.php +++ b/lib/Db/RowCellUsergroupMapper.php @@ -21,10 +21,12 @@ public function __construct( parent::__construct($db, $this->table, RowCellUsergroup::class); } + #[\Override] public function filterValueToQueryParam(Column $column, mixed $value): mixed { return $value; } + #[\Override] public function applyDataToEntity(Column $column, RowCellSuper $cell, $data): void { if (!RowCellUsergroup::verifyUserGroupArray($data)) { throw new \InvalidArgumentException('Provided value is not valid user group data'); @@ -33,6 +35,7 @@ public function applyDataToEntity(Column $column, RowCellSuper $cell, $data): vo $cell->setValueWrapper($data); } + #[\Override] public function formatEntity(Column $column, RowCellSuper $cell) { $displayName = $cell->getValueType() === 0 ? ($this->userManager->getDisplayName($cell->getValue()) ?? $cell->getValue()) : $cell->getValue(); return [ @@ -42,6 +45,7 @@ public function formatEntity(Column $column, RowCellSuper $cell) { ]; } + #[\Override] public function hasMultipleValues(): bool { return true; } diff --git a/lib/Db/RowSleeve.php b/lib/Db/RowSleeve.php index 3c765e8173..49900f6250 100644 --- a/lib/Db/RowSleeve.php +++ b/lib/Db/RowSleeve.php @@ -36,6 +36,7 @@ public function __construct() { $this->addType('tableId', 'integer'); } + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/RowSleeveMapper.php b/lib/Db/RowSleeveMapper.php index ce023d88a3..68e9cb007c 100644 --- a/lib/Db/RowSleeveMapper.php +++ b/lib/Db/RowSleeveMapper.php @@ -18,11 +18,9 @@ /** @template-extends QBMapper */ class RowSleeveMapper extends QBMapper { protected string $table = 'tables_row_sleeves'; - protected LoggerInterface $logger; - public function __construct(IDBConnection $db, LoggerInterface $logger) { + public function __construct(IDBConnection $db, protected LoggerInterface $logger) { parent::__construct($db, $this->table, RowSleeve::class); - $this->logger = $logger; } /** diff --git a/lib/Db/Share.php b/lib/Db/Share.php index 7109cc9fc9..3582e267bc 100644 --- a/lib/Db/Share.php +++ b/lib/Db/Share.php @@ -75,6 +75,7 @@ public function __construct() { /** * @psalm-return TablesShare */ + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/ShareMapper.php b/lib/Db/ShareMapper.php index 5dc3596031..3e72c8de8c 100644 --- a/lib/Db/ShareMapper.php +++ b/lib/Db/ShareMapper.php @@ -18,11 +18,9 @@ /** @template-extends QBMapper */ class ShareMapper extends QBMapper { protected string $table = 'tables_shares'; - protected LoggerInterface $logger; - public function __construct(LoggerInterface $logger, IDBConnection $db) { + public function __construct(protected LoggerInterface $logger, IDBConnection $db) { parent::__construct($db, $this->table, Share::class); - $this->logger = $logger; } /** diff --git a/lib/Db/Table.php b/lib/Db/Table.php index 64bf3f3418..0bcee46105 100644 --- a/lib/Db/Table.php +++ b/lib/Db/Table.php @@ -85,6 +85,7 @@ public function __construct() { /** * @psalm-return TablesTable */ + #[\Override] public function jsonSerialize(): array { return [ 'id' => $this->id, diff --git a/lib/Db/TableMapper.php b/lib/Db/TableMapper.php index f78e5e4c3e..74e58abc46 100644 --- a/lib/Db/TableMapper.php +++ b/lib/Db/TableMapper.php @@ -18,11 +18,9 @@ /** @template-extends QBMapper */ class TableMapper extends QBMapper { protected string $table = 'tables_tables'; - private UserHelper $userHelper; - public function __construct(IDBConnection $db, UserHelper $userHelper) { + public function __construct(IDBConnection $db, private UserHelper $userHelper) { parent::__construct($db, $this->table, Table::class); - $this->userHelper = $userHelper; } /** diff --git a/lib/Db/View.php b/lib/Db/View.php index 6dc436d05e..063f22e7e3 100644 --- a/lib/Db/View.php +++ b/lib/Db/View.php @@ -104,13 +104,9 @@ public function getFilterArray():array { // a filter(group) was stored with a not-selected column - it may break impressively. // filter them out now until we have a permanent fix foreach ($filters as &$filterGroups) { - $filterGroups = array_filter($filterGroups, function (array $item) { - return $item['columnId'] !== null; - }); + $filterGroups = array_filter($filterGroups, fn(array $item) => $item['columnId'] !== null); } - return array_filter($filters, function (array $item) { - return !empty($item); - }); + return array_filter($filters, fn(array $item) => !empty($item)); } private function getArray(?string $json): array { @@ -148,6 +144,7 @@ public function setOwnership(string $ownership): void { /** * @psalm-return TablesView */ + #[\Override] public function jsonSerialize(): array { $serialisedJson = [ 'id' => $this->id, diff --git a/lib/Helper/ColumnsHelper.php b/lib/Helper/ColumnsHelper.php index 5abdea7ea0..5fe604f606 100644 --- a/lib/Helper/ColumnsHelper.php +++ b/lib/Helper/ColumnsHelper.php @@ -39,15 +39,15 @@ public function resolveSearchValue(string $placeholder, string $userId): string case 'stars-3': return '3'; case 'stars-4': return '4'; case 'stars-5': return '5'; - case 'datetime-date-today': return date('Y-m-d') ? date('Y-m-d') : ''; - case 'datetime-date-start-of-year': return date('Y-01-01') ? date('Y-01-01') : ''; - case 'datetime-date-start-of-month': return date('Y-m-01') ? date('Y-m-01') : ''; + case 'datetime-date-today': return date('Y-m-d') ?: ''; + case 'datetime-date-start-of-year': return date('Y-01-01') ?: ''; + case 'datetime-date-start-of-month': return date('Y-m-01') ?: ''; case 'datetime-date-start-of-week': $day = date('w'); $result = date('Y-m-d', strtotime('-' . $day . ' days')); return $result ?: ''; case 'datetime-time-now': return date('H:i'); - case 'datetime-now': return date('Y-m-d H:i') ? date('Y-m-d H:i') : ''; + case 'datetime-now': return date('Y-m-d H:i') ?: ''; default: return $placeholder; } } diff --git a/lib/Helper/GroupHelper.php b/lib/Helper/GroupHelper.php index 29d1b9720b..0ffecaa43c 100644 --- a/lib/Helper/GroupHelper.php +++ b/lib/Helper/GroupHelper.php @@ -11,11 +11,9 @@ use Psr\Log\LoggerInterface; class GroupHelper { - private LoggerInterface $logger; private IGroupManager $groupManager; - public function __construct(LoggerInterface $logger, IGroupManager $groupManager) { - $this->logger = $logger; + public function __construct(private LoggerInterface $logger, IGroupManager $groupManager) { $this->groupManager = $groupManager; } diff --git a/lib/Helper/UserHelper.php b/lib/Helper/UserHelper.php index ca7aa7f510..ab3e4e3692 100644 --- a/lib/Helper/UserHelper.php +++ b/lib/Helper/UserHelper.php @@ -17,21 +17,18 @@ class UserHelper { private IUserManager $userManager; - private LoggerInterface $logger; - private IGroupManager $groupManager; - public function __construct(IUserManager $userManager, LoggerInterface $logger, IGroupManager $groupManager) { + public function __construct(IUserManager $userManager, private LoggerInterface $logger, IGroupManager $groupManager) { $this->userManager = $userManager; - $this->logger = $logger; $this->groupManager = $groupManager; } public function getUserDisplayName(string $userId): string { try { $user = $this->getUser($userId); - return $user->getDisplayName() ? $user->getDisplayName() : $userId; - } catch (InternalError $e) { + return $user->getDisplayName() ?: $userId; + } catch (InternalError) { $this->logger->info('no user given, will return userId'); return $userId; } @@ -65,7 +62,7 @@ public function getGroupsForUser(string $userId): array { public function getGroupIdsForUser(string $userId): ?array { try { $userGroups = $this->getGroupsForUser($userId); - } catch (InternalError $e) { + } catch (InternalError) { return null; } diff --git a/lib/Listener/AddMissingIndicesListener.php b/lib/Listener/AddMissingIndicesListener.php index 45dd95ae5d..59b9de4e5f 100644 --- a/lib/Listener/AddMissingIndicesListener.php +++ b/lib/Listener/AddMissingIndicesListener.php @@ -15,6 +15,7 @@ * @template-implements IEventListener */ final class AddMissingIndicesListener implements IEventListener { + #[\Override] public function handle(Event $event): void { if (!$event instanceof AddMissingIndicesEvent) { return; diff --git a/lib/Listener/AnalyticsDatasourceListener.php b/lib/Listener/AnalyticsDatasourceListener.php index cccf725b60..a882707cfc 100644 --- a/lib/Listener/AnalyticsDatasourceListener.php +++ b/lib/Listener/AnalyticsDatasourceListener.php @@ -16,6 +16,7 @@ * @template-implements IEventListener */ class AnalyticsDatasourceListener implements IEventListener { + #[\Override] public function handle(Event $event): void { if (!($event instanceof DatasourceEvent)) { // Unrelated diff --git a/lib/Listener/BeforeTemplateRenderedListener.php b/lib/Listener/BeforeTemplateRenderedListener.php index 7bce96c24e..cda3d92ff7 100644 --- a/lib/Listener/BeforeTemplateRenderedListener.php +++ b/lib/Listener/BeforeTemplateRenderedListener.php @@ -26,6 +26,7 @@ public function __construct( /** * @inheritDoc */ + #[\Override] public function handle(Event $event): void { if (!$event instanceof BeforeTemplateRenderedEvent) { return; diff --git a/lib/Listener/LoadAdditionalListener.php b/lib/Listener/LoadAdditionalListener.php index d7261388ee..e33cbbcfcb 100644 --- a/lib/Listener/LoadAdditionalListener.php +++ b/lib/Listener/LoadAdditionalListener.php @@ -15,6 +15,7 @@ /** @template-implements IEventListener */ class LoadAdditionalListener implements IEventListener { + #[\Override] public function handle(Event $event): void { if (!($event instanceof LoadAdditionalScriptsEvent)) { return; diff --git a/lib/Listener/TablesReferenceListener.php b/lib/Listener/TablesReferenceListener.php index a1a564a388..5c0291ad17 100644 --- a/lib/Listener/TablesReferenceListener.php +++ b/lib/Listener/TablesReferenceListener.php @@ -25,6 +25,7 @@ public function __construct( ) { } + #[\Override] public function handle(Event $event): void { if (!$event instanceof RenderReferenceEvent) { return; diff --git a/lib/Listener/UserDeletedListener.php b/lib/Listener/UserDeletedListener.php index a035deeabc..d91a9b9afc 100644 --- a/lib/Listener/UserDeletedListener.php +++ b/lib/Listener/UserDeletedListener.php @@ -18,15 +18,11 @@ * @template-implements IEventListener */ class UserDeletedListener implements IEventListener { - private TableService $tableService; - - private LoggerInterface $logger; - - public function __construct(TableService $tableService, LoggerInterface $logger) { - $this->tableService = $tableService; - $this->logger = $logger; - } + public function __construct(private TableService $tableService, private LoggerInterface $logger) + { + } + #[\Override] public function handle(Event $event): void { if (!($event instanceof BeforeUserDeletedEvent)) { return; @@ -42,7 +38,7 @@ public function handle(Event $event): void { $this->tableService->delete($table->getId(), $event->getUser()->getUID()); } $this->logger->debug('tables for the deleted user removed'); - } catch (InternalError $e) { + } catch (InternalError) { } } } diff --git a/lib/Listener/WhenRowDeletedAuditLogListener.php b/lib/Listener/WhenRowDeletedAuditLogListener.php index 1f8627d7c3..a7112c050f 100644 --- a/lib/Listener/WhenRowDeletedAuditLogListener.php +++ b/lib/Listener/WhenRowDeletedAuditLogListener.php @@ -21,6 +21,7 @@ public function __construct( ) { } + #[\Override] public function handle(Event $event): void { if (!($event instanceof RowDeletedEvent)) { return; diff --git a/lib/Listener/WhenTableDeletedAuditLogListener.php b/lib/Listener/WhenTableDeletedAuditLogListener.php index 8c58b2c614..729fe7be97 100644 --- a/lib/Listener/WhenTableDeletedAuditLogListener.php +++ b/lib/Listener/WhenTableDeletedAuditLogListener.php @@ -21,6 +21,7 @@ public function __construct( ) { } + #[\Override] public function handle(Event $event): void { if (!($event instanceof TableDeletedEvent)) { return; diff --git a/lib/Listener/WhenTableTransferredAuditLogListener.php b/lib/Listener/WhenTableTransferredAuditLogListener.php index dcf6a60519..ce0fcb8434 100644 --- a/lib/Listener/WhenTableTransferredAuditLogListener.php +++ b/lib/Listener/WhenTableTransferredAuditLogListener.php @@ -21,6 +21,7 @@ public function __construct( ) { } + #[\Override] public function handle(Event $event): void { if (!($event instanceof TableOwnershipTransferredEvent)) { return; diff --git a/lib/Listener/WhenViewDeletedAuditLogListener.php b/lib/Listener/WhenViewDeletedAuditLogListener.php index 6e0db13488..ab45995452 100644 --- a/lib/Listener/WhenViewDeletedAuditLogListener.php +++ b/lib/Listener/WhenViewDeletedAuditLogListener.php @@ -21,6 +21,7 @@ public function __construct( ) { } + #[\Override] public function handle(Event $event): void { if (!($event instanceof ViewDeletedEvent)) { return; diff --git a/lib/Middleware/Attribute/RequireEntity.php b/lib/Middleware/Attribute/RequireEntity.php new file mode 100644 index 0000000000..1ca8b2babd --- /dev/null +++ b/lib/Middleware/Attribute/RequireEntity.php @@ -0,0 +1,33 @@ +typeParam; + } + + public function getIdParam(): string { + return $this->idParam; + } + + public function getType(): ?int { + return $this->type; + } +} diff --git a/lib/Middleware/PermissionMiddleware.php b/lib/Middleware/PermissionMiddleware.php index fb4f6a1a5e..8283e56b10 100644 --- a/lib/Middleware/PermissionMiddleware.php +++ b/lib/Middleware/PermissionMiddleware.php @@ -23,20 +23,16 @@ class PermissionMiddleware extends Middleware { private IControllerMethodReflector $reflector; - private PermissionsService $permissionsService; - private ?string $userId; private IRequest $request; public function __construct( IControllerMethodReflector $reflector, - PermissionsService $permissionsService, + private PermissionsService $permissionsService, IRequest $request, - ?string $userId, + private ?string $userId, ) { $this->reflector = $reflector; - $this->permissionsService = $permissionsService; - $this->userId = $userId; $this->request = $request; } @@ -44,6 +40,7 @@ public function __construct( * @throws PermissionError * @throws InternalError */ + #[\Override] public function beforeController(Controller $controller, string $methodName) { $this->assertPermission($controller, $methodName); $this->assertCanManageNode(); @@ -229,6 +226,7 @@ protected function assertCanManageContext(): void { } } + #[\Override] public function afterException($controller, $methodName, \Exception $exception) { if ($exception instanceof PermissionError) { return new Http\DataResponse(['message' => $exception->getMessage()], Http::STATUS_FORBIDDEN); diff --git a/lib/Migration/DbRowSleeveSequence.php b/lib/Migration/DbRowSleeveSequence.php index 925f09bd9c..3d0ece70bd 100644 --- a/lib/Migration/DbRowSleeveSequence.php +++ b/lib/Migration/DbRowSleeveSequence.php @@ -26,6 +26,7 @@ public function __construct( /** * @inheritDoc */ + #[\Override] public function getName() { return 'Fixing the sequence of the row-sleeves table'; } @@ -33,6 +34,7 @@ public function getName() { /** * @inheritDoc */ + #[\Override] public function run(IOutput $output) { $legacyRowTransferRunComplete = $this->config->getAppValue('tables', 'legacyRowTransferRunComplete', 'false') === 'true'; $sequenceRepairComplete = $this->config->getAppValue('tables', 'sequenceRepairComplete', 'false') === 'true'; @@ -56,9 +58,7 @@ public function run(IOutput $output) { $schema = $this->db->createSchema(); $sequences = $schema->getSequences(); - $candidates = array_filter($sequences, function (string $sequenceName): bool { - return str_contains($sequenceName, 'tables_row_sleeves'); - }, ARRAY_FILTER_USE_KEY); + $candidates = array_filter($sequences, fn(string $sequenceName): bool => str_contains($sequenceName, 'tables_row_sleeves'), ARRAY_FILTER_USE_KEY); if (count($candidates) > 1) { $this->logger->error('Unexpected number of sequences, aborting.', [ diff --git a/lib/Migration/FixContextsDefaults.php b/lib/Migration/FixContextsDefaults.php index 1b0d477e26..3ffc9f5eb6 100644 --- a/lib/Migration/FixContextsDefaults.php +++ b/lib/Migration/FixContextsDefaults.php @@ -27,6 +27,7 @@ public function __construct( /** * @inheritDoc */ + #[\Override] public function getName() { return 'Fix navigation bar default of existing contexts to show for all'; } @@ -34,6 +35,7 @@ public function getName() { /** * @inheritDoc */ + #[\Override] public function run(IOutput $output) { $appVersion = $this->config->getAppValue(Application::APP_ID, 'installed_version', '0.0'); if (\version_compare($appVersion, '0.8.0-beta.1', '>')) { diff --git a/lib/Migration/NewDbStructureRepairStep.php b/lib/Migration/NewDbStructureRepairStep.php index 64ac8219dd..fc49b272bd 100644 --- a/lib/Migration/NewDbStructureRepairStep.php +++ b/lib/Migration/NewDbStructureRepairStep.php @@ -23,25 +23,16 @@ class NewDbStructureRepairStep implements IRepairStep { - protected LoggerInterface $logger; - protected TableService $tableService; - protected LegacyRowMapper $legacyRowMapper; - protected Row2Mapper $rowMapper; - protected ColumnService $columnService; protected IConfig $config; - public function __construct(LoggerInterface $logger, TableService $tableService, ColumnService $columnService, LegacyRowMapper $legacyRowMapper, Row2Mapper $rowMapper, IConfig $config) { - $this->logger = $logger; - $this->tableService = $tableService; - $this->columnService = $columnService; - $this->legacyRowMapper = $legacyRowMapper; - $this->rowMapper = $rowMapper; + public function __construct(protected LoggerInterface $logger, protected TableService $tableService, protected ColumnService $columnService, protected LegacyRowMapper $legacyRowMapper, protected Row2Mapper $rowMapper, IConfig $config) { $this->config = $config; } /** * Returns the step's name */ + #[\Override] public function getName(): string { return 'Copy the data into the new db structure'; } @@ -49,6 +40,7 @@ public function getName(): string { /** * @param IOutput $output */ + #[\Override] public function run(IOutput $output) { $legacyRowTransferRunComplete = $this->config->getAppValue('tables', 'legacyRowTransferRunComplete', 'false'); @@ -60,7 +52,7 @@ public function run(IOutput $output) { try { $tables = $this->tableService->findAll('', true, true, false); $output->info('Found ' . count($tables) . ' table(s)'); - } catch (InternalError $e) { + } catch (InternalError) { $output->warning('Error while fetching tables. Will aboard.'); return; } diff --git a/lib/Migration/Version000000Date20210921000000.php b/lib/Migration/Version000000Date20210921000000.php index 4dc55a254e..b776c9deb9 100644 --- a/lib/Migration/Version000000Date20210921000000.php +++ b/lib/Migration/Version000000Date20210921000000.php @@ -24,6 +24,7 @@ class Version000000Date20210921000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws SchemaException */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000200Date20220428000000.php b/lib/Migration/Version000200Date20220428000000.php index 66f0da9bfd..bbfa3134d3 100644 --- a/lib/Migration/Version000200Date20220428000000.php +++ b/lib/Migration/Version000200Date20220428000000.php @@ -24,6 +24,7 @@ class Version000200Date20220428000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws SchemaException */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000203Date20230124000000.php b/lib/Migration/Version000203Date20230124000000.php index bc27c20711..b7b93944df 100644 --- a/lib/Migration/Version000203Date20230124000000.php +++ b/lib/Migration/Version000203Date20230124000000.php @@ -24,6 +24,7 @@ class Version000203Date20230124000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws SchemaException */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000400Date20230406000000.php b/lib/Migration/Version000400Date20230406000000.php index d6e84990b8..c5c85b4859 100644 --- a/lib/Migration/Version000400Date20230406000000.php +++ b/lib/Migration/Version000400Date20230406000000.php @@ -26,6 +26,7 @@ class Version000400Date20230406000000 extends SimpleMigrationStep { * @throws SchemaException * @throws Exception */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000600Date20230703000000.php b/lib/Migration/Version000600Date20230703000000.php index 6a15cb5ef6..a5e3293240 100644 --- a/lib/Migration/Version000600Date20230703000000.php +++ b/lib/Migration/Version000600Date20230703000000.php @@ -26,6 +26,7 @@ class Version000600Date20230703000000 extends SimpleMigrationStep { * @throws SchemaException * @throws Exception */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000700Date20230916000000.php b/lib/Migration/Version000700Date20230916000000.php index 8173ff70bc..e19b043e09 100644 --- a/lib/Migration/Version000700Date20230916000000.php +++ b/lib/Migration/Version000700Date20230916000000.php @@ -50,6 +50,7 @@ class Version000700Date20230916000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws Exception */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000800Date20240213123743.php b/lib/Migration/Version000800Date20240213123743.php index d265cc873b..fb187b6647 100644 --- a/lib/Migration/Version000800Date20240213123743.php +++ b/lib/Migration/Version000800Date20240213123743.php @@ -24,6 +24,7 @@ class Version000800Date20240213123743 extends SimpleMigrationStep { /** * @throws SchemaException */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { // Introduction of Contexts tables diff --git a/lib/Migration/Version000800Date20240222000000.php b/lib/Migration/Version000800Date20240222000000.php index a6e9546b1b..73b963092f 100644 --- a/lib/Migration/Version000800Date20240222000000.php +++ b/lib/Migration/Version000800Date20240222000000.php @@ -24,6 +24,7 @@ class Version000800Date20240222000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws Exception */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000800Date20240712000000.php b/lib/Migration/Version000800Date20240712000000.php index b3c4d8e2d2..f36e5b6185 100644 --- a/lib/Migration/Version000800Date20240712000000.php +++ b/lib/Migration/Version000800Date20240712000000.php @@ -16,6 +16,7 @@ use OCP\Migration\SimpleMigrationStep; class Version000800Date20240712000000 extends SimpleMigrationStep { + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000800Date20240828000000.php b/lib/Migration/Version000800Date20240828000000.php index 96ac21abc0..e586eeb5c3 100644 --- a/lib/Migration/Version000800Date20240828000000.php +++ b/lib/Migration/Version000800Date20240828000000.php @@ -24,6 +24,7 @@ class Version000800Date20240828000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws Exception */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Migration/Version000900Date20240314000000.php b/lib/Migration/Version000900Date20240314000000.php index 3929cc5197..52065fc76d 100644 --- a/lib/Migration/Version000900Date20240314000000.php +++ b/lib/Migration/Version000900Date20240314000000.php @@ -24,6 +24,7 @@ class Version000900Date20240314000000 extends SimpleMigrationStep { * @return null|ISchemaWrapper * @throws Exception */ + #[\Override] public function changeSchema(IOutput $output, Closure $schemaClosure, array $options): ?ISchemaWrapper { /** @var ISchemaWrapper $schema */ $schema = $schemaClosure(); diff --git a/lib/Model/Permissions.php b/lib/Model/Permissions.php index 28ab53e01e..f7c8b36c2c 100644 --- a/lib/Model/Permissions.php +++ b/lib/Model/Permissions.php @@ -23,6 +23,7 @@ public function __construct( /** * @return array{read: bool, create: bool, update: bool, delete: bool, manage: bool} */ + #[\Override] public function jsonSerialize(): array { // manageTable is not serialized as it is used in the backend only return [ diff --git a/lib/Model/Public/Row.php b/lib/Model/Public/Row.php index d21db098b0..3d3d540b95 100644 --- a/lib/Model/Public/Row.php +++ b/lib/Model/Public/Row.php @@ -40,6 +40,7 @@ public function __construct( * * @since 0.8 */ + #[\Override] public function jsonSerialize(): array { return [ 'tableId' => $this->tableId, diff --git a/lib/Model/RowDataInput.php b/lib/Model/RowDataInput.php index dbef7fde0b..e3c9a46010 100644 --- a/lib/Model/RowDataInput.php +++ b/lib/Model/RowDataInput.php @@ -29,6 +29,7 @@ public function add(int $columnId, mixed $value): self { return $this; } + #[\Override] public function offsetExists(mixed $offset): bool { foreach ($this->data as $data) { if ($data[self::DATA_KEY] === $offset[self::DATA_KEY]) { @@ -38,14 +39,17 @@ public function offsetExists(mixed $offset): bool { return false; } + #[\Override] public function offsetGet(mixed $offset): mixed { return $this->data[$offset]; } + #[\Override] public function offsetSet(mixed $offset, mixed $value): void { $this->data[$offset] = $value; } + #[\Override] public function offsetUnset(mixed $offset): void { if (isset($this->data[$offset])) { unset($this->data[$offset]); @@ -61,22 +65,27 @@ public function hasColumn(int $columnId): bool { return false; } + #[\Override] public function current(): mixed { return current($this->data); } + #[\Override] public function next(): void { next($this->data); } + #[\Override] public function key(): mixed { return key($this->data); } + #[\Override] public function valid(): bool { return $this->key() !== null; } + #[\Override] public function rewind(): void { reset($this->data); } diff --git a/lib/Model/TableScheme.php b/lib/Model/TableScheme.php index ca82f71174..4f44037863 100644 --- a/lib/Model/TableScheme.php +++ b/lib/Model/TableScheme.php @@ -13,30 +13,24 @@ class TableScheme implements JsonSerializable { - protected ?string $title = null; - protected ?string $emoji = null; - - /** @var Column[]|null */ - protected ?array $columns = null; - - /** @var View[]|null */ - protected ?array $views = null; - protected ?string $description = null; - protected ?string $tablesVersion = null; - - public function __construct(string $title, string $emoji, array $columns, array $view, string $description, string $tablesVersion) { - $this->tablesVersion = $tablesVersion; - $this->title = $title; - $this->emoji = $emoji; - $this->columns = $columns; - $this->description = $description; - $this->views = $view; - } + public function __construct( + protected ?string $title, + protected ?string $emoji, + /** @var Column[]|null */ + protected ?array $columns, + /** @var View[]|null */ + protected ?array $views, + protected ?string $description, + protected ?string $tablesVersion + ) + { + } public function getTitle():string { return $this->title | ''; } + #[\Override] public function jsonSerialize(): array { return [ 'title' => $this->title ?: '', diff --git a/lib/Reference/ContentReferenceHelper.php b/lib/Reference/ContentReferenceHelper.php index ae161bf7f6..d815a52321 100644 --- a/lib/Reference/ContentReferenceHelper.php +++ b/lib/Reference/ContentReferenceHelper.php @@ -42,6 +42,7 @@ public function __construct(IURLGenerator $urlGenerator, parent::__construct($urlGenerator, $viewService, $tableService, $columnService, $rowService, $linkReferenceProvider, $userId, $config, $logger); } + #[\Override] public function matchReference(string $referenceText, ?string $type = null): bool { if ($this->userId === null) { return false; @@ -71,6 +72,7 @@ public function matchReference(string $referenceText, ?string $type = null): boo /** @psalm-suppress InvalidReturnType * @noinspection DuplicatedCode */ + #[\Override] public function resolveReference(string $referenceText): ?IReference { if ($this->matchReference($referenceText)) { if ($this->matchReference($referenceText, 'table')) { @@ -91,7 +93,7 @@ public function resolveReference(string $referenceText): ?IReference { } else { $e = new Exception('Could not map ' . $referenceText . ' to any known type.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } catch (Exception|Throwable $e) { /** @psalm-suppress InvalidReturnStatement */ @@ -113,7 +115,7 @@ public function resolveReference(string $referenceText): ?IReference { $referenceInfo['title'] = $element->getTitle(); } - $reference->setDescription($element->getOwnerDisplayName() ? $element->getOwnerDisplayName() : $element->getOwnership()); + $reference->setDescription($element->getOwnerDisplayName() ?: $element->getOwnership()); $referenceInfo['ownership'] = $element->getOwnership(); $referenceInfo['ownerDisplayName'] = $element->getOwnerDisplayName(); @@ -146,7 +148,7 @@ public function resolveReference(string $referenceText): ?IReference { } elseif ($this->matchReference($referenceText, 'view')) { $referenceInfo['rows'] = $this->rowService->findAllByView($elementId, $this->userId, 100, 0); } - } catch (InternalError|PermissionError|DoesNotExistException|MultipleObjectsReturnedException $e) { + } catch (InternalError|PermissionError|DoesNotExistException|MultipleObjectsReturnedException) { } $reference->setRichObject( diff --git a/lib/Reference/ContentReferenceProvider.php b/lib/Reference/ContentReferenceProvider.php index 7799b8a209..6b32d152d3 100644 --- a/lib/Reference/ContentReferenceProvider.php +++ b/lib/Reference/ContentReferenceProvider.php @@ -12,17 +12,16 @@ use OCP\Collaboration\Reference\IReferenceProvider; class ContentReferenceProvider implements IReferenceProvider { - private ContentReferenceHelper $referenceHelper; private ReferenceManager $referenceManager; - public function __construct(ContentReferenceHelper $referenceHelper, ReferenceManager $referenceManager) { - $this->referenceHelper = $referenceHelper; + public function __construct(private ContentReferenceHelper $referenceHelper, ReferenceManager $referenceManager) { $this->referenceManager = $referenceManager; } /** * @inheritDoc */ + #[\Override] public function matchReference(string $referenceText): bool { return $this->referenceHelper->matchReference($referenceText); } @@ -30,6 +29,7 @@ public function matchReference(string $referenceText): bool { /** * @inheritDoc */ + #[\Override] public function resolveReference(string $referenceText): ?IReference { return $this->referenceHelper->resolveReference($referenceText); } @@ -37,6 +37,7 @@ public function resolveReference(string $referenceText): ?IReference { /** * @inheritDoc */ + #[\Override] public function getCachePrefix(string $referenceId): string { return $this->referenceHelper->getCachePrefix($referenceId); } @@ -44,6 +45,7 @@ public function getCachePrefix(string $referenceId): string { /** * @inheritDoc */ + #[\Override] public function getCacheKey(string $referenceId): ?string { return $this->referenceHelper->getCacheKey($referenceId); } diff --git a/lib/Reference/ReferenceHelper.php b/lib/Reference/ReferenceHelper.php index 034af148e7..9ef1abc40b 100644 --- a/lib/Reference/ReferenceHelper.php +++ b/lib/Reference/ReferenceHelper.php @@ -27,35 +27,22 @@ class ReferenceHelper { protected const RICH_OBJECT_TYPE = Application::APP_ID . '_link'; - - protected ?string $userId; protected IURLGenerator $urlGenerator; protected LinkReferenceProvider $linkReferenceProvider; - protected ViewService $viewService; - protected TableService $tableService; - protected ColumnService $columnService; - protected RowService $rowService; protected IConfig $config; - protected LoggerInterface $logger; public function __construct(IURLGenerator $urlGenerator, - ViewService $viewService, - TableService $tableService, - ColumnService $columnService, - RowService $rowService, + protected ViewService $viewService, + protected TableService $tableService, + protected ColumnService $columnService, + protected RowService $rowService, LinkReferenceProvider $linkReferenceProvider, - ?string $userId, + protected ?string $userId, IConfig $config, - LoggerInterface $logger) { - $this->userId = $userId; + protected LoggerInterface $logger) { $this->urlGenerator = $urlGenerator; $this->linkReferenceProvider = $linkReferenceProvider; - $this->viewService = $viewService; - $this->tableService = $tableService; - $this->rowService = $rowService; - $this->columnService = $columnService; $this->config = $config; - $this->logger = $logger; } public function matchReference(string $referenceText, ?string $type = null): bool { @@ -106,7 +93,7 @@ public function resolveReference(string $referenceText): ?IReference { } else { $e = new Exception('Neither table nor view is given.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } catch (Exception|Throwable $e) { /** @psalm-suppress InvalidReturnStatement */ @@ -125,7 +112,7 @@ public function resolveReference(string $referenceText): ?IReference { $referenceInfo['title'] = $element->getTitle(); } - $reference->setDescription($element->getOwnerDisplayName() ? $element->getOwnerDisplayName() : $element->getOwnership()); + $reference->setDescription($element->getOwnerDisplayName() ?: $element->getOwnership()); $referenceInfo['ownership'] = $element->getOwnership(); $referenceInfo['ownerDisplayName'] = $element->getOwnerDisplayName(); @@ -146,7 +133,7 @@ public function resolveReference(string $referenceText): ?IReference { } elseif ($this->matchReference($referenceText, 'view')) { $referenceInfo['rows'] = $this->rowService->findAllByView($elementId, $this->userId, 10, 0); } - } catch (InternalError|PermissionError|DoesNotExistException|MultipleObjectsReturnedException $e) { + } catch (InternalError|PermissionError|DoesNotExistException|MultipleObjectsReturnedException) { // TODO add logging } @@ -221,7 +208,7 @@ private function randomString(int $length): string { $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; $randString = ''; for ($i = 0; $i < $length; $i++) { - $randString = $characters[rand(0, strlen($characters))]; + $randString = $characters[random_int(0, strlen($characters))]; } return $randString; } diff --git a/lib/Reference/ReferenceProvider.php b/lib/Reference/ReferenceProvider.php index 09ec9e9322..414e42a883 100644 --- a/lib/Reference/ReferenceProvider.php +++ b/lib/Reference/ReferenceProvider.php @@ -16,13 +16,11 @@ use OCP\IURLGenerator; class ReferenceProvider extends ADiscoverableReferenceProvider implements ISearchableReferenceProvider { - private ReferenceHelper $referenceHelper; private ReferenceManager $referenceManager; private IURLGenerator $urlGenerator; private IL10N $l10n; - public function __construct(IL10N $l10n, IURLGenerator $urlGenerator, ReferenceHelper $referenceHelper, ReferenceManager $referenceManager) { - $this->referenceHelper = $referenceHelper; + public function __construct(IL10N $l10n, IURLGenerator $urlGenerator, private ReferenceHelper $referenceHelper, ReferenceManager $referenceManager) { $this->referenceManager = $referenceManager; $this->urlGenerator = $urlGenerator; $this->l10n = $l10n; @@ -31,6 +29,7 @@ public function __construct(IL10N $l10n, IURLGenerator $urlGenerator, ReferenceH /** * @inheritDoc */ + #[\Override] public function getId(): string { return Application::APP_ID . '-ref-tables'; } @@ -38,6 +37,7 @@ public function getId(): string { /** * @inheritDoc */ + #[\Override] public function getTitle(): string { return $this->l10n->t('Nextcloud tables'); } @@ -45,6 +45,7 @@ public function getTitle(): string { /** * @inheritDoc */ + #[\Override] public function getOrder(): int { return 10; } @@ -52,6 +53,7 @@ public function getOrder(): int { /** * @inheritDoc */ + #[\Override] public function getIconUrl(): string { return $this->urlGenerator->getAbsoluteURL( $this->urlGenerator->imagePath(Application::APP_ID, 'app-dark.svg') @@ -61,6 +63,7 @@ public function getIconUrl(): string { /** * @inheritDoc */ + #[\Override] public function getSupportedSearchProviderIds(): array { // Not needed as we implement our own picker component // return ['tables-search-tables']; @@ -70,6 +73,7 @@ public function getSupportedSearchProviderIds(): array { /** * @inheritDoc */ + #[\Override] public function matchReference(string $referenceText): bool { return $this->referenceHelper->matchReference($referenceText); } @@ -77,6 +81,7 @@ public function matchReference(string $referenceText): bool { /** * @inheritDoc */ + #[\Override] public function resolveReference(string $referenceText): ?IReference { return $this->referenceHelper->resolveReference($referenceText); } @@ -84,6 +89,7 @@ public function resolveReference(string $referenceText): ?IReference { /** * @inheritDoc */ + #[\Override] public function getCachePrefix(string $referenceId): string { return $this->referenceHelper->getCachePrefix($referenceId); } @@ -91,6 +97,7 @@ public function getCachePrefix(string $referenceId): string { /** * @inheritDoc */ + #[\Override] public function getCacheKey(string $referenceId): ?string { return $this->referenceHelper->getCacheKey($referenceId); } diff --git a/lib/Search/SearchTablesProvider.php b/lib/Search/SearchTablesProvider.php index f5b08693a3..1d7260d7f9 100644 --- a/lib/Search/SearchTablesProvider.php +++ b/lib/Search/SearchTablesProvider.php @@ -24,25 +24,22 @@ class SearchTablesProvider implements IProvider { private IAppManager $appManager; private IL10N $l10n; - private ViewService $viewService; - private TableService $tableService; private IURLGenerator $urlGenerator; public function __construct(IAppManager $appManager, IL10N $l10n, - ViewService $viewService, - TableService $tableService, + private ViewService $viewService, + private TableService $tableService, IURLGenerator $urlGenerator) { $this->appManager = $appManager; $this->l10n = $l10n; - $this->viewService = $viewService; - $this->tableService = $tableService; $this->urlGenerator = $urlGenerator; } /** * @inheritDoc */ + #[\Override] public function getId(): string { return 'tables-search-tables'; } @@ -50,6 +47,7 @@ public function getId(): string { /** * @inheritDoc */ + #[\Override] public function getName(): string { return $this->l10n->t('Nextcloud tables'); } @@ -57,8 +55,9 @@ public function getName(): string { /** * @inheritDoc */ + #[\Override] public function getOrder(string $route, array $routeParameters): int { - if (strpos($route, Application::APP_ID . '.') === 0) { + if (str_starts_with($route, Application::APP_ID . '.')) { // Active app, prefer Tables results return -1; } @@ -69,6 +68,7 @@ public function getOrder(string $route, array $routeParameters): int { /** * @inheritDoc */ + #[\Override] public function search(IUser $user, ISearchQuery $query): SearchResult { if (!$this->appManager->isEnabledForUser(Application::APP_ID, $user)) { return SearchResult::complete($this->getName(), []); @@ -88,29 +88,25 @@ public function search(IUser $user, ISearchQuery $query): SearchResult { // look for tables $tables = $this->tableService->search($term, $limit, $offset); - $formattedTablesResults = array_map(function (Table $table) use ($appIconUrl): SearchResultEntry { - return new SearchResultEntry( + $formattedTablesResults = array_map(fn(Table $table): SearchResultEntry => new SearchResultEntry( $appIconUrl, $table->getEmoji() . ' ' . $table->getTitle(), - ($table->getOwnerDisplayName() ? $table->getOwnerDisplayName() : $table->getOwnership()) . ', ' . $this->l10n->n('%n row', '%n rows', $table->getRowsCount()) . ', ' . $this->l10n->t('table'), + ($table->getOwnerDisplayName() ?: $table->getOwnership()) . ', ' . $this->l10n->n('%n row', '%n rows', $table->getRowsCount()) . ', ' . $this->l10n->t('table'), $this->getInternalLink($table->getId(), 'table'), '', false - ); - }, $tables); + ), $tables); // look for views $views = $this->viewService->search($term, $limit, $offset); - $formattedViewResults = array_map(function (View $view) use ($viewIconUrl): SearchResultEntry { - return new SearchResultEntry( + $formattedViewResults = array_map(fn(View $view): SearchResultEntry => new SearchResultEntry( $viewIconUrl, $view->getEmoji() . ' ' . $view->getTitle(), - ($view->getOwnerDisplayName() ? $view->getOwnerDisplayName(): $view->getOwnership()) . ', ' . $this->l10n->n('%n row', '%n rows', $view->getRowsCount()) . ', ' . $this->l10n->t('table view'), + ($view->getOwnerDisplayName() ?: $view->getOwnership()) . ', ' . $this->l10n->n('%n row', '%n rows', $view->getRowsCount()) . ', ' . $this->l10n->t('table view'), $this->getInternalLink($view->getId(), 'view'), '', false - ); - }, $views); + ), $views); return SearchResult::paginated( $this->getName(), diff --git a/lib/Service/ColumnService.php b/lib/Service/ColumnService.php index ce8236e0f5..61f9eff347 100644 --- a/lib/Service/ColumnService.php +++ b/lib/Service/ColumnService.php @@ -27,36 +27,21 @@ * @psalm-import-type TablesColumn from ResponseDefinitions */ class ColumnService extends SuperService { - private ColumnMapper $mapper; - - private TableMapper $tableMapper; - - private ViewService $viewService; - - private RowService $rowService; - private IL10N $l; - private UserHelper $userHelper; - public function __construct( PermissionsService $permissionsService, LoggerInterface $logger, ?string $userId, - ColumnMapper $mapper, - TableMapper $tableMapper, - ViewService $viewService, - RowService $rowService, + private ColumnMapper $mapper, + private TableMapper $tableMapper, + private ViewService $viewService, + private RowService $rowService, IL10N $l, - UserHelper $userHelper, + private UserHelper $userHelper, ) { parent::__construct($logger, $userId, $permissionsService); - $this->mapper = $mapper; - $this->tableMapper = $tableMapper; - $this->viewService = $viewService; - $this->rowService = $rowService; $this->l = $l; - $this->userHelper = $userHelper; } @@ -70,7 +55,7 @@ public function findAllByTable(int $tableId, ?int $viewId = null, ?string $userI return $this->enhanceColumns($this->mapper->findAllByTable($tableId)); } catch (\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } else { throw new PermissionError('no read access to table id = ' . $tableId); @@ -91,13 +76,13 @@ public function findAllByView(int $viewId, ?string $userId = null): array { $view = $this->viewService->find($viewId, true, $userId); } catch (InternalError|MultipleObjectsReturnedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (PermissionError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new PermissionError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new PermissionError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $viewColumnIds = $view->getColumnsArray(); $viewColumns = $this->mapper->findAll($viewColumnIds); @@ -163,31 +148,31 @@ public function create( $view = $this->viewService->find($viewId); } catch (InternalError|MultipleObjectsReturnedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (PermissionError $e) { throw new PermissionError('Can not load given view, no permission.'); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $table = $this->tableMapper->find($view->getTableId()); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } elseif ($tableId) { try { $table = $this->tableMapper->find($tableId); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } else { throw new InternalError('Cannot create column without table or view in context'); @@ -226,7 +211,7 @@ public function create( $entity = $this->mapper->insert($item); } catch (\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if (isset($view) && $view) { // Add columns to view(s) @@ -237,12 +222,12 @@ public function create( $view = $this->viewService->find($viewId); } catch (InternalError|MultipleObjectsReturnedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); - } catch (PermissionError $e) { + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + } catch (PermissionError) { throw new PermissionError('Can not add column to view, no permission.'); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $this->viewService->update($viewId, ['columns' => json_encode(array_merge($view->getColumnsArray(), [$entity->getId()]))], $userId, true); } @@ -371,10 +356,10 @@ public function delete(int $id, bool $skipRowCleanup = false, ?string $userId = $item = $this->mapper->find($id); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -387,13 +372,13 @@ public function delete(int $id, bool $skipRowCleanup = false, ?string $userId = $this->rowService->deleteColumnDataFromRows($item); } catch (InternalError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $table = $this->tableMapper->find($item->getTableId()); } catch (DoesNotExistException|MultipleObjectsReturnedException|\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $this->viewService->deleteColumnDataFromViews($id, $table); } @@ -402,7 +387,7 @@ public function delete(int $id, bool $skipRowCleanup = false, ?string $userId = $this->mapper->delete($item); } catch (\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $this->enhanceColumn($item); } @@ -435,7 +420,7 @@ public function findOrCreateColumnsByTitleForTableAsArray(?int $tableId, ?int $v } else { $e = new Exception('Either tableId nor viewId is given.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $i = -1; diff --git a/lib/Service/ColumnTypes/DatetimeBusiness.php b/lib/Service/ColumnTypes/DatetimeBusiness.php index 2d03771b30..9c7e936a05 100644 --- a/lib/Service/ColumnTypes/DatetimeBusiness.php +++ b/lib/Service/ColumnTypes/DatetimeBusiness.php @@ -18,6 +18,7 @@ class DatetimeBusiness extends SuperBusiness implements IColumnTypeBusiness { * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { if ($value === '' || $value === null) { return ''; @@ -46,6 +47,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { if ($value === '' || $value === null) { return true; @@ -53,7 +55,7 @@ public function canBeParsed($value, ?Column $column = null): bool { try { new DateTime($value); - } catch (Exception $e) { + } catch (Exception) { return false; } return true; diff --git a/lib/Service/ColumnTypes/DatetimeDateBusiness.php b/lib/Service/ColumnTypes/DatetimeDateBusiness.php index 5cbc8abafe..a407b05707 100644 --- a/lib/Service/ColumnTypes/DatetimeDateBusiness.php +++ b/lib/Service/ColumnTypes/DatetimeDateBusiness.php @@ -16,6 +16,7 @@ class DatetimeDateBusiness extends SuperBusiness implements IColumnTypeBusiness * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { return json_encode($this->isValidDate((string)$value, 'Y-m-d') ? (string)$value : ''); } @@ -25,6 +26,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { return $this->isValidDate((string)$value, 'Y-m-d'); } diff --git a/lib/Service/ColumnTypes/DatetimeTimeBusiness.php b/lib/Service/ColumnTypes/DatetimeTimeBusiness.php index e0d41e4b52..c86564f69a 100644 --- a/lib/Service/ColumnTypes/DatetimeTimeBusiness.php +++ b/lib/Service/ColumnTypes/DatetimeTimeBusiness.php @@ -16,6 +16,7 @@ class DatetimeTimeBusiness extends SuperBusiness implements IColumnTypeBusiness * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { return json_encode($this->isValidDate((string)$value, 'H:i') ? $value : ''); } @@ -25,6 +26,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { return $this->isValidDate((string)$value, 'H:i'); } diff --git a/lib/Service/ColumnTypes/NumberBusiness.php b/lib/Service/ColumnTypes/NumberBusiness.php index 30f190521d..0ed031878a 100644 --- a/lib/Service/ColumnTypes/NumberBusiness.php +++ b/lib/Service/ColumnTypes/NumberBusiness.php @@ -16,6 +16,7 @@ class NumberBusiness extends SuperBusiness implements IColumnTypeBusiness { * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { if ($value === null) { return ''; @@ -29,6 +30,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { return !$value || floatval($value); } diff --git a/lib/Service/ColumnTypes/NumberProgressBusiness.php b/lib/Service/ColumnTypes/NumberProgressBusiness.php index e9f2337ecd..c1b2ba96c7 100644 --- a/lib/Service/ColumnTypes/NumberProgressBusiness.php +++ b/lib/Service/ColumnTypes/NumberProgressBusiness.php @@ -16,6 +16,7 @@ class NumberProgressBusiness extends SuperBusiness implements IColumnTypeBusines * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { return json_encode((int)$value); } @@ -25,6 +26,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { return !$value || ((int)$value >= 0 && (int)$value <= 100); } diff --git a/lib/Service/ColumnTypes/NumberStarsBusiness.php b/lib/Service/ColumnTypes/NumberStarsBusiness.php index a1d59443d9..709e2291d5 100644 --- a/lib/Service/ColumnTypes/NumberStarsBusiness.php +++ b/lib/Service/ColumnTypes/NumberStarsBusiness.php @@ -16,6 +16,7 @@ class NumberStarsBusiness extends SuperBusiness implements IColumnTypeBusiness { * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { return json_encode((int)$value); } @@ -25,6 +26,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { return !$value || in_array((int)$value, [0,1,2,3,4,5]); } diff --git a/lib/Service/ColumnTypes/SelectionBusiness.php b/lib/Service/ColumnTypes/SelectionBusiness.php index 7f1be94145..935412a9e6 100644 --- a/lib/Service/ColumnTypes/SelectionBusiness.php +++ b/lib/Service/ColumnTypes/SelectionBusiness.php @@ -16,9 +16,10 @@ class SelectionBusiness extends SuperBusiness implements IColumnTypeBusiness { * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { if (!$column) { - $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]); + $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . self::class, ['exception' => new \Exception()]); return ''; } @@ -46,9 +47,10 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { if (!$column) { - $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]); + $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . self::class, ['exception' => new \Exception()]); return false; } if ($value === null) { diff --git a/lib/Service/ColumnTypes/SelectionCheckBusiness.php b/lib/Service/ColumnTypes/SelectionCheckBusiness.php index 8d396071f5..e13046afa7 100644 --- a/lib/Service/ColumnTypes/SelectionCheckBusiness.php +++ b/lib/Service/ColumnTypes/SelectionCheckBusiness.php @@ -18,6 +18,7 @@ class SelectionCheckBusiness extends SuperBusiness implements IColumnTypeBusines * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { $found = in_array($value, self::PATTERN_POSITIVE, true); return json_encode($found ? 'true' : 'false'); @@ -28,6 +29,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { if ($value === null) { return true; diff --git a/lib/Service/ColumnTypes/SelectionMultiBusiness.php b/lib/Service/ColumnTypes/SelectionMultiBusiness.php index b6891531df..fa2100e345 100644 --- a/lib/Service/ColumnTypes/SelectionMultiBusiness.php +++ b/lib/Service/ColumnTypes/SelectionMultiBusiness.php @@ -18,9 +18,10 @@ class SelectionMultiBusiness extends SuperBusiness implements IColumnTypeBusines * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { if (!$column) { - $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]); + $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . self::class, ['exception' => new \Exception()]); return json_encode([]); } @@ -77,9 +78,10 @@ private function getOptionIdForValue($value): ?int { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { if (!$column) { - $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]); + $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . self::class, ['exception' => new \Exception()]); return false; } diff --git a/lib/Service/ColumnTypes/SuperBusiness.php b/lib/Service/ColumnTypes/SuperBusiness.php index c73f7af9d7..24ec90e566 100644 --- a/lib/Service/ColumnTypes/SuperBusiness.php +++ b/lib/Service/ColumnTypes/SuperBusiness.php @@ -13,11 +13,9 @@ class SuperBusiness { - protected LoggerInterface $logger; - - public function __construct(LoggerInterface $logger) { - $this->logger = $logger; - } + public function __construct(protected LoggerInterface $logger) + { + } /** * @param mixed $value diff --git a/lib/Service/ColumnTypes/TextLinkBusiness.php b/lib/Service/ColumnTypes/TextLinkBusiness.php index 29f873ae04..072378e925 100644 --- a/lib/Service/ColumnTypes/TextLinkBusiness.php +++ b/lib/Service/ColumnTypes/TextLinkBusiness.php @@ -16,6 +16,7 @@ class TextLinkBusiness extends SuperBusiness implements IColumnTypeBusiness { * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { if ($value === null) { return ''; @@ -67,6 +68,7 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { if (!$value) { return true; diff --git a/lib/Service/ColumnTypes/UsergroupBusiness.php b/lib/Service/ColumnTypes/UsergroupBusiness.php index a74c480a3c..e89bb8f810 100644 --- a/lib/Service/ColumnTypes/UsergroupBusiness.php +++ b/lib/Service/ColumnTypes/UsergroupBusiness.php @@ -23,9 +23,10 @@ class UsergroupBusiness extends SuperBusiness implements IColumnTypeBusiness { * @param Column|null $column * @return string */ + #[\Override] public function parseValue($value, ?Column $column = null): string { if (!$column) { - $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]); + $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . self::class, ['exception' => new \Exception()]); return json_encode([]); } @@ -41,9 +42,10 @@ public function parseValue($value, ?Column $column = null): string { * @param Column|null $column * @return bool */ + #[\Override] public function canBeParsed($value, ?Column $column = null): bool { if (!$column) { - $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . __CLASS__, ['exception' => new \Exception()]); + $this->logger->warning('No column given, but expected on ' . __FUNCTION__ . ' within ' . self::class, ['exception' => new \Exception()]); return false; } diff --git a/lib/Service/ContextService.php b/lib/Service/ContextService.php index e6064ed446..76c8d14bb8 100644 --- a/lib/Service/ContextService.php +++ b/lib/Service/ContextService.php @@ -131,7 +131,7 @@ public function create(string $name, string $iconName, string $description, arra $context->setOwnerType($ownerType); - $this->atomic(function () use ($context, $nodes) { + $this->atomic(function () use ($context, $nodes): void { $this->contextMapper->insert($context); if (!empty($nodes)) { @@ -271,7 +271,7 @@ public function delete(int $contextId, string $userId): Context { public function deleteNodeRel(int $nodeId, int $nodeType): void { try { $nodeRelIds = $this->contextNodeRelMapper->getRelIdsForNode($nodeId, $nodeType); - $this->atomic(function () use ($nodeRelIds) { + $this->atomic(function () use ($nodeRelIds): void { $this->pageContentMapper->deleteByNodeRelIds($nodeRelIds); $this->contextNodeRelMapper->deleteByNodeRelIds($nodeRelIds); }, $this->dbc); diff --git a/lib/Service/FavoritesService.php b/lib/Service/FavoritesService.php index 26c3e3d752..6df4cfed5e 100644 --- a/lib/Service/FavoritesService.php +++ b/lib/Service/FavoritesService.php @@ -18,19 +18,15 @@ class FavoritesService { private IDBConnection $connection; - private PermissionsService $permissionsService; - private ?string $userId; private bool $cached = false; private CappedMemoryCache $cache; public function __construct( IDBConnection $connection, - PermissionsService $permissionsService, - ?string $userId, + private PermissionsService $permissionsService, + private ?string $userId, ) { $this->connection = $connection; - $this->permissionsService = $permissionsService; - $this->userId = $userId; // The cache usage is currently not unique to the user id as only a memory cache is used $this->cache = new CappedMemoryCache(); } diff --git a/lib/Service/ImportService.php b/lib/Service/ImportService.php index 2bd0470643..8fb77deb44 100644 --- a/lib/Service/ImportService.php +++ b/lib/Service/ImportService.php @@ -38,10 +38,6 @@ class ImportService extends SuperService { private IRootFolder $rootFolder; - private ColumnService $columnService; - private RowService $rowService; - private TableService $tableService; - private ViewService $viewService; private IUserManager $userManager; private ?int $tableId = null; @@ -59,13 +55,9 @@ class ImportService extends SuperService { private array $columnsConfig = []; public function __construct(PermissionsService $permissionsService, LoggerInterface $logger, ?string $userId, - IRootFolder $rootFolder, ColumnService $columnService, RowService $rowService, TableService $tableService, ViewService $viewService, IUserManager $userManager) { + IRootFolder $rootFolder, private ColumnService $columnService, private RowService $rowService, private TableService $tableService, private ViewService $viewService, IUserManager $userManager) { parent::__construct($logger, $userId, $permissionsService); $this->rootFolder = $rootFolder; - $this->columnService = $columnService; - $this->rowService = $rowService; - $this->tableService = $tableService; - $this->viewService = $viewService; $this->userManager = $userManager; } @@ -77,7 +69,7 @@ public function previewImport(?int $tableId, ?int $viewId, string $path): array } else { $e = new \Exception('Neither tableId nor viewId is given.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $this->createUnknownColumns = false; @@ -255,12 +247,12 @@ public function import(?int $tableId, ?int $viewId, string $path, bool $createMi if (!$this->tableId && !$this->viewId) { $e = new \Exception('Neither tableId nor viewId is given.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if ($this->tableId && $this->viewId) { $e = new \LogicException('Both table ID and view ID are provided, but only one of them is allowed'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if ($this->userId === null || $this->userManager->get($this->userId) === null) { @@ -440,7 +432,7 @@ private function createRow(Row $row): void { $this->countErrors++; } catch (NotFoundError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (\Throwable $e) { $this->countErrors++; $this->logger->error('Error while creating new row for import.', ['exception' => $e]); diff --git a/lib/Service/PermissionsService.php b/lib/Service/PermissionsService.php index 6fdd88a3ce..0ec0f99bb6 100644 --- a/lib/Service/PermissionsService.php +++ b/lib/Service/PermissionsService.php @@ -29,45 +29,9 @@ use Throwable; class PermissionsService { - private TableMapper $tableMapper; - - private ViewMapper $viewMapper; - - private ShareMapper $shareMapper; - - private UserHelper $userHelper; - - private CircleHelper $circleHelper; - - protected LoggerInterface $logger; - - protected ?string $userId = null; - - protected bool $isCli = false; - - private ContextMapper $contextMapper; - - public function __construct( - LoggerInterface $logger, - ?string $userId, - TableMapper $tableMapper, - ViewMapper $viewMapper, - ShareMapper $shareMapper, - ContextMapper $contextMapper, - UserHelper $userHelper, - CircleHelper $circleHelper, - bool $isCLI, - ) { - $this->tableMapper = $tableMapper; - $this->viewMapper = $viewMapper; - $this->shareMapper = $shareMapper; - $this->userHelper = $userHelper; - $this->logger = $logger; - $this->userId = $userId; - $this->isCli = $isCLI; - $this->contextMapper = $contextMapper; - $this->circleHelper = $circleHelper; - } + public function __construct(protected LoggerInterface $logger, protected ?string $userId, private TableMapper $tableMapper, private ViewMapper $viewMapper, private ShareMapper $shareMapper, private ContextMapper $contextMapper, private UserHelper $userHelper, private CircleHelper $circleHelper, protected bool $isCli) + { + } /** @@ -84,7 +48,7 @@ public function preCheckUserId(?string $userId = null, bool $canBeEmpty = true): if ($userId === null) { $e = new \Exception(); - $error = 'PreCheck for userId failed, requested in ' . get_class($this) . '.'; + $error = 'PreCheck for userId failed, requested in ' . static::class . '.'; $this->logger->debug($error, ['exception' => new \Exception()]); throw new InternalError($error); } @@ -112,7 +76,7 @@ public function canReadTable(Table $table, ?string $userId = null): bool { public function canUpdateTable(Table $table, ?string $userId = null): bool { try { $userId = $this->preCheckUserId($userId); - } catch (InternalError $e) { + } catch (InternalError) { return false; } @@ -148,10 +112,10 @@ public function canManageNodeById(int $nodeType, int $nodeId, ?string $userId = public function canManageContextById(int $contextId, ?string $userId = null): bool { try { $context = $this->contextMapper->findById($contextId, $userId); - } catch (DoesNotExistException $e) { + } catch (DoesNotExistException) { $this->logger->warning('Context does not exist'); return false; - } catch (MultipleObjectsReturnedException $e) { + } catch (MultipleObjectsReturnedException) { $this->logger->warning('Multiple contexts found for this ID'); return false; } catch (Exception $e) { @@ -174,7 +138,7 @@ public function canAccessContextById(int $contextId, ?string $userId = null): bo try { $this->contextMapper->findById($contextId, $userId ?? $this->userId); return true; - } catch (NotFoundError $e) { + } catch (NotFoundError) { return false; } } @@ -223,10 +187,10 @@ public function canManageContext(Context $context, ?string $userId = null): bool public function canManageTableById(int $tableId, ?string $userId = null): bool { try { $table = $this->tableMapper->find($tableId); - } catch (MultipleObjectsReturnedException $e) { + } catch (MultipleObjectsReturnedException) { $this->logger->warning('Multiple tables were found for this id'); return false; - } catch (DoesNotExistException $e) { + } catch (DoesNotExistException) { $this->logger->warning('No table was found for this id'); return false; } catch (Exception $e) { @@ -239,10 +203,10 @@ public function canManageTableById(int $tableId, ?string $userId = null): bool { public function canManageViewById(int $viewId, ?string $userId = null): bool { try { $view = $this->viewMapper->find($viewId); - } catch (MultipleObjectsReturnedException $e) { + } catch (MultipleObjectsReturnedException) { $this->logger->warning('Multiple tables were found for this id'); return false; - } catch (DoesNotExistException $e) { + } catch (DoesNotExistException) { $this->logger->warning('No table was found for this id'); return false; } catch (InternalError|Exception $e) { @@ -392,7 +356,7 @@ public function canReadShare(Share $share, ?string $userId = null): bool { if ($this->canManageElementById($share->getNodeId(), $share->getNodeType())) { return true; } - } catch (InternalError $e) { + } catch (InternalError) { $this->logger->warning('Cannot check manage permissions, permission denied'); return false; } @@ -414,7 +378,7 @@ public function canReadShare(Share $share, ?string $userId = null): bool { return true; } } - } catch (InternalError $e) { + } catch (InternalError) { $this->logger->warning('Cannot get user groups, permission denied'); return false; } @@ -479,21 +443,11 @@ public function getSharedPermissionsIfSharedWithMe(int $elementId, string $eleme } if (count($shares) > 0) { - $read = array_reduce($shares, function ($carry, $share) { - return $carry || ($share->getPermissionRead()); - }, false); - $create = array_reduce($shares, function ($carry, $share) { - return $carry || ($share->getPermissionCreate()); - }, false); - $update = array_reduce($shares, function ($carry, $share) { - return $carry || ($share->getPermissionUpdate()); - }, false); - $delete = array_reduce($shares, function ($carry, $share) { - return $carry || ($share->getPermissionDelete()); - }, false); - $manage = array_reduce($shares, function ($carry, $share) { - return $carry || ($share->getPermissionManage()); - }, false); + $read = array_reduce($shares, fn($carry, $share) => $carry || ($share->getPermissionRead()), false); + $create = array_reduce($shares, fn($carry, $share) => $carry || ($share->getPermissionCreate()), false); + $update = array_reduce($shares, fn($carry, $share) => $carry || ($share->getPermissionUpdate()), false); + $delete = array_reduce($shares, fn($carry, $share) => $carry || ($share->getPermissionDelete()), false); + $manage = array_reduce($shares, fn($carry, $share) => $carry || ($share->getPermissionManage()), false); return new Permissions( read: $read || $update || $delete || $manage, @@ -644,7 +598,7 @@ private function basisCheck(Table|View|Context $element, string $nodeType, ?stri if ($permissions->manage) { return true; } - } catch (NotFoundError $e) { + } catch (NotFoundError) { return false; } return false; diff --git a/lib/Service/RowService.php b/lib/Service/RowService.php index 8f4e2c6507..0aff45fed7 100644 --- a/lib/Service/RowService.php +++ b/lib/Service/RowService.php @@ -127,17 +127,17 @@ public function find(int $id): Row2 { $columns = $this->columnMapper->findAllByTable($id); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $row = $this->row2Mapper->find($id, $columns); } catch (InternalError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage(), $e->getCode(), $e); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage(), $e->getCode(), $e); } catch (NotFoundError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -163,7 +163,7 @@ public function create(?int $tableId, ?int $viewId, RowDataInput|array $data): R if ($this->userId === null || $this->userId === '') { $e = new \Exception('No user id in context, but needed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $view = null; @@ -176,7 +176,7 @@ public function create(?int $tableId, ?int $viewId, RowDataInput|array $data): R throw new NotFoundError('Given view could not be found. More details can be found in the log.'); } catch (InternalError|Exception|MultipleObjectsReturnedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -194,7 +194,7 @@ public function create(?int $tableId, ?int $viewId, RowDataInput|array $data): R throw new NotFoundError('Given table could not be found. More details can be found in the log.'); } catch (MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -213,7 +213,7 @@ public function create(?int $tableId, ?int $viewId, RowDataInput|array $data): R $data = $this->cleanupData($data, $columns, $tableId, $viewId); $data = $this->enhanceWithViewDefaults($view, $data); - $tableId = $tableId ?? $view->getTableId(); + $tableId ??= $view->getTableId(); $row2 = new Row2(); $row2->setTableId($tableId); $row2->setData($data); @@ -225,7 +225,7 @@ public function create(?int $tableId, ?int $viewId, RowDataInput|array $data): R return $this->filterRowResult($view, $insertedRow); } catch (InternalError|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -298,7 +298,7 @@ private function cleanupData(RowDataInput $data, array $columns, ?int $tableId, if (!$column) { $e = new \Exception('No column found, can not parse value.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // parse given value to respect the column type value format @@ -355,16 +355,16 @@ private function getRowById(int $rowId): Row2 { if ($this->row2Mapper->getTableIdForRow($rowId) === null) { $e = new \Exception('No table id in row, but needed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $row = $this->row2Mapper->find($rowId, $this->columnMapper->findAllByTable($this->row2Mapper->getTableIdForRow($rowId))); $row->markAsLoaded(); } catch (InternalError|DoesNotExistException|MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (NotFoundError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $this->tmpRows[$rowId] = $row; return $row; @@ -394,10 +394,10 @@ public function updateSet( $item = $this->getRowById($id); } catch (InternalError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (NotFoundError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if ($viewId) { @@ -405,29 +405,29 @@ public function updateSet( if (!$this->permissionsService->canReadRowsByElementId($viewId, 'view', $userId)) { $e = new \Exception('Row not found.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if (!$this->permissionsService->canUpdateRowsByViewId($viewId)) { $e = new \Exception('Update row is not allowed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new PermissionError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new PermissionError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $view = $this->viewMapper->find($viewId); } catch (InternalError|MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // is row in view? if (!$this->row2Mapper->isRowInViewPresent($id, $view, $userId)) { $e = new \Exception('Update row is not allowed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // fetch all needed columns @@ -435,7 +435,7 @@ public function updateSet( $columns = $this->columnMapper->findMultiple($view->getColumnsArray()); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } else { // if no view id is set, we assume a table and take the tableId from the row @@ -445,18 +445,18 @@ public function updateSet( if (!$this->permissionsService->canReadRowsByElementId($item->getTableId(), 'table', $userId)) { $e = new \Exception('Row not found.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if (!$this->permissionsService->canUpdateRowsByTableId($tableId)) { $e = new \Exception('Update row is not allowed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new PermissionError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new PermissionError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $columns = $this->columnMapper->findAllByTable($tableId); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -497,10 +497,10 @@ public function delete(int $id, ?int $viewId, string $userId): Row2 { $item = $this->getRowById($id); } catch (InternalError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (NotFoundError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if ($viewId) { @@ -508,35 +508,35 @@ public function delete(int $id, ?int $viewId, string $userId): Row2 { if (!$this->permissionsService->canReadRowsByElementId($viewId, 'view', $userId)) { $e = new \Exception('Row not found.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if (!$this->permissionsService->canDeleteRowsByViewId($viewId)) { $e = new \Exception('Update row is not allowed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new PermissionError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new PermissionError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $view = $this->viewMapper->find($viewId); } catch (InternalError|DoesNotExistException|MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if (!$this->row2Mapper->isRowInViewPresent($id, $view, $userId)) { $e = new \Exception('Update row is not allowed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } else { // security if (!$this->permissionsService->canReadRowsByElementId($item->getTableId(), 'table', $userId)) { $e = new \Exception('Row not found.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } if (!$this->permissionsService->canDeleteRowsByTableId($item->getTableId())) { $e = new \Exception('Update row is not allowed.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new PermissionError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new PermissionError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -550,7 +550,7 @@ public function delete(int $id, ?int $viewId, string $userId): Row2 { return $this->filterRowResult($view ?? null, $deletedRow); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } diff --git a/lib/Service/SearchService.php b/lib/Service/SearchService.php index dee78cdc75..93b5a28700 100644 --- a/lib/Service/SearchService.php +++ b/lib/Service/SearchService.php @@ -14,15 +14,8 @@ class SearchService extends SuperService { - private RowService $rowService; - private TableService $tableService; - private ViewService $viewService; - - public function __construct(PermissionsService $permissionsService, LoggerInterface $logger, ?string $userId, RowService $rowService, TableService $tableService, ViewService $viewService) { + public function __construct(PermissionsService $permissionsService, LoggerInterface $logger, ?string $userId, private RowService $rowService, private TableService $tableService, private ViewService $viewService) { parent::__construct($logger, $userId, $permissionsService); - $this->rowService = $rowService; - $this->tableService = $tableService; - $this->viewService = $viewService; } public function all(string $term = ''): array { diff --git a/lib/Service/ShareService.php b/lib/Service/ShareService.php index d7ac5934f4..bddc9fbfd1 100644 --- a/lib/Service/ShareService.php +++ b/lib/Service/ShareService.php @@ -44,43 +44,22 @@ class ShareService extends SuperService { use TTransactional; - protected ShareMapper $mapper; - - protected TableMapper $tableMapper; - - protected ViewMapper $viewMapper; - - protected UserHelper $userHelper; - - protected GroupHelper $groupHelper; - - protected CircleHelper $circleHelper; - - private ContextNavigationMapper $contextNavigationMapper; - private IDBConnection $dbc; public function __construct( PermissionsService $permissionsService, LoggerInterface $logger, ?string $userId, - ShareMapper $shareMapper, - TableMapper $tableMapper, - ViewMapper $viewMapper, - UserHelper $userHelper, - GroupHelper $groupHelper, - CircleHelper $circleHelper, - ContextNavigationMapper $contextNavigationMapper, + protected ShareMapper $mapper, + protected TableMapper $tableMapper, + protected ViewMapper $viewMapper, + protected UserHelper $userHelper, + protected GroupHelper $groupHelper, + protected CircleHelper $circleHelper, + private ContextNavigationMapper $contextNavigationMapper, IDBConnection $dbc, ) { parent::__construct($logger, $userId, $permissionsService); - $this->mapper = $shareMapper; - $this->tableMapper = $tableMapper; - $this->viewMapper = $viewMapper; - $this->userHelper = $userHelper; - $this->groupHelper = $groupHelper; - $this->circleHelper = $circleHelper; - $this->contextNavigationMapper = $contextNavigationMapper; $this->dbc = $dbc; } @@ -244,7 +223,7 @@ public function create(int $nodeId, string $nodeType, string $receiver, string $ if (!$this->userId) { $e = new \Exception('No user given.'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $time = new DateTime(); $item = new Share(); @@ -299,10 +278,10 @@ public function updatePermission(int $id, string $permission, bool $value): Shar $item = $this->mapper->find($id); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -338,7 +317,7 @@ public function updatePermission(int $id, string $permission, bool $value): Shar $share = $this->mapper->update($item); } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $this->addReceiverDisplayName($share); } @@ -352,7 +331,7 @@ public function updateDisplayMode(int $shareId, int $displayMode, string $userId if ($item->getNodeType() !== 'context') { // Contexts-only property - throw new InvalidArgumentException(get_class($this) . ' - ' . __FUNCTION__ . ': nav bar display mode can be set for shared contexts only'); + throw new InvalidArgumentException(static::class . ' - ' . __FUNCTION__ . ': nav bar display mode can be set for shared contexts only'); } if ($userId === '') { @@ -370,10 +349,10 @@ public function updateDisplayMode(int $shareId, int $displayMode, string $userId return $this->contextNavigationMapper->setDisplayModeByShareId($shareId, $displayMode, $userId); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (Exception|MultipleObjectsReturnedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -389,10 +368,10 @@ public function delete(int $id): Share { $item = $this->mapper->find($id); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -407,7 +386,7 @@ public function delete(int $id): Share { } } catch (Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $this->addReceiverDisplayName($item); } @@ -448,7 +427,7 @@ private function addReceiverDisplayNames(array $shares): array { public function deleteAllForTable(Table $table):void { try { $this->mapper->deleteByNode($table->getId(), 'table'); - } catch (Exception $e) { + } catch (Exception) { $this->logger->error('something went wrong while deleting shares for table: ' . $table->getId()); } } @@ -456,14 +435,14 @@ public function deleteAllForTable(Table $table):void { public function deleteAllForView(View $view):void { try { $this->mapper->deleteByNode($view->getId(), 'view'); - } catch (Exception $e) { + } catch (Exception) { $this->logger->error('something went wrong while deleting shares for view: ' . $view->getId()); } } public function deleteAllForContext(Context $context): void { try { - $this->atomic(function () use ($context) { + $this->atomic(function () use ($context): void { $shares = $this->mapper->findAllSharesForNode('context', $context->getId(), $this->userId); foreach ($shares as $share) { /** @var Share $share */ @@ -471,7 +450,7 @@ public function deleteAllForContext(Context $context): void { } $this->mapper->deleteByNode($context->getId(), 'context'); }, $this->dbc); - } catch (Exception $e) { + } catch (Exception) { $this->logger->error('something went wrong while deleting shares for context: ' . $context->getId()); } } diff --git a/lib/Service/SuperService.php b/lib/Service/SuperService.php index d2e24a21be..492dc42ca6 100644 --- a/lib/Service/SuperService.php +++ b/lib/Service/SuperService.php @@ -10,15 +10,7 @@ use Psr\Log\LoggerInterface; class SuperService { - protected PermissionsService $permissionsService; - - protected LoggerInterface $logger; - - protected ?string $userId; - - public function __construct(LoggerInterface $logger, ?string $userId, PermissionsService $permissionsService) { - $this->permissionsService = $permissionsService; - $this->logger = $logger; - $this->userId = $userId; - } + public function __construct(protected LoggerInterface $logger, protected ?string $userId, protected PermissionsService $permissionsService) + { + } } diff --git a/lib/Service/Support/DefaultAuditLogService.php b/lib/Service/Support/DefaultAuditLogService.php index 68f43dc4bb..8e8bab820b 100644 --- a/lib/Service/Support/DefaultAuditLogService.php +++ b/lib/Service/Support/DefaultAuditLogService.php @@ -16,6 +16,7 @@ public function __construct( ) { } + #[\Override] public function log(string $message, array $context): void { $auditEvent = new CriticalActionPerformedEvent($message, $context); diff --git a/lib/Service/TableService.php b/lib/Service/TableService.php index 76ed465871..8117837b92 100644 --- a/lib/Service/TableService.php +++ b/lib/Service/TableService.php @@ -92,7 +92,7 @@ public function findAll(?string $userId = null, bool $skipTableEnhancement = fal $allTables[$tutorialTable->getId()] = $tutorialTable; } catch (InternalError|PermissionError|DoesNotExistException|MultipleObjectsReturnedException|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -167,7 +167,7 @@ private function enhanceTable(Table $table, string $userId): void { try { $shares = $this->shareService->findAll('table', $table->getId()); $table->setHasShares(count($shares) !== 0); - } catch (InternalError $e) { + } catch (InternalError) { } } @@ -181,7 +181,7 @@ private function enhanceTable(Table $table, string $userId): void { // add the column count try { $table->setColumnsCount($this->columnService->getColumnsCount($table->getId())); - } catch (PermissionError $e) { + } catch (PermissionError) { $table->setColumnsCount(0); } @@ -192,11 +192,11 @@ private function enhanceTable(Table $table, string $userId): void { $permissions = $this->shareService->getSharedPermissionsIfSharedWithMe($table->getId(), 'table', $userId); $table->setIsShared(true); $table->setOnSharePermissions($permissions); - } catch (NotFoundError $e) { + } catch (NotFoundError) { try { $table->setOnSharePermissions($this->permissionsService->getPermissionArrayForNodeFromContexts($table->getId(), 'table', $userId)); $table->setIsShared(true); - } catch (NotFoundError $e) { + } catch (NotFoundError) { } } @@ -284,7 +284,7 @@ public function create(string $title, string $template, ?string $emoji, ?string $table = $this->tableTemplateService->makeTemplate($newTable, $template); } catch (InternalError|PermissionError|DoesNotExistException|MultipleObjectsReturnedException|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } else { $table = $this->addOwnerDisplayName($newTable); @@ -294,7 +294,7 @@ public function create(string $title, string $template, ?string $emoji, ?string $this->enhanceTable($table, $userId); } catch (InternalError|PermissionError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $table; } @@ -319,10 +319,10 @@ public function setOwner(int $id, string $newOwnerUserId, ?string $userId = null $table = $this->mapper->find($id); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -335,7 +335,7 @@ public function setOwner(int $id, string $newOwnerUserId, ?string $userId = null $table = $this->mapper->update($table); } catch (OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // change owners of related shares @@ -344,7 +344,7 @@ public function setOwner(int $id, string $newOwnerUserId, ?string $userId = null } catch (InternalError $e) { $this->logger->error('Could not update related shares for a table transfer!'); $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $event = new TableOwnershipTransferredEvent( @@ -373,10 +373,10 @@ public function delete(int $id, ?string $userId = null): Table { $item = $this->mapper->find($id); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -389,7 +389,7 @@ public function delete(int $id, ?string $userId = null): Table { $this->rowService->deleteAllByTable($id, $userId); } catch (PermissionError|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // delete all views for that table @@ -399,7 +399,7 @@ public function delete(int $id, ?string $userId = null): Table { $this->viewService->deleteAllByTable($item, $userId); } catch (InternalError|PermissionError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // delete all columns for that table @@ -407,14 +407,14 @@ public function delete(int $id, ?string $userId = null): Table { $columns = $this->columnService->findAllByTable($id, null, $userId); } catch (InternalError|PermissionError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } foreach ($columns as $column) { try { $this->columnService->delete($column->id, true, $userId); } catch (InternalError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -430,7 +430,7 @@ public function delete(int $id, ?string $userId = null): Table { $this->mapper->delete($item); } catch (OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } $event = new TableDeletedEvent(table: $item); @@ -458,10 +458,10 @@ public function update(int $id, ?string $title, ?string $emoji, ?string $descrip $table = $this->mapper->find($id); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (MultipleObjectsReturnedException|OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -488,13 +488,13 @@ public function update(int $id, ?string $title, ?string $emoji, ?string $descrip $table = $this->mapper->update($table); } catch (OcpDbException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } try { $this->enhanceTable($table, $userId); } catch (InternalError|PermissionError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } return $table; } @@ -515,7 +515,7 @@ public function search(string $term, int $limit = 100, int $offset = 0, ?string $this->enhanceTable($table, $userId); } return $tables; - } catch (InternalError|PermissionError|OcpDbException $e) { + } catch (InternalError|PermissionError|OcpDbException) { return []; } } diff --git a/lib/Service/TableTemplateService.php b/lib/Service/TableTemplateService.php index 099f3060e9..8658c92bb4 100644 --- a/lib/Service/TableTemplateService.php +++ b/lib/Service/TableTemplateService.php @@ -475,9 +475,7 @@ private function makeVacationRequests(Table $table):void { [ 'title' => $this->l->t('Open Request'), 'emoji' => '️📝', - 'columns' => json_encode(array_values(array_map(function ($col) { - return $col->getId(); - }, $columns))), + 'columns' => json_encode(array_values(array_map(fn($col) => $col->getId(), $columns))), 'sort' => json_encode([['columnId' => $columns['from']->getId(), 'mode' => 'ASC']]), 'filter' => json_encode([[['columnId' => $columns['approved']->getId(), 'operator' => 'is-empty', 'value' => '']]]), ] @@ -486,9 +484,7 @@ private function makeVacationRequests(Table $table):void { [ 'title' => $this->l->t('Request Status'), 'emoji' => '️❓', - 'columns' => json_encode(array_values(array_map(function ($col) { - return $col->getId(); - }, $columns))), + 'columns' => json_encode(array_values(array_map(fn($col) => $col->getId(), $columns))), 'sort' => json_encode([['columnId' => Column::TYPE_META_UPDATED_BY, 'mode' => 'ASC']]), 'filter' => json_encode([[['columnId' => Column::TYPE_META_CREATED_BY, 'operator' => 'is-equal', 'value' => '@my-name']]]), ] @@ -497,9 +493,7 @@ private function makeVacationRequests(Table $table):void { [ 'title' => $this->l->t('Closed requests'), 'emoji' => '️✅', - 'columns' => json_encode(array_values(array_map(function ($col) { - return $col->getId(); - }, $columns))), + 'columns' => json_encode(array_values(array_map(fn($col) => $col->getId(), $columns))), 'sort' => json_encode([['columnId' => Column::TYPE_META_UPDATED_BY, 'mode' => 'ASC']]), 'filter' => json_encode([[['columnId' => $columns['approved']->getId(), 'operator' => 'is-equal', 'value' => '@checked']], [['columnId' => $columns['approved']->getId(), 'operator' => 'is-equal', 'value' => '@unchecked']]]), ] @@ -831,7 +825,7 @@ private function createRow(Table $table, array $values): void { $this->logger->warning('Exception occurred while creating a row: ' . $e->getMessage()); } catch (NotFoundError $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } diff --git a/lib/Service/ViewService.php b/lib/Service/ViewService.php index 9b36bd8842..54de423513 100644 --- a/lib/Service/ViewService.php +++ b/lib/Service/ViewService.php @@ -34,18 +34,7 @@ * @psalm-import-type TablesView from ResponseDefinitions */ class ViewService extends SuperService { - private ViewMapper $mapper; - - private ShareService $shareService; - - private RowService $rowService; - - protected UserHelper $userHelper; - - protected FavoritesService $favoritesService; - protected IL10N $l; - private ContextService $contextService; protected IEventDispatcher $eventDispatcher; @@ -53,24 +42,18 @@ public function __construct( PermissionsService $permissionsService, LoggerInterface $logger, ?string $userId, - ViewMapper $mapper, - ShareService $shareService, - RowService $rowService, - UserHelper $userHelper, - FavoritesService $favoritesService, + private ViewMapper $mapper, + private ShareService $shareService, + private RowService $rowService, + protected UserHelper $userHelper, + protected FavoritesService $favoritesService, IEventDispatcher $eventDispatcher, - ContextService $contextService, + private ContextService $contextService, IL10N $l, ) { parent::__construct($logger, $userId, $permissionsService); $this->l = $l; - $this->mapper = $mapper; - $this->shareService = $shareService; - $this->rowService = $rowService; - $this->userHelper = $userHelper; - $this->favoritesService = $favoritesService; $this->eventDispatcher = $eventDispatcher; - $this->contextService = $contextService; } /** @@ -128,10 +111,10 @@ public function find(int $id, bool $skipEnhancement = false, ?string $userId = n $view = $this->mapper->find($id); } catch (InternalError|\OCP\DB\Exception|MultipleObjectsReturnedException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -311,10 +294,10 @@ public function delete(int $id, ?string $userId = null): View { $view = $this->mapper->find($id); } catch (InternalError|MultipleObjectsReturnedException|\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } catch (DoesNotExistException $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new NotFoundError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new NotFoundError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } // security @@ -336,7 +319,7 @@ public function delete(int $id, ?string $userId = null): View { return $deletedView; } catch (\OCP\DB\Exception $e) { $this->logger->error($e->getMessage(), ['exception' => $e]); - throw new InternalError(get_class($this) . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); + throw new InternalError(static::class . ' - ' . __FUNCTION__ . ': ' . $e->getMessage()); } } @@ -409,7 +392,7 @@ private function enhanceView(View $view, string $userId): void { throw new InternalError($e->getMessage()); } $view->setOnSharePermissions($permissions); - } catch (NotFoundError $e) { + } catch (NotFoundError) { } catch (\Exception $e) { $this->logger->warning('Exception occurred while setting shared permissions: ' . $e->getMessage() . ' No permissions granted.'); $view->setOnSharePermissions(new Permissions()); @@ -420,7 +403,7 @@ private function enhanceView(View $view, string $userId): void { try { $allShares = $this->shareService->findAll('view', $view->getId()); $view->setHasShares(count($allShares) !== 0); - } catch (InternalError $e) { + } catch (InternalError) { } } @@ -432,7 +415,7 @@ private function enhanceView(View $view, string $userId): void { // add the rows count try { $view->setRowsCount($this->rowService->getViewRowsCount($view, $userId)); - } catch (InternalError|PermissionError $e) { + } catch (InternalError|PermissionError) { } // Remove detailed view filtering and sorting information if necessary @@ -440,10 +423,9 @@ private function enhanceView(View $view, string $userId): void { $rawFilterArray = $view->getFilterArray(); if ($rawFilterArray) { $view->setFilterArray( - array_map(static function ($filterGroup) { - // Instead of filter just indicate that there is a filter, but hide details - return array_map(null, $filterGroup); - }, + array_map(static fn($filterGroup) => + // Instead of filter just indicate that there is a filter, but hide details + array_map(null, $filterGroup), $rawFilterArray)); } $rawSortArray = $view->getSortArray(); @@ -502,22 +484,16 @@ public function deleteColumnDataFromViews(int $columnId, Table $table) { throw new InternalError($e->getMessage()); } foreach ($views as $view) { - $filteredSortingRules = array_filter($view->getSortArray(), function (array $sort) use ($columnId) { - return $sort['columnId'] !== $columnId; - }); + $filteredSortingRules = array_filter($view->getSortArray(), fn(array $sort) => $sort['columnId'] !== $columnId); $filteredSortingRules = array_values($filteredSortingRules); $filteredFilters = array_filter( array_map( - function (array $filterGroup) use ($columnId) { - return array_filter( + fn(array $filterGroup) => array_filter( $filterGroup, - function (array $filter) use ($columnId) { - return $filter['columnId'] !== $columnId; - } - ); - }, + fn(array $filter) => $filter['columnId'] !== $columnId + ), $view->getFilterArray() ), @@ -551,7 +527,7 @@ public function search(string $term, int $limit = 100, int $offset = 0, ?string $this->enhanceView($view, $userId); } return $views; - } catch (InternalError|\OCP\DB\Exception $e) { + } catch (InternalError|\OCP\DB\Exception) { return []; } } diff --git a/psalm.xml b/psalm.xml index 54cf837e10..f486c8aa93 100644 --- a/psalm.xml +++ b/psalm.xml @@ -4,13 +4,14 @@ - SPDX-License-Identifier: AGPL-3.0-or-later --> diff --git a/rector.php b/rector.php new file mode 100644 index 0000000000..85869576b3 --- /dev/null +++ b/rector.php @@ -0,0 +1,24 @@ +withPaths([ + __DIR__ . '/appinfo', + __DIR__ . '/lib', + __DIR__ . '/tests', + ]) + // uncomment to reach your current PHP version + ->withPhpSets(php80: true) + ->withTypeCoverageLevel(0) + ->withSets([ + NextcloudSets::NEXTCLOUD_27, + ]); diff --git a/tests/integration/features/bootstrap/FeatureContext.php b/tests/integration/features/bootstrap/FeatureContext.php index 864673c6ef..979e7b1677 100644 --- a/tests/integration/features/bootstrap/FeatureContext.php +++ b/tests/integration/features/bootstrap/FeatureContext.php @@ -122,7 +122,7 @@ public function createTableV2(string $user, string $title, string $tableName, ?s $newTable = $this->getDataFromResponse($this->response)['ocs']['data']; $this->tableIds[$tableName] = $newTable['id']; - $this->collectionManager->register($newTable, 'table', $newTable['id'], $tableName, function () use ($user, $tableName) { + $this->collectionManager->register($newTable, 'table', $newTable['id'], $tableName, function () use ($user, $tableName): void { $this->deleteTableV2($user, $tableName); }); @@ -510,7 +510,7 @@ private function tableNodeToCsv(TableNode $node): string { $out = ''; foreach ($node->getRows() as $row) { foreach ($row as $value) { - if ($out !== '' && substr($out, -1) !== "\n") { + if ($out !== '' && !str_ends_with($out, "\n")) { $out .= ','; } $out .= trim($value); @@ -690,7 +690,7 @@ public function createView(string $user, string $title, string $tableName, strin $newItem = $this->getDataFromResponse($this->response); $this->viewIds[$viewName] = $newItem['id']; - $this->collectionManager->register($newItem, 'view', $newItem['id'], $viewName, function () use ($user, $viewName) { + $this->collectionManager->register($newItem, 'view', $newItem['id'], $viewName, function () use ($user, $viewName): void { $this->deleteViewWithoutAssertion($user, $viewName); unset($this->viewIds[$viewName]); }); @@ -1871,7 +1871,7 @@ public function sendRequestFullUrl($verb, $fullUrl, $body = null, array $headers $options = array_merge($options, ['cookies' => $this->getUserCookieJar($this->currentUser)]); if ($this->currentUser === 'admin') { $options['auth'] = ['admin', 'admin']; - } elseif (strpos($this->currentUser, 'guest') !== 0) { + } elseif (!str_starts_with($this->currentUser, 'guest')) { $options['auth'] = [$this->currentUser, self::TEST_PASSWORD]; } if ($body instanceof TableNode) { @@ -1890,9 +1890,7 @@ public function sendRequestFullUrl($verb, $fullUrl, $body = null, array $headers try { $this->response = $client->{$verb}($fullUrl, $options); - } catch (ClientException $ex) { - $this->response = $ex->getResponse(); - } catch (\GuzzleHttp\Exception\ServerException $ex) { + } catch (ClientException|\GuzzleHttp\Exception\ServerException $ex) { $this->response = $ex->getResponse(); } } @@ -2013,7 +2011,7 @@ public function attemptCreateContext(string $user, string $alias, string $name, $exceptionCaught = false; try { $this->createContext($user, $alias, $name, $icon, $description, $table); - } catch (ExpectationFailedException $e) { + } catch (ExpectationFailedException) { $exceptionCaught = true; } @@ -2053,7 +2051,7 @@ public function createContext(string $user, string $alias, string $name, string $newContext = $this->getDataFromResponse($this->response)['ocs']['data']; - $this->collectionManager->register($newContext, 'context', $newContext['id'], $alias, function () use ($newContext) { + $this->collectionManager->register($newContext, 'context', $newContext['id'], $alias, function () use ($newContext): void { $this->deleteContextWithFetchCheck($newContext['id'], $newContext['owner']); }); @@ -2180,7 +2178,7 @@ public function userAttemptsToFetchContext(string $user, string $contextAlias): $caughtException = false; try { $this->userFetchesContext($user, $contextAlias); - } catch (ExpectationFailedException $e) { + } catch (ExpectationFailedException) { $caughtException = true; } @@ -2230,9 +2228,7 @@ public function theyWillFindContextsAndNoOther(string $contextAliasList): void { $receivedContexts = $this->getDataFromResponse($this->response)['ocs']['data']; $aliases = $contextAliasList === '' ? [] : explode(',', $contextAliasList); - $expectedContextIds = array_map(function (string $alias) { - return $this->collectionManager->getByAlias('context', trim($alias))['id']; - }, $aliases); + $expectedContextIds = array_map(fn(string $alias) => $this->collectionManager->getByAlias('context', trim($alias))['id'], $aliases); sort($expectedContextIds); $actualContextIds = []; @@ -2340,7 +2336,7 @@ public function userAttemptsToDeleteContext(string $user, string $contextAlias): $exceptionCaught = false; try { $this->deleteContext($context['id'], $user); - } catch (ExpectationFailedException $e) { + } catch (ExpectationFailedException) { $exceptionCaught = true; } @@ -2401,7 +2397,7 @@ public function userTransfersTheTheContextTo(string $user, string $contextAlias, ); if ($this->response->getStatusCode() === 200) { $context['owner'] = $recipientUser; - $this->collectionManager->update($context, 'context', $context['id'], function () use ($context, $recipientUser) { + $this->collectionManager->update($context, 'context', $context['id'], function () use ($context, $recipientUser): void { $this->deleteContextWithFetchCheck($context['id'], $recipientUser); }); } diff --git a/tests/unit/Service/Support/DefaultAuditLogServiceTest.php b/tests/unit/Service/Support/DefaultAuditLogServiceTest.php index 7e6275c6e7..ba55677e8a 100644 --- a/tests/unit/Service/Support/DefaultAuditLogServiceTest.php +++ b/tests/unit/Service/Support/DefaultAuditLogServiceTest.php @@ -30,9 +30,7 @@ public function testLog(): void { $this->eventDispatcher ->expects($this->once()) ->method('dispatchTyped') - ->with($this->callback(function (CriticalActionPerformedEvent $event) use ($message, $context) { - return $event->getLogMessage() === $message && $event->getParameters() === $context; - })); + ->with($this->callback(fn(CriticalActionPerformedEvent $event) => $event->getLogMessage() === $message && $event->getParameters() === $context)); $this->service->log($message, $context); } diff --git a/tests/unit/bootstrap.php b/tests/unit/bootstrap.php index 4ff11d2ee8..f9ff7d904b 100644 --- a/tests/unit/bootstrap.php +++ b/tests/unit/bootstrap.php @@ -13,7 +13,7 @@ \OC::$loader->addValidRoot(\OC::$SERVERROOT . '/tests'); \OC_App::loadApp('tables'); -if (!class_exists('\PHPUnit\Framework\TestCase')) { +if (!class_exists(\PHPUnit\Framework\TestCase::class)) { require_once('PHPUnit/Autoload.php'); } OC_Hook::clear(); diff --git a/vendor-bin/rector/composer.json b/vendor-bin/rector/composer.json new file mode 100644 index 0000000000..5b5324ac9b --- /dev/null +++ b/vendor-bin/rector/composer.json @@ -0,0 +1,6 @@ +{ + "require-dev": { + "rector/rector": "2.0.9", + "nextcloud/rector": "^0.3.1" + } +} diff --git a/vendor-bin/rector/composer.lock b/vendor-bin/rector/composer.lock new file mode 100644 index 0000000000..4744a169a5 --- /dev/null +++ b/vendor-bin/rector/composer.lock @@ -0,0 +1,198 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "3c187a2f501fcd52237809fa1613aeea", + "packages": [], + "packages-dev": [ + { + "name": "nextcloud/rector", + "version": "v0.3.1", + "source": { + "type": "git", + "url": "https://github.com/nextcloud-libraries/rector.git", + "reference": "25e71025c3acdf346f2d26034d3edd8e17e4596e" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/nextcloud-libraries/rector/zipball/25e71025c3acdf346f2d26034d3edd8e17e4596e", + "reference": "25e71025c3acdf346f2d26034d3edd8e17e4596e", + "shasum": "" + }, + "require": { + "php": "^8.1" + }, + "require-dev": { + "phpunit/phpunit": "^10.5", + "ramsey/devtools": "^2.0", + "rector/rector": "^1.2" + }, + "type": "library", + "extra": { + "captainhook": { + "force-install": true + }, + "ramsey/devtools": { + "memory-limit": "-1", + "command-prefix": "dev" + }, + "ramsey/conventional-commits": { + "configFile": "conventional-commits.json" + } + }, + "autoload": { + "psr-4": { + "Nextcloud\\Rector\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "AGPL-3.0-or-later" + ], + "authors": [ + { + "name": "Christoph Wurst", + "email": "christoph@winzerhof-wurst.at", + "homepage": "https://wuc.me" + } + ], + "description": "Rector upgrade rules for Nextcloud", + "keywords": [ + "nextcloud", + "refactoring" + ], + "support": { + "issues": "https://github.com/nextcloud-libraries/rector/issues", + "source": "https://github.com/nextcloud-libraries/rector/tree/v0.3.1" + }, + "time": "2025-02-06T09:32:20+00:00" + }, + { + "name": "phpstan/phpstan", + "version": "2.1.8", + "source": { + "type": "git", + "url": "https://github.com/phpstan/phpstan.git", + "reference": "f9adff3b87c03b12cc7e46a30a524648e497758f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/phpstan/phpstan/zipball/f9adff3b87c03b12cc7e46a30a524648e497758f", + "reference": "f9adff3b87c03b12cc7e46a30a524648e497758f", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0" + }, + "conflict": { + "phpstan/phpstan-shim": "*" + }, + "bin": [ + "phpstan", + "phpstan.phar" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "PHPStan - PHP Static Analysis Tool", + "keywords": [ + "dev", + "static analysis" + ], + "support": { + "docs": "https://phpstan.org/user-guide/getting-started", + "forum": "https://github.com/phpstan/phpstan/discussions", + "issues": "https://github.com/phpstan/phpstan/issues", + "security": "https://github.com/phpstan/phpstan/security/policy", + "source": "https://github.com/phpstan/phpstan-src" + }, + "funding": [ + { + "url": "https://github.com/ondrejmirtes", + "type": "github" + }, + { + "url": "https://github.com/phpstan", + "type": "github" + } + ], + "time": "2025-03-09T09:30:48+00:00" + }, + { + "name": "rector/rector", + "version": "2.0.9", + "source": { + "type": "git", + "url": "https://github.com/rectorphp/rector.git", + "reference": "4393230e478c0006795770fe74c223b5c64ed68c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/rectorphp/rector/zipball/4393230e478c0006795770fe74c223b5c64ed68c", + "reference": "4393230e478c0006795770fe74c223b5c64ed68c", + "shasum": "" + }, + "require": { + "php": "^7.4|^8.0", + "phpstan/phpstan": "^2.1.3" + }, + "conflict": { + "rector/rector-doctrine": "*", + "rector/rector-downgrade-php": "*", + "rector/rector-phpunit": "*", + "rector/rector-symfony": "*" + }, + "suggest": { + "ext-dom": "To manipulate phpunit.xml via the custom-rule command" + }, + "bin": [ + "bin/rector" + ], + "type": "library", + "autoload": { + "files": [ + "bootstrap.php" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "description": "Instant Upgrade and Automated Refactoring of any PHP code", + "keywords": [ + "automation", + "dev", + "migration", + "refactoring" + ], + "support": { + "issues": "https://github.com/rectorphp/rector/issues", + "source": "https://github.com/rectorphp/rector/tree/2.0.9" + }, + "funding": [ + { + "url": "https://github.com/tomasvotruba", + "type": "github" + } + ], + "time": "2025-02-10T08:14:01+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": {}, + "platform-dev": {}, + "plugin-api-version": "2.6.0" +}