From 44481e1c2a3bbeef0a5085ad913746033cd4d729 Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Wed, 11 May 2022 11:38:07 +0200 Subject: [PATCH] Switch from OC::$server->get to OCP\Server::get And add a bit more typing to some classes + psalm issues Signed-off-by: Carl Schwan --- composer.json | 1 + composer.lock | 12 +- lib/Activity/ActivityManager.php | 24 +- lib/AppInfo/Application.php | 38 +- .../Resources/ResourceProvider.php | 19 +- .../Resources/ResourceProviderCard.php | 22 +- lib/Command/BoardImport.php | 3 +- lib/Controller/PageController.php | 24 +- lib/Db/AclMapper.php | 5 +- lib/Db/AssignmentMapper.php | 4 +- lib/Db/BoardMapper.php | 23 +- lib/Db/CardMapper.php | 4 +- lib/Db/ChangeHelper.php | 8 +- lib/Db/StackMapper.php | 4 +- lib/Notification/Notifier.php | 8 +- lib/Provider/DeckProvider.php | 21 +- lib/Service/BoardService.php | 71 +- lib/Service/CardService.php | 55 +- lib/Service/CirclesService.php | 12 +- lib/Service/CommentService.php | 20 +- lib/Service/ConfigService.php | 41 +- lib/Service/DefaultBoardService.php | 12 - lib/Service/FileService.php | 3 + lib/Service/FilesAppService.php | 35 +- lib/Service/Importer/BoardImportService.php | 49 +- lib/Service/StackService.php | 30 +- lib/Sharing/DeckShareProvider.php | 54 +- lib/Sharing/Listener.php | 9 +- psalm.xml | 3 + templates/main.php | 7 +- .../database/AssignmentMapperTest.php | 20 +- .../database/BoardDatabaseTest.php | 16 +- .../database/TransferOwnershipTest.php | 20 +- tests/psalm-baseline.xml | 134 +--- tests/stub.phpstub | 642 ++++++++++++++++++ tests/unit/Db/AclMapperTest.php | 8 +- tests/unit/Db/AttachmentMapperTest.php | 3 +- tests/unit/Db/BoardMapperTest.php | 19 +- tests/unit/Notification/NotifierTest.php | 13 +- tests/unit/Service/BoardServiceTest.php | 6 + tests/unit/Service/CardServiceTest.php | 14 +- .../Systems/TrelloJsonServiceTest.php | 6 +- tests/unit/Service/StackServiceTest.php | 7 +- tests/unit/controller/BoardControllerTest.php | 4 +- tests/unit/controller/PageControllerTest.php | 7 +- 45 files changed, 1034 insertions(+), 506 deletions(-) create mode 100644 tests/stub.phpstub diff --git a/composer.json b/composer.json index b3c9ee616..92636eb8d 100644 --- a/composer.json +++ b/composer.json @@ -36,6 +36,7 @@ "cs:check": "php-cs-fixer fix --dry-run --diff", "cs:fix": "php-cs-fixer fix", "psalm": "psalm", + "psalm:update-baseline": "psalm --update-baseline", "psalm:fix": "psalm --alter --issues=InvalidReturnType,InvalidNullableReturnType,MismatchingDocblockParamType,MismatchingDocblockReturnType,MissingParamType,InvalidFalsableReturnType", "test": [ "@test:unit", diff --git a/composer.lock b/composer.lock index 8ee9594b0..3d4726a88 100644 --- a/composer.lock +++ b/composer.lock @@ -305,12 +305,12 @@ "source": { "type": "git", "url": "https://github.com/ChristophWurst/nextcloud_composer.git", - "reference": "cd35b7f4519d9b1c836443ec5dcd973d7f0f9cdd" + "reference": "5e9719488fe558db974ef45f289a6911fe2c6850" }, "dist": { "type": "zip", - "url": "https://api.github.com/repos/ChristophWurst/nextcloud_composer/zipball/cd35b7f4519d9b1c836443ec5dcd973d7f0f9cdd", - "reference": "cd35b7f4519d9b1c836443ec5dcd973d7f0f9cdd", + "url": "https://api.github.com/repos/ChristophWurst/nextcloud_composer/zipball/5e9719488fe558db974ef45f289a6911fe2c6850", + "reference": "5e9719488fe558db974ef45f289a6911fe2c6850", "shasum": "" }, "require": { @@ -323,7 +323,7 @@ "type": "library", "extra": { "branch-alias": { - "dev-master": "24.0.0-dev" + "dev-master": "25.0.0-dev" } }, "notification-url": "https://packagist.org/downloads/", @@ -341,7 +341,7 @@ "issues": "https://github.com/ChristophWurst/nextcloud_composer/issues", "source": "https://github.com/ChristophWurst/nextcloud_composer/tree/master" }, - "time": "2022-03-11T01:33:55+00:00" + "time": "2022-05-11T02:03:08+00:00" }, { "name": "composer/package-versions-deprecated", @@ -5473,5 +5473,5 @@ "platform-overrides": { "php": "7.4" }, - "plugin-api-version": "2.3.0" + "plugin-api-version": "2.2.0" } diff --git a/lib/Activity/ActivityManager.php b/lib/Activity/ActivityManager.php index baedf109d..9fc7286fa 100644 --- a/lib/Activity/ActivityManager.php +++ b/lib/Activity/ActivityManager.php @@ -45,7 +45,9 @@ use OCP\AppFramework\Db\DoesNotExistException; use OCP\AppFramework\Db\MultipleObjectsReturnedException; use OCP\Comments\IComment; use OCP\IUser; +use OCP\Server; use OCP\L10N\IFactory; +use Psr\Log\LoggerInterface; class ActivityManager { public const DECK_NOAUTHOR_COMMENT_SYSTEM_ENFORCED = 'DECK_NOAUTHOR_COMMENT_SYSTEM_ENFORCED'; @@ -53,14 +55,14 @@ class ActivityManager { public const SUBJECT_PARAMS_MAX_LENGTH = 4000; public const SHORTENED_DESCRIPTION_MAX_LENGTH = 2000; - private $manager; - private $userId; - private $permissionService; - private $boardMapper; - private $cardMapper; - private $aclMapper; - private $stackMapper; - private $l10nFactory; + private IManager $manager; + private ?string $userId; + private PermissionService $permissionService; + private BoardMapper $boardMapper; + private CardMapper $cardMapper; + private AclMapper $aclMapper; + private StackMapper $stackMapper; + private IFactory $l10nFactory; public const DECK_OBJECT_BOARD = 'deck_board'; public const DECK_OBJECT_CARD = 'deck_card'; @@ -114,7 +116,7 @@ class ActivityManager { StackMapper $stackMapper, AclMapper $aclMapper, IFactory $l10nFactory, - $userId + ?string $userId ) { $this->manager = $manager; $this->permissionService = $permissionsService; @@ -310,10 +312,10 @@ class ActivityManager { try { $object = $this->findObjectForEntity($objectType, $entity); } catch (DoesNotExistException $e) { - \OC::$server->getLogger()->error('Could not create activity entry for ' . $subject . '. Entity not found.', (array)$entity); + Server::get(LoggerInterface::class)->error('Could not create activity entry for ' . $subject . '. Entity not found.', (array)$entity); return null; } catch (MultipleObjectsReturnedException $e) { - \OC::$server->getLogger()->error('Could not create activity entry for ' . $subject . '. Entity not found.', (array)$entity); + Server::get(LoggerInterface::class)->error('Could not create activity entry for ' . $subject . '. Entity not found.', (array)$entity); return null; } diff --git a/lib/AppInfo/Application.php b/lib/AppInfo/Application.php index 54a9c7967..53eb60258 100644 --- a/lib/AppInfo/Application.php +++ b/lib/AppInfo/Application.php @@ -36,6 +36,7 @@ use OCA\Deck\Db\AclMapper; use OCA\Deck\Db\AssignmentMapper; use OCA\Deck\Db\BoardMapper; use OCA\Deck\Db\CardMapper; +use OCA\Deck\Db\User; use OCA\Deck\Event\AclCreatedEvent; use OCA\Deck\Event\AclDeletedEvent; use OCA\Deck\Event\AclUpdatedEvent; @@ -62,15 +63,16 @@ use OCP\Comments\CommentsEntityEvent; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Group\Events\GroupDeletedEvent; use OCP\IConfig; use OCP\IDBConnection; -use OCP\IGroup; use OCP\IGroupManager; -use OCP\IServerContainer; -use OCP\IUser; +use OCP\IRequest; +use OCP\Server; use OCP\IUserManager; use OCP\Notification\IManager as NotificationManager; use OCP\Share\IManager; +use OCP\User\Events\UserDeletedEvent; use OCP\Util; use Psr\Container\ContainerInterface; @@ -79,13 +81,8 @@ class Application extends App implements IBootstrap { public const COMMENT_ENTITY_TYPE = 'deckCard'; - /** @var IServerContainer */ - private $server; - public function __construct(array $urlParams = []) { parent::__construct(self::APP_ID, $urlParams); - - $this->server = \OC::$server; } public function boot(IBootContext $context): void { @@ -141,33 +138,43 @@ class Application extends App implements IBootstrap { private function registerUserGroupHooks(IUserManager $userManager, IGroupManager $groupManager): void { $container = $this->getContainer(); + /** @var IEventDispatcher $eventDispatcher */ + $eventDispatcher = $container->get(IEventDispatcher::class); // Delete user/group acl entries when they get deleted - $userManager->listen('\OC\User', 'postDelete', static function (IUser $user) use ($container) { + $eventDispatcher->addListener(UserDeletedEvent::class, static function (Event $event) use ($container): void { + if (!($event instanceof UserDeletedEvent)) { + return; + } + $user = $event->getUser(); // delete existing acl entries for deleted user /** @var AclMapper $aclMapper */ - $aclMapper = $container->query(AclMapper::class); + $aclMapper = $container->get(AclMapper::class); $acls = $aclMapper->findByParticipant(Acl::PERMISSION_TYPE_USER, $user->getUID()); foreach ($acls as $acl) { $aclMapper->delete($acl); } // delete existing user assignments - $assignmentMapper = $container->query(AssignmentMapper::class); + $assignmentMapper = $container->get(AssignmentMapper::class); $assignments = $assignmentMapper->findByParticipant($user->getUID()); foreach ($assignments as $assignment) { $assignmentMapper->delete($assignment); } /** @var BoardMapper $boardMapper */ - $boardMapper = $container->query(BoardMapper::class); + $boardMapper = $container->get(BoardMapper::class); $boards = $boardMapper->findAllByOwner($user->getUID()); foreach ($boards as $board) { $boardMapper->delete($board); } }); - $groupManager->listen('\OC\Group', 'postDelete', static function (IGroup $group) use ($container) { + $eventDispatcher->addListener(GroupDeletedEvent::class, static function (Event $event) use ($container): void { + if (!($event instanceof GroupDeletedEvent)) { + return; + } + $group = $event->getGroup(); /** @var AclMapper $aclMapper */ - $aclMapper = $container->query(AclMapper::class); + $aclMapper = $container->get(AclMapper::class); $aclMapper->findByParticipant(Acl::PERMISSION_TYPE_GROUP, $group->getGID()); $acls = $aclMapper->findByParticipant(Acl::PERMISSION_TYPE_GROUP, $group->getGID()); foreach ($acls as $acl) { @@ -181,6 +188,7 @@ class Application extends App implements IBootstrap { $event->addEntityCollection(self::COMMENT_ENTITY_TYPE, function ($name) { /** @var CardMapper */ $cardMapper = $this->getContainer()->get(CardMapper::class); + /** @var PermissionService $permissionService */ $permissionService = $this->getContainer()->get(PermissionService::class); try { @@ -203,7 +211,7 @@ class Application extends App implements IBootstrap { $resourceManager->registerResourceProvider(ResourceProviderCard::class); $symfonyAdapter->addListener('\OCP\Collaboration\Resources::loadAdditionalScripts', static function () { - if (strpos(\OC::$server->getRequest()->getPathInfo(), '/call/') === 0) { + if (strpos(Server::get(IRequest::class)->getPathInfo(), '/call/') === 0) { // Talk integration has its own entrypoint which already includes collections handling return; } diff --git a/lib/Collaboration/Resources/ResourceProvider.php b/lib/Collaboration/Resources/ResourceProvider.php index b4677148d..10daab298 100644 --- a/lib/Collaboration/Resources/ResourceProvider.php +++ b/lib/Collaboration/Resources/ResourceProvider.php @@ -32,20 +32,23 @@ use OCP\AppFramework\QueryException; use OCP\Collaboration\Resources\IManager; use OCP\Collaboration\Resources\IProvider; use OCP\Collaboration\Resources\IResource; +use OCP\IURLGenerator; use OCP\IUser; +use OCP\Server; class ResourceProvider implements IProvider { public const RESOURCE_TYPE = 'deck'; - private $boardMapper; - private $permissionService; + private BoardMapper $boardMapper; + private PermissionService $permissionService; + private IURLGenerator $urlGenerator; - /** @var array */ - protected $nodes = []; + protected array $nodes = []; - public function __construct(BoardMapper $boardMapper, PermissionService $permissionService) { + public function __construct(BoardMapper $boardMapper, PermissionService $permissionService, IURLGenerator $urlGenerator) { $this->boardMapper = $boardMapper; $this->permissionService = $permissionService; + $this->urlGenerator = $urlGenerator; } /** @@ -70,14 +73,14 @@ class ResourceProvider implements IProvider { */ public function getResourceRichObject(IResource $resource): array { $board = $this->getBoard($resource); - $link = \OC::$server->getURLGenerator()->linkToRoute('deck.page.index') . '#/board/' . $resource->getId(); + $link = $this->urlGenerator->linkToRoute('deck.page.index') . '#/board/' . $resource->getId(); return [ 'type' => self::RESOURCE_TYPE, 'id' => $resource->getId(), 'name' => $board->getTitle(), 'link' => $link, - 'iconUrl' => \OC::$server->getURLGenerator()->imagePath('deck', 'deck-dark.svg') + 'iconUrl' => $this->urlGenerator->imagePath('deck', 'deck-dark.svg') ]; } @@ -118,7 +121,7 @@ class ResourceProvider implements IProvider { public function invalidateAccessCache($boardId = null) { try { /** @var IManager $resourceManager */ - $resourceManager = \OC::$server->query(IManager::class); + $resourceManager = Server::get(IManager::class); } catch (QueryException $e) { } if ($boardId !== null) { diff --git a/lib/Collaboration/Resources/ResourceProviderCard.php b/lib/Collaboration/Resources/ResourceProviderCard.php index e436ba684..3fe957283 100644 --- a/lib/Collaboration/Resources/ResourceProviderCard.php +++ b/lib/Collaboration/Resources/ResourceProviderCard.php @@ -37,24 +37,16 @@ use OCP\Collaboration\Resources\IResource; use OCP\Collaboration\Resources\ResourceException; use OCP\IURLGenerator; use OCP\IUser; +use OCP\Server; class ResourceProviderCard implements IProvider { public const RESOURCE_TYPE = 'deck-card'; - /** @var CardMapper */ - private $cardMapper; - - /** @var BoardMapper */ - private $boardMapper; - - /** @var PermissionService */ - private $permissionService; - - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var array */ - protected $nodes = []; + private CardMapper $cardMapper; + private BoardMapper $boardMapper; + private PermissionService $permissionService; + private IURLGenerator $urlGenerator; + protected array $nodes = []; public function __construct(CardMapper $cardMapper, BoardMapper $boardMapper, PermissionService $permissionService, IURLGenerator $urlGenerator) { $this->cardMapper = $cardMapper; @@ -147,7 +139,7 @@ class ResourceProviderCard implements IProvider { public function invalidateAccessCache($cardId = null) { try { /** @var IManager $resourceManager */ - $resourceManager = \OC::$server->query(IManager::class); + $resourceManager = Server::get(IManager::class); } catch (QueryException $e) { } if ($cardId !== null) { diff --git a/lib/Command/BoardImport.php b/lib/Command/BoardImport.php index 15fec07b2..ae0388f91 100644 --- a/lib/Command/BoardImport.php +++ b/lib/Command/BoardImport.php @@ -30,8 +30,7 @@ use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; class BoardImport extends Command { - /** @var BoardImportCommandService */ - private $boardImportCommandService; + private BoardImportCommandService $boardImportCommandService; public function __construct( BoardImportCommandService $boardImportCommandService diff --git a/lib/Controller/PageController.php b/lib/Controller/PageController.php index 711b7e8ad..4fe6b2664 100644 --- a/lib/Controller/PageController.php +++ b/lib/Controller/PageController.php @@ -30,6 +30,7 @@ use OCA\Files\Event\LoadSidebar; use OCA\Viewer\Event\LoadViewer; use OCP\AppFramework\Http\ContentSecurityPolicy; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; use OCP\IInitialStateService; use OCP\IRequest; use OCP\AppFramework\Http\TemplateResponse; @@ -41,16 +42,17 @@ use OCA\Deck\Db\Acl; use OCA\Deck\Service\CardService; class PageController extends Controller { - private $permissionService; - private $initialState; - private $configService; - private $eventDispatcher; - private $cardMapper; - private $urlGenerator; - private $cardService; + private PermissionService $permissionService; + private IInitialStateService $initialState; + private ConfigService $configService; + private IEventDispatcher $eventDispatcher; + private CardMapper $cardMapper; + private IURLGenerator $urlGenerator; + private CardService $cardService; + private IConfig $config; public function __construct( - $AppName, + string $AppName, IRequest $request, PermissionService $permissionService, IInitialStateService $initialStateService, @@ -58,7 +60,8 @@ class PageController extends Controller { IEventDispatcher $eventDispatcher, CardMapper $cardMapper, IURLGenerator $urlGenerator, - CardService $cardService + CardService $cardService, + IConfig $config ) { parent::__construct($AppName, $request); @@ -69,6 +72,7 @@ class PageController extends Controller { $this->cardMapper = $cardMapper; $this->urlGenerator = $urlGenerator; $this->cardService = $cardService; + $this->config = $config; } /** @@ -90,7 +94,7 @@ class PageController extends Controller { $response = new TemplateResponse('deck', 'main'); - if (\OC::$server->getConfig()->getSystemValueBool('debug', false)) { + if ($this->config->getSystemValueBool('debug', false)) { $csp = new ContentSecurityPolicy(); $csp->addAllowedConnectDomain('*'); $csp->addAllowedScriptDomain('*'); diff --git a/lib/Db/AclMapper.php b/lib/Db/AclMapper.php index f3d6ea3d9..4ffbda695 100644 --- a/lib/Db/AclMapper.php +++ b/lib/Db/AclMapper.php @@ -53,11 +53,12 @@ class AclMapper extends DeckMapper implements IPermissionMapper { /** * @param numeric $userId - * @param numeric $aclId + * @param numeric $id * @return bool * @throws \OCP\DB\Exception */ - public function isOwner($userId, $aclId): bool { + public function isOwner($userId, $id): bool { + $aclId = $id; $qb = $this->db->getQueryBuilder(); $qb->select('acl.id') ->from($this->getTableName(), 'acl') diff --git a/lib/Db/AssignmentMapper.php b/lib/Db/AssignmentMapper.php index 98a2ead71..65fa2ba8d 100644 --- a/lib/Db/AssignmentMapper.php +++ b/lib/Db/AssignmentMapper.php @@ -77,8 +77,8 @@ class AssignmentMapper extends QBMapper implements IPermissionMapper { } - public function isOwner($userId, $cardId): bool { - return $this->cardMapper->isOwner($userId, $cardId); + public function isOwner($userId, $id): bool { + return $this->cardMapper->isOwner($userId, $id); } public function findBoardId($id): ?int { diff --git a/lib/Db/BoardMapper.php b/lib/Db/BoardMapper.php index 93be76d7e..25a671f1c 100644 --- a/lib/Db/BoardMapper.php +++ b/lib/Db/BoardMapper.php @@ -42,9 +42,9 @@ class BoardMapper extends QBMapper implements IPermissionMapper { private $circlesService; private $logger; - /** @var CappedMemoryCache */ + /** @var CappedMemoryCache */ private $userBoardCache; - /** @var CappedMemoryCache */ + /** @var CappedMemoryCache */ private $boardCache; public function __construct( @@ -131,14 +131,9 @@ class BoardMapper extends QBMapper implements IPermissionMapper { /** * Find all boards for a given user - * - * @param $userId - * @param null $limit - * @param null $offset - * @return array */ public function findAllByUser(string $userId, ?int $limit = null, ?int $offset = null, ?int $since = null, - bool $includeArchived = true, ?int $before = null, ?string $term = null) { + bool $includeArchived = true, ?int $before = null, ?string $term = null): array { // FIXME this used to be a UNION to get boards owned by $userId and the user shares in one single query // Is it possible with the query builder? $qb = $this->db->getQueryBuilder(); @@ -247,15 +242,9 @@ class BoardMapper extends QBMapper implements IPermissionMapper { /** * Find all boards for a given user - * - * @param $userId - * @param $groups - * @param null $limit - * @param null $offset - * @return array */ public function findAllByGroups(string $userId, array $groups, ?int $limit = null, ?int $offset = null, ?int $since = null, - bool $includeArchived = true, ?int $before = null, ?string $term = null) { + bool $includeArchived = true, ?int $before = null, ?string $term = null): array { if (count($groups) <= 0) { return []; } @@ -414,8 +403,8 @@ class BoardMapper extends QBMapper implements IPermissionMapper { return parent::delete($entity); } - public function isOwner($userId, $boardId): bool { - $board = $this->find($boardId); + public function isOwner($userId, $id): bool { + $board = $this->find($id); return ($board->getOwner() === $userId); } diff --git a/lib/Db/CardMapper.php b/lib/Db/CardMapper.php index 4f62dfa67..883e425d1 100644 --- a/lib/Db/CardMapper.php +++ b/lib/Db/CardMapper.php @@ -563,10 +563,10 @@ class CardMapper extends QBMapper implements IPermissionMapper { $qb->execute(); } - public function isOwner($userId, $cardId): bool { + public function isOwner($userId, $id): bool { $sql = 'SELECT owner FROM `*PREFIX*deck_boards` WHERE `id` IN (SELECT board_id FROM `*PREFIX*deck_stacks` WHERE id IN (SELECT stack_id FROM `*PREFIX*deck_cards` WHERE id = ?))'; $stmt = $this->db->prepare($sql); - $stmt->bindParam(1, $cardId, \PDO::PARAM_INT, 0); + $stmt->bindParam(1, $id, \PDO::PARAM_INT, 0); $stmt->execute(); $row = $stmt->fetch(); return ($row['owner'] === $userId); diff --git a/lib/Db/ChangeHelper.php b/lib/Db/ChangeHelper.php index 2e884fdb8..bb9342886 100644 --- a/lib/Db/ChangeHelper.php +++ b/lib/Db/ChangeHelper.php @@ -24,6 +24,7 @@ namespace OCA\Deck\Db; use OCP\ICacheFactory; +use OCP\ICache; use OCP\IDBConnection; use OCP\IRequest; @@ -31,13 +32,16 @@ class ChangeHelper { public const TYPE_BOARD = 'boardChanged'; public const TYPE_CARD = 'cardChanged'; - private $db; + private IDBConnection $db; + private ICache $cache; + private IRequest $request; + private ?string $userId; public function __construct( IDBConnection $db, ICacheFactory $cacheFactory, IRequest $request, - $userId + ?string $userId ) { $this->db = $db; $this->cache = $cacheFactory->createDistributed('deck_changes'); diff --git a/lib/Db/StackMapper.php b/lib/Db/StackMapper.php index bf9f274a4..819919e32 100644 --- a/lib/Db/StackMapper.php +++ b/lib/Db/StackMapper.php @@ -129,12 +129,12 @@ class StackMapper extends DeckMapper implements IPermissionMapper { * @return bool * @throws \OCP\DB\Exception */ - public function isOwner($userId, $stackId): bool { + public function isOwner($userId, $id): bool { $qb = $this->db->getQueryBuilder(); $qb->select('s.id') ->from($this->getTableName(), 's') ->innerJoin('s', 'deck_boards', 'b', 'b.id = s.board_id') - ->where($qb->expr()->eq('s.id', $qb->createNamedParameter($stackId, IQueryBuilder::PARAM_INT))) + ->where($qb->expr()->eq('s.id', $qb->createNamedParameter($id, IQueryBuilder::PARAM_INT))) ->andWhere($qb->expr()->eq('owner', $qb->createNamedParameter($userId, IQueryBuilder::PARAM_STR))); return count($qb->executeQuery()->fetchAll()) > 0; diff --git a/lib/Notification/Notifier.php b/lib/Notification/Notifier.php index dac50bcb2..0a9425828 100644 --- a/lib/Notification/Notifier.php +++ b/lib/Notification/Notifier.php @@ -114,7 +114,7 @@ class Notifier implements INotifier { $dn = $params[2]; } $notification->setParsedSubject( - (string) $l->t('The card "%s" on "%s" has been assigned to you by %s.', [$params[0], $params[1], $dn]) + $l->t('The card "%s" on "%s" has been assigned to you by %s.', [$params[0], $params[1], $dn]) ); $notification->setRichSubject( $l->t('{user} has assigned the card {deck-card} on {deck-board} to you.'), @@ -151,7 +151,7 @@ class Notifier implements INotifier { } $notification->setParsedSubject( - (string) $l->t('The card "%s" on "%s" has reached its due date.', $params) + $l->t('The card "%s" on "%s" has reached its due date.', $params) ); $notification->setRichSubject( $l->t('The card {deck-card} on {deck-board} has reached its due date.'), @@ -189,7 +189,7 @@ class Notifier implements INotifier { $dn = $params[2]; } $notification->setParsedSubject( - (string) $l->t('%s has mentioned you in a comment on "%s".', [$dn, $params[0]]) + $l->t('%s has mentioned you in a comment on "%s".', [$dn, $params[0]]) ); $notification->setRichSubject( $l->t('{user} has mentioned you in a comment on {deck-card}.'), @@ -226,7 +226,7 @@ class Notifier implements INotifier { $dn = $params[1]; } $notification->setParsedSubject( - (string) $l->t('The board "%s" has been shared with you by %s.', [$params[0], $dn]) + $l->t('The board "%s" has been shared with you by %s.', [$params[0], $dn]) ); $notification->setRichSubject( $l->t('{user} has shared {deck-board} with you.'), diff --git a/lib/Provider/DeckProvider.php b/lib/Provider/DeckProvider.php index 3a8ff9ea7..d9dc9cf55 100644 --- a/lib/Provider/DeckProvider.php +++ b/lib/Provider/DeckProvider.php @@ -54,22 +54,11 @@ use OCP\IURLGenerator; class DeckProvider implements IFullTextSearchProvider { public const DECK_PROVIDER_ID = 'deck'; - - /** @var IL10N */ - private $l10n; - - /** @var IUrlGenerator */ - private $urlGenerator; - - /** @var FullTextSearchService */ - private $fullTextSearchService; - - - /** @var IRunner */ - private $runner; - - /** @var IIndexOptions */ - private $indexOptions = []; + private IL10N $l10n; + private IUrlGenerator $urlGenerator; + private FullTextSearchService $fullTextSearchService; + private ?IRunner $runner = null; + private ?IIndexOptions $indexOptions = null; /** diff --git a/lib/Service/BoardService.php b/lib/Service/BoardService.php index 5d6a88ba5..b6e749f61 100644 --- a/lib/Service/BoardService.php +++ b/lib/Service/BoardService.php @@ -24,7 +24,6 @@ namespace OCA\Deck\Service; -use Doctrine\DBAL\Exception\UniqueConstraintViolationException; use OCA\Deck\Activity\ActivityManager; use OCA\Deck\Activity\ChangeSet; use OCA\Deck\AppInfo\Application; @@ -45,37 +44,38 @@ use OCA\Deck\Notification\NotificationHelper; use OCP\AppFramework\Db\DoesNotExistException; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; +use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IL10N; +use OCP\DB\Exception as DbException; use OCA\Deck\Db\Board; use OCA\Deck\Db\BoardMapper; use OCA\Deck\Db\LabelMapper; use OCP\IUserManager; use OCA\Deck\BadRequestException; use OCP\IURLGenerator; +use OCP\Server; class BoardService { - private $boardMapper; - private $stackMapper; - private $labelMapper; - private $aclMapper; - /** @var IConfig */ - private $config; - private $l10n; - private $permissionService; - private $notificationHelper; - private $assignedUsersMapper; - private $userManager; - private $groupManager; - private $userId; - private $activityManager; - private $eventDispatcher; - private $changeHelper; - private $cardMapper; - - private $boardsCache = null; - private $urlGenerator; - + private BoardMapper $boardMapper; + private StackMapper $stackMapper; + private LabelMapper $labelMapper; + private AclMapper $aclMapper; + private IConfig $config; + private IL10N $l10n; + private PermissionService $permissionService; + private NotificationHelper $notificationHelper; + private AssignmentMapper $assignedUsersMapper; + private IUserManager $userManager; + private IGroupManager $groupManager; + private ?string $userId; + private ActivityManager $activityManager; + private IEventDispatcher $eventDispatcher; + private ChangeHelper $changeHelper; + private CardMapper $cardMapper; + private ?array $boardsCache = null; + private IURLGenerator $urlGenerator; + private IDBConnection $connection; public function __construct( BoardMapper $boardMapper, @@ -94,7 +94,8 @@ class BoardService { IEventDispatcher $eventDispatcher, ChangeHelper $changeHelper, IURLGenerator $urlGenerator, - $userId + IDBConnection $connection, + ?string $userId ) { $this->boardMapper = $boardMapper; $this->stackMapper = $stackMapper; @@ -113,6 +114,7 @@ class BoardService { $this->userId = $userId; $this->urlGenerator = $urlGenerator; $this->cardMapper = $cardMapper; + $this->connection = $connection; } /** @@ -534,7 +536,7 @@ class BoardService { // TODO: use the dispatched event for this try { - $resourceProvider = \OC::$server->query(\OCA\Deck\Collaboration\Resources\ResourceProvider::class); + $resourceProvider = Server::get(\OCA\Deck\Collaboration\Resources\ResourceProvider::class); $resourceProvider->invalidateAccessCache($boardId); } catch (\Exception $e) { } @@ -590,18 +592,12 @@ class BoardService { } /** - * @param $id - * @return \OCP\AppFramework\Db\Entity * @throws DoesNotExistException * @throws \OCA\Deck\NoPermissionException * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException * @throws BadRequestException */ - public function deleteAcl($id) { - if (is_numeric($id) === false) { - throw new BadRequestException('id must be a number'); - } - + public function deleteAcl(int $id): bool { $this->permissionService->checkPermission($this->aclMapper, $id, Acl::PERMISSION_SHARE); /** @var Acl $acl */ $acl = $this->aclMapper->find($id); @@ -620,7 +616,7 @@ class BoardService { $version = \OCP\Util::getVersion()[0]; if ($version >= 16) { try { - $resourceProvider = \OC::$server->query(\OCA\Deck\Collaboration\Resources\ResourceProvider::class); + $resourceProvider = Server::get(\OCA\Deck\Collaboration\Resources\ResourceProvider::class); $resourceProvider->invalidateAccessCache($acl->getBoardId()); } catch (\Exception $e) { } @@ -681,7 +677,7 @@ class BoardService { } public function transferBoardOwnership(int $boardId, string $newOwner, bool $changeContent = false): Board { - \OC::$server->getDatabaseConnection()->beginTransaction(); + $this->connection->beginTransaction(); try { $board = $this->boardMapper->find($boardId); $previousOwner = $board->getOwner(); @@ -690,7 +686,10 @@ class BoardService { if (!$changeContent) { try { $this->addAcl($boardId, Acl::PERMISSION_TYPE_USER, $previousOwner, true, true, true); - } catch (UniqueConstraintViolationException $e) { + } catch (DbException $e) { + if ($e->getReason() !== DbException::REASON_UNIQUE_CONSTRAINT_VIOLATION) { + throw $e; + } } } $this->boardMapper->transferOwnership($previousOwner, $newOwner, $boardId); @@ -700,10 +699,10 @@ class BoardService { $this->assignedUsersMapper->remapAssignedUser($boardId, $previousOwner, $newOwner); $this->cardMapper->remapCardOwner($boardId, $previousOwner, $newOwner); } - \OC::$server->getDatabaseConnection()->commit(); + $this->connection->commit(); return $this->boardMapper->find($boardId); } catch (\Throwable $e) { - \OC::$server->getDatabaseConnection()->rollBack(); + $this->connection->rollBack(); throw $e; } } diff --git a/lib/Service/CardService.php b/lib/Service/CardService.php index 8b5f9a652..6ee4cf081 100644 --- a/lib/Service/CardService.php +++ b/lib/Service/CardService.php @@ -45,26 +45,30 @@ use OCA\Deck\StatusException; use OCA\Deck\BadRequestException; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IRequest; use OCP\IUserManager; use OCP\IURLGenerator; +use Psr\Log\LoggerInterface; class CardService { - private $cardMapper; - private $stackMapper; - private $boardMapper; - private $labelMapper; - private $permissionService; - private $boardService; - private $notificationHelper; - private $assignedUsersMapper; - private $attachmentService; - private $currentUser; - private $activityManager; - private $commentsManager; - private $changeHelper; - private $eventDispatcher; - private $userManager; - private $urlGenerator; + private CardMapper $cardMapper; + private StackMapper $stackMapper; + private BoardMapper $boardMapper; + private LabelMapper $labelMapper; + private PermissionService $permissionService; + private BoardService $boardService; + private NotificationHelper $notificationHelper; + private AssignmentMapper $assignedUsersMapper; + private AttachmentService $attachmentService; + private ?string $currentUser; + private ActivityManager $activityManager; + private ICommentsManager $commentsManager; + private ChangeHelper $changeHelper; + private IEventDispatcher $eventDispatcher; + private IUserManager $userManager; + private IURLGenerator $urlGenerator; + private LoggerInterface $logger; + private IRequest $request; public function __construct( CardMapper $cardMapper, @@ -82,7 +86,9 @@ class CardService { ChangeHelper $changeHelper, IEventDispatcher $eventDispatcher, IURLGenerator $urlGenerator, - $userId + LoggerInterface $logger, + IRequest $request, + ?string $userId ) { $this->cardMapper = $cardMapper; $this->stackMapper = $stackMapper; @@ -100,6 +106,8 @@ class CardService { $this->eventDispatcher = $eventDispatcher; $this->currentUser = $userId; $this->urlGenerator = $urlGenerator; + $this->logger = $logger; + $this->request = $request; } public function enrich($card) { @@ -131,23 +139,18 @@ class CardService { } /** - * @param $cardId * @return \OCA\Deck\Db\RelationalEntity * @throws \OCA\Deck\NoPermissionException * @throws \OCP\AppFramework\Db\DoesNotExistException * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException * @throws BadRequestException */ - public function find($cardId) { - if (is_numeric($cardId) === false) { - throw new BadRequestException('card id must be a number'); - } - + public function find(int $cardId) { $this->permissionService->checkPermission($this->cardMapper, $cardId, Acl::PERMISSION_READ); $card = $this->cardMapper->find($cardId); $assignedUsers = $this->assignedUsersMapper->findAll($card->getId()); $attachments = $this->attachmentService->findAll($cardId, true); - if (\OC::$server->getRequest()->getParam('apiVersion') === '1.0') { + if ($this->request->getParam('apiVersion') === '1.0') { $attachments = array_filter($attachments, function ($attachment) { return $attachment->getType() === 'deck_file'; }); @@ -162,7 +165,7 @@ class CardService { try { $this->permissionService->checkPermission($this->boardMapper, $boardId, Acl::PERMISSION_READ); } catch (NoPermissionException $e) { - \OC::$server->getLogger()->error('Unable to check permission for a previously obtained board ' . $boardId, ['exception' => $e]); + $this->logger->error('Unable to check permission for a previously obtained board ' . $boardId, ['exception' => $e]); return []; } $cards = $this->cardMapper->findCalendarEntries($boardId); @@ -486,7 +489,7 @@ class CardService { * @throws StatusException * @throws \OCA\Deck\NoPermissionException * @throws \OCP\AppFramework\Db\DoesNotExistException - * @throws \OCP\AppFramework\Db\ + * @throws \OCP\AppFramework\Db\MultipleObjectsReturnedException * @throws BadRequestException */ public function archive($id) { diff --git a/lib/Service/CirclesService.php b/lib/Service/CirclesService.php index 6a471b41d..8dc285e53 100644 --- a/lib/Service/CirclesService.php +++ b/lib/Service/CirclesService.php @@ -31,6 +31,7 @@ use OCA\Circles\Model\Circle; use OCA\Circles\Model\Member; use OCA\Circles\Model\Probes\CircleProbe; use OCP\App\IAppManager; +use OCP\Server; use Throwable; /** @@ -38,7 +39,7 @@ use Throwable; * having the app disabled is properly handled */ class CirclesService { - private $circlesEnabled; + private bool $circlesEnabled; public function __construct(IAppManager $appManager) { $this->circlesEnabled = $appManager->isEnabledForUser('circles'); @@ -56,8 +57,7 @@ class CirclesService { try { // Enforce current user condition since we always want the full list of members - /** @var CirclesManager $circlesManager */ - $circlesManager = \OC::$server->get(CirclesManager::class); + $circlesManager = Server::get(CirclesManager::class); $circlesManager->startSuperSession(); return $circlesManager->getCircle($circleId); } catch (Throwable $e) { @@ -71,8 +71,7 @@ class CirclesService { } try { - /** @var CirclesManager $circlesManager */ - $circlesManager = \OC::$server->get(CirclesManager::class); + $circlesManager = Server::get(CirclesManager::class); $federatedUser = $circlesManager->getFederatedUser($userId, Member::TYPE_USER); $circlesManager->startSession($federatedUser); $circle = $circlesManager->getCircle($circleId); @@ -93,8 +92,7 @@ class CirclesService { } try { - /** @var CirclesManager $circlesManager */ - $circlesManager = \OC::$server->get(CirclesManager::class); + $circlesManager = Server::get(CirclesManager::class); $federatedUser = $circlesManager->getFederatedUser($userId, Member::TYPE_USER); $circlesManager->startSession($federatedUser); $probe = new CircleProbe(); diff --git a/lib/Service/CommentService.php b/lib/Service/CommentService.php index c389a9ad2..e9768d710 100644 --- a/lib/Service/CommentService.php +++ b/lib/Service/CommentService.php @@ -40,20 +40,14 @@ use OutOfBoundsException; use function is_numeric; class CommentService { + private ICommentsManager $commentsManager; + private IUserManager $userManager; + private CardMapper $cardMapper; + private PermissionService $permissionService; + private ILogger $logger; + private ?string $userId; - /** - * @var ICommentsManager - */ - private $commentsManager; - /** - * @var IUserManager - */ - private $userManager; - /** @var ILogger */ - private $logger; - private $userId; - - public function __construct(ICommentsManager $commentsManager, PermissionService $permissionService, CardMapper $cardMapper, IUserManager $userManager, ILogger $logger, $userId) { + public function __construct(ICommentsManager $commentsManager, PermissionService $permissionService, CardMapper $cardMapper, IUserManager $userManager, ILogger $logger, ?string $userId) { $this->commentsManager = $commentsManager; $this->permissionService = $permissionService; $this->cardMapper = $cardMapper; diff --git a/lib/Service/ConfigService.php b/lib/Service/ConfigService.php index 2250dbf92..00a42030e 100644 --- a/lib/Service/ConfigService.php +++ b/lib/Service/ConfigService.php @@ -32,7 +32,6 @@ use OCA\Deck\NoPermissionException; use OCP\IConfig; use OCP\IGroup; use OCP\IGroupManager; -use OCP\IUserSession; class ConfigService { public const SETTING_BOARD_NOTIFICATION_DUE_OFF = 'off'; @@ -40,23 +39,21 @@ class ConfigService { public const SETTING_BOARD_NOTIFICATION_DUE_ALL = 'all'; public const SETTING_BOARD_NOTIFICATION_DUE_DEFAULT = self::SETTING_BOARD_NOTIFICATION_DUE_ASSIGNED; - private $config; - private $userId; - private $groupManager; + private IConfig $config; + private ?string $userId; + private IGroupManager $groupManager; public function __construct( IConfig $config, - IGroupManager $groupManager + IGroupManager $groupManager, + ?string $userId ) { $this->groupManager = $groupManager; $this->config = $config; + $this->userId = $userId; } - public function getUserId() { - if (!$this->userId) { - $user = \OC::$server->get(IUserSession::class)->getUser(); - $this->userId = $user ? $user->getUID() : null; - } + public function getUserId(): ?string { return $this->userId; } @@ -75,8 +72,11 @@ class ConfigService { return $data; } - public function get($key) { - $result = null; + /** + * @return bool|array{id: string, displayname: string}[] + * @throws NoPermissionException + */ + public function get(string $key) { [$scope] = explode(':', $key, 2); switch ($scope) { case 'groupLimit': @@ -90,11 +90,12 @@ class ConfigService { } return (bool)$this->config->getUserValue($this->getUserId(), Application::APP_ID, 'calendar', true); case 'cardDetailsInModal': - if ($this->getUserId() === null) { - return false; - } + if ($this->getUserId() === null) { + return false; + } return (bool)$this->config->getUserValue($this->getUserId(), Application::APP_ID, 'cardDetailsInModal', true); } + return false; } public function isCalendarEnabled(int $boardId = null): bool { @@ -157,7 +158,10 @@ class ConfigService { return $result; } - private function setGroupLimit($value) { + /** + * @return string[] + */ + private function setGroupLimit(array $value): array { $groups = []; foreach ($value as $group) { $groups[] = $group['id']; @@ -167,7 +171,7 @@ class ConfigService { return $groups; } - private function getGroupLimitList() { + private function getGroupLimitList(): array { $value = $this->config->getAppValue(Application::APP_ID, 'groupLimit', ''); $groups = explode(',', $value); if ($value === '') { @@ -176,9 +180,10 @@ class ConfigService { return $groups; } + /** @return array{id: string, displayname: string}[] */ private function getGroupLimit() { $groups = $this->getGroupLimitList(); - $groups = array_map(function ($groupId) { + $groups = array_map(function (string $groupId): ?array { /** @var IGroup $groups */ $group = $this->groupManager->get($groupId); if ($group === null) { diff --git a/lib/Service/DefaultBoardService.php b/lib/Service/DefaultBoardService.php index 12df32513..a9f31d0ac 100644 --- a/lib/Service/DefaultBoardService.php +++ b/lib/Service/DefaultBoardService.php @@ -88,18 +88,6 @@ class DefaultBoardService { * @throws BadRequestException */ public function createDefaultBoard(string $title, string $userId, string $color) { - if ($title === false || $title === null) { - throw new BadRequestException('title must be provided'); - } - - if ($userId === false || $userId === null) { - throw new BadRequestException('userId must be provided'); - } - - if ($color === false || $color === null) { - throw new BadRequestException('color must be provided'); - } - $defaultBoard = $this->boardService->create($title, $userId, $color); $defaultStacks = []; $defaultCards = []; diff --git a/lib/Service/FileService.php b/lib/Service/FileService.php index 7158c6d7c..5a3dbfb20 100644 --- a/lib/Service/FileService.php +++ b/lib/Service/FileService.php @@ -219,8 +219,11 @@ class FileService implements IAttachmentService { throw new \Exception('no instance id!'); } $name = 'appdata_' . $instanceId; + /** @var \OCP\Files\Folder $appDataFolder */ $appDataFolder = $this->rootFolder->get($name); + /** @var \OCP\Files\Folder $appDataFolder */ $appDataFolder = $appDataFolder->get('deck'); + /** @var \OCP\Files\Folder $cardFolder */ $cardFolder = $appDataFolder->get($folderName); return $cardFolder->get($attachment->getData()); } diff --git a/lib/Service/FilesAppService.php b/lib/Service/FilesAppService.php index 2f978f1cf..3fa399078 100644 --- a/lib/Service/FilesAppService.php +++ b/lib/Service/FilesAppService.php @@ -44,18 +44,19 @@ use OCP\Share\IShare; use Psr\Log\LoggerInterface; class FilesAppService implements IAttachmentService, ICustomAttachmentService { - private $request; - private $rootFolder; - private $shareProvider; - private $shareManager; - private $userId; - private $configService; - private $l10n; - private $preview; - private $mimeTypeDetector; - private $permissionService; - private $cardMapper; - private $logger; + private IRequest $request; + private IRootFolder $rootFolder; + private DeckShareProvider $shareProvider; + private IManager $shareManager; + private ?string $userId; + private ConfigService $configService; + private IL10N $l10n; + private IPreview $preview; + private IMimeTypeDetector $mimeTypeDetector; + private PermissionService $permissionService; + private CardMapper $cardMapper; + private LoggerInterface $logger; + private IDBConnection $connection; public function __construct( IRequest $request, @@ -69,7 +70,8 @@ class FilesAppService implements IAttachmentService, ICustomAttachmentService { PermissionService $permissionService, CardMapper $cardMapper, LoggerInterface $logger, - string $userId = null + IDBConnection $connection, + ?string $userId ) { $this->request = $request; $this->l10n = $l10n; @@ -83,6 +85,7 @@ class FilesAppService implements IAttachmentService, ICustomAttachmentService { $this->permissionService = $permissionService; $this->cardMapper = $cardMapper; $this->logger = $logger; + $this->connection = $connection; } public function listAttachments(int $cardId): array { @@ -108,9 +111,7 @@ class FilesAppService implements IAttachmentService, ICustomAttachmentService { } public function getAttachmentCount(int $cardId): int { - /** @var IDBConnection $qb */ - $db = \OC::$server->getDatabaseConnection(); - $qb = $db->getQueryBuilder(); + $qb = $this->connection->getQueryBuilder(); $qb->select('s.id', 'f.fileid', 'f.path') ->selectAlias('st.id', 'storage_string_id') ->from('share', 's') @@ -125,7 +126,7 @@ class FilesAppService implements IAttachmentService, ICustomAttachmentService { )); $count = 0; - $cursor = $qb->execute(); + $cursor = $qb->executeQuery(); while ($data = $cursor->fetch()) { if ($this->shareProvider->isAccessibleResult($data)) { $count++; diff --git a/lib/Service/Importer/BoardImportService.php b/lib/Service/Importer/BoardImportService.php index 72b8b0c28..39c2273fe 100644 --- a/lib/Service/Importer/BoardImportService.php +++ b/lib/Service/Importer/BoardImportService.php @@ -47,34 +47,22 @@ use OCP\Comments\ICommentsManager; use OCP\Comments\NotFoundException as CommentNotFoundException; use OCP\EventDispatcher\IEventDispatcher; use OCP\IUserManager; +use OCP\Server; class BoardImportService { - /** @var IUserManager */ - private $userManager; - /** @var BoardMapper */ - private $boardMapper; - /** @var AclMapper */ - private $aclMapper; - /** @var LabelMapper */ - private $labelMapper; - /** @var StackMapper */ - private $stackMapper; - /** @var CardMapper */ - private $cardMapper; - /** @var AssignmentMapper */ - private $assignmentMapper; - /** @var AttachmentMapper */ - private $attachmentMapper; - /** @var ICommentsManager */ - private $commentsManager; - /** @var IEventDispatcher */ - private $eventDispatcher; - /** @var string */ - private $system = ''; - /** @var null|ABoardImportService */ - private $systemInstance; - /** @var array */ - private $allowedSystems = []; + private IUserManager $userManager; + private BoardMapper $boardMapper; + private AclMapper $aclMapper; + private LabelMapper $labelMapper; + private StackMapper $stackMapper; + private CardMapper $cardMapper; + private AssignmentMapper $assignmentMapper; + private AttachmentMapper $attachmentMapper; + private ICommentsManager $commentsManager; + private IEventDispatcher $eventDispatcher; + private string $system = ''; + private ?ABoardImportService $systemInstance; + private array $allowedSystems = []; /** * Data object created from config JSON * @@ -89,10 +77,7 @@ class BoardImportService { * @psalm-suppress PropertyNotSetInConstructor */ private $data; - /** - * @var Board - */ - private $board; + private Board $board; public function __construct( IUserManager $userManager, @@ -198,7 +183,7 @@ class BoardImportService { } if (!is_object($this->systemInstance)) { $systemClass = 'OCA\\Deck\\Service\\Importer\\Systems\\' . ucfirst($this->getSystem()) . 'Service'; - $this->systemInstance = \OC::$server->get($systemClass); + $this->systemInstance = Server::get($systemClass); $this->systemInstance->setImportService($this); } return $this->systemInstance; @@ -343,7 +328,7 @@ class BoardImportService { } public function insertAttachment(Attachment $attachment, string $content): Attachment { - $service = \OC::$server->get(FileService::class); + $service = Server::get(FileService::class); $folder = $service->getFolder($attachment); if ($folder->fileExists($attachment->getData())) { diff --git a/lib/Service/StackService.php b/lib/Service/StackService.php index 5d993b8e3..971992a68 100644 --- a/lib/Service/StackService.php +++ b/lib/Service/StackService.php @@ -39,19 +39,21 @@ use OCA\Deck\Db\StackMapper; use OCA\Deck\Model\CardDetails; use OCA\Deck\NoPermissionException; use OCA\Deck\StatusException; +use Psr\Log\LoggerInterface; class StackService { - private $stackMapper; - private $cardMapper; - private $boardMapper; - private $labelMapper; - private $permissionService; - private $boardService; - private $cardService; - private $assignedUsersMapper; - private $attachmentService; - private $activityManager; - private $changeHelper; + private StackMapper $stackMapper; + private CardMapper $cardMapper; + private BoardMapper $boardMapper; + private LabelMapper $labelMapper; + private PermissionService $permissionService; + private BoardService $boardService; + private CardService $cardService; + private AssignmentMapper $assignedUsersMapper; + private AttachmentService $attachmentService; + private ActivityManager $activityManager; + private ChangeHelper $changeHelper; + private LoggerInterface $logger; public function __construct( StackMapper $stackMapper, @@ -64,7 +66,8 @@ class StackService { AssignmentMapper $assignedUsersMapper, AttachmentService $attachmentService, ActivityManager $activityManager, - ChangeHelper $changeHelper + ChangeHelper $changeHelper, + LoggerInterface $logger ) { $this->stackMapper = $stackMapper; $this->boardMapper = $boardMapper; @@ -77,6 +80,7 @@ class StackService { $this->attachmentService = $attachmentService; $this->activityManager = $activityManager; $this->changeHelper = $changeHelper; + $this->logger = $logger; } private function enrichStackWithCards($stack, $since = -1) { @@ -158,7 +162,7 @@ class StackService { try { $this->permissionService->checkPermission(null, $boardId, Acl::PERMISSION_READ); } catch (NoPermissionException $e) { - \OC::$server->getLogger()->error('Unable to check permission for a previously obtained board ' . $boardId, ['exception' => $e]); + $this->logger->error('Unable to check permission for a previously obtained board ' . $boardId, ['exception' => $e]); return []; } return $this->stackMapper->findAll($boardId); diff --git a/lib/Sharing/DeckShareProvider.php b/lib/Sharing/DeckShareProvider.php index cff74fab0..0745cbbda 100644 --- a/lib/Sharing/DeckShareProvider.php +++ b/lib/Sharing/DeckShareProvider.php @@ -65,22 +65,16 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { public const SHARE_TYPE_DECK_USER = IShare::TYPE_DECK_USER; - /** @var IDBConnection */ - private $dbConnection; - /** @var IManager */ - private $shareManager; - /** @var AttachmentCacheHelper */ - private $attachmentCacheHelper; - /** @var BoardMapper */ - private $boardMapper; - /** @var CardMapper */ - private $cardMapper; - /** @var PermissionService */ - private $permissionService; - /** @var ITimeFactory */ - private $timeFactory; - /** @var IL10N */ - private $l; + private IDBConnection $dbConnection; + private IManager $shareManager; + private AttachmentCacheHelper $attachmentCacheHelper; + private BoardMapper $boardMapper; + private CardMapper $cardMapper; + private PermissionService $permissionService; + private ITimeFactory $timeFactory; + private IL10N $l; + private IMimeTypeLoader $mimeTypeLoader; + private ?string $userId; public function __construct( IDBConnection $connection, @@ -89,7 +83,10 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { CardMapper $cardMapper, PermissionService $permissionService, AttachmentCacheHelper $attachmentCacheHelper, - IL10N $l + IL10N $l, + ITimeFactory $timeFactory, + IMimeTypeLoader $mimeTypeLoader, + ?string $userId ) { $this->dbConnection = $connection; $this->shareManager = $shareManager; @@ -97,9 +94,10 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { $this->cardMapper = $cardMapper; $this->attachmentCacheHelper = $attachmentCacheHelper; $this->permissionService = $permissionService; - $this->l = $l; - $this->timeFactory = \OC::$server->get(ITimeFactory::class); + $this->timeFactory = $timeFactory; + $this->mimeTypeLoader = $mimeTypeLoader; + $this->userId = $userId; } public static function register(IEventDispatcher $dispatcher): void { @@ -207,13 +205,13 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { ->setValue('file_target', $qb->createNamedParameter($target)) ->setValue('permissions', $qb->createNamedParameter($permissions)) ->setValue('token', $qb->createNamedParameter($token)) - ->setValue('stime', $qb->createNamedParameter(\OC::$server->get(ITimeFactory::class)->getTime())); + ->setValue('stime', $qb->createNamedParameter($this->timeFactory->getTime())); if ($expirationDate !== null) { $qb->setValue('expiration', $qb->createNamedParameter($expirationDate, 'datetime')); } - $qb->execute(); + $qb->executeStatement(); return $qb->getLastInsertId(); } @@ -281,7 +279,7 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { $entryData = $data; $entryData['permissions'] = $entryData['f_permissions']; $entryData['parent'] = $entryData['f_parent']; - $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData, \OC::$server->get(IMimeTypeLoader::class))); + $share->setNodeCacheEntry(Cache::cacheEntryFromData($entryData, $this->mimeTypeLoader)); } return $share; } @@ -474,14 +472,14 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { 'file_target' => $qb->createNamedParameter($share->getTarget()), 'permissions' => $qb->createNamedParameter($share->getPermissions()), 'stime' => $qb->createNamedParameter($share->getShareTime()->getTimestamp()), - ])->execute(); + ])->executeStatement(); } else { // Already a userroom share. Update it. $qb = $this->dbConnection->getQueryBuilder(); $qb->update('share') ->set('file_target', $qb->createNamedParameter($share->getTarget())) ->where($qb->expr()->eq('id', $qb->createNamedParameter($data['id']))) - ->execute(); + ->executeStatement(); } return $share; @@ -821,7 +819,7 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { $qb->expr()->eq('s.item_type', $qb->createNamedParameter('folder')) )); - $cursor = $qb->execute(); + $cursor = $qb->executeQuery(); while ($data = $cursor->fetch()) { if (!$this->isAccessibleResult($data)) { continue; @@ -836,9 +834,7 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { } $cursor->closeCursor(); - $shares = $this->resolveSharesForRecipient($shares, \OC::$server->getUserSession()->getUser()->getUID()); - - return $shares; + return $this->resolveSharesForRecipient($shares, $this->userId); } public function isAccessibleResult(array $data): bool { @@ -941,7 +937,7 @@ class DeckShareProvider implements \OCP\Share\IShareProvider { $qb->expr()->eq('item_type', $qb->createNamedParameter('file')), $qb->expr()->eq('item_type', $qb->createNamedParameter('folder')) )); - $cursor = $qb->execute(); + $cursor = $qb->executeQuery(); $users = []; while ($row = $cursor->fetch()) { diff --git a/lib/Sharing/Listener.php b/lib/Sharing/Listener.php index 8fa954fcd..21e38304e 100644 --- a/lib/Sharing/Listener.php +++ b/lib/Sharing/Listener.php @@ -29,14 +29,13 @@ namespace OCA\Deck\Sharing; use OC\Files\Filesystem; use OCA\Deck\Service\ConfigService; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Server; use OCP\Share\Events\VerifyMountPointEvent; use OCP\Share\IShare; use Symfony\Component\EventDispatcher\GenericEvent; class Listener { - - /** @var ConfigService */ - private $configService; + private ConfigService $configService; public function __construct(ConfigService $configService) { $this->configService = $configService; @@ -52,13 +51,13 @@ class Listener { public static function listenPreShare(GenericEvent $event): void { /** @var self $listener */ - $listener = \OC::$server->query(self::class); + $listener = Server::get(self::class); $listener->overwriteShareTarget($event); } public static function listenVerifyMountPointEvent(VerifyMountPointEvent $event): void { /** @var self $listener */ - $listener = \OC::$server->query(self::class); + $listener = Server::get(self::class); $listener->overwriteMountPoint($event); } diff --git a/psalm.xml b/psalm.xml index b171e8627..178ff30fd 100644 --- a/psalm.xml +++ b/psalm.xml @@ -7,6 +7,9 @@ xsi:schemaLocation="https://getpsalm.org/schema/config vendor/vimeo/psalm/config.xsd" errorBaseline="tests/psalm-baseline.xml" > + + + diff --git a/templates/main.php b/templates/main.php index 6960eb9fb..a5de6b08e 100644 --- a/templates/main.php +++ b/templates/main.php @@ -22,7 +22,8 @@ */ -style('deck', 'globalstyles'); -script('deck', 'deck-main'); +OCP\Util::addStyle('deck', 'globalstyles'); +OCP\Util::addScript('deck', 'deck-main'); -\OC::$server->getEventDispatcher()->dispatch('\OCP\Collaboration\Resources::loadAdditionalScripts'); +\OCP\Server::get(\OCP\EventDispatcher\IEventDispatcher::class) + ->dispatch('\OCP\Collaboration\Resources::loadAdditionalScripts'); diff --git a/tests/integration/database/AssignmentMapperTest.php b/tests/integration/database/AssignmentMapperTest.php index 6999e1093..7066c494a 100644 --- a/tests/integration/database/AssignmentMapperTest.php +++ b/tests/integration/database/AssignmentMapperTest.php @@ -28,6 +28,10 @@ use OCA\Deck\Service\AssignmentService; use OCA\Deck\Service\BoardService; use OCA\Deck\Service\StackService; use OCA\Deck\Service\CardService; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Server; /** * @group DB @@ -56,7 +60,7 @@ class AssignmentMapperTest extends \Test\TestCase { $backend = new \Test\Util\User\Dummy(); \OC_User::useBackend($backend); - \OC::$server->getUserManager()->registerBackend($backend); + Server::get(IUserManager::class)->registerBackend($backend); $backend->createUser(self::TEST_USER1, self::TEST_USER1); $backend->createUser(self::TEST_USER2, self::TEST_USER2); $backend->createUser(self::TEST_USER3, self::TEST_USER3); @@ -75,17 +79,17 @@ class AssignmentMapperTest extends \Test\TestCase { $groupBackend->addToGroup(self::TEST_USER3, 'group2'); $groupBackend->addToGroup(self::TEST_USER4, 'group3'); $groupBackend->addToGroup(self::TEST_USER2, self::TEST_GROUP1); - \OC::$server->getGroupManager()->addBackend($groupBackend); + Server::get(IGroupManager::class)->addBackend($groupBackend); } public function setUp(): void { parent::setUp(); - \OC::$server->getUserSession()->login(self::TEST_USER1, self::TEST_USER1); - $this->boardService = \OC::$server->query(BoardService::class); - $this->stackService = \OC::$server->query(StackService::class); - $this->cardService = \OC::$server->query(CardService::class); - $this->assignmentService = \OC::$server->query(AssignmentService::class); - $this->assignedUsersMapper = \OC::$server->query(AssignmentMapper::class); + Server::get(IUserSession::class)->login(self::TEST_USER1, self::TEST_USER1); + $this->boardService = Server::get(BoardService::class); + $this->stackService = Server::get(StackService::class); + $this->cardService = Server::get(CardService::class); + $this->assignmentService = Server::get(AssignmentService::class); + $this->assignedUsersMapper = Server::get(AssignmentMapper::class); $this->createBoardWithExampleData(); } diff --git a/tests/integration/database/BoardDatabaseTest.php b/tests/integration/database/BoardDatabaseTest.php index 80d0e111f..8a0dd1a43 100644 --- a/tests/integration/database/BoardDatabaseTest.php +++ b/tests/integration/database/BoardDatabaseTest.php @@ -21,6 +21,12 @@ * */ +use OCA\Deck\Db\Board; +use OCA\Deck\Service\BoardService; +use OCP\IGroupManager; +use OCP\IUserSession; +use OCP\Server; + /** * @group DB */ @@ -31,7 +37,7 @@ class BoardDatabaseTest extends \Test\TestCase { public const TEST_USER4 = "test-share-user4"; public const TEST_GROUP1 = "test-share-group1"; - /** @var \OCA\Deck\Service\BoardService */ + /** @var BoardService */ private $boardService; public static function setUpBeforeClass(): void { @@ -57,15 +63,15 @@ class BoardDatabaseTest extends \Test\TestCase { $groupBackend->addToGroup(self::TEST_USER3, 'group2'); $groupBackend->addToGroup(self::TEST_USER4, 'group3'); $groupBackend->addToGroup(self::TEST_USER2, self::TEST_GROUP1); - \OC::$server->getGroupManager()->addBackend($groupBackend); + Server::get(IGroupManager::class)->addBackend($groupBackend); } public function setUp(): void { parent::setUp(); - \OC::$server->getUserSession()->login(self::TEST_USER1, self::TEST_USER1); - $this->boardService = \OC::$server->query("\OCA\Deck\Service\BoardService"); + Server::get(IUserSession::class)->login(self::TEST_USER1, self::TEST_USER1); + $this->boardService = Server::get(BoardService::class); } public function testCreate() { - $board = new \OCA\Deck\Db\Board(); + $board = new Board(); $board->setTitle('Test'); $board->setOwner(self::TEST_USER1); $board->setColor('000000'); diff --git a/tests/integration/database/TransferOwnershipTest.php b/tests/integration/database/TransferOwnershipTest.php index a88178c06..bba5e12dd 100644 --- a/tests/integration/database/TransferOwnershipTest.php +++ b/tests/integration/database/TransferOwnershipTest.php @@ -7,6 +7,10 @@ use OCA\Deck\Db\Assignment; use OCA\Deck\Db\AssignmentMapper; use OCA\Deck\Db\Board; use OCA\Deck\Db\Card; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\Server; /** * @group DB @@ -38,7 +42,7 @@ class TransferOwnershipTest extends \Test\TestCase { $backend = new \Test\Util\User\Dummy(); \OC_User::useBackend($backend); - \OC::$server->getUserManager()->registerBackend($backend); + Server::get(IUserManager::class)->registerBackend($backend); $backend->createUser(self::TEST_USER_1, self::TEST_USER_1); $backend->createUser(self::TEST_USER_2, self::TEST_USER_2); $backend->createUser(self::TEST_USER_3, self::TEST_USER_3); @@ -46,17 +50,17 @@ class TransferOwnershipTest extends \Test\TestCase { $groupBackend = new \Test\Util\Group\Dummy(); $groupBackend->createGroup(self::TEST_GROUP); $groupBackend->addToGroup(self::TEST_USER_1, self::TEST_GROUP); - \OC::$server->getGroupManager()->addBackend($groupBackend); + Server::get(IGroupManager::class)->addBackend($groupBackend); } public function setUp(): void { parent::setUp(); - \OC::$server->getUserSession()->login(self::TEST_USER_1, self::TEST_USER_1); - $this->boardService = \OC::$server->query(BoardService::class); - $this->stackService = \OC::$server->query(StackService::class); - $this->cardService = \OC::$server->query(CardService::class); - $this->assignmentService = \OC::$server->query(AssignmentService::class); - $this->assignmentMapper = \OC::$server->query(AssignmentMapper::class); + Server::get(IUserSession::class)->login(self::TEST_USER_1, self::TEST_USER_1); + $this->boardService = Server::get(BoardService::class); + $this->stackService = Server::get(StackService::class); + $this->cardService = Server::get(CardService::class); + $this->assignmentService = Server::get(AssignmentService::class); + $this->assignmentMapper = Server::get(AssignmentMapper::class); $this->createBoardWithExampleData(); } diff --git a/tests/psalm-baseline.xml b/tests/psalm-baseline.xml index 9c34589b5..3d3cd7ffb 100644 --- a/tests/psalm-baseline.xml +++ b/tests/psalm-baseline.xml @@ -1,5 +1,5 @@ - + $message !== null @@ -81,29 +81,6 @@ NotFound - - - $aclId - - - - - $cardId - - - - - $boardId - - - $limit !== null - $limit !== null - $limit !== null - $offset !== null - $offset !== null - $offset !== null - - VCalendar @@ -114,39 +91,10 @@ $entity->getId() - - $cardId - getUserIdGroups - - - $this->cache - $this->request - $this->userId - - - $this->cache - $this->cache - $this->cache - $this->cache - $this->request - $this->userId - - - - - \OCA\Circles\Model\Circle - - - $this->object - $this->object - $this->object - \OCA\Circles\Model\Circle - - $labelId @@ -158,29 +106,11 @@ VCalendar - - - $stackId - - $schemaClosure - - - (string) $l->t('%s has mentioned you in a comment on "%s".', [$dn, $params[0]]) - (string) $l->t('The board "%s" has been shared with you by %s.', [$params[0], $dn]) - (string) $l->t('The card "%s" on "%s" has been assigned to you by %s.', [$params[0], $params[1], $dn]) - (string) $l->t('The card "%s" on "%s" has reached its due date.', $params) - - - - - [] - - $cardId @@ -196,75 +126,15 @@ findAll - - - \OCP\AppFramework\Db\ - - - - ?Circle - - - $circlesManager - $circlesManager - $circlesManager - - - - - $this->cardMapper - $this->permissionService - - - $this->cardMapper - $this->cardMapper - $this->cardMapper - $this->cardMapper - $this->permissionService - $this->permissionService - $this->permissionService - $this->permissionService - - - - - $color === false || $color === null - $color === null - $title === false || $title === null - $title === null - $userId === false || $userId === null - $userId === null - - - $color === false - $title === false - $userId === false - + - - $this->rootFolder - IRootFolder - is_resource($content) is_resource($content) - - - $this->rootFolder - $this->rootFolder - IRootFolder - - - - - $circle - Member - - BadRquestException diff --git a/tests/stub.phpstub b/tests/stub.phpstub new file mode 100644 index 000000000..acc8d618a --- /dev/null +++ b/tests/stub.phpstub @@ -0,0 +1,642 @@ + + * + * @license GNU AGPL version 3 or any later version + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + * + */ + +namespace OCA\Circles\Model { + class Member { + public const LEVEL_NONE = 0; + public const LEVEL_MEMBER = 1; + public const LEVEL_MODERATOR = 4; + public const LEVEL_ADMIN = 8; + public const LEVEL_OWNER = 9; + + public const TYPE_SINGLE = 0; + public const TYPE_USER = 1; + public const TYPE_GROUP = 2; + public const TYPE_MAIL = 4; + public const TYPE_CONTACT = 8; + public const TYPE_CIRCLE = 16; + public const TYPE_APP = 10000; + + public const ALLOWING_ALL_TYPES = 31; + + public const APP_CIRCLES = 10001; + public const APP_OCC = 10002; + public const APP_DEFAULT = 11000; + } + + class Circle { + public function getUniqueId(): string {} + public function getDisplayName(): string {} + public function getOwner(): string {} + public function getSingleId(): string {} + public function getInheritedMembers(): array {} + } +} + +namespace OCA\Circles\Model\Probes { + class CircleProble { + public function __construct() {} + } +} + +namespace OCA\Circles { + class CirclesManager { + } +} + +namespace { + + use OCP\IServerContainer; + + class OC { + static $CLI = false; + /** @var IServerContainer */ + static $server; + } +} + +namespace OC\Files\Node { + use OCP\Files\FileInfo; + abstract class Node implements \OCP\Files\Node { + /** @return FileInfo|\ArrayAccess */ + public function getFileInfo() {} + + /** @return \OCP\Files\Mount\IMountPoint */ + public function getMountPoint() {} + } +} + +namespace OC\Hooks { + class Emitter { + public function emit(string $class, string $value, array $option) {} + /** Closure $closure */ + public function listen(string $class, string $value, $closure) {} + } + class BasicEmitter extends Emitter { + } +} + +namespace OC\Cache { + /** + * @template T + */ + class CappedMemoryCache implements \ArrayAccess { + /** @return ?T */ + public function get($key) {} + /** @param T $value */ + public function set($key, $value, $ttl = '') {} + #[\ReturnTypeWillChange] + public function &offsetGet($offset) { } + public function offsetSet($offset, $value): void { } + public function offsetUnset($offset): void { } + } +} + +namespace OC\Core\Command { + use Symfony\Component\Console\Input\InputInterface; + use Symfony\Component\Console\Output\OutputInterface; + class Base { + public const OUTPUT_FORMAT_PLAIN = 'plain'; + public const OUTPUT_FORMAT_JSON = 'json'; + public const OUTPUT_FORMAT_JSON_PRETTY = 'json_pretty'; + + public function __construct() {} + protected function configure() {} + public function run(InputInterface $input, OutputInterface $output) {} + public function setName(string $name) {} + public function getHelper(string $name) {} + protected function writeArrayInOutputFormat(InputInterface $input, OutputInterface $output, $items, $prefix = ' - ') { + } + } +} + +namespace OC\Files\ObjectStore { + class NoopScanner {} +} + +namespace Symfony\Component\Console\Helper { + use Symfony\Component\Console\Output\OutputInterface; + class Table { + public function __construct(OutputInterface $text) {} + public function setHeaders(array $header) {} + public function setRows(array $rows) {} + public function render() {} + } +} + +namespace Symfony\Component\Console\Input { + class InputInterface { + public function getOption(string $key) {} + public function setOption(string $key, $value) {} + public function getArgument(string $key) {} + } + class InputArgument { + const REQUIRED = 0; + const OPTIONAL = 1; + const IS_ARRAY = 1; + } + class InputOption { + const VALUE_NONE = 1; + const VALUE_REQUIRED = 1; + const VALUE_OPTIONAL = 1; + } +} + +namespace Symfony\Component\Console\Question { + class ConfirmationQuestion { + public function __construct(string $text, bool $default) {} + } +} + +namespace Symfony\Component\Console\Output { + class OutputInterface { + public const VERBOSITY_VERBOSE = 1; + public function writeln($text, int $flat = 0) {} + } +} + +namespace OC\Files\Cache { + use OCP\Files\Cache\ICache; + use OCP\Files\Cache\ICacheEntry; + use OCP\Files\Search\ISearchQuery; + use OCP\Files\Search\ISearchOperator; + use OCP\Files\Search\ISearchQuery; + use OCP\Files\IMimeTypeLoader; + + class Cache implements ICache { + /** + * @param \OCP\Files\Cache\ICache $cache + */ + public function __construct($cache) { + $this->cache = $cache; + } + public function getNumericStorageId() { } + public function get() { } + public function getIncomplete() {} + public function getPathById($id) {} + public function getAll() {} + public function get($file) {} + public function getFolderContents($folder) {} + public function getFolderContentsById($fileId) {} + public function put($file, array $data) {} + public function insert($file, array $data) {} + public function update($id, array $data) {} + public function getId($file) {} + public function getParentId($file) {} + public function inCache($file) {} + public function remove($file) {} + public function move($source, $target) {} + public function moveFromCache(ICache $sourceCache, $sourcePath, $targetPath) {} + public function clear() {} + public function getStatus($file) {} + public function search($pattern) {} + public function searchByMime($mimetype) {} + public function searchQuery(ISearchQuery $query) {} + public function correctFolderSize($path, $data = null, $isBackgroundScan = false) {} + public function copyFromCache(ICache $sourceCache, ICacheEntry $sourceEntry, string $targetPath): int {} + public function normalize($path) {} + public function getQueryFilterForStorage(): ISearchOperator {} + public function getCacheEntryFromSearchResult(ICacheEntry $rawEntry): ?ICacheEntry {} + public static function cacheEntryFromData($data, IMimeTypeLoader $mimetypeLoader): ICacheEntry {} + } +} + +namespace OC\Files\Cache\Wrapper { + use OC\Files\Cache\Cache; + class CacheWrapper extends Cache {} +} + + +namespace OC\Files { + use OCP\Files\Cache\ICacheEntry; + use OCP\Files\Mount\IMountPoint; + use OCP\IUser; + + class Filesystem { + public static function addStorageWrapper(string $wrapperName, callable $wrapper, int $priority = 50) { + } + public static function normalizePath(string $path): string {} + } + + class FileInfo implements \OCP\Files\FileInfo { + /** + * @param string|boolean $path + * @param \OCP\Files\Storage\IStorage $storage + * @param string $internalPath + * @param array|ICacheEntry $data + * @param \OCP\Files\Mount\IMountPoint $mount + * @param \OCP\IUser|null $owner + */ + public function __construct($path, $storage, $internalPath, $data, $mount, $owner = null) {} + } + class View { + public function __construct(string $path) {} + public function unlink($path) {} + public function is_dir($path): bool {} + public function mkdir($path) {} + public function getRoot(): string {} + public function getOwner(string $path): string {} + } +} + +namespace OC\User { + use OCP\UserInterface; + use OCP\IUser; + use Symfony\Component\EventDispatcher\EventDispatcherInterface; + class User implements IUser { + public function __construct(string $uid, ?UserInterface $backend, EventDispatcherInterface $dispatcher, $emitter = null, IConfig $config = null, $urlGenerator = null) {} + } +} + +namespace OCA\DAV\Upload { + + use Sabre\DAV\File; + + abstract class FutureFile extends File {} +} + +namespace OCA\DAV\Connector\Sabre { + + class Node { + public function getFileInfo(): \OCP\Files\FileInfo {} + } +} + +namespace OC\BackgroundJob { + + use OCP\BackgroundJob\IJob; + use OCP\BackgroundJob\IJobList; + use OCP\ILogger; + + abstract class TimedJob implements IJob { + public function execute(IJobList $jobList, ILogger $logger = null) { + } + + abstract protected function run($argument); + + public function setId(int $id) { + } + + public function setLastRun(int $lastRun) { + } + + public function setArgument($argument) { + } + + public function getId() { + } + + public function getLastRun() { + } + + public function getArgument() { + } + } +} + +namespace OC\Files\Mount { + use OC\Files\Filesystem; + use OC\Files\Storage\Storage; + use OC\Files\Storage\StorageFactory; + use OCP\Files\Mount\IMountPoint; + + class MountPoint implements IMountPoint { + /** + * @var \OC\Files\Storage\Storage $storage + */ + protected $storage = null; + protected $class; + protected $storageId; + protected $rootId = null; + + /** @var int|null */ + protected $mountId; + + /** + * @param string|\OCP\Files\Storage\IStorage $storage + * @param string $mountpoint + * @param array $arguments (optional) configuration for the storage backend + * @param \OCP\Files\Storage\IStorageFactory $loader + * @param array $mountOptions mount specific options + * @param int|null $mountId + * @throws \Exception + */ + public function __construct($storage, $mountpoint, $arguments = null, $loader = null, $mountOptions = null, $mountId = null) { + throw new \Exception('stub'); + } + + /** + * get complete path to the mount point, relative to data/ + * + * @return string + */ + public function getMountPoint() { + throw new \Exception('stub'); + } + + /** + * Sets the mount point path, relative to data/ + * + * @param string $mountPoint new mount point + */ + public function setMountPoint($mountPoint) { + throw new \Exception('stub'); + } + + /** + * @return \OCP\Files\Storage\IStorage + */ + public function getStorage() { + throw new \Exception('stub'); + } + + /** + * @return string + */ + public function getStorageId() { + throw new \Exception('stub'); + } + + /** + * @return int + */ + public function getNumericStorageId() { + throw new \Exception('stub'); + } + + /** + * @param string $path + * @return string + */ + public function getInternalPath($path) { + throw new \Exception('stub'); + } + + /** + * @param callable $wrapper + */ + public function wrapStorage($wrapper) { + throw new \Exception('stub'); + } + + /** + * Get a mount option + * + * @param string $name Name of the mount option to get + * @param mixed $default Default value for the mount option + * @return mixed + */ + public function getOption($name, $default) { + throw new \Exception('stub'); + } + + /** + * Get all options for the mount + * + * @return array + */ + public function getOptions() { + throw new \Exception('stub'); + } + + /** + * @return int + */ + public function getStorageRootId() { + throw new \Exception('stub'); + } + + public function getMountId() { + throw new \Exception('stub'); + } + + public function getMountType() { + throw new \Exception('stub'); + } + + public function getMountProvider(): string { + throw new \Exception('stub'); + } + } +} + +namespace OC\Files\Storage\Wrapper{ + + use OCP\Files\Cache\ICache; + use OCP\Files\Cache\ICacheEntry; + use OCP\Files\Search\ISearchQuery; + use OCP\Files\Storage\IStorage; + + class Wrapper implements IStorage { + public function __construct(array $parameters) { + } + + public function getWrapperStorage(): ?IStorage {} + + public function getId() {} + + public function mkdir($path) {} + + public function rmdir($path) {} + + public function opendir($path) { + throw new \Exception('stub'); + } + + public function is_dir($path) { + throw new \Exception('stub'); + } + + public function is_file($path) { + throw new \Exception('stub'); + } + + public function stat($path) { + throw new \Exception('stub'); + } + + public function filetype($path) { + throw new \Exception('stub'); + } + + public function filesize($path) { + throw new \Exception('stub'); + } + + public function isCreatable($path) { + throw new \Exception('stub'); + } + + public function isReadable($path) { + throw new \Exception('stub'); + } + + public function isUpdatable($path) { + throw new \Exception('stub'); + } + + public function isDeletable($path) { + throw new \Exception('stub'); + } + + public function isSharable($path) { + throw new \Exception('stub'); + } + + public function getPermissions($path) { + throw new \Exception('stub'); + } + + public function file_exists($path) { + throw new \Exception('stub'); + } + + public function filemtime($path) { + throw new \Exception('stub'); + } + + public function file_get_contents($path) { + throw new \Exception('stub'); + } + + public function file_put_contents($path, $data) { + throw new \Exception('stub'); + } + + public function unlink($path) { + throw new \Exception('stub'); + } + + public function rename($path1, $path2) { + throw new \Exception('stub'); + } + + public function copy($path1, $path2) { + throw new \Exception('stub'); + } + + public function fopen($path, $mode) { + throw new \Exception('stub'); + } + + public function getMimeType($path) { + throw new \Exception('stub'); + } + + public function hash($type, $path, $raw = false) { + throw new \Exception('stub'); + } + + public function free_space($path) { + throw new \Exception('stub'); + } + + public function touch($path, $mtime = null) { + throw new \Exception('stub'); + } + + public function getLocalFile($path) { + throw new \Exception('stub'); + } + + public function hasUpdated($path, $time) { + throw new \Exception('stub'); + } + + public function getETag($path) { + throw new \Exception('stub'); + } + + public function isLocal() { + throw new \Exception('stub'); + } + + public function instanceOfStorage($class) { + throw new \Exception('stub'); + } + + public function getDirectDownload($path) { + throw new \Exception('stub'); + } + + public function verifyPath($path, $fileName) { + throw new \Exception('stub'); + } + + public function copyFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) { + throw new \Exception('stub'); + } + + public function moveFromStorage(IStorage $sourceStorage, $sourceInternalPath, $targetInternalPath) { + throw new \Exception('stub'); + } + + public function test() { + throw new \Exception('stub'); + } + + public function getAvailability() { + throw new \Exception('stub'); + } + + public function setAvailability($isAvailable) { + throw new \Exception('stub'); + } + + public function getOwner($path) { + throw new \Exception('stub'); + } + + public function getCache() { + throw new \Exception('stub'); + } + + public function getPropagator() { + throw new \Exception('stub'); + } + + public function getScanner() { + throw new \Exception('stub'); + } + + public function getUpdater() { + throw new \Exception('stub'); + } + + public function getWatcher() { + throw new \Exception('stub'); + } + } + + class Jail extends Wrapper { + public function getUnjailedPath(string $path): string {} + } + + class Quota extends Wrapper { + public function getQuota() {} + } + + class PermissionsMask extends Wrapper { + public function getQuota() {} + } +} diff --git a/tests/unit/Db/AclMapperTest.php b/tests/unit/Db/AclMapperTest.php index b985669f7..528fbb834 100644 --- a/tests/unit/Db/AclMapperTest.php +++ b/tests/unit/Db/AclMapperTest.php @@ -24,8 +24,10 @@ namespace OCA\Deck\Db; use OCA\Deck\Service\CirclesService; +use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\AppFramework\Db\MapperTestUtility; @@ -46,15 +48,15 @@ class AclMapperTest extends MapperTestUtility { public function setup(): void { parent::setUp(); - $this->dbConnection = \OC::$server->getDatabaseConnection(); + $this->dbConnection = Server::get(IDBConnection::class); $this->aclMapper = new AclMapper($this->dbConnection); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->boardMapper = new BoardMapper( $this->dbConnection, - \OC::$server->query(LabelMapper::class), + Server::get(LabelMapper::class), $this->aclMapper, - \OC::$server->query(StackMapper::class), + Server::get(StackMapper::class), $this->userManager, $this->groupManager, $this->createMock(CirclesService::class), diff --git a/tests/unit/Db/AttachmentMapperTest.php b/tests/unit/Db/AttachmentMapperTest.php index 32585cc5b..306714a28 100644 --- a/tests/unit/Db/AttachmentMapperTest.php +++ b/tests/unit/Db/AttachmentMapperTest.php @@ -26,6 +26,7 @@ namespace OCA\Deck\Db; use OCP\AppFramework\Db\DoesNotExistException; use OCP\IDBConnection; use OCP\IUserManager; +use OCP\Server; use Test\AppFramework\Db\MapperTestUtility; /** @@ -52,7 +53,7 @@ class AttachmentMapperTest extends MapperTestUtility { $this->userManager = $this->createMock(IUserManager::class); $this->cardMapper = $this->createMock(CardMapper::class); - $this->dbConnection = \OC::$server->getDatabaseConnection(); + $this->dbConnection = Server::get(IDBConnection::class); $this->attachmentMapper = new AttachmentMapper( $this->dbConnection, $this->cardMapper, diff --git a/tests/unit/Db/BoardMapperTest.php b/tests/unit/Db/BoardMapperTest.php index 43420333d..9fbd5aca8 100644 --- a/tests/unit/Db/BoardMapperTest.php +++ b/tests/unit/Db/BoardMapperTest.php @@ -27,6 +27,7 @@ use OCA\Deck\Service\CirclesService; use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUserManager; +use OCP\Server; use Psr\Log\LoggerInterface; use Test\AppFramework\Db\MapperTestUtility; @@ -56,19 +57,19 @@ class BoardMapperTest extends MapperTestUtility { $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); - $this->dbConnection = \OC::$server->getDatabaseConnection(); + $this->dbConnection = Server::get(IDBConnection::class); $this->boardMapper = new BoardMapper( $this->dbConnection, - \OC::$server->query(LabelMapper::class), - \OC::$server->query(AclMapper::class), - \OC::$server->query(StackMapper::class), + Server::get(LabelMapper::class), + Server::get(AclMapper::class), + Server::get(StackMapper::class), $this->userManager, $this->groupManager, $this->createMock(CirclesService::class), $this->createMock(LoggerInterface::class) ); - $this->aclMapper = \OC::$server->query(AclMapper::class); - $this->labelMapper = \OC::$server->query(LabelMapper::class); + $this->aclMapper = Server::get(AclMapper::class); + $this->labelMapper = Server::get(LabelMapper::class); $this->boards = [ $this->boardMapper->insert($this->getBoard('MyBoard 1', 'user1')), @@ -89,8 +90,7 @@ class BoardMapperTest extends MapperTestUtility { $board->resetUpdatedFields(); } } - /** @return Acl */ - public function getAcl($type = 'user', $participant = 'admin', $edit = false, $share = false, $manage = false, $boardId = 123) { + public function getAcl($type = 'user', $participant = 'admin', $edit = false, $share = false, $manage = false, $boardId = 123): ACL { $acl = new Acl(); $acl->setParticipant($participant); $acl->setType('user'); @@ -101,8 +101,7 @@ class BoardMapperTest extends MapperTestUtility { return $acl; } - /** @return Board */ - public function getBoard($title, $owner) { + public function getBoard($title, $owner): Board { $board = new Board(); $board->setTitle($title); $board->setOwner($owner); diff --git a/tests/unit/Notification/NotifierTest.php b/tests/unit/Notification/NotifierTest.php index 52edf7dd4..229948216 100644 --- a/tests/unit/Notification/NotifierTest.php +++ b/tests/unit/Notification/NotifierTest.php @@ -33,6 +33,7 @@ use OCP\IUser; use OCP\IUserManager; use OCP\L10N\IFactory; use OCP\Notification\INotification; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; class NotifierTest extends \Test\TestCase { @@ -70,7 +71,7 @@ class NotifierTest extends \Test\TestCase { $this->stackMapper, $this->boardMapper ); - $this->l10n = \OC::$server->getL10N('deck'); + $this->l10n = Server::get(IFactory::class)->get('deck'); $this->l10nFactory->expects($this->once()) ->method('get') ->willReturn($this->l10n); @@ -78,7 +79,7 @@ class NotifierTest extends \Test\TestCase { public function testPrepareWrongApp() { $this->expectException(\InvalidArgumentException::class); - /** @var INotification $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') @@ -88,7 +89,7 @@ class NotifierTest extends \Test\TestCase { } public function testPrepareCardOverdue() { - /** @var INotification $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') @@ -131,7 +132,7 @@ class NotifierTest extends \Test\TestCase { } public function testPrepareCardCommentMentioned() { - /** @var INotification $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') @@ -188,7 +189,7 @@ class NotifierTest extends \Test\TestCase { ->method('findStackFromCardId') ->willReturn($this->buildMockStack(123)); - /** @var INotification $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') @@ -272,7 +273,7 @@ class NotifierTest extends \Test\TestCase { /** @dataProvider dataPrepareBoardShared */ public function testPrepareBoardShared($withUserFound = true) { - /** @var INotification $notification */ + /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); $notification->expects($this->once()) ->method('getApp') diff --git a/tests/unit/Service/BoardServiceTest.php b/tests/unit/Service/BoardServiceTest.php index 702e16cd4..128865c8e 100644 --- a/tests/unit/Service/BoardServiceTest.php +++ b/tests/unit/Service/BoardServiceTest.php @@ -39,9 +39,11 @@ use OCA\Deck\NoPermissionException; use OCA\Deck\Notification\NotificationHelper; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; +use OCP\IDBConnection; use OCP\IUser; use OCP\IUserManager; use OCP\IGroupManager; +use PHPUnit\Framework\MockObject\MockObject; use \Test\TestCase; use OCP\IURLGenerator; @@ -80,6 +82,8 @@ class BoardServiceTest extends TestCase { private $userId = 'admin'; /** @var IURLGenerator */ private $urlGenerator; + /** @var IDBConnection|MockObject */ + private $connection; public function setUp(): void { parent::setUp(); @@ -99,6 +103,7 @@ class BoardServiceTest extends TestCase { $this->changeHelper = $this->createMock(ChangeHelper::class); $this->eventDispatcher = $this->createMock(IEventDispatcher::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->connection = $this->createMock(IDBConnection::class); $this->service = new BoardService( $this->boardMapper, @@ -117,6 +122,7 @@ class BoardServiceTest extends TestCase { $this->eventDispatcher, $this->changeHelper, $this->urlGenerator, + $this->connection, $this->userId ); diff --git a/tests/unit/Service/CardServiceTest.php b/tests/unit/Service/CardServiceTest.php index ca260dc9b..dd18e67e9 100644 --- a/tests/unit/Service/CardServiceTest.php +++ b/tests/unit/Service/CardServiceTest.php @@ -38,9 +38,11 @@ use OCA\Deck\StatusException; use OCP\Activity\IEvent; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IRequest; use OCP\IUser; use OCP\IUserManager; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; use OCP\IURLGenerator; @@ -76,9 +78,12 @@ class CardServiceTest extends TestCase { private $eventDispatcher; /** @var ChangeHelper|MockObject */ private $changeHelper; - /** @var IURLGenerator|MockObject */ private $urlGenerator; + /** @var IRequest|MockObject */ + private $request; + /** @var LoggerInterface|MockObject */ + private $logger; public function setUp(): void { parent::setUp(); @@ -97,6 +102,11 @@ class CardServiceTest extends TestCase { $this->eventDispatcher = $this->createMock(IEventDispatcher::class); $this->changeHelper = $this->createMock(ChangeHelper::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->request = $this->createMock(IRequest::class); + + $this->logger->expects($this->any())->method('error'); + $this->cardService = new CardService( $this->cardMapper, $this->stackMapper, @@ -113,6 +123,8 @@ class CardServiceTest extends TestCase { $this->changeHelper, $this->eventDispatcher, $this->urlGenerator, + $this->logger, + $this->request, 'user1' ); } diff --git a/tests/unit/Service/Importer/Systems/TrelloJsonServiceTest.php b/tests/unit/Service/Importer/Systems/TrelloJsonServiceTest.php index 6eec07a9b..46c0799d1 100644 --- a/tests/unit/Service/Importer/Systems/TrelloJsonServiceTest.php +++ b/tests/unit/Service/Importer/Systems/TrelloJsonServiceTest.php @@ -27,11 +27,11 @@ use OCP\IL10N; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; +use OCP\Server; use PHPUnit\Framework\MockObject\MockObject; class TrelloJsonServiceTest extends \Test\TestCase { - /** @var TrelloJsonService */ - private $service; + private TrelloJsonService $service; /** @var IURLGenerator|MockObject */ private $urlGenerator; /** @var IUserManager|MockObject */ @@ -128,7 +128,7 @@ class TrelloJsonServiceTest extends \Test\TestCase { } public function testGetBoardWithSuccess() { - $importService = \OC::$server->get(BoardImportService::class); + $importService = Server::get(BoardImportService::class); $data = json_decode(file_get_contents(__DIR__ . '/../../../../data/data-trelloJson.json')); $importService->setData($data); diff --git a/tests/unit/Service/StackServiceTest.php b/tests/unit/Service/StackServiceTest.php index 913a74f69..f7ad493b4 100644 --- a/tests/unit/Service/StackServiceTest.php +++ b/tests/unit/Service/StackServiceTest.php @@ -33,6 +33,7 @@ use OCA\Deck\Db\Label; use OCA\Deck\Db\LabelMapper; use OCA\Deck\Db\Stack; use OCA\Deck\Db\StackMapper; +use Psr\Log\LoggerInterface; use \Test\TestCase; /** @@ -67,6 +68,8 @@ class StackServiceTest extends TestCase { private $activityManager; /** @var ChangeHelper|\PHPUnit\Framework\MockObject\MockObject */ private $changeHelper; + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + private $logger; public function setUp(): void { parent::setUp(); @@ -81,6 +84,7 @@ class StackServiceTest extends TestCase { $this->labelMapper = $this->createMock(LabelMapper::class); $this->activityManager = $this->createMock(ActivityManager::class); $this->changeHelper = $this->createMock(ChangeHelper::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->stackService = new StackService( $this->stackMapper, @@ -93,7 +97,8 @@ class StackServiceTest extends TestCase { $this->assignedUsersMapper, $this->attachmentService, $this->activityManager, - $this->changeHelper + $this->changeHelper, + $this->logger ); } diff --git a/tests/unit/controller/BoardControllerTest.php b/tests/unit/controller/BoardControllerTest.php index d9dffb928..505d96fda 100644 --- a/tests/unit/controller/BoardControllerTest.php +++ b/tests/unit/controller/BoardControllerTest.php @@ -167,7 +167,7 @@ class BoardControllerTest extends \Test\TestCase { $this->boardService->expects($this->once()) ->method('deleteAcl') ->with(1) - ->willReturn(1); - $this->assertEquals(1, $this->controller->deleteAcl(1)); + ->willReturn(true); + $this->assertEquals(true, $this->controller->deleteAcl(1)); } } diff --git a/tests/unit/controller/PageControllerTest.php b/tests/unit/controller/PageControllerTest.php index a7d78adc3..81c10bfbe 100644 --- a/tests/unit/controller/PageControllerTest.php +++ b/tests/unit/controller/PageControllerTest.php @@ -31,6 +31,7 @@ use OCA\Deck\Service\PermissionService; use OCP\EventDispatcher\IEventDispatcher; use OCP\IInitialStateService; use OCP\IRequest; +use OCP\IConfig; use OCP\IURLGenerator; use PHPUnit\Framework\TestCase; @@ -53,6 +54,8 @@ class PageControllerTest extends TestCase { * @var mixed|CardService|\PHPUnit\Framework\MockObject\MockObject */ private $cardService; + /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ + private $config; public function setUp(): void { $this->request = $this->createMock(IRequest::class); @@ -63,6 +66,7 @@ class PageControllerTest extends TestCase { $this->cardMapper = $this->createMock(CardMapper::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->cardService = $this->createMock(CardService::class); + $this->config = $this->createMock(IConfig::class); $this->controller = new PageController( 'deck', @@ -73,7 +77,8 @@ class PageControllerTest extends TestCase { $this->eventDispatcher, $this->cardMapper, $this->urlGenerator, - $this->cardService + $this->cardService, + $this->config ); }