From c8c8f9382f4eb3e4ece1c37be288fda7b01bf06b Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 17 Dec 2021 16:05:45 +0100 Subject: [PATCH 01/23] Move createSubscription and deleteSubscription event handlers to proper listeners Signed-off-by: Thomas Citharel --- .../composer/composer/autoload_classmap.php | 2 + .../dav/composer/composer/autoload_static.php | 2 + apps/dav/lib/AppInfo/Application.php | 52 ++---------- .../Listener/SubscriptionCreationListener.php | 81 +++++++++++++++++++ .../Listener/SubscriptionDeletionListener.php | 78 ++++++++++++++++++ 5 files changed, 170 insertions(+), 45 deletions(-) create mode 100644 apps/dav/lib/Listener/SubscriptionCreationListener.php create mode 100644 apps/dav/lib/Listener/SubscriptionDeletionListener.php diff --git a/apps/dav/composer/composer/autoload_classmap.php b/apps/dav/composer/composer/autoload_classmap.php index cf02a3221fbe0..1b6176be2e370 100644 --- a/apps/dav/composer/composer/autoload_classmap.php +++ b/apps/dav/composer/composer/autoload_classmap.php @@ -239,6 +239,8 @@ 'OCA\\DAV\\Listener\\CalendarDeletionDefaultUpdaterListener' => $baseDir . '/../lib/Listener/CalendarDeletionDefaultUpdaterListener.php', 'OCA\\DAV\\Listener\\CalendarObjectReminderUpdaterListener' => $baseDir . '/../lib/Listener/CalendarObjectReminderUpdaterListener.php', 'OCA\\DAV\\Listener\\CardListener' => $baseDir . '/../lib/Listener/CardListener.php', + 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => $baseDir . '/../lib/Listener/SubscriptionCreationListener.php', + 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => $baseDir . '/../lib/Listener/SubscriptionDeletionListener.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndex.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndexBackgroundJob' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndexBackgroundJob.php', 'OCA\\DAV\\Migration\\BuildSocialSearchIndex' => $baseDir . '/../lib/Migration/BuildSocialSearchIndex.php', diff --git a/apps/dav/composer/composer/autoload_static.php b/apps/dav/composer/composer/autoload_static.php index d164ab2b1ce71..0f5f6c7b87a76 100644 --- a/apps/dav/composer/composer/autoload_static.php +++ b/apps/dav/composer/composer/autoload_static.php @@ -254,6 +254,8 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Listener\\CalendarDeletionDefaultUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarDeletionDefaultUpdaterListener.php', 'OCA\\DAV\\Listener\\CalendarObjectReminderUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarObjectReminderUpdaterListener.php', 'OCA\\DAV\\Listener\\CardListener' => __DIR__ . '/..' . '/../lib/Listener/CardListener.php', + 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionCreationListener.php', + 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionDeletionListener.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndex.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndexBackgroundJob' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndexBackgroundJob.php', 'OCA\\DAV\\Migration\\BuildSocialSearchIndex' => __DIR__ . '/..' . '/../lib/Migration/BuildSocialSearchIndex.php', diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index f29161d69760a..bfb5ab55ee127 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -36,17 +36,14 @@ use OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob; use OCA\DAV\CalDAV\Activity\Backend; use OCA\DAV\CalDAV\BirthdayService; -use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\CalendarManager; use OCA\DAV\CalDAV\CalendarProvider; -use OCA\DAV\CalDAV\Reminder\Backend as ReminderBackend; use OCA\DAV\CalDAV\Reminder\NotificationProvider\AudioProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider; use OCA\DAV\CalDAV\Reminder\NotificationProviderManager; use OCA\DAV\CalDAV\Reminder\Notifier; -use OCA\DAV\CalDAV\WebcalCaching\RefreshWebcalService; use OCA\DAV\Capabilities; use OCA\DAV\CardDAV\CardDavBackend; use OCA\DAV\CardDAV\ContactsManager; @@ -70,6 +67,8 @@ use OCA\DAV\Events\CardCreatedEvent; use OCA\DAV\Events\CardDeletedEvent; use OCA\DAV\Events\CardUpdatedEvent; +use OCA\DAV\Events\SubscriptionCreatedEvent; +use OCA\DAV\Events\SubscriptionDeletedEvent; use OCA\DAV\HookManager; use OCA\DAV\Listener\ActivityUpdaterListener; use OCA\DAV\Listener\AddressbookListener; @@ -77,6 +76,8 @@ use OCA\DAV\Listener\CalendarDeletionDefaultUpdaterListener; use OCA\DAV\Listener\CalendarObjectReminderUpdaterListener; use OCA\DAV\Listener\CardListener; +use OCA\DAV\Listener\SubscriptionCreationListener; +use OCA\DAV\Listener\SubscriptionDeletionListener; use OCA\DAV\Search\ContactsSearchProvider; use OCA\DAV\Search\EventsSearchProvider; use OCA\DAV\Search\TasksSearchProvider; @@ -154,6 +155,9 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(CalendarObjectRestoredEvent::class, CalendarObjectReminderUpdaterListener::class); $context->registerEventListener(CalendarShareUpdatedEvent::class, CalendarContactInteractionListener::class); + $context->registerEventListener(SubscriptionCreatedEvent::class, SubscriptionCreationListener::class); + $context->registerEventListener(SubscriptionDeletedEvent::class, SubscriptionDeletionListener::class); + $context->registerEventListener(AddressBookCreatedEvent::class, AddressbookListener::class); $context->registerEventListener(AddressBookDeletedEvent::class, AddressbookListener::class); @@ -274,48 +278,6 @@ function (GenericEvent $event) { } ); - $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', - function (GenericEvent $event) use ($container, $serverContainer) { - $jobList = $serverContainer->getJobList(); - $subscriptionData = $event->getArgument('subscriptionData'); - - /** - * Initial subscription refetch - * - * @var RefreshWebcalService $refreshWebcalService - */ - $refreshWebcalService = $container->query(RefreshWebcalService::class); - $refreshWebcalService->refreshSubscription( - (string) $subscriptionData['principaluri'], - (string) $subscriptionData['uri'] - ); - - $jobList->add(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [ - 'principaluri' => $subscriptionData['principaluri'], - 'uri' => $subscriptionData['uri'] - ]); - } - ); - - $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', - function (GenericEvent $event) use ($container, $serverContainer) { - $jobList = $serverContainer->getJobList(); - $subscriptionData = $event->getArgument('subscriptionData'); - - $jobList->remove(\OCA\DAV\BackgroundJob\RefreshWebcalJob::class, [ - 'principaluri' => $subscriptionData['principaluri'], - 'uri' => $subscriptionData['uri'] - ]); - - /** @var CalDavBackend $calDavBackend */ - $calDavBackend = $container->get(CalDavBackend::class); - $calDavBackend->purgeAllCachedEventsForSubscription($subscriptionData['id']); - /** @var ReminderBackend $calDavBackend */ - $reminderBackend = $container->get(ReminderBackend::class); - $reminderBackend->cleanRemindersForCalendar((int) $subscriptionData['id']); - } - ); - $eventHandler = function () use ($container, $serverContainer): void { try { /** @var UpdateCalendarResourcesRoomsBackgroundJob $job */ diff --git a/apps/dav/lib/Listener/SubscriptionCreationListener.php b/apps/dav/lib/Listener/SubscriptionCreationListener.php new file mode 100644 index 0000000000000..7cd01827c38de --- /dev/null +++ b/apps/dav/lib/Listener/SubscriptionCreationListener.php @@ -0,0 +1,81 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Listener; + +use OCA\DAV\BackgroundJob\RefreshWebcalJob; +use OCA\DAV\CalDAV\WebcalCaching\RefreshWebcalService; +use OCA\DAV\Events\SubscriptionCreatedEvent; +use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use Psr\Log\LoggerInterface; + +/** + * @template-implements IEventListener<\OCA\DAV\Events\SubscriptionCreatedEvent> + */ +class SubscriptionCreationListener implements IEventListener { + + /** @var IJobList */ + private $jobList; + + /** @var RefreshWebcalService */ + private $refreshWebcalService; + + /** @var LoggerInterface */ + private $logger; + + public function __construct(IJobList $jobList, RefreshWebcalService $refreshWebcalService, + LoggerInterface $logger) { + $this->jobList = $jobList; + $this->refreshWebcalService = $refreshWebcalService; + $this->logger = $logger; + } + + /** + * In case the user has set their default calendar to the deleted one + */ + public function handle(Event $event): void { + if (!($event instanceof SubscriptionCreatedEvent)) { + // Not what we subscribed to + return; + } + + $subscriptionId = $event->getSubscriptionId(); + $subscriptionData = $event->getSubscriptionData(); + + $this->logger->debug('Refreshing webcal data for subscription ' . $subscriptionId); + $this->refreshWebcalService->refreshSubscription( + (string) $subscriptionData['principaluri'], + (string) $subscriptionData['uri'] + ); + + $this->logger->debug('Scheduling webcal data refreshment for subscription ' . $subscriptionId); + $this->jobList->add(RefreshWebcalJob::class, [ + 'principaluri' => $subscriptionData['principaluri'], + 'uri' => $subscriptionData['uri'] + ]); + } +} diff --git a/apps/dav/lib/Listener/SubscriptionDeletionListener.php b/apps/dav/lib/Listener/SubscriptionDeletionListener.php new file mode 100644 index 0000000000000..d59314c6f1076 --- /dev/null +++ b/apps/dav/lib/Listener/SubscriptionDeletionListener.php @@ -0,0 +1,78 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Listener; + +use OCA\DAV\BackgroundJob\RefreshWebcalJob; +use OCA\DAV\CalDAV\Reminder\Backend as ReminderBackend; +use OCA\DAV\Events\SubscriptionDeletedEvent; +use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use Psr\Log\LoggerInterface; + +/** + * @template-implements IEventListener<\OCA\DAV\Events\SubscriptionDeletedEvent> + */ +class SubscriptionDeletionListener implements IEventListener { + + /** @var IJobList */ + private $jobList; + + /** @var ReminderBackend */ + private $reminderBackend; + + /** @var LoggerInterface */ + private $logger; + + public function __construct(IJobList $jobList, ReminderBackend $reminderBackend, + LoggerInterface $logger) { + $this->jobList = $jobList; + $this->reminderBackend = $reminderBackend; + $this->logger = $logger; + } + + /** + * In case the user has set their default calendar to the deleted one + */ + public function handle(Event $event): void { + if (!($event instanceof SubscriptionDeletedEvent)) { + // Not what we subscribed to + return; + } + + $subscriptionId = $event->getSubscriptionId(); + $subscriptionData = $event->getSubscriptionData(); + + $this->logger->debug('Removing refresh webcal job for subscription ' . $subscriptionId); + $this->jobList->remove(RefreshWebcalJob::class, [ + 'principaluri' => $subscriptionData['principaluri'], + 'uri' => $subscriptionData['uri'] + ]); + + $this->logger->debug('Cleaning all reminders for subscription ' . $subscriptionId); + $this->reminderBackend->cleanRemindersForCalendar($subscriptionId); + } +} From bfdfd3e2fd42d2235b18952c7c1ea829bae1101d Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 17 Dec 2021 16:08:33 +0100 Subject: [PATCH 02/23] Remove uses of LegacyDispatcher for create/delete subscriptions Signed-off-by: Thomas Citharel --- apps/dav/lib/CalDAV/CalDavBackend.php | 13 ------------- 1 file changed, 13 deletions(-) diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index d949f32c1fcd2..70bfac84775a0 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -2542,12 +2542,6 @@ public function createSubscription($principalUri, $uri, array $properties) { $subscriptionRow = $this->getSubscriptionById($subscriptionId); $this->dispatcher->dispatchTyped(new SubscriptionCreatedEvent($subscriptionId, $subscriptionRow)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createSubscription', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::createSubscription', - [ - 'subscriptionId' => $subscriptionId, - 'subscriptionData' => $subscriptionRow, - ])); return $subscriptionId; } @@ -2616,13 +2610,6 @@ public function updateSubscription($subscriptionId, PropPatch $propPatch) { public function deleteSubscription($subscriptionId) { $subscriptionRow = $this->getSubscriptionById($subscriptionId); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::deleteSubscription', - [ - 'subscriptionId' => $subscriptionId, - 'subscriptionData' => $this->getSubscriptionById($subscriptionId), - ])); - $query = $this->db->getQueryBuilder(); $query->delete('calendarsubscriptions') ->where($query->expr()->eq('id', $query->createNamedParameter($subscriptionId))) From dfa2cc3be451bd5a45874ba6b2114fb361d3a546 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 17 Dec 2021 16:39:19 +0100 Subject: [PATCH 03/23] Move every event to listeners and remove all uses of legacy dispatcher Signed-off-by: Thomas Citharel --- apps/dav/appinfo/v1/caldav.php | 2 - .../composer/composer/autoload_classmap.php | 3 + .../dav/composer/composer/autoload_static.php | 3 + apps/dav/lib/AppInfo/Application.php | 18 +++-- apps/dav/lib/CalDAV/Activity/Backend.php | 2 +- apps/dav/lib/CalDAV/CalDavBackend.php | 58 ---------------- apps/dav/lib/Command/CreateCalendar.php | 2 - .../Listener/CalendarPublicationListener.php | 67 ++++++++++++++++++ .../Listener/CalendarShareUpdateListener.php | 69 +++++++++++++++++++ .../CalendarUnpublicationListener.php | 67 ++++++++++++++++++ apps/dav/lib/RootCollection.php | 2 +- .../unit/CalDAV/AbstractCalDavBackend.php | 8 +-- .../tests/unit/CalDAV/CalDavBackendTest.php | 3 - .../unit/CalDAV/PublicCalendarRootTest.php | 3 - 14 files changed, 220 insertions(+), 87 deletions(-) create mode 100644 apps/dav/lib/Listener/CalendarPublicationListener.php create mode 100644 apps/dav/lib/Listener/CalendarShareUpdateListener.php create mode 100644 apps/dav/lib/Listener/CalendarUnpublicationListener.php diff --git a/apps/dav/appinfo/v1/caldav.php b/apps/dav/appinfo/v1/caldav.php index 75400264f7530..260192b4d9b08 100644 --- a/apps/dav/appinfo/v1/caldav.php +++ b/apps/dav/appinfo/v1/caldav.php @@ -61,7 +61,6 @@ $random = \OC::$server->getSecureRandom(); $logger = \OC::$server->getLogger(); $dispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class); -$legacyDispatcher = \OC::$server->getEventDispatcher(); $config = \OC::$server->get(\OCP\IConfig::class); $calDavBackend = new CalDavBackend( @@ -72,7 +71,6 @@ $random, $logger, $dispatcher, - $legacyDispatcher, $config, true ); diff --git a/apps/dav/composer/composer/autoload_classmap.php b/apps/dav/composer/composer/autoload_classmap.php index 1b6176be2e370..3ff69ac8a8b7f 100644 --- a/apps/dav/composer/composer/autoload_classmap.php +++ b/apps/dav/composer/composer/autoload_classmap.php @@ -238,6 +238,9 @@ 'OCA\\DAV\\Listener\\CalendarContactInteractionListener' => $baseDir . '/../lib/Listener/CalendarContactInteractionListener.php', 'OCA\\DAV\\Listener\\CalendarDeletionDefaultUpdaterListener' => $baseDir . '/../lib/Listener/CalendarDeletionDefaultUpdaterListener.php', 'OCA\\DAV\\Listener\\CalendarObjectReminderUpdaterListener' => $baseDir . '/../lib/Listener/CalendarObjectReminderUpdaterListener.php', + 'OCA\\DAV\\Listener\\CalendarPublicationListener' => $baseDir . '/../lib/Listener/CalendarPublicationListener.php', + 'OCA\\DAV\\Listener\\CalendarShareUpdateListener' => $baseDir . '/../lib/Listener/CalendarShareUpdateListener.php', + 'OCA\\DAV\\Listener\\CalendarUnpublicationListener' => $baseDir . '/../lib/Listener/CalendarUnpublicationListener.php', 'OCA\\DAV\\Listener\\CardListener' => $baseDir . '/../lib/Listener/CardListener.php', 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => $baseDir . '/../lib/Listener/SubscriptionCreationListener.php', 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => $baseDir . '/../lib/Listener/SubscriptionDeletionListener.php', diff --git a/apps/dav/composer/composer/autoload_static.php b/apps/dav/composer/composer/autoload_static.php index 0f5f6c7b87a76..6e734b49847c9 100644 --- a/apps/dav/composer/composer/autoload_static.php +++ b/apps/dav/composer/composer/autoload_static.php @@ -253,6 +253,9 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Listener\\CalendarContactInteractionListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarContactInteractionListener.php', 'OCA\\DAV\\Listener\\CalendarDeletionDefaultUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarDeletionDefaultUpdaterListener.php', 'OCA\\DAV\\Listener\\CalendarObjectReminderUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarObjectReminderUpdaterListener.php', + 'OCA\\DAV\\Listener\\CalendarPublicationListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarPublicationListener.php', + 'OCA\\DAV\\Listener\\CalendarShareUpdateListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarShareUpdateListener.php', + 'OCA\\DAV\\Listener\\CalendarUnpublicationListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarUnpublicationListener.php', 'OCA\\DAV\\Listener\\CardListener' => __DIR__ . '/..' . '/../lib/Listener/CardListener.php', 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionCreationListener.php', 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionDeletionListener.php', diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index bfb5ab55ee127..eafab3743691a 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -61,8 +61,10 @@ use OCA\DAV\Events\CalendarObjectMovedToTrashEvent; use OCA\DAV\Events\CalendarObjectRestoredEvent; use OCA\DAV\Events\CalendarObjectUpdatedEvent; +use OCA\DAV\Events\CalendarPublishedEvent; use OCA\DAV\Events\CalendarRestoredEvent; use OCA\DAV\Events\CalendarShareUpdatedEvent; +use OCA\DAV\Events\CalendarUnpublishedEvent; use OCA\DAV\Events\CalendarUpdatedEvent; use OCA\DAV\Events\CardCreatedEvent; use OCA\DAV\Events\CardDeletedEvent; @@ -75,6 +77,9 @@ use OCA\DAV\Listener\CalendarContactInteractionListener; use OCA\DAV\Listener\CalendarDeletionDefaultUpdaterListener; use OCA\DAV\Listener\CalendarObjectReminderUpdaterListener; +use OCA\DAV\Listener\CalendarPublicationListener; +use OCA\DAV\Listener\CalendarShareUpdateListener; +use OCA\DAV\Listener\CalendarUnpublicationListener; use OCA\DAV\Listener\CardListener; use OCA\DAV\Listener\SubscriptionCreationListener; use OCA\DAV\Listener\SubscriptionDeletionListener; @@ -154,6 +159,9 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(CalendarObjectRestoredEvent::class, ActivityUpdaterListener::class); $context->registerEventListener(CalendarObjectRestoredEvent::class, CalendarObjectReminderUpdaterListener::class); $context->registerEventListener(CalendarShareUpdatedEvent::class, CalendarContactInteractionListener::class); + $context->registerEventListener(CalendarPublishedEvent::class, CalendarPublicationListener::class); + $context->registerEventListener(CalendarUnpublishedEvent::class, CalendarUnpublicationListener::class); + $context->registerEventListener(CalendarShareUpdatedEvent::class, CalendarShareUpdateListener::class); $context->registerEventListener(SubscriptionCreatedEvent::class, SubscriptionCreationListener::class); $context->registerEventListener(SubscriptionDeletedEvent::class, SubscriptionDeletionListener::class); @@ -256,16 +264,6 @@ public function registerHooks(HookManager $hm, // Here we should recalculate if reminders should be sent to new or old sharees }); - $dispatcher->addListener('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', function (GenericEvent $event) use ($container) { - /** @var Backend $backend */ - $backend = $container->query(Backend::class); - $backend->onCalendarPublication( - $event->getArgument('calendarData'), - $event->getArgument('public') - ); - }); - - $dispatcher->addListener('OCP\Federation\TrustedServerEvent::remove', function (GenericEvent $event) { /** @var CardDavBackend $cardDavBackend */ diff --git a/apps/dav/lib/CalDAV/Activity/Backend.php b/apps/dav/lib/CalDAV/Activity/Backend.php index 84ba50b8c37b6..af2d790e10d05 100644 --- a/apps/dav/lib/CalDAV/Activity/Backend.php +++ b/apps/dav/lib/CalDAV/Activity/Backend.php @@ -119,7 +119,7 @@ public function onCalendarDelete(array $calendarData, array $shares): void { * @param array $calendarData * @param bool $publishStatus */ - public function onCalendarPublication(array $calendarData, $publishStatus) { + public function onCalendarPublication(array $calendarData, bool $publishStatus): void { $this->triggerCalendarActivity($publishStatus ? Calendar::SUBJECT_PUBLISH : Calendar::SUBJECT_UNPUBLISH, $calendarData); } diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 70bfac84775a0..2294ba58a9d8b 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -95,8 +95,6 @@ use Sabre\VObject\Property; use Sabre\VObject\Reader; use Sabre\VObject\Recur\EventIterator; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Component\EventDispatcher\GenericEvent; use function array_merge; use function array_values; use function explode; @@ -225,9 +223,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription /** @var IEventDispatcher */ private $dispatcher; - /** @var EventDispatcherInterface */ - private $legacyDispatcher; - /** @var IConfig */ private $config; @@ -247,7 +242,6 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @param ISecureRandom $random * @param ILogger $logger * @param IEventDispatcher $dispatcher - * @param EventDispatcherInterface $legacyDispatcher * @param bool $legacyEndpoint */ public function __construct(IDBConnection $db, @@ -257,7 +251,6 @@ public function __construct(IDBConnection $db, ISecureRandom $random, ILogger $logger, IEventDispatcher $dispatcher, - EventDispatcherInterface $legacyDispatcher, IConfig $config, bool $legacyEndpoint = false) { $this->db = $db; @@ -267,7 +260,6 @@ public function __construct(IDBConnection $db, $this->random = $random; $this->logger = $logger; $this->dispatcher = $dispatcher; - $this->legacyDispatcher = $legacyDispatcher; $this->config = $config; $this->legacyEndpoint = $legacyEndpoint; } @@ -1336,15 +1328,6 @@ public function createCalendarObject($calendarId, $objectUri, $calendarData, $ca $subscriptionRow = $this->getSubscriptionById($calendarId); $this->dispatcher->dispatchTyped(new CachedCalendarObjectCreatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::createCachedCalendarObject', - [ - 'subscriptionId' => $calendarId, - 'calendarData' => $subscriptionRow, - 'shares' => [], - 'objectData' => $objectRow, - ] - )); } return '"' . $extraData['etag'] . '"'; @@ -1401,15 +1384,6 @@ public function updateCalendarObject($calendarId, $objectUri, $calendarData, $ca $subscriptionRow = $this->getSubscriptionById($calendarId); $this->dispatcher->dispatchTyped(new CachedCalendarObjectUpdatedEvent((int)$calendarId, $subscriptionRow, [], $objectRow)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::updateCachedCalendarObject', - [ - 'subscriptionId' => $calendarId, - 'calendarData' => $subscriptionRow, - 'shares' => [], - 'objectData' => $objectRow, - ] - )); } } @@ -1517,15 +1491,6 @@ public function deleteCalendarObject($calendarId, $objectUri, $calendarType = se $subscriptionRow = $this->getSubscriptionById($calendarId); $this->dispatcher->dispatchTyped(new CachedCalendarObjectDeletedEvent((int)$calendarId, $subscriptionRow, [], $data)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::deleteCachedCalendarObject', - [ - 'subscriptionId' => $calendarId, - 'calendarData' => $subscriptionRow, - 'shares' => [], - 'objectData' => $data, - ] - )); } } else { $pathInfo = pathinfo($data['uri']); @@ -2589,13 +2554,6 @@ public function updateSubscription($subscriptionId, PropPatch $propPatch) { $subscriptionRow = $this->getSubscriptionById($subscriptionId); $this->dispatcher->dispatchTyped(new SubscriptionUpdatedEvent((int)$subscriptionId, $subscriptionRow, [], $mutations)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::updateSubscription', - [ - 'subscriptionId' => $subscriptionId, - 'subscriptionData' => $subscriptionRow, - 'propertyMutations' => $mutations, - ])); return true; }); @@ -2907,15 +2865,6 @@ public function updateShares($shareable, $add, $remove) { $calendarRow = $this->getCalendarById($calendarId); $oldShares = $this->getShares($calendarId); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::updateShares', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::updateShares', - [ - 'calendarId' => $calendarId, - 'calendarData' => $calendarRow, - 'shares' => $oldShares, - 'add' => $add, - 'remove' => $remove, - ])); $this->calendarSharingBackend->updateShares($shareable, $add, $remove); $this->dispatcher->dispatchTyped(new CalendarShareUpdatedEvent((int)$calendarId, $calendarRow, $oldShares, $add, $remove)); @@ -2937,13 +2886,6 @@ public function getShares($resourceId) { public function setPublishStatus($value, $calendar) { $calendarId = $calendar->getResourceId(); $calendarData = $this->getCalendarById($calendarId); - $this->legacyDispatcher->dispatch('\OCA\DAV\CalDAV\CalDavBackend::publishCalendar', new GenericEvent( - '\OCA\DAV\CalDAV\CalDavBackend::updateShares', - [ - 'calendarId' => $calendarId, - 'calendarData' => $calendarData, - 'public' => $value, - ])); $query = $this->db->getQueryBuilder(); if ($value) { diff --git a/apps/dav/lib/Command/CreateCalendar.php b/apps/dav/lib/Command/CreateCalendar.php index 1d81880924537..e6e8dd2025b16 100644 --- a/apps/dav/lib/Command/CreateCalendar.php +++ b/apps/dav/lib/Command/CreateCalendar.php @@ -93,7 +93,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $random = \OC::$server->getSecureRandom(); $logger = \OC::$server->getLogger(); $dispatcher = \OC::$server->get(IEventDispatcher::class); - $legacyDispatcher = \OC::$server->getEventDispatcher(); $config = \OC::$server->get(IConfig::class); $name = $input->getArgument('name'); @@ -105,7 +104,6 @@ protected function execute(InputInterface $input, OutputInterface $output): int $random, $logger, $dispatcher, - $legacyDispatcher, $config ); $caldav->createCalendar("principals/users/$user", $name, []); diff --git a/apps/dav/lib/Listener/CalendarPublicationListener.php b/apps/dav/lib/Listener/CalendarPublicationListener.php new file mode 100644 index 0000000000000..cb89ccf12b637 --- /dev/null +++ b/apps/dav/lib/Listener/CalendarPublicationListener.php @@ -0,0 +1,67 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Listener; + +use OCA\DAV\CalDAV\Activity\Backend; +use OCA\DAV\Events\CalendarPublishedEvent; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use Psr\Log\LoggerInterface; + +/** + * @template-implements IEventListener<\OCA\DAV\Events\CalendarPublishedEvent> + */ +class CalendarPublicationListener implements IEventListener { + + /** @var Backend */ + private $activityBackend; + + /** @var LoggerInterface */ + private $logger; + + public function __construct(Backend $activityBackend, + LoggerInterface $logger) { + $this->activityBackend = $activityBackend; + $this->logger = $logger; + } + + /** + * In case the user has set their default calendar to the deleted one + */ + public function handle(Event $event): void { + if (!($event instanceof CalendarPublishedEvent)) { + // Not what we subscribed to + return; + } + + $this->logger->debug('Creating activity for Calendar being published'); + + $this->activityBackend->onCalendarPublication( + $event->getCalendarData(), + true + ); + } +} diff --git a/apps/dav/lib/Listener/CalendarShareUpdateListener.php b/apps/dav/lib/Listener/CalendarShareUpdateListener.php new file mode 100644 index 0000000000000..470c50e7be699 --- /dev/null +++ b/apps/dav/lib/Listener/CalendarShareUpdateListener.php @@ -0,0 +1,69 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Listener; + +use OCA\DAV\CalDAV\Activity\Backend; +use OCA\DAV\Events\CalendarShareUpdatedEvent; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use Psr\Log\LoggerInterface; + +/** + * @template-implements IEventListener<\OCA\DAV\Events\CalendarShareUpdatedEvent> + */ +class CalendarShareUpdateListener implements IEventListener { + + /** @var Backend */ + private $activityBackend; + + /** @var LoggerInterface */ + private $logger; + + public function __construct(Backend $activityBackend, + LoggerInterface $logger) { + $this->activityBackend = $activityBackend; + $this->logger = $logger; + } + + /** + * In case the user has set their default calendar to the deleted one + */ + public function handle(Event $event): void { + if (!($event instanceof CalendarShareUpdatedEvent)) { + // Not what we subscribed to + return; + } + + $this->logger->debug("Creating activity for Calendar having it's shares updated"); + + $this->activityBackend->onCalendarUpdateShares( + $event->getCalendarData(), + $event->getOldShares(), + $event->getAdded(), + $event->getRemoved() + ); + } +} diff --git a/apps/dav/lib/Listener/CalendarUnpublicationListener.php b/apps/dav/lib/Listener/CalendarUnpublicationListener.php new file mode 100644 index 0000000000000..92e9db22afb0f --- /dev/null +++ b/apps/dav/lib/Listener/CalendarUnpublicationListener.php @@ -0,0 +1,67 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Listener; + +use OCA\DAV\CalDAV\Activity\Backend; +use OCA\DAV\Events\CalendarUnpublishedEvent; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use Psr\Log\LoggerInterface; + +/** + * @template-implements IEventListener<\OCA\DAV\Events\CalendarUnpublishedEvent> + */ +class CalendarUnpublicationListener implements IEventListener { + + /** @var Backend */ + private $activityBackend; + + /** @var LoggerInterface */ + private $logger; + + public function __construct(Backend $activityBackend, + LoggerInterface $logger) { + $this->activityBackend = $activityBackend; + $this->logger = $logger; + } + + /** + * In case the user has set their default calendar to the deleted one + */ + public function handle(Event $event): void { + if (!($event instanceof CalendarUnpublishedEvent)) { + // Not what we subscribed to + return; + } + + $this->logger->debug('Creating activity for Calendar being unpublished'); + + $this->activityBackend->onCalendarPublication( + $event->getCalendarData(), + false + ); + } +} diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index 2e5952f6efd57..fac66a4bbcf67 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -7,6 +7,7 @@ * @author Georg Ehrke * @author Joas Schilling * @author Roeland Jago Douma + * @author Thomas Citharel * @author Thomas Müller * @author Vincent Petry * @@ -106,7 +107,6 @@ public function __construct() { $random, $logger, $dispatcher, - $legacyDispatcher, $config ); $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users', $psrLogger); diff --git a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php index c659e2ccc6ddb..e0ae86a89016e 100644 --- a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php +++ b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php @@ -7,6 +7,7 @@ * @author Joas Schilling * @author Morris Jobke * @author Roeland Jago Douma + * @author Thomas Citharel * @author Thomas Müller * * @license AGPL-3.0 @@ -42,7 +43,6 @@ use OCP\Share\IManager as ShareManager; use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet; use Sabre\DAV\Xml\Property\Href; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; /** @@ -65,8 +65,6 @@ abstract class AbstractCalDavBackend extends TestCase { protected $groupManager; /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ protected $dispatcher; - /** @var EventDispatcherInterface|\PHPUnit\Framework\MockObject\MockObject */ - protected $legacyDispatcher; /** @var ISecureRandom */ private $random; @@ -84,7 +82,6 @@ protected function setUp(): void { $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->dispatcher = $this->createMock(IEventDispatcher::class); - $this->legacyDispatcher = $this->createMock(EventDispatcherInterface::class); $this->principal = $this->getMockBuilder(Principal::class) ->setConstructorArgs([ $this->userManager, @@ -120,7 +117,6 @@ protected function setUp(): void { $this->random, $this->logger, $this->dispatcher, - $this->legacyDispatcher, $this->config ); @@ -147,8 +143,6 @@ private function cleanupForPrincipal($principal): void { $calendars = $this->backend->getCalendarsForUser($principal); $this->dispatcher->expects(self::any()) ->method('dispatchTyped'); - $this->legacyDispatcher->expects(self::any()) - ->method('dispatch'); foreach ($calendars as $calendar) { $this->backend->deleteCalendar($calendar['id'], true); } diff --git a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php index 3a5cf56409c16..8e4bb1f79324b 100644 --- a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php @@ -150,9 +150,6 @@ public function testCalendarSharing($userCanRead, $userCanWrite, $groupCanRead, $calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); $this->assertCount(1, $calendars); $calendar = new Calendar($this->backend, $calendars[0], $l10n, $config, $logger); - $this->legacyDispatcher->expects($this->at(0)) - ->method('dispatch') - ->with('\OCA\DAV\CalDAV\CalDavBackend::updateShares'); $this->backend->updateShares($calendar, $add, []); $calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER1); $this->assertCount(1, $calendars); diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php index f3f53067d0dde..2bcb3940911a7 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php @@ -43,7 +43,6 @@ use OCP\IUserManager; use OCP\Security\ISecureRandom; use Psr\Log\LoggerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Test\TestCase; /** @@ -86,7 +85,6 @@ protected function setUp(): void { $this->logger = $this->createMock(ILogger::class); $this->psrLogger = $this->createMock(LoggerInterface::class); $dispatcher = $this->createMock(IEventDispatcher::class); - $legacyDispatcher = $this->createMock(EventDispatcherInterface::class); $config = $this->createMock(IConfig::class); $this->principal->expects($this->any())->method('getGroupMembership') @@ -105,7 +103,6 @@ protected function setUp(): void { $this->random, $this->logger, $dispatcher, - $legacyDispatcher, $config ); $this->l10n = $this->getMockBuilder(IL10N::class) From 10af3ab2b4ef791bde3b5a3d60c52801af38c190 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Fri, 17 Dec 2021 17:24:08 +0100 Subject: [PATCH 04/23] Add tests for new Listeners Signed-off-by: Thomas Citharel --- .../CalendarPublicationListenerTest.php | 68 ++++++++++++++++ .../CalendarShareUpdateListenerTest.php | 71 +++++++++++++++++ .../CalendarUnpublicationListenerTest.php | 68 ++++++++++++++++ .../SubscriptionCreationListenerTest.php | 77 +++++++++++++++++++ .../SubscriptionDeletionListenerTest.php | 76 ++++++++++++++++++ 5 files changed, 360 insertions(+) create mode 100644 apps/dav/tests/unit/CalDAV/Listener/CalendarPublicationListenerTest.php create mode 100644 apps/dav/tests/unit/CalDAV/Listener/CalendarShareUpdateListenerTest.php create mode 100644 apps/dav/tests/unit/CalDAV/Listener/CalendarUnpublicationListenerTest.php create mode 100644 apps/dav/tests/unit/CalDAV/Listener/SubscriptionCreationListenerTest.php create mode 100644 apps/dav/tests/unit/CalDAV/Listener/SubscriptionDeletionListenerTest.php diff --git a/apps/dav/tests/unit/CalDAV/Listener/CalendarPublicationListenerTest.php b/apps/dav/tests/unit/CalDAV/Listener/CalendarPublicationListenerTest.php new file mode 100644 index 0000000000000..1648ce564d61b --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/Listener/CalendarPublicationListenerTest.php @@ -0,0 +1,68 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Tests\unit\CalDAV\Listeners; + +use OCA\DAV\CalDAV\Activity\Backend; +use OCA\DAV\Events\CalendarPublishedEvent; +use OCA\DAV\Listener\CalendarPublicationListener; +use OCP\EventDispatcher\Event; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class CalendarPublicationListenerTest extends TestCase { + + /** @var Backend|MockObject */ + private $activityBackend; + + /** @var LoggerInterface|MockObject */ + private $logger; + + /** @var CalendarPublicationListener */ + private $calendarPublicationListener; + + /** @var CalendarPublishedEvent|MockObject */ + private $event; + + protected function setUp(): void { + parent::setUp(); + + $this->activityBackend = $this->createMock(Backend::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->event = $this->createMock(CalendarPublishedEvent::class); + $this->calendarPublicationListener = new CalendarPublicationListener($this->activityBackend, $this->logger); + } + + public function testInvalidEvent(): void { + $this->activityBackend->expects($this->never())->method('onCalendarPublication'); + $this->logger->expects($this->never())->method('debug'); + $this->calendarPublicationListener->handle(new Event()); + } + + public function testEvent(): void { + $this->event->expects($this->once())->method('getCalendarData')->with()->willReturn([]); + $this->activityBackend->expects($this->once())->method('onCalendarPublication')->with([], true); + $this->logger->expects($this->once())->method('debug'); + $this->calendarPublicationListener->handle($this->event); + } +} diff --git a/apps/dav/tests/unit/CalDAV/Listener/CalendarShareUpdateListenerTest.php b/apps/dav/tests/unit/CalDAV/Listener/CalendarShareUpdateListenerTest.php new file mode 100644 index 0000000000000..9cf48ceb7b448 --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/Listener/CalendarShareUpdateListenerTest.php @@ -0,0 +1,71 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Tests\unit\CalDAV\Listeners; + +use OCA\DAV\CalDAV\Activity\Backend; +use OCA\DAV\Events\CalendarShareUpdatedEvent; +use OCA\DAV\Listener\CalendarShareUpdateListener; +use OCP\EventDispatcher\Event; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class CalendarShareUpdateListenerTest extends TestCase { + + /** @var Backend|MockObject */ + private $activityBackend; + + /** @var LoggerInterface|MockObject */ + private $logger; + + /** @var CalendarShareUpdateListener */ + private $calendarPublicationListener; + + /** @var CalendarShareUpdatedEvent|MockObject */ + private $event; + + protected function setUp(): void { + parent::setUp(); + + $this->activityBackend = $this->createMock(Backend::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->event = $this->createMock(CalendarShareUpdatedEvent::class); + $this->calendarPublicationListener = new CalendarShareUpdateListener($this->activityBackend, $this->logger); + } + + public function testInvalidEvent(): void { + $this->activityBackend->expects($this->never())->method('onCalendarUpdateShares'); + $this->logger->expects($this->never())->method('debug'); + $this->calendarPublicationListener->handle(new Event()); + } + + public function testEvent(): void { + $this->event->expects($this->once())->method('getCalendarData')->with()->willReturn([]); + $this->event->expects($this->once())->method('getOldShares')->with()->willReturn([]); + $this->event->expects($this->once())->method('getAdded')->with()->willReturn([]); + $this->event->expects($this->once())->method('getRemoved')->with()->willReturn([]); + $this->activityBackend->expects($this->once())->method('onCalendarUpdateShares')->with([], [], [], []); + $this->logger->expects($this->once())->method('debug'); + $this->calendarPublicationListener->handle($this->event); + } +} diff --git a/apps/dav/tests/unit/CalDAV/Listener/CalendarUnpublicationListenerTest.php b/apps/dav/tests/unit/CalDAV/Listener/CalendarUnpublicationListenerTest.php new file mode 100644 index 0000000000000..1bd0bbcc59aec --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/Listener/CalendarUnpublicationListenerTest.php @@ -0,0 +1,68 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Tests\unit\CalDAV\Listeners; + +use OCA\DAV\CalDAV\Activity\Backend; +use OCA\DAV\Events\CalendarUnpublishedEvent; +use OCA\DAV\Listener\CalendarUnpublicationListener; +use OCP\EventDispatcher\Event; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class CalendarUnpublicationListenerTest extends TestCase { + + /** @var Backend|MockObject */ + private $activityBackend; + + /** @var LoggerInterface|MockObject */ + private $logger; + + /** @var CalendarUnpublicationListener */ + private $calendarPublicationListener; + + /** @var CalendarUnpublishedEvent|MockObject */ + private $event; + + protected function setUp(): void { + parent::setUp(); + + $this->activityBackend = $this->createMock(Backend::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->event = $this->createMock(CalendarUnpublishedEvent::class); + $this->calendarPublicationListener = new CalendarUnpublicationListener($this->activityBackend, $this->logger); + } + + public function testInvalidEvent(): void { + $this->activityBackend->expects($this->never())->method('onCalendarPublication'); + $this->logger->expects($this->never())->method('debug'); + $this->calendarPublicationListener->handle(new Event()); + } + + public function testEvent(): void { + $this->event->expects($this->once())->method('getCalendarData')->with()->willReturn([]); + $this->activityBackend->expects($this->once())->method('onCalendarPublication')->with([], false); + $this->logger->expects($this->once())->method('debug'); + $this->calendarPublicationListener->handle($this->event); + } +} diff --git a/apps/dav/tests/unit/CalDAV/Listener/SubscriptionCreationListenerTest.php b/apps/dav/tests/unit/CalDAV/Listener/SubscriptionCreationListenerTest.php new file mode 100644 index 0000000000000..1939ab32e843c --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/Listener/SubscriptionCreationListenerTest.php @@ -0,0 +1,77 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Tests\unit\CalDAV\Listeners; + +use OCA\DAV\BackgroundJob\RefreshWebcalJob; +use OCA\DAV\CalDAV\WebcalCaching\RefreshWebcalService; +use OCA\DAV\Events\SubscriptionCreatedEvent; +use OCA\DAV\Listener\SubscriptionCreationListener; +use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\Event; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class SubscriptionCreationListenerTest extends TestCase { + + /** @var RefreshWebcalService|MockObject */ + private $refreshWebcalService; + + /** @var IJobList|MockObject */ + private $jobList; + + /** @var LoggerInterface|MockObject */ + private $logger; + + /** @var SubscriptionCreationListener */ + private $calendarPublicationListener; + + /** @var SubscriptionCreatedEvent|MockObject */ + private $event; + + protected function setUp(): void { + parent::setUp(); + + $this->refreshWebcalService = $this->createMock(RefreshWebcalService::class); + $this->jobList = $this->createMock(IJobList::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->event = $this->createMock(SubscriptionCreatedEvent::class); + $this->calendarPublicationListener = new SubscriptionCreationListener($this->jobList, $this->refreshWebcalService, $this->logger); + } + + public function testInvalidEvent(): void { + $this->refreshWebcalService->expects($this->never())->method('refreshSubscription'); + $this->jobList->expects($this->never())->method('add'); + $this->logger->expects($this->never())->method('debug'); + $this->calendarPublicationListener->handle(new Event()); + } + + public function testEvent(): void { + $this->event->expects($this->once())->method('getSubscriptionId')->with()->willReturn(5); + $this->event->expects($this->once())->method('getSubscriptionData')->with()->willReturn(['principaluri' => 'principaluri', 'uri' => 'uri']); + $this->refreshWebcalService->expects($this->once())->method('refreshSubscription')->with('principaluri', 'uri'); + $this->jobList->expects($this->once())->method('add')->with(RefreshWebcalJob::class, ['principaluri' => 'principaluri', 'uri' => 'uri']); + $this->logger->expects($this->exactly(2))->method('debug'); + $this->calendarPublicationListener->handle($this->event); + } +} diff --git a/apps/dav/tests/unit/CalDAV/Listener/SubscriptionDeletionListenerTest.php b/apps/dav/tests/unit/CalDAV/Listener/SubscriptionDeletionListenerTest.php new file mode 100644 index 0000000000000..650354d63b303 --- /dev/null +++ b/apps/dav/tests/unit/CalDAV/Listener/SubscriptionDeletionListenerTest.php @@ -0,0 +1,76 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Tests\unit\CalDAV\Listeners; + +use OCA\DAV\BackgroundJob\RefreshWebcalJob; +use OCA\DAV\CalDAV\Reminder\Backend; +use OCA\DAV\Events\SubscriptionDeletedEvent; +use OCA\DAV\Listener\SubscriptionDeletionListener; +use OCP\BackgroundJob\IJobList; +use OCP\EventDispatcher\Event; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class SubscriptionDeletionListenerTest extends TestCase { + + /** @var Backend|MockObject */ + private $reminderBackend; + + /** @var IJobList|MockObject */ + private $jobList; + + /** @var LoggerInterface|MockObject */ + private $logger; + + /** @var SubscriptionDeletionListener */ + private $calendarPublicationListener; + + /** @var SubscriptionDeletedEvent|MockObject */ + private $event; + + protected function setUp(): void { + parent::setUp(); + + $this->reminderBackend = $this->createMock(Backend::class); + $this->jobList = $this->createMock(IJobList::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->event = $this->createMock(SubscriptionDeletedEvent::class); + $this->calendarPublicationListener = new SubscriptionDeletionListener($this->jobList, $this->reminderBackend, $this->logger); + } + + public function testInvalidEvent(): void { + $this->jobList->expects($this->never())->method('remove'); + $this->logger->expects($this->never())->method('debug'); + $this->calendarPublicationListener->handle(new Event()); + } + + public function testEvent(): void { + $this->event->expects($this->once())->method('getSubscriptionId')->with()->willReturn(5); + $this->event->expects($this->once())->method('getSubscriptionData')->with()->willReturn(['principaluri' => 'principaluri', 'uri' => 'uri']); + $this->jobList->expects($this->once())->method('remove')->with(RefreshWebcalJob::class, ['principaluri' => 'principaluri', 'uri' => 'uri']); + $this->reminderBackend->expects($this->once())->method('cleanRemindersForCalendar')->with(5); + $this->logger->expects($this->exactly(2))->method('debug'); + $this->calendarPublicationListener->handle($this->event); + } +} From 180e695dee0281395c321fca1420aa1bfa9a36af Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 19:01:20 +0100 Subject: [PATCH 05/23] Remove usages of legacyDispatcher in CardDAVBackend Signed-off-by: Thomas Citharel --- apps/dav/appinfo/v1/carddav.php | 2 +- .../composer/composer/autoload_classmap.php | 2 + .../dav/composer/composer/autoload_static.php | 2 + apps/dav/lib/AppInfo/Application.php | 46 +- apps/dav/lib/CardDAV/CardDavBackend.php | 291 ++++++------- apps/dav/lib/Listener/BirthdayListener.php | 55 +++ .../lib/Listener/ClearPhotoCacheListener.php | 49 +++ .../tests/unit/CardDAV/CardDavBackendTest.php | 401 ++++++++++-------- 8 files changed, 479 insertions(+), 369 deletions(-) create mode 100644 apps/dav/lib/Listener/BirthdayListener.php create mode 100644 apps/dav/lib/Listener/ClearPhotoCacheListener.php diff --git a/apps/dav/appinfo/v1/carddav.php b/apps/dav/appinfo/v1/carddav.php index 53449b91c4bff..1b694f84d1db9 100644 --- a/apps/dav/appinfo/v1/carddav.php +++ b/apps/dav/appinfo/v1/carddav.php @@ -59,7 +59,7 @@ 'principals/' ); $db = \OC::$server->getDatabaseConnection(); -$cardDavBackend = new CardDavBackend($db, $principalBackend, \OC::$server->getUserManager(), \OC::$server->getGroupManager(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class), \OC::$server->getEventDispatcher()); +$cardDavBackend = new CardDavBackend($db, $principalBackend, \OC::$server->getUserManager(), \OC::$server->getGroupManager(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class)); $debugging = \OC::$server->getConfig()->getSystemValue('debug', false); diff --git a/apps/dav/composer/composer/autoload_classmap.php b/apps/dav/composer/composer/autoload_classmap.php index 3ff69ac8a8b7f..96a81218e6a30 100644 --- a/apps/dav/composer/composer/autoload_classmap.php +++ b/apps/dav/composer/composer/autoload_classmap.php @@ -235,6 +235,7 @@ 'OCA\\DAV\\HookManager' => $baseDir . '/../lib/HookManager.php', 'OCA\\DAV\\Listener\\ActivityUpdaterListener' => $baseDir . '/../lib/Listener/ActivityUpdaterListener.php', 'OCA\\DAV\\Listener\\AddressbookListener' => $baseDir . '/../lib/Listener/AddressbookListener.php', + 'OCA\\DAV\\Listener\\BirthdayListener' => $baseDir . '/../lib/Listener/BirthdayListener.php', 'OCA\\DAV\\Listener\\CalendarContactInteractionListener' => $baseDir . '/../lib/Listener/CalendarContactInteractionListener.php', 'OCA\\DAV\\Listener\\CalendarDeletionDefaultUpdaterListener' => $baseDir . '/../lib/Listener/CalendarDeletionDefaultUpdaterListener.php', 'OCA\\DAV\\Listener\\CalendarObjectReminderUpdaterListener' => $baseDir . '/../lib/Listener/CalendarObjectReminderUpdaterListener.php', @@ -242,6 +243,7 @@ 'OCA\\DAV\\Listener\\CalendarShareUpdateListener' => $baseDir . '/../lib/Listener/CalendarShareUpdateListener.php', 'OCA\\DAV\\Listener\\CalendarUnpublicationListener' => $baseDir . '/../lib/Listener/CalendarUnpublicationListener.php', 'OCA\\DAV\\Listener\\CardListener' => $baseDir . '/../lib/Listener/CardListener.php', + 'OCA\\DAV\\Listener\\ClearPhotoCacheListener' => $baseDir . '/../lib/Listener/ClearPhotoCacheListener.php', 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => $baseDir . '/../lib/Listener/SubscriptionCreationListener.php', 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => $baseDir . '/../lib/Listener/SubscriptionDeletionListener.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndex.php', diff --git a/apps/dav/composer/composer/autoload_static.php b/apps/dav/composer/composer/autoload_static.php index 6e734b49847c9..7c6bae0d4c2b0 100644 --- a/apps/dav/composer/composer/autoload_static.php +++ b/apps/dav/composer/composer/autoload_static.php @@ -250,6 +250,7 @@ class ComposerStaticInitDAV 'OCA\\DAV\\HookManager' => __DIR__ . '/..' . '/../lib/HookManager.php', 'OCA\\DAV\\Listener\\ActivityUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/ActivityUpdaterListener.php', 'OCA\\DAV\\Listener\\AddressbookListener' => __DIR__ . '/..' . '/../lib/Listener/AddressbookListener.php', + 'OCA\\DAV\\Listener\\BirthdayListener' => __DIR__ . '/..' . '/../lib/Listener/BirthdayListener.php', 'OCA\\DAV\\Listener\\CalendarContactInteractionListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarContactInteractionListener.php', 'OCA\\DAV\\Listener\\CalendarDeletionDefaultUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarDeletionDefaultUpdaterListener.php', 'OCA\\DAV\\Listener\\CalendarObjectReminderUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarObjectReminderUpdaterListener.php', @@ -257,6 +258,7 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Listener\\CalendarShareUpdateListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarShareUpdateListener.php', 'OCA\\DAV\\Listener\\CalendarUnpublicationListener' => __DIR__ . '/..' . '/../lib/Listener/CalendarUnpublicationListener.php', 'OCA\\DAV\\Listener\\CardListener' => __DIR__ . '/..' . '/../lib/Listener/CardListener.php', + 'OCA\\DAV\\Listener\\ClearPhotoCacheListener' => __DIR__ . '/..' . '/../lib/Listener/ClearPhotoCacheListener.php', 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionCreationListener.php', 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionDeletionListener.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndex.php', diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index eafab3743691a..03ae7a82218c2 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -35,7 +35,6 @@ use Exception; use OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob; use OCA\DAV\CalDAV\Activity\Backend; -use OCA\DAV\CalDAV\BirthdayService; use OCA\DAV\CalDAV\CalendarManager; use OCA\DAV\CalDAV\CalendarProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\AudioProvider; @@ -74,6 +73,7 @@ use OCA\DAV\HookManager; use OCA\DAV\Listener\ActivityUpdaterListener; use OCA\DAV\Listener\AddressbookListener; +use OCA\DAV\Listener\BirthdayListener; use OCA\DAV\Listener\CalendarContactInteractionListener; use OCA\DAV\Listener\CalendarDeletionDefaultUpdaterListener; use OCA\DAV\Listener\CalendarObjectReminderUpdaterListener; @@ -81,6 +81,7 @@ use OCA\DAV\Listener\CalendarShareUpdateListener; use OCA\DAV\Listener\CalendarUnpublicationListener; use OCA\DAV\Listener\CardListener; +use OCA\DAV\Listener\ClearPhotoCacheListener; use OCA\DAV\Listener\SubscriptionCreationListener; use OCA\DAV\Listener\SubscriptionDeletionListener; use OCA\DAV\Search\ContactsSearchProvider; @@ -174,6 +175,11 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(CardCreatedEvent::class, CardListener::class); $context->registerEventListener(CardDeletedEvent::class, CardListener::class); $context->registerEventListener(CardUpdatedEvent::class, CardListener::class); + $context->registerEventListener(CardCreatedEvent::class, BirthdayListener::class); + $context->registerEventListener(CardDeletedEvent::class, BirthdayListener::class); + $context->registerEventListener(CardUpdatedEvent::class, BirthdayListener::class); + $context->registerEventListener(CardDeletedEvent::class, ClearPhotoCacheListener::class); + $context->registerEventListener(CardUpdatedEvent::class, ClearPhotoCacheListener::class); $context->registerNotifierService(Notifier::class); @@ -205,44 +211,6 @@ public function registerHooks(HookManager $hm, } }); - $birthdayListener = function ($event) use ($container): void { - if ($event instanceof GenericEvent) { - /** @var BirthdayService $b */ - $b = $container->query(BirthdayService::class); - $b->onCardChanged( - (int) $event->getArgument('addressBookId'), - (string) $event->getArgument('cardUri'), - (string) $event->getArgument('cardData') - ); - } - }; - - $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::createCard', $birthdayListener); - $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $birthdayListener); - $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', function ($event) use ($container) { - if ($event instanceof GenericEvent) { - /** @var BirthdayService $b */ - $b = $container->query(BirthdayService::class); - $b->onCardDeleted( - (int) $event->getArgument('addressBookId'), - (string) $event->getArgument('cardUri') - ); - } - }); - - $clearPhotoCache = function ($event) use ($container): void { - if ($event instanceof GenericEvent) { - /** @var PhotoCache $p */ - $p = $container->query(PhotoCache::class); - $p->delete( - $event->getArgument('addressBookId'), - $event->getArgument('cardUri') - ); - } - }; - $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $clearPhotoCache); - $dispatcher->addListener('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $clearPhotoCache); - $dispatcher->addListener('OC\AccountManager::userUpdated', function (GenericEvent $event) use ($container) { $user = $event->getSubject(); /** @var SyncService $syncService */ diff --git a/apps/dav/lib/CardDAV/CardDavBackend.php b/apps/dav/lib/CardDAV/CardDavBackend.php index 1c1754ff752f3..1845345f89bfe 100644 --- a/apps/dav/lib/CardDAV/CardDavBackend.php +++ b/apps/dav/lib/CardDAV/CardDavBackend.php @@ -35,6 +35,7 @@ */ namespace OCA\DAV\CardDAV; +use InvalidArgumentException; use OCA\DAV\Connector\Sabre\Principal; use OCA\DAV\DAV\Sharing\Backend; use OCA\DAV\DAV\Sharing\IShareable; @@ -45,6 +46,7 @@ use OCA\DAV\Events\CardCreatedEvent; use OCA\DAV\Events\CardDeletedEvent; use OCA\DAV\Events\CardUpdatedEvent; +use OCP\DB\Exception; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\EventDispatcher\IEventDispatcher; use OCP\IDBConnection; @@ -56,10 +58,10 @@ use Sabre\CardDAV\Backend\SyncSupport; use Sabre\CardDAV\Plugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\PropPatch; use Sabre\VObject\Component\VCard; use Sabre\VObject\Reader; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Component\EventDispatcher\GenericEvent; +use function array_key_exists; class CardDavBackend implements BackendInterface, SyncSupport { public const PERSONAL_ADDRESSBOOK_URI = 'contacts'; @@ -97,9 +99,6 @@ class CardDavBackend implements BackendInterface, SyncSupport { /** @var IEventDispatcher */ private $dispatcher; - /** @var EventDispatcherInterface */ - private $legacyDispatcher; - private $etagCache = []; /** @@ -110,29 +109,27 @@ class CardDavBackend implements BackendInterface, SyncSupport { * @param IUserManager $userManager * @param IGroupManager $groupManager * @param IEventDispatcher $dispatcher - * @param EventDispatcherInterface $legacyDispatcher */ public function __construct(IDBConnection $db, Principal $principalBackend, IUserManager $userManager, IGroupManager $groupManager, - IEventDispatcher $dispatcher, - EventDispatcherInterface $legacyDispatcher) { + IEventDispatcher $dispatcher) { $this->db = $db; $this->principalBackend = $principalBackend; $this->userManager = $userManager; $this->dispatcher = $dispatcher; - $this->legacyDispatcher = $legacyDispatcher; $this->sharingBackend = new Backend($this->db, $this->userManager, $groupManager, $principalBackend, 'addressbook'); } /** * Return the number of address books for a principal * - * @param $principalUri + * @param string $principalUri * @return int + * @throws Exception */ - public function getAddressBooksForUserCount($principalUri) { + public function getAddressBooksForUserCount(string $principalUri): int { $principalUri = $this->convertPrincipal($principalUri, true); $query = $this->db->getQueryBuilder(); $query->select($query->func()->count('*')) @@ -161,32 +158,12 @@ public function getAddressBooksForUserCount($principalUri) { * * @param string $principalUri * @return array + * @throws Exception + * @throws \Sabre\DAV\Exception */ public function getAddressBooksForUser($principalUri) { $principalUriOriginal = $principalUri; - $principalUri = $this->convertPrincipal($principalUri, true); - $query = $this->db->getQueryBuilder(); - $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken']) - ->from('addressbooks') - ->where($query->expr()->eq('principaluri', $query->createNamedParameter($principalUri))); - - $addressBooks = []; - - $result = $query->execute(); - while ($row = $result->fetch()) { - $addressBooks[$row['id']] = [ - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $this->convertPrincipal($row['principaluri'], false), - '{DAV:}displayname' => $row['displayname'], - '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], - '{http://calendarserver.org/ns/}getctag' => $row['synctoken'], - '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0', - ]; - - $this->addOwnerPrincipal($addressBooks[$row['id']]); - } - $result->closeCursor(); + $addressBooks = $this->getUserAddressBooks($principalUri); // query for shared addressbooks $principals = $this->principalBackend->getGroupMembership($principalUriOriginal, true); @@ -202,7 +179,7 @@ public function getAddressBooksForUser($principalUri) { ->andWhere($query->expr()->eq('s.type', $query->createParameter('type'))) ->setParameter('type', 'addressbook') ->setParameter('principaluri', $principals, IQueryBuilder::PARAM_STR_ARRAY) - ->execute(); + ->executeQuery(); $readOnlyPropertyName = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only'; while ($row = $result->fetch()) { @@ -246,7 +223,17 @@ public function getAddressBooksForUser($principalUri) { return array_values($addressBooks); } - public function getUsersOwnAddressBooks($principalUri) { + /** + * @throws Exception + */ + public function getUsersOwnAddressBooks($principalUri): array { + return array_values($this->getUserAddressBooks($principalUri)); + } + + /** + * @throws Exception + */ + private function getUserAddressBooks(string $principalUri): array { $principalUri = $this->convertPrincipal($principalUri, true); $query = $this->db->getQueryBuilder(); $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken']) @@ -255,7 +242,7 @@ public function getUsersOwnAddressBooks($principalUri) { $addressBooks = []; - $result = $query->execute(); + $result = $query->executeQuery(); while ($row = $result->fetch()) { $addressBooks[$row['id']] = [ 'id' => $row['id'], @@ -270,11 +257,10 @@ public function getUsersOwnAddressBooks($principalUri) { $this->addOwnerPrincipal($addressBooks[$row['id']]); } $result->closeCursor(); - - return array_values($addressBooks); + return $addressBooks; } - private function getUserDisplayName($uid) { + private function getUserDisplayName(string $uid): string { if (!isset($this->userDisplayNames[$uid])) { $user = $this->userManager->get($uid); @@ -290,13 +276,14 @@ private function getUserDisplayName($uid) { /** * @param int $addressBookId + * @throws Exception */ public function getAddressBookById($addressBookId) { $query = $this->db->getQueryBuilder(); $result = $query->select(['id', 'uri', 'displayname', 'principaluri', 'description', 'synctoken']) ->from('addressbooks') ->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId))) - ->execute(); + ->executeQuery(); $row = $result->fetch(); $result->closeCursor(); @@ -304,24 +291,14 @@ public function getAddressBookById($addressBookId) { return null; } - $addressBook = [ - 'id' => $row['id'], - 'uri' => $row['uri'], - 'principaluri' => $row['principaluri'], - '{DAV:}displayname' => $row['displayname'], - '{' . Plugin::NS_CARDDAV . '}addressbook-description' => $row['description'], - '{http://calendarserver.org/ns/}getctag' => $row['synctoken'], - '{http://sabredav.org/ns}sync-token' => $row['synctoken'] ?: '0', - ]; - - $this->addOwnerPrincipal($addressBook); - - return $addressBook; + return $this->convertAddressBook($row); } /** + * @param $principal * @param $addressBookUri * @return array|null + * @throws Exception */ public function getAddressBooksByUri($principal, $addressBookUri) { $query = $this->db->getQueryBuilder(); @@ -330,7 +307,7 @@ public function getAddressBooksByUri($principal, $addressBookUri) { ->where($query->expr()->eq('uri', $query->createNamedParameter($addressBookUri))) ->andWhere($query->expr()->eq('principaluri', $query->createNamedParameter($principal))) ->setMaxResults(1) - ->execute(); + ->executeQuery(); $row = $result->fetch(); $result->closeCursor(); @@ -338,6 +315,10 @@ public function getAddressBooksByUri($principal, $addressBookUri) { return null; } + return $this->convertAddressBook($row); + } + + private function convertAddressBook(array $row): array { $addressBook = [ 'id' => $row['id'], 'uri' => $row['uri'], @@ -366,10 +347,10 @@ public function getAddressBooksByUri($principal, $addressBookUri) { * Read the PropPatch documentation for more info and examples. * * @param string $addressBookId - * @param \Sabre\DAV\PropPatch $propPatch + * @param PropPatch $propPatch * @return void */ - public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatch) { + public function updateAddressBook($addressBookId, PropPatch $propPatch) { $supportedProperties = [ '{DAV:}displayname', '{' . Plugin::NS_CARDDAV . '}addressbook-description', @@ -394,7 +375,7 @@ public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatc $query->set($key, $query->createNamedParameter($value)); } $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId))) - ->execute(); + ->executeStatement(); $this->addChange($addressBookId, "", 2); @@ -413,7 +394,7 @@ public function updateAddressBook($addressBookId, \Sabre\DAV\PropPatch $propPatc * @param string $url Just the 'basename' of the url. * @param array $properties * @return int - * @throws BadRequest + * @throws BadRequest|Exception */ public function createAddressBook($principalUri, $url, array $properties) { $values = [ @@ -453,7 +434,7 @@ public function createAddressBook($principalUri, $url, array $properties) { 'synctoken' => $query->createParameter('synctoken'), ]) ->setParameters($values) - ->execute(); + ->executeStatement(); $addressBookId = $query->getLastInsertId(); $addressBookRow = $this->getAddressBookById($addressBookId); @@ -467,6 +448,7 @@ public function createAddressBook($principalUri, $url, array $properties) { * * @param mixed $addressBookId * @return void + * @throws Exception */ public function deleteAddressBook($addressBookId) { $addressBookData = $this->getAddressBookById($addressBookId); @@ -476,23 +458,23 @@ public function deleteAddressBook($addressBookId) { $query->delete($this->dbCardsTable) ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid'))) ->setParameter('addressbookid', $addressBookId) - ->execute(); + ->executeStatement(); $query->delete('addressbookchanges') ->where($query->expr()->eq('addressbookid', $query->createParameter('addressbookid'))) ->setParameter('addressbookid', $addressBookId) - ->execute(); + ->executeStatement(); $query->delete('addressbooks') ->where($query->expr()->eq('id', $query->createParameter('id'))) ->setParameter('id', $addressBookId) - ->execute(); + ->executeStatement(); $this->sharingBackend->deleteAllShares($addressBookId); $query->delete($this->dbCardsPropertiesTable) ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))) - ->execute(); + ->executeStatement(); if ($addressBookData) { $this->dispatcher->dispatchTyped(new AddressBookDeletedEvent((int) $addressBookId, $addressBookData, $shares)); @@ -517,6 +499,7 @@ public function deleteAddressBook($addressBookId) { * * @param mixed $addressBookId * @return array + * @throws Exception */ public function getCards($addressBookId) { $query = $this->db->getQueryBuilder(); @@ -553,7 +536,8 @@ public function getCards($addressBookId) { * * @param mixed $addressBookId * @param string $cardUri - * @return array + * @return array|false + * @throws Exception */ public function getCard($addressBookId, $cardUri) { $query = $this->db->getQueryBuilder(); @@ -563,7 +547,7 @@ public function getCard($addressBookId, $cardUri) { ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri))) ->setMaxResults(1); - $result = $query->execute(); + $result = $query->executeQuery(); $row = $result->fetch(); if (!$row) { return false; @@ -590,6 +574,7 @@ public function getCard($addressBookId, $cardUri) { * @param mixed $addressBookId * @param string[] $uris * @return array + * @throws Exception */ public function getMultipleCards($addressBookId, array $uris) { if (empty($uris)) { @@ -607,7 +592,7 @@ public function getMultipleCards($addressBookId, array $uris) { foreach ($chunks as $uris) { $query->setParameter('uri', $uris, IQueryBuilder::PARAM_STR_ARRAY); - $result = $query->execute(); + $result = $query->executeQuery(); while ($row = $result->fetch()) { $row['etag'] = '"' . $row['etag'] . '"'; @@ -649,6 +634,8 @@ public function getMultipleCards($addressBookId, array $uris) { * @param string $cardUri * @param string $cardData * @return string + * @throws BadRequest + * @throws Exception */ public function createCard($addressBookId, $cardUri, $cardData) { $etag = md5($cardData); @@ -660,11 +647,11 @@ public function createCard($addressBookId, $cardUri, $cardData) { ->where($q->expr()->eq('addressbookid', $q->createNamedParameter($addressBookId))) ->andWhere($q->expr()->eq('uid', $q->createNamedParameter($uid))) ->setMaxResults(1); - $result = $q->execute(); + $result = $q->executeQuery(); $count = (bool)$result->fetchOne(); $result->closeCursor(); if ($count) { - throw new \Sabre\DAV\Exception\BadRequest('VCard object with uid already exists in this addressbook collection.'); + throw new BadRequest('VCard object with uid already exists in this addressbook collection.'); } $query = $this->db->getQueryBuilder(); @@ -678,7 +665,7 @@ public function createCard($addressBookId, $cardUri, $cardData) { 'etag' => $query->createNamedParameter($etag), 'uid' => $query->createNamedParameter($uid), ]) - ->execute(); + ->executeStatement(); $etagCacheKey = "$addressBookId#$cardUri"; $this->etagCache[$etagCacheKey] = $etag; @@ -690,11 +677,6 @@ public function createCard($addressBookId, $cardUri, $cardData) { $shares = $this->getShares($addressBookId); $objectRow = $this->getCard($addressBookId, $cardUri); $this->dispatcher->dispatchTyped(new CardCreatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::createCard', - new GenericEvent(null, [ - 'addressBookId' => $addressBookId, - 'cardUri' => $cardUri, - 'cardData' => $cardData])); return '"' . $etag . '"'; } @@ -723,6 +705,8 @@ public function createCard($addressBookId, $cardUri, $cardData) { * @param string $cardUri * @param string $cardData * @return string + * @throws Exception + * @throws BadRequest */ public function updateCard($addressBookId, $cardUri, $cardData) { $uid = $this->getUID($cardData); @@ -743,7 +727,7 @@ public function updateCard($addressBookId, $cardUri, $cardData) { ->set('uid', $query->createNamedParameter($uid)) ->where($query->expr()->eq('uri', $query->createNamedParameter($cardUri))) ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))) - ->execute(); + ->executeStatement(); $this->etagCache[$etagCacheKey] = $etag; @@ -754,12 +738,6 @@ public function updateCard($addressBookId, $cardUri, $cardData) { $shares = $this->getShares($addressBookId); $objectRow = $this->getCard($addressBookId, $cardUri); $this->dispatcher->dispatchTyped(new CardUpdatedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::updateCard', - new GenericEvent(null, [ - 'addressBookId' => $addressBookId, - 'cardUri' => $cardUri, - 'cardData' => $cardData])); - return '"' . $etag . '"'; } @@ -769,6 +747,7 @@ public function updateCard($addressBookId, $cardUri, $cardData) { * @param mixed $addressBookId * @param string $cardUri * @return bool + * @throws Exception */ public function deleteCard($addressBookId, $cardUri) { $addressBookData = $this->getAddressBookById($addressBookId); @@ -777,25 +756,20 @@ public function deleteCard($addressBookId, $cardUri) { try { $cardId = $this->getCardId($addressBookId, $cardUri); - } catch (\InvalidArgumentException $e) { + } catch (InvalidArgumentException $e) { $cardId = null; } $query = $this->db->getQueryBuilder(); $ret = $query->delete($this->dbCardsTable) ->where($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))) ->andWhere($query->expr()->eq('uri', $query->createNamedParameter($cardUri))) - ->execute(); + ->executeStatement(); $this->addChange($addressBookId, $cardUri, 3); if ($ret === 1) { if ($cardId !== null) { $this->dispatcher->dispatchTyped(new CardDeletedEvent((int)$addressBookId, $addressBookData, $shares, $objectRow)); - $this->legacyDispatcher->dispatch('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', - new GenericEvent(null, [ - 'addressBookId' => $addressBookId, - 'cardUri' => $cardUri])); - $this->purgeProperties($addressBookId, $cardId); } return true; @@ -859,6 +833,7 @@ public function deleteCard($addressBookId, $cardUri) { * @param int $syncLevel * @param int|null $limit * @return array + * @throws Exception */ public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, $limit = null) { // Current synctoken @@ -868,7 +843,7 @@ public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, ->where( $qb->expr()->eq('id', $qb->createNamedParameter($addressBookId)) ); - $stmt = $qb->execute(); + $stmt = $qb->executeQuery(); $currentToken = $stmt->fetchOne(); $stmt->closeCursor(); @@ -883,8 +858,8 @@ public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, 'deleted' => [], ]; + $qb = $this->db->getQueryBuilder(); if ($syncToken) { - $qb = $this->db->getQueryBuilder(); $qb->select('uri', 'operation') ->from('addressbookchanges') ->where( @@ -900,13 +875,13 @@ public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, } // Fetching all changes - $stmt = $qb->execute(); + $stmt = $qb->executeQuery(); $changes = []; // This loop ensures that any duplicates are overwritten, only the // last change on a node is relevant. - while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + while ($row = $stmt->fetch()) { $changes[$row['uri']] = $row['operation']; } $stmt->closeCursor(); @@ -925,15 +900,14 @@ public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, } } } else { - $qb = $this->db->getQueryBuilder(); $qb->select('uri') ->from('cards') ->where( $qb->expr()->eq('addressbookid', $qb->createNamedParameter($addressBookId)) ); // No synctoken supplied, this is the initial sync. - $stmt = $qb->execute(); - $result['added'] = $stmt->fetchAll(\PDO::FETCH_COLUMN); + $stmt = $qb->executeQuery(); + $result['added'] = $stmt->fetchAll(PDO::FETCH_COLUMN); $stmt->closeCursor(); } return $result; @@ -946,20 +920,30 @@ public function getChangesForAddressBook($addressBookId, $syncToken, $syncLevel, * @param string $objectUri * @param int $operation 1 = add, 2 = modify, 3 = delete * @return void + * @throws Exception */ - protected function addChange($addressBookId, $objectUri, $operation) { - $sql = 'INSERT INTO `*PREFIX*addressbookchanges`(`uri`, `synctoken`, `addressbookid`, `operation`) SELECT ?, `synctoken`, ?, ? FROM `*PREFIX*addressbooks` WHERE `id` = ?'; - $stmt = $this->db->prepare($sql); - $stmt->execute([ - $objectUri, - $addressBookId, - $operation, - $addressBookId - ]); - $stmt = $this->db->prepare('UPDATE `*PREFIX*addressbooks` SET `synctoken` = `synctoken` + 1 WHERE `id` = ?'); - $stmt->execute([ - $addressBookId - ]); + protected function addChange(int $addressBookId, string $objectUri, int $operation): void { + $qb = $this->db->getQueryBuilder(); + $this->db->beginTransaction(); + $query = $qb->select('synctoken') + ->from('addressbooks') + ->where($qb->expr()->eq('id', $qb->createNamedParameter($addressBookId))) + ->executeQuery(); + $currentToken = $query->fetchOne() ?? 0; + $qb->insert('addressbookchanges') + ->values([ + 'uri' => $qb->createNamedParameter($objectUri), + 'synctoken' => $qb->createNamedParameter($currentToken), + 'addressbookid' => $qb->createNamedParameter($addressBookId), + 'operation' => $qb->createNamedParameter($operation) + ]) + ->executeStatement(); + + $qb->update('addressbooks') + ->set('synctoken', $qb->createNamedParameter((int) $currentToken + 1, IQueryBuilder::PARAM_INT)) + ->where($qb->expr()->eq('id', $qb->createNamedParameter($addressBookId))) + ->executeStatement(); + $this->db->commit(); } /** @@ -967,7 +951,7 @@ protected function addChange($addressBookId, $objectUri, $operation) { * @param bool $modified * @return string */ - private function readBlob($cardData, &$modified = false) { + private function readBlob($cardData, bool &$modified = false): string { if (is_resource($cardData)) { $cardData = stream_get_contents($cardData); } @@ -1003,8 +987,9 @@ private function readBlob($cardData, &$modified = false) { * @param IShareable $shareable * @param string[] $add * @param string[] $remove + * @throws Exception */ - public function updateShares(IShareable $shareable, $add, $remove) { + public function updateShares(IShareable $shareable, array $add, array $remove): void { $addressBookId = $shareable->getResourceId(); $addressBookData = $this->getAddressBookById($addressBookId); $oldShares = $this->getShares($addressBookId); @@ -1027,8 +1012,9 @@ public function updateShares(IShareable $shareable, $add, $remove) { * - 'wildcard' - Whether the search should use wildcards * @psalm-param array{escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options * @return array an array of contacts which are arrays of key-value-pairs + * @throws Exception */ - public function search($addressBookId, $pattern, $searchProperties, $options = []): array { + public function search(int $addressBookId, string $pattern, array $searchProperties, array $options = []): array { return $this->searchByAddressBookIds([$addressBookId], $pattern, $searchProperties, $options); } @@ -1040,6 +1026,8 @@ public function search($addressBookId, $pattern, $searchProperties, $options = [ * @param array $searchProperties * @param array $options * @return array + * @throws Exception + * @throws \Sabre\DAV\Exception */ public function searchPrincipalUri(string $principalUri, string $pattern, @@ -1059,13 +1047,14 @@ public function searchPrincipalUri(string $principalUri, * @param array $options * @psalm-param array{types?: bool, escape_like_param?: bool, limit?: int, offset?: int, wildcard?: bool} $options * @return array + * @throws Exception */ private function searchByAddressBookIds(array $addressBookIds, string $pattern, array $searchProperties, array $options = []): array { - $escapePattern = !\array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false; - $useWildcards = !\array_key_exists('wildcard', $options) || $options['wildcard'] !== false; + $escapePattern = !array_key_exists('escape_like_param', $options) || $options['escape_like_param'] !== false; + $useWildcards = !array_key_exists('wildcard', $options) || $options['wildcard'] !== false; $query2 = $this->db->getQueryBuilder(); @@ -1123,10 +1112,10 @@ private function searchByAddressBookIds(array $addressBookIds, $query2->setFirstResult($options['offset']); } - $result = $query2->execute(); + $result = $query2->executeQuery(); $matches = $result->fetchAll(); $result->closeCursor(); - $matches = array_map(function ($match) { + $matches = array_map(static function ($match) { return (int)$match['cardid']; }, $matches); @@ -1158,14 +1147,15 @@ private function searchByAddressBookIds(array $addressBookIds, * @param int $bookId * @param string $name * @return array + * @throws Exception */ - public function collectCardProperties($bookId, $name) { + public function collectCardProperties(int $bookId, string $name): array { $query = $this->db->getQueryBuilder(); $result = $query->selectDistinct('value') ->from($this->dbCardsPropertiesTable) ->where($query->expr()->eq('name', $query->createNamedParameter($name))) ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($bookId))) - ->execute(); + ->executeQuery(); $all = $result->fetchAll(PDO::FETCH_COLUMN); $result->closeCursor(); @@ -1178,19 +1168,20 @@ public function collectCardProperties($bookId, $name) { * * @param int $id * @return string + * @throws Exception */ - public function getCardUri($id) { + public function getCardUri(int $id): string { $query = $this->db->getQueryBuilder(); $query->select('uri')->from($this->dbCardsTable) ->where($query->expr()->eq('id', $query->createParameter('id'))) ->setParameter('id', $id); - $result = $query->execute(); + $result = $query->executeQuery(); $uri = $result->fetch(); $result->closeCursor(); if (!isset($uri['uri'])) { - throw new \InvalidArgumentException('Card does not exists: ' . $id); + throw new InvalidArgumentException('Card does not exists: ' . $id); } return $uri['uri']; @@ -1201,15 +1192,16 @@ public function getCardUri($id) { * * @param int $addressBookId * @param string $uri - * @returns array + * @return array + * @throws Exception */ - public function getContact($addressBookId, $uri) { + public function getContact(int $addressBookId, string $uri): array { $result = []; $query = $this->db->getQueryBuilder(); $query->select('*')->from($this->dbCardsTable) ->where($query->expr()->eq('uri', $query->createNamedParameter($uri))) ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))); - $queryResult = $query->execute(); + $queryResult = $query->executeQuery(); $contact = $queryResult->fetch(); $queryResult->closeCursor(); @@ -1237,9 +1229,10 @@ public function getContact($addressBookId, $uri) { * * readOnly - boolean * * summary - Optional, a description for the share * + * @param int $addressBookId * @return array */ - public function getShares($addressBookId) { + public function getShares(int $addressBookId): array { return $this->sharingBackend->getShares($addressBookId); } @@ -1249,8 +1242,9 @@ public function getShares($addressBookId) { * @param int $addressBookId * @param string $cardUri * @param string $vCardSerialized + * @throws Exception */ - protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) { + protected function updateProperties(int $addressBookId, string $cardUri, string $vCardSerialized): void { $cardId = $this->getCardId($addressBookId, $cardUri); $vCard = $this->readCard($vCardSerialized); @@ -1269,7 +1263,7 @@ protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) ); foreach ($vCard->children() as $property) { - if (!in_array($property->name, self::$indexProperties)) { + if (!in_array($property->name, self::$indexProperties, true)) { continue; } $preferred = 0; @@ -1282,7 +1276,7 @@ protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) $query->setParameter('name', $property->name); $query->setParameter('value', mb_strcut($property->getValue(), 0, 254)); $query->setParameter('preferred', $preferred); - $query->execute(); + $query->executeStatement(); } } @@ -1292,7 +1286,7 @@ protected function updateProperties($addressBookId, $cardUri, $vCardSerialized) * @param string $cardData * @return VCard */ - protected function readCard($cardData) { + protected function readCard(string $cardData): VCard { return Reader::read($cardData); } @@ -1301,13 +1295,14 @@ protected function readCard($cardData) { * * @param int $addressBookId * @param int $cardId + * @throws Exception */ - protected function purgeProperties($addressBookId, $cardId) { + protected function purgeProperties(int $addressBookId, int $cardId): void { $query = $this->db->getQueryBuilder(); $query->delete($this->dbCardsPropertiesTable) ->where($query->expr()->eq('cardid', $query->createNamedParameter($cardId))) ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))); - $query->execute(); + $query->executeStatement(); } /** @@ -1316,19 +1311,20 @@ protected function purgeProperties($addressBookId, $cardId) { * @param int $addressBookId * @param string $uri * @return int + * @throws Exception */ - protected function getCardId($addressBookId, $uri) { + protected function getCardId(int $addressBookId, string $uri): int { $query = $this->db->getQueryBuilder(); $query->select('id')->from($this->dbCardsTable) ->where($query->expr()->eq('uri', $query->createNamedParameter($uri))) ->andWhere($query->expr()->eq('addressbookid', $query->createNamedParameter($addressBookId))); - $result = $query->execute(); + $result = $query->executeQuery(); $cardIds = $result->fetch(); $result->closeCursor(); if (!isset($cardIds['id'])) { - throw new \InvalidArgumentException('Card does not exists: ' . $uri); + throw new InvalidArgumentException('Card does not exists: ' . $uri); } return (int)$cardIds['id']; @@ -1336,16 +1332,12 @@ protected function getCardId($addressBookId, $uri) { /** * For shared address books the sharee is set in the ACL of the address book - * - * @param $addressBookId - * @param $acl - * @return array */ - public function applyShareAcl($addressBookId, $acl) { + public function applyShareAcl(int $addressBookId, array $acl): array { return $this->sharingBackend->applyShareAcl($addressBookId, $acl); } - private function convertPrincipal($principalUri, $toV2) { + private function convertPrincipal(string $principalUri, bool $toV2): string { if ($this->principalBackend->getPrincipalPrefix() === 'principals') { [, $name] = \Sabre\Uri\split($principalUri); if ($toV2 === true) { @@ -1356,18 +1348,14 @@ private function convertPrincipal($principalUri, $toV2) { return $principalUri; } - private function addOwnerPrincipal(&$addressbookInfo) { + private function addOwnerPrincipal(&$addressbookInfo): void { $ownerPrincipalKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal'; - $displaynameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname'; - if (isset($addressbookInfo[$ownerPrincipalKey])) { - $uri = $addressbookInfo[$ownerPrincipalKey]; - } else { - $uri = $addressbookInfo['principaluri']; - } + $displayNameKey = '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname'; + $uri = $addressbookInfo[$ownerPrincipalKey] ?? $addressbookInfo['principaluri']; $principalInformation = $this->principalBackend->getPrincipalByPath($uri); if (isset($principalInformation['{DAV:}displayname'])) { - $addressbookInfo[$displaynameKey] = $principalInformation['{DAV:}displayname']; + $addressbookInfo[$displayNameKey] = $principalInformation['{DAV:}displayname']; } } @@ -1378,12 +1366,11 @@ private function addOwnerPrincipal(&$addressbookInfo) { * @return string the uid * @throws BadRequest if no UID is available */ - private function getUID($cardData) { - if ($cardData != '') { + private function getUID(string $cardData): string { + if ($cardData !== '') { $vCard = Reader::read($cardData); if ($vCard->UID) { - $uid = $vCard->UID->getValue(); - return $uid; + return $vCard->UID->getValue(); } // should already be handled, but just in case throw new BadRequest('vCards on CardDAV servers MUST have a UID property'); diff --git a/apps/dav/lib/Listener/BirthdayListener.php b/apps/dav/lib/Listener/BirthdayListener.php new file mode 100644 index 0000000000000..5861d5313cbde --- /dev/null +++ b/apps/dav/lib/Listener/BirthdayListener.php @@ -0,0 +1,55 @@ + + * + * @author Christoph Wurst + * + * @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\DAV\Listener; + +use OCA\DAV\CalDAV\BirthdayService; +use OCA\DAV\Events\CardCreatedEvent; +use OCA\DAV\Events\CardDeletedEvent; +use OCA\DAV\Events\CardUpdatedEvent; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; + +class BirthdayListener implements IEventListener { + /** @var BirthdayService */ + private $birthdayService; + + public function __construct(BirthdayService $birthdayService) { + $this->birthdayService = $birthdayService; + } + + public function handle(Event $event): void { + if ($event instanceof CardCreatedEvent || $event instanceof CardUpdatedEvent) { + $cardData = $event->getCardData(); + + $this->birthdayService->onCardChanged($event->getAddressBookId(), $cardData['uri'], $cardData['carddata']); + } + + if ($event instanceof CardDeletedEvent) { + $cardData = $event->getCardData(); + $this->birthdayService->onCardDeleted($event->getAddressBookId(), $cardData['uri']); + } + } +} diff --git a/apps/dav/lib/Listener/ClearPhotoCacheListener.php b/apps/dav/lib/Listener/ClearPhotoCacheListener.php new file mode 100644 index 0000000000000..f7fbb9d9eb674 --- /dev/null +++ b/apps/dav/lib/Listener/ClearPhotoCacheListener.php @@ -0,0 +1,49 @@ + + * + * @author Christoph Wurst + * + * @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\DAV\Listener; + +use OCA\DAV\CardDAV\PhotoCache; +use OCA\DAV\Events\CardDeletedEvent; +use OCA\DAV\Events\CardUpdatedEvent; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; + +class ClearPhotoCacheListener implements IEventListener { + /** @var PhotoCache */ + private $photoCache; + + public function __construct(PhotoCache $photoCache) { + $this->photoCache = $photoCache; + } + + public function handle(Event $event): void { + if ($event instanceof CardUpdatedEvent || $event instanceof CardDeletedEvent) { + $cardData = $event->getCardData(); + + $this->photoCache->delete($event->getAddressBookId(), $cardData['uri']); + } + } +} diff --git a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php index 7eda691d19937..7a34ef60dd574 100644 --- a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php +++ b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php @@ -32,12 +32,15 @@ */ namespace OCA\DAV\Tests\unit\CardDAV; +use InvalidArgumentException; +use OC; use OC\KnownUser\KnownUserService; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\CardDAV\AddressBook; use OCA\DAV\CardDAV\CardDavBackend; use OCA\DAV\Connector\Sabre\Principal; use OCP\App\IAppManager; +use OCP\DB\Exception; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; @@ -48,12 +51,13 @@ use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Share\IManager as ShareManager; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\PropPatch; use Sabre\VObject\Component\VCard; use Sabre\VObject\Property\Text; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Symfony\Component\EventDispatcher\GenericEvent; use Test\TestCase; /** @@ -68,19 +72,16 @@ class CardDavBackendTest extends TestCase { /** @var CardDavBackend */ private $backend; - /** @var Principal | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Principal | MockObject */ private $principal; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ private $userManager; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IGroupManager|MockObject */ private $groupManager; - /** @var EventDispatcherInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $legacyDispatcher; - - /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IEventDispatcher|MockObject */ private $dispatcher; /** @var IDBConnection */ @@ -127,6 +128,11 @@ class CardDavBackendTest extends TestCase { 'N:TestNoUID;;;;'.PHP_EOL. 'END:VCARD'; + /** + * @throws Exception + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface|\Sabre\DAV\Exception + */ protected function setUp(): void { parent::setUp(); @@ -144,7 +150,7 @@ protected function setUp(): void { $this->createMock(IConfig::class), $this->createMock(IFactory::class) ]) - ->setMethods(['getPrincipalByPath', 'getGroupMembership']) + ->onlyMethods(['getPrincipalByPath', 'getGroupMembership']) ->getMock(); $this->principal->method('getPrincipalByPath') ->willReturn([ @@ -155,11 +161,10 @@ protected function setUp(): void { ->withAnyParameters() ->willReturn([self::UNIT_TEST_GROUP]); $this->dispatcher = $this->createMock(IEventDispatcher::class); - $this->legacyDispatcher = $this->createMock(EventDispatcherInterface::class); - $this->db = \OC::$server->getDatabaseConnection(); + $this->db = OC::$server->get(IDBConnection::class); - $this->backend = new CardDavBackend($this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher); + $this->backend = new CardDavBackend($this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher); // start every test with a empty cards_properties and cards table $query = $this->db->getQueryBuilder(); $query->delete('cards_properties')->execute(); @@ -169,6 +174,10 @@ protected function setUp(): void { $this->tearDown(); } + /** + * @throws \Sabre\DAV\Exception + * @throws Exception + */ protected function tearDown(): void { parent::tearDown(); @@ -185,14 +194,19 @@ protected function tearDown(): void { } } - public function testAddressBookOperations() { + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testAddressBookOperations(): void { // create a new address book $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); $this->assertEquals(1, $this->backend->getAddressBooksForUserCount(self::UNIT_TEST_USER)); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); + $this->assertCount(1, $books); $this->assertEquals('Example', $books[0]['{DAV:}displayname']); $this->assertEquals('User\'s displayname', $books[0]['{http://nextcloud.com/ns}owner-displayname']); @@ -204,30 +218,23 @@ public function testAddressBookOperations() { $this->backend->updateAddressBook($books[0]['id'], $patch); $patch->commit(); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); + $this->assertCount(1, $books); $this->assertEquals('Unit test', $books[0]['{DAV:}displayname']); $this->assertEquals('Addressbook used for unit testing', $books[0]['{urn:ietf:params:xml:ns:carddav}addressbook-description']); // delete the address book $this->backend->deleteAddressBook($books[0]['id']); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($books)); + $this->assertCount(0, $books); } - public function testAddressBookSharing() { - $this->userManager->expects($this->any()) - ->method('userExists') - ->willReturn(true); - - $this->groupManager->expects($this->any()) - ->method('groupExists') - ->willReturn(true); - - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $l = $this->createMock(IL10N::class); - $addressBook = new AddressBook($this->backend, $books[0], $l); + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testAddressBookSharing(): void { + $addressBook = $this->configureSharing(); $this->backend->updateShares($addressBook, [ [ 'href' => 'principal:' . self::UNIT_TEST_USER1, @@ -237,47 +244,50 @@ public function testAddressBookSharing() { ] ], []); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1); - $this->assertEquals(1, count($books)); + $this->assertCount(1, $books); // delete the address book $this->backend->deleteAddressBook($books[0]['id']); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(0, count($books)); + $this->assertCount(0, $books); } - public function testCardOperations() { + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testCardOperations(): void { - /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backend */ + /** @var CardDavBackend | MockObject $backend */ $backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['updateProperties', 'purgeProperties'])->getMock(); + ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher]) + ->onlyMethods(['updateProperties', 'purgeProperties'])->getMock(); // create a new address book $backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); $books = $backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); + $this->assertCount(1, $books); $bookId = $books[0]['id']; - $uri = $this->getUniqueID('card'); + $uri = self::getUniqueID('card'); // updateProperties is expected twice, once for createCard and once for updateCard - $backend->expects($this->at(0))->method('updateProperties')->with($bookId, $uri, $this->vcardTest0); - $backend->expects($this->at(1))->method('updateProperties')->with($bookId, $uri, $this->vcardTest1); + $backend->expects($this->exactly(2))->method('updateProperties')->withConsecutive( + [$bookId, $uri, $this->vcardTest0], + [$bookId, $uri, $this->vcardTest1] + ); // Expect event - $this->legacyDispatcher->expects($this->at(0)) - ->method('dispatch') - ->with('\OCA\DAV\CardDAV\CardDavBackend::createCard', $this->callback(function (GenericEvent $e) use ($bookId, $uri) { - return $e->getArgument('addressBookId') === $bookId && - $e->getArgument('cardUri') === $uri && - $e->getArgument('cardData') === $this->vcardTest0; - })); + $this->dispatcher + ->expects($this->exactly(3)) + ->method('dispatchTyped'); // create a card $backend->createCard($bookId, $uri, $this->vcardTest0); // get all the cards $cards = $backend->getCards($bookId); - $this->assertEquals(1, count($cards)); + $this->assertCount(1, $cards); $this->assertEquals($this->vcardTest0, $cards[0]['carddata']); // get the cards @@ -290,45 +300,25 @@ public function testCardOperations() { $this->assertArrayHasKey('size', $card); $this->assertEquals($this->vcardTest0, $card['carddata']); - // Expect event - $this->legacyDispatcher->expects($this->at(0)) - ->method('dispatch') - ->with('\OCA\DAV\CardDAV\CardDavBackend::updateCard', $this->callback(function (GenericEvent $e) use ($bookId, $uri) { - return $e->getArgument('addressBookId') === $bookId && - $e->getArgument('cardUri') === $uri && - $e->getArgument('cardData') === $this->vcardTest1; - })); - // update the card $backend->updateCard($bookId, $uri, $this->vcardTest1); $card = $backend->getCard($bookId, $uri); $this->assertEquals($this->vcardTest1, $card['carddata']); - // Expect event - $this->legacyDispatcher->expects($this->at(0)) - ->method('dispatch') - ->with('\OCA\DAV\CardDAV\CardDavBackend::deleteCard', $this->callback(function (GenericEvent $e) use ($bookId, $uri) { - return $e->getArgument('addressBookId') === $bookId && - $e->getArgument('cardUri') === $uri; - })); - // delete the card $backend->expects($this->once())->method('purgeProperties')->with($bookId, $card['id']); $backend->deleteCard($bookId, $uri); $cards = $backend->getCards($bookId); - $this->assertEquals(0, count($cards)); + $this->assertCount(0, $cards); } - public function testMultiCard() { - $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['updateProperties'])->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testMultiCard(): void { + $bookId = $this->provideAddressBook(); // create a card $uri0 = self::getUniqueID('card'); @@ -340,8 +330,8 @@ public function testMultiCard() { // get all the cards $cards = $this->backend->getCards($bookId); - $this->assertEquals(3, count($cards)); - usort($cards, function ($a, $b) { + $this->assertCount(3, $cards); + usort($cards, static function ($a, $b) { return $a['id'] < $b['id'] ? -1 : 1; }); @@ -351,8 +341,8 @@ public function testMultiCard() { // get the cards 1 & 2 (not 0) $cards = $this->backend->getMultipleCards($bookId, [$uri1, $uri2]); - $this->assertEquals(2, count($cards)); - usort($cards, function ($a, $b) { + $this->assertCount(2, $cards); + usort($cards, static function ($a, $b) { return $a['id'] < $b['id'] ? -1 : 1; }); foreach ($cards as $index => $card) { @@ -369,73 +359,76 @@ public function testMultiCard() { $this->backend->deleteCard($bookId, $uri1); $this->backend->deleteCard($bookId, $uri2); $cards = $this->backend->getCards($bookId); - $this->assertEquals(0, count($cards)); + $this->assertCount(0, $cards); } - public function testMultipleUIDOnDifferentAddressbooks() { + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testMultipleUIDOnDifferentAddressbooks(): void { $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['updateProperties'])->getMock(); + ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher]) + ->onlyMethods(['updateProperties'])->getMock(); // create 2 new address books $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example2', []); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(2, count($books)); + $this->assertCount(2, $books); $bookId0 = $books[0]['id']; $bookId1 = $books[1]['id']; // create a card - $uri0 = $this->getUniqueID('card'); + $uri0 = self::getUniqueID('card'); $this->backend->createCard($bookId0, $uri0, $this->vcardTest0); // create another card with same uid but in second address book - $uri1 = $this->getUniqueID('card'); + $uri1 = self::getUniqueID('card'); $this->backend->createCard($bookId1, $uri1, $this->vcardTest0); } - public function testMultipleUIDDenied() { - $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['updateProperties'])->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testMultipleUIDDenied(): void { + $bookId = $this->provideAddressBook(); // create a card - $uri0 = $this->getUniqueID('card'); + $uri0 = self::getUniqueID('card'); $this->backend->createCard($bookId, $uri0, $this->vcardTest0); // create another card with same uid - $uri1 = $this->getUniqueID('card'); + $uri1 = self::getUniqueID('card'); $this->expectException(BadRequest::class); - $test = $this->backend->createCard($bookId, $uri1, $this->vcardTest0); + $this->backend->createCard($bookId, $uri1, $this->vcardTest0); } - public function testNoValidUID() { - $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['updateProperties'])->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testNoValidUID(): void { + $bookId = $this->provideAddressBook(); // create a card without uid - $uri1 = $this->getUniqueID('card'); + $uri1 = self::getUniqueID('card'); $this->expectException(BadRequest::class); - $test = $this->backend->createCard($bookId, $uri1, $this->vcardTestNoUID); + $this->backend->createCard($bookId, $uri1, $this->vcardTestNoUID); } - public function testDeleteWithoutCard() { + /** + * @throws BadRequest + * @throws Exception + */ + public function testDeleteWithoutCard(): void { $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods([ + ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher]) + ->onlyMethods([ 'getCardId', 'addChange', 'purgeProperties', @@ -446,16 +439,16 @@ public function testDeleteWithoutCard() { // create a new address book $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); $books = $this->backend->getUsersOwnAddressBooks(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); + $this->assertCount(1, $books); $bookId = $books[0]['id']; - $uri = $this->getUniqueID('card'); + $uri = self::getUniqueID('card'); // create a new address book $this->backend->expects($this->once()) ->method('getCardId') ->with($bookId, $uri) - ->willThrowException(new \InvalidArgumentException()); + ->willThrowException(new InvalidArgumentException()); $this->backend->expects($this->exactly(2)) ->method('addChange') ->withConsecutive( @@ -472,23 +465,19 @@ public function testDeleteWithoutCard() { $this->assertTrue($this->backend->deleteCard($bookId, $uri)); } - public function testSyncSupport() { - $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['updateProperties'])->getMock(); - - // create a new address book - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - $bookId = $books[0]['id']; + /** + * @throws BadRequest + * @throws Exception|\Sabre\DAV\Exception + */ + public function testSyncSupport(): void { + $bookId = $this->provideAddressBook(); // fist call without synctoken $changes = $this->backend->getChangesForAddressBook($bookId, '', 1); $syncToken = $changes['syncToken']; // add a change - $uri0 = $this->getUniqueID('card'); + $uri0 = self::getUniqueID('card'); $this->backend->createCard($bookId, $uri0, $this->vcardTest0); // look for changes @@ -496,60 +485,55 @@ public function testSyncSupport() { $this->assertEquals($uri0, $changes['added'][0]); } - public function testSharing() { - $this->userManager->expects($this->any()) - ->method('userExists') - ->willReturn(true); - - $this->groupManager->expects($this->any()) - ->method('groupExists') - ->willReturn(true); - - $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); - $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($books)); - - $l = $this->createMock(IL10N::class); - $exampleBook = new AddressBook($this->backend, $books[0], $l); + /** + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + public function testSharing(): void { + $exampleBook = $this->configureSharing(); $this->backend->updateShares($exampleBook, [['href' => 'principal:' . self::UNIT_TEST_USER1]], []); $shares = $this->backend->getShares($exampleBook->getResourceId()); - $this->assertEquals(1, count($shares)); + $this->assertCount(1, $shares); // adding the same sharee again has no effect $this->backend->updateShares($exampleBook, [['href' => 'principal:' . self::UNIT_TEST_USER1]], []); $shares = $this->backend->getShares($exampleBook->getResourceId()); - $this->assertEquals(1, count($shares)); + $this->assertCount(1, $shares); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1); - $this->assertEquals(1, count($books)); + $this->assertCount(1, $books); $this->backend->updateShares($exampleBook, [], ['principal:' . self::UNIT_TEST_USER1]); $shares = $this->backend->getShares($exampleBook->getResourceId()); - $this->assertEquals(0, count($shares)); + $this->assertCount(0, $shares); $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER1); - $this->assertEquals(0, count($books)); + $this->assertCount(0, $books); } - public function testUpdateProperties() { + /** + * @throws Exception + */ + public function testUpdateProperties(): void { $bookId = 42; $cardUri = 'card-uri'; $cardId = 2; $backend = $this->getMockBuilder(CardDavBackend::class) - ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher, $this->legacyDispatcher]) - ->setMethods(['getCardId'])->getMock(); + ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher]) + ->onlyMethods(['getCardId'])->getMock(); - $backend->expects($this->any())->method('getCardId')->willReturn($cardId); + $backend->method('getCardId')->willReturn($cardId); // add properties for new vCard $vCard = new VCard(); $vCard->UID = $cardUri; $vCard->FN = 'John Doe'; - $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); + self::invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); $query = $this->db->getQueryBuilder(); $query->select('*') @@ -559,7 +543,7 @@ public function testUpdateProperties() { $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(2, count($result)); + $this->assertCount(2, $result); $this->assertSame('UID', $result[0]['name']); $this->assertSame($cardUri, $result[0]['value']); @@ -574,7 +558,7 @@ public function testUpdateProperties() { // update properties for existing vCard $vCard = new VCard(); $vCard->UID = $cardUri; - $this->invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); + self::invokePrivate($backend, 'updateProperties', [$bookId, $cardUri, $vCard->serialize()]); $query = $this->db->getQueryBuilder(); $query->select('*') @@ -584,7 +568,7 @@ public function testUpdateProperties() { $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame('UID', $result[0]['name']); $this->assertSame($cardUri, $result[0]['value']); @@ -592,7 +576,10 @@ public function testUpdateProperties() { $this->assertSame($cardId, (int)$result[0]['cardid']); } - public function testPurgeProperties() { + /** + * @throws Exception + */ + public function testPurgeProperties(): void { $query = $this->db->getQueryBuilder(); $query->insert('cards_properties') ->values( @@ -619,7 +606,7 @@ public function testPurgeProperties() { ); $query->execute(); - $this->invokePrivate($this->backend, 'purgeProperties', [1, 1]); + self::invokePrivate($this->backend, 'purgeProperties', [1, 1]); $query = $this->db->getQueryBuilder(); $query->select('*') @@ -629,12 +616,15 @@ public function testPurgeProperties() { $result = $qResult->fetchAll(); $qResult->closeCursor(); - $this->assertSame(1, count($result)); + $this->assertCount(1, $result); $this->assertSame(1 ,(int)$result[0]['addressbookid']); $this->assertSame(2 ,(int)$result[0]['cardid']); } - public function testGetCardId() { + /** + * @throws Exception + */ + public function testGetCardId(): void { $query = $this->db->getQueryBuilder(); $query->insert('cards') @@ -652,14 +642,14 @@ public function testGetCardId() { $id = $query->getLastInsertId(); $this->assertSame($id, - $this->invokePrivate($this->backend, 'getCardId', [1, 'uri'])); + self::invokePrivate($this->backend, 'getCardId', [1, 'uri'])); } - public function testGetCardIdFailed() { - $this->expectException(\InvalidArgumentException::class); + public function testGetCardIdFailed(): void { + $this->expectException(InvalidArgumentException::class); - $this->invokePrivate($this->backend, 'getCardId', [1, 'uri']); + self::invokePrivate($this->backend, 'getCardId', [1, 'uri']); } /** @@ -669,8 +659,9 @@ public function testGetCardIdFailed() { * @param array $properties * @param array $options * @param array $expected + * @throws Exception */ - public function testSearch($pattern, $properties, $options, $expected) { + public function testSearch(string $pattern, array $properties, array $options, array $expected): void { /** @var VCard $vCards */ $vCards = []; $vCards[0] = new VCard(); @@ -762,7 +753,7 @@ public function testSearch($pattern, $properties, $options, $expected) { $result = $this->backend->search(0, $pattern, $properties, $options); // check result - $this->assertSame(count($expected), count($result)); + $this->assertCount(count($expected), $result); $found = []; foreach ($result as $r) { foreach ($expected as $exp) { @@ -773,10 +764,10 @@ public function testSearch($pattern, $properties, $options, $expected) { } } - $this->assertSame(count($expected), count($found)); + $this->assertCount(count($expected), $found); } - public function dataTestSearch() { + public function dataTestSearch(): array { return [ ['John', ['FN'], [], [['uri0', 'John Doe'], ['uri1', 'John M. Doe']]], ['M. Doe', ['FN'], [], [['uri1', 'John M. Doe']]], @@ -790,7 +781,10 @@ public function dataTestSearch() { ]; } - public function testGetCardUri() { + /** + * @throws Exception + */ + public function testGetCardUri(): void { $query = $this->db->getQueryBuilder(); $query->insert($this->dbCardsTable) ->values( @@ -811,13 +805,19 @@ public function testGetCardUri() { } - public function testGetCardUriFailed() { - $this->expectException(\InvalidArgumentException::class); + /** + * @throws Exception + */ + public function testGetCardUriFailed(): void { + $this->expectException(InvalidArgumentException::class); $this->backend->getCardUri(1); } - public function testGetContact() { + /** + * @throws Exception + */ + public function testGetContact(): void { $query = $this->db->getQueryBuilder(); for ($i = 0; $i < 2; $i++) { $query->insert($this->dbCardsTable) @@ -835,7 +835,7 @@ public function testGetContact() { } $result = $this->backend->getContact(0, 'uri0'); - $this->assertSame(8, count($result)); + $this->assertCount(8, $result); $this->assertSame(0, (int)$result['addressbookid']); $this->assertSame('uri0', $result['uri']); $this->assertSame(5489543, (int)$result['lastmodified']); @@ -848,11 +848,17 @@ public function testGetContact() { $this->assertEmpty($result); } - public function testGetContactFail() { + /** + * @throws Exception + */ + public function testGetContactFail(): void { $this->assertEmpty($this->backend->getContact(0, 'uri')); } - public function testCollectCardProperties() { + /** + * @throws Exception + */ + public function testCollectCardProperties(): void { $query = $this->db->getQueryBuilder(); $query->insert($this->dbCardsPropertiesTable) ->values( @@ -869,4 +875,45 @@ public function testCollectCardProperties() { $result = $this->backend->collectCardProperties(666, 'FN'); $this->assertEquals(['John Doe'], $result); } + + /** + * @return AddressBook + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + private function configureSharing(): AddressBook { + $this->userManager + ->method('userExists') + ->willReturn(true); + + $this->groupManager + ->method('groupExists') + ->willReturn(true); + + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertCount(1, $books); + + $l = $this->createMock(IL10N::class); + return new AddressBook($this->backend, $books[0], $l); + } + + /** + * @return int + * @throws BadRequest + * @throws Exception + * @throws \Sabre\DAV\Exception + */ + private function provideAddressBook(): int { + $this->backend = $this->getMockBuilder(CardDavBackend::class) + ->setConstructorArgs([$this->db, $this->principal, $this->userManager, $this->groupManager, $this->dispatcher]) + ->onlyMethods(['updateProperties'])->getMock(); + + // create a new address book + $this->backend->createAddressBook(self::UNIT_TEST_USER, 'Example', []); + $books = $this->backend->getAddressBooksForUser(self::UNIT_TEST_USER); + $this->assertCount(1, $books); + return $books[0]['id']; + } } From ab076298be32123baa5be2dbd98ceac402d9287e Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 19:03:54 +0100 Subject: [PATCH 06/23] Update some depreciated calls Signed-off-by: Thomas Citharel --- apps/dav/lib/AppInfo/Application.php | 15 ++- apps/dav/lib/AppInfo/PluginManager.php | 2 +- apps/dav/lib/Avatars/RootCollection.php | 3 +- apps/dav/lib/CalDAV/CalendarHome.php | 9 +- .../InvitationResponseServer.php | 24 ++-- .../Reminder/NotificationProviderManager.php | 2 +- apps/dav/lib/CardDAV/UserAddressBooks.php | 5 +- apps/dav/lib/Command/CreateCalendar.php | 19 +-- apps/dav/lib/Connector/Sabre/Directory.php | 3 +- apps/dav/lib/Connector/Sabre/File.php | 9 +- .../lib/Connector/Sabre/MaintenancePlugin.php | 3 +- apps/dav/lib/Connector/Sabre/Node.php | 2 +- apps/dav/lib/Connector/Sabre/Principal.php | 2 + .../dav/lib/Connector/Sabre/ServerFactory.php | 22 ++-- apps/dav/lib/Files/BrowserErrorPagePlugin.php | 2 +- apps/dav/lib/Files/RootCollection.php | 3 +- apps/dav/lib/RootCollection.php | 64 ++++++---- apps/dav/lib/Server.php | 118 ++++++++++-------- apps/dav/lib/Upload/UploadHome.php | 3 +- .../Sabre/RequestTest/RequestTestCase.php | 32 +++-- 20 files changed, 206 insertions(+), 136 deletions(-) diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index 03ae7a82218c2..5281747a4df24 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -93,11 +93,14 @@ use OCP\AppFramework\Bootstrap\IBootstrap; use OCP\AppFramework\Bootstrap\IRegistrationContext; use OCP\AppFramework\IAppContainer; +use OCP\BackgroundJob\IJobList; use OCP\Calendar\IManager as ICalendarManager; use OCP\Contacts\IManager as IContactsManager; use OCP\ILogger; use OCP\IServerContainer; +use OCP\IURLGenerator; use OCP\IUser; +use OCP\IUserSession; use Psr\Container\ContainerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; @@ -235,7 +238,7 @@ public function registerHooks(HookManager $hm, $dispatcher->addListener('OCP\Federation\TrustedServerEvent::remove', function (GenericEvent $event) { /** @var CardDavBackend $cardDavBackend */ - $cardDavBackend = \OC::$server->query(CardDavBackend::class); + $cardDavBackend = \OC::$server->get(CardDavBackend::class); $addressBookUri = $event->getSubject(); $addressBook = $cardDavBackend->getAddressBooksByUri('principals/system/system', $addressBookUri); if (!is_null($addressBook)) { @@ -249,7 +252,7 @@ function (GenericEvent $event) { /** @var UpdateCalendarResourcesRoomsBackgroundJob $job */ $job = $container->query(UpdateCalendarResourcesRoomsBackgroundJob::class); $job->run([]); - $serverContainer->getJobList()->setLastRun($job); + $serverContainer->get(IJobList::class)->setLastRun($job); } catch (Exception $ex) { $serverContainer->getLogger()->logException($ex); } @@ -261,7 +264,7 @@ function (GenericEvent $event) { public function registerContactsManager(IContactsManager $cm, IAppContainer $container): void { $cm->register(function () use ($container, $cm): void { - $user = \OC::$server->getUserSession()->getUser(); + $user = \OC::$server->get(IUserSession::class)->getUser(); if (!is_null($user)) { $this->setupContactsProvider($cm, $container, $user->getUID()); } else { @@ -275,7 +278,7 @@ private function setupContactsProvider(IContactsManager $contactsManager, string $userID): void { /** @var ContactsManager $cm */ $cm = $container->query(ContactsManager::class); - $urlGenerator = $container->getServer()->getURLGenerator(); + $urlGenerator = $container->getServer()->get(IURLGenerator::class); $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator); } @@ -283,14 +286,14 @@ private function setupSystemContactsProvider(IContactsManager $contactsManager, IAppContainer $container): void { /** @var ContactsManager $cm */ $cm = $container->query(ContactsManager::class); - $urlGenerator = $container->getServer()->getURLGenerator(); + $urlGenerator = $container->getServer()->get(IURLGenerator::class); $cm->setupSystemContactsProvider($contactsManager, $urlGenerator); } public function registerCalendarManager(ICalendarManager $calendarManager, IAppContainer $container): void { $calendarManager->register(function () use ($container, $calendarManager) { - $user = \OC::$server->getUserSession()->getUser(); + $user = \OC::$server->get(IUserSession::class)->getUser(); if ($user !== null) { $this->setupCalendarProvider($calendarManager, $container, $user->getUID()); } diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index 0b83d6a9205a1..dc67f9ca73c14 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -253,7 +253,7 @@ private function extractCalendarPluginList(array $array): array { private function createClass(string $className): object { try { - return $this->container->query($className); + return $this->container->get($className); } catch (QueryException $e) { if (class_exists($className)) { return new $className(); diff --git a/apps/dav/lib/Avatars/RootCollection.php b/apps/dav/lib/Avatars/RootCollection.php index c5e78624d4473..e88b29e02531c 100644 --- a/apps/dav/lib/Avatars/RootCollection.php +++ b/apps/dav/lib/Avatars/RootCollection.php @@ -24,6 +24,7 @@ */ namespace OCA\DAV\Avatars; +use OCP\IAvatarManager; use Sabre\DAVACL\AbstractPrincipalCollection; class RootCollection extends AbstractPrincipalCollection { @@ -39,7 +40,7 @@ class RootCollection extends AbstractPrincipalCollection { * @return AvatarHome */ public function getChildForPrincipal(array $principalInfo) { - $avatarManager = \OC::$server->getAvatarManager(); + $avatarManager = \OC::$server->get(IAvatarManager::class); return new AvatarHome($principalInfo, $avatarManager); } diff --git a/apps/dav/lib/CalDAV/CalendarHome.php b/apps/dav/lib/CalDAV/CalendarHome.php index ceeba31800e06..bb1ca6e2da808 100644 --- a/apps/dav/lib/CalDAV/CalendarHome.php +++ b/apps/dav/lib/CalDAV/CalendarHome.php @@ -31,6 +31,9 @@ use OCA\DAV\CalDAV\Integration\ICalendarProvider; use OCA\DAV\CalDAV\Trashbin\TrashbinHome; use Psr\Log\LoggerInterface; +use OCP\App\IAppManager; +use OCP\IConfig; +use OCP\L10N\IFactory; use Sabre\CalDAV\Backend\BackendInterface; use Sabre\CalDAV\Backend\NotificationSupport; use Sabre\CalDAV\Backend\SchedulingSupport; @@ -61,11 +64,11 @@ class CalendarHome extends \Sabre\CalDAV\CalendarHome { public function __construct(BackendInterface $caldavBackend, $principalInfo, LoggerInterface $logger) { parent::__construct($caldavBackend, $principalInfo); - $this->l10n = \OC::$server->getL10N('dav'); - $this->config = \OC::$server->getConfig(); + $this->l10n = \OC::$server->get(IFactory::class)->get('dav'); + $this->config = \OC::$server->get(IConfig::class); $this->pluginManager = new PluginManager( \OC::$server, - \OC::$server->getAppManager() + \OC::$server->get(IAppManager::class) ); $this->logger = $logger; } diff --git a/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php b/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php index 5317dc1b169d7..c6d7e03758057 100644 --- a/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php +++ b/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php @@ -32,14 +32,20 @@ use OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin; use OCA\DAV\Connector\Sabre\CachingTree; use OCA\DAV\Connector\Sabre\DavAclPlugin; +use OCA\DAV\Connector\Sabre\MaintenancePlugin; +use OCA\DAV\Connector\Sabre\Server; use OCA\DAV\Events\SabrePluginAuthInitEvent; use OCA\DAV\RootCollection; +use OCP\App\IAppManager; use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; +use OCP\IURLGenerator; +use OCP\L10N\IFactory; use Sabre\VObject\ITip\Message; class InvitationResponseServer { - /** @var \OCA\DAV\Connector\Sabre\Server */ + /** @var Server */ public $server; /** @@ -49,19 +55,19 @@ public function __construct(bool $public = true) { $baseUri = \OC::$WEBROOT . '/remote.php/dav/'; $logger = \OC::$server->getLogger(); /** @var IEventDispatcher $dispatcher */ - $dispatcher = \OC::$server->query(IEventDispatcher::class); + $dispatcher = \OC::$server->get(IEventDispatcher::class); $root = new RootCollection(); - $this->server = new \OCA\DAV\Connector\Sabre\Server(new CachingTree($root)); + $this->server = new Server(new CachingTree($root)); // Add maintenance plugin - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin(\OC::$server->getConfig(), \OC::$server->getL10N('dav'))); + $this->server->addPlugin(new MaintenancePlugin(\OC::$server->get(IConfig::class), \OC::$server->get(IFactory::class)->get('dav'))); // Set URL explicitly due to reverse-proxy situations $this->server->httpRequest->setUrl($baseUri); $this->server->setBaseUri($baseUri); - $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->getConfig())); + $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->get(IConfig::class))); $this->server->addPlugin(new AnonymousOptionsPlugin()); // allow custom principal uri option @@ -89,13 +95,13 @@ public function __construct(bool $public = true) { // calendar plugins $this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin()); $this->server->addPlugin(new \Sabre\CalDAV\ICSExportPlugin()); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->getConfig())); + $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); $this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin()); $this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin()); //$this->server->addPlugin(new \OCA\DAV\DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest())); $this->server->addPlugin(new \OCA\DAV\CalDAV\Publishing\PublishPlugin( - \OC::$server->getConfig(), - \OC::$server->getURLGenerator() + \OC::$server->get(IConfig::class), + \OC::$server->get(IURLGenerator::class) )); // wait with registering these until auth is handled and the filesystem is setup @@ -103,7 +109,7 @@ public function __construct(bool $public = true) { // register plugins from apps $pluginManager = new PluginManager( \OC::$server, - \OC::$server->getAppManager() + \OC::$server->get(IAppManager::class) ); foreach ($pluginManager->getAppPlugins() as $appPlugin) { $this->server->addPlugin($appPlugin); diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php b/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php index cd8030a117720..9cab336fd6d65 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php @@ -73,7 +73,7 @@ public function getProvider(string $type):INotificationProvider { * @throws \OCP\AppFramework\QueryException */ public function registerProvider(string $providerClassName):void { - $provider = \OC::$server->query($providerClassName); + $provider = \OC::$server->get($providerClassName); if (!$provider instanceof INotificationProvider) { throw new \InvalidArgumentException('Invalid notification provider registered'); diff --git a/apps/dav/lib/CardDAV/UserAddressBooks.php b/apps/dav/lib/CardDAV/UserAddressBooks.php index 9895730112017..fa3168f396598 100644 --- a/apps/dav/lib/CardDAV/UserAddressBooks.php +++ b/apps/dav/lib/CardDAV/UserAddressBooks.php @@ -32,6 +32,7 @@ use OCA\DAV\CardDAV\Integration\ExternalAddressBook; use OCP\IConfig; use OCP\IL10N; +use OCP\L10N\IFactory; use Sabre\CardDAV\Backend; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\CardDAV\IAddressBook; @@ -63,10 +64,10 @@ public function __construct(Backend\BackendInterface $carddavBackend, */ public function getChildren() { if ($this->l10n === null) { - $this->l10n = \OC::$server->getL10N('dav'); + $this->l10n = \OC::$server->get(IFactory::class)->get('dav'); } if ($this->config === null) { - $this->config = \OC::$server->getConfig(); + $this->config = \OC::$server->get(IConfig::class); } $addressBooks = $this->carddavBackend->getAddressBooksForUser($this->principalUri); diff --git a/apps/dav/lib/Command/CreateCalendar.php b/apps/dav/lib/Command/CreateCalendar.php index e6e8dd2025b16..c923a8d760285 100644 --- a/apps/dav/lib/Command/CreateCalendar.php +++ b/apps/dav/lib/Command/CreateCalendar.php @@ -29,11 +29,16 @@ use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\Connector\Sabre\Principal; +use OCP\App\IAppManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUserManager; +use OCP\IUserSession; +use OCP\L10N\IFactory; +use OCP\Security\ISecureRandom; +use OCP\Share\IManager; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -82,15 +87,15 @@ protected function execute(InputInterface $input, OutputInterface $output): int $principalBackend = new Principal( $this->userManager, $this->groupManager, - \OC::$server->getShareManager(), - \OC::$server->getUserSession(), - \OC::$server->getAppManager(), - \OC::$server->query(ProxyMapper::class), + \OC::$server->get(IManager::class), + \OC::$server->get(IUserSession::class), + \OC::$server->get(IAppManager::class), + \OC::$server->get(ProxyMapper::class), \OC::$server->get(KnownUserService::class), - \OC::$server->getConfig(), - \OC::$server->getL10NFactory(), + \OC::$server->get(IConfig::class), + \OC::$server->get(IFactory::class), ); - $random = \OC::$server->getSecureRandom(); + $random = \OC::$server->get(ISecureRandom::class); $logger = \OC::$server->getLogger(); $dispatcher = \OC::$server->get(IEventDispatcher::class); $config = \OC::$server->get(IConfig::class); diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index 3ae4416d3632f..08406e4cfb09c 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -40,6 +40,7 @@ use OCP\Files\FileInfo; use OCP\Files\ForbiddenException; use OCP\Files\InvalidPathException; +use OCP\Files\Mount\IMountManager; use OCP\Files\NotPermittedException; use OCP\Files\StorageNotAvailableException; use OCP\Lock\ILockingProvider; @@ -404,7 +405,7 @@ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) { $sourcePath = $sourceNode->getPath(); $isMovableMount = false; - $sourceMount = \OC::$server->getMountManager()->find($this->fileView->getAbsolutePath($sourcePath)); + $sourceMount = \OC::$server->get(IMountManager::class)->find($this->fileView->getAbsolutePath($sourcePath)); $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath)); if ($sourceMount instanceof MoveableMount && $internalPath === '') { $isMovableMount = true; diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index 4768fc3dc44eb..91af83db0e3b0 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -54,6 +54,7 @@ use OCP\Files\FileInfo; use OCP\Files\ForbiddenException; use OCP\Files\GenericFileException; +use OCP\Files\IMimeTypeDetector; use OCP\Files\InvalidContentException; use OCP\Files\InvalidPathException; use OCP\Files\LockNotAcquiredException; @@ -64,6 +65,8 @@ use OCP\IL10N; use OCP\ILogger; use OCP\L10N\IFactory as IL10NFactory; +use OCP\IConfig; +use OCP\IRequest; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Share\IManager; @@ -99,7 +102,7 @@ public function __construct(View $view, FileInfo $info, IManager $shareManager = if (isset($request)) { $this->request = $request; } else { - $this->request = \OC::$server->getRequest(); + $this->request = \OC::$server->get(IRequest::class); } } @@ -402,7 +405,7 @@ public function put($data) { } private function getPartFileBasePath($path) { - $partFileInStorage = \OC::$server->getConfig()->getSystemValue('part_file_in_storage', true); + $partFileInStorage = \OC::$server->get(IConfig::class)->getSystemValue('part_file_in_storage', true); if ($partFileInStorage) { return $path; } else { @@ -534,7 +537,7 @@ public function getContentType() { if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'PROPFIND') { return $mimeType; } - return \OC::$server->getMimeTypeDetector()->getSecureMimeType($mimeType); + return \OC::$server->get(IMimeTypeDetector::class)->getSecureMimeType($mimeType); } /** diff --git a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php index e7e3b273b98b1..ca0e649bf5908 100644 --- a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php +++ b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php @@ -29,6 +29,7 @@ use OCP\IConfig; use OCP\IL10N; +use OCP\L10N\IFactory; use OCP\Util; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\ServerPlugin; @@ -53,7 +54,7 @@ class MaintenancePlugin extends ServerPlugin { */ public function __construct(IConfig $config, IL10N $l10n) { $this->config = $config; - $this->l10n = \OC::$server->getL10N('dav'); + $this->l10n = \OC::$server->get(IFactory::class)->get('dav'); } diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php index 79b4db0e32773..69c691b2860c1 100644 --- a/apps/dav/lib/Connector/Sabre/Node.php +++ b/apps/dav/lib/Connector/Sabre/Node.php @@ -89,7 +89,7 @@ public function __construct(View $view, FileInfo $info, IManager $shareManager = if ($shareManager) { $this->shareManager = $shareManager; } else { - $this->shareManager = \OC::$server->getShareManager(); + $this->shareManager = \OC::$server->get(IManager::class); } } diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 8002f96379880..0f7e0ac136e2c 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -38,7 +38,9 @@ namespace OCA\DAV\Connector\Sabre; use OC\KnownUser\KnownUserService; +use OCA\Circles\Api\v1\Circles; use OCA\Circles\Exceptions\CircleNotFoundException; +use OCA\Circles\Model\Circle; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\Traits\PrincipalProxyTrait; use OCP\App\IAppManager; diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index 095fb631c2b3e..02a2e284ce159 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -34,9 +34,12 @@ use OCP\Files\Folder; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\Files\BrowserErrorPagePlugin; +use OCP\App\IAppManager; +use OCP\Comments\ICommentsManager; use OCP\Files\Mount\IMountManager; use OCP\IConfig; use OCP\IDBConnection; +use OCP\IGroupManager; use OCP\IL10N; use OCP\ILogger; use OCP\IPreview; @@ -44,6 +47,9 @@ use OCP\ITagManager; use OCP\IUserSession; use OCP\SabrePluginEvent; +use OCP\Share\IManager; +use OCP\SystemTag\ISystemTagManager; +use OCP\SystemTag\ISystemTagObjectMapper; use Sabre\DAV\Auth\Plugin; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -187,19 +193,19 @@ public function createServer($baseUri, $objectTree, $this->userSession, $userFolder, - \OC::$server->getShareManager() + \OC::$server->get(IManager::class) )); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->getCommentsManager(), $this->userSession)); + $server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->get(ICommentsManager::class), $this->userSession)); $server->addPlugin(new \OCA\DAV\Connector\Sabre\FilesReportPlugin( $objectTree, $view, - \OC::$server->getSystemTagManager(), - \OC::$server->getSystemTagObjectMapper(), - \OC::$server->getTagManager(), + \OC::$server->get(ISystemTagManager::class), + \OC::$server->get(ISystemTagObjectMapper::class), + \OC::$server->get(ITagManager::class), $this->userSession, - \OC::$server->getGroupManager(), + \OC::$server->get(IGroupManager::class), $userFolder, - \OC::$server->getAppManager() + \OC::$server->get(IAppManager::class) )); // custom properties plugin must be the last one $server->addPlugin( @@ -219,7 +225,7 @@ public function createServer($baseUri, $this->eventDispatcher->dispatch($event); $pluginManager = new PluginManager( \OC::$server, - \OC::$server->getAppManager() + \OC::$server->get(IAppManager::class) ); foreach ($pluginManager->getAppPlugins() as $appPlugin) { $server->addPlugin($appPlugin); diff --git a/apps/dav/lib/Files/BrowserErrorPagePlugin.php b/apps/dav/lib/Files/BrowserErrorPagePlugin.php index b3ce591bd4a8e..b53d1caac5cdf 100644 --- a/apps/dav/lib/Files/BrowserErrorPagePlugin.php +++ b/apps/dav/lib/Files/BrowserErrorPagePlugin.php @@ -94,7 +94,7 @@ public function logException(\Exception $ex) { * @return bool|string */ public function generateBody(int $httpCode) { - $request = \OC::$server->getRequest(); + $request = \OC::$server->get(IRequest::class); $templateName = 'exception'; if ($httpCode === 403 || $httpCode === 404) { diff --git a/apps/dav/lib/Files/RootCollection.php b/apps/dav/lib/Files/RootCollection.php index 15498ec26ec37..897c8ed5b875f 100644 --- a/apps/dav/lib/Files/RootCollection.php +++ b/apps/dav/lib/Files/RootCollection.php @@ -26,6 +26,7 @@ namespace OCA\DAV\Files; use OCP\Files\FileInfo; +use OCP\IUserSession; use Sabre\DAV\INode; use Sabre\DAV\SimpleCollection; use Sabre\DAVACL\AbstractPrincipalCollection; @@ -44,7 +45,7 @@ class RootCollection extends AbstractPrincipalCollection { */ public function getChildForPrincipal(array $principalInfo) { [,$name] = \Sabre\Uri\split($principalInfo['uri']); - $user = \OC::$server->getUserSession()->getUser(); + $user = \OC::$server->get(IUserSession::class)->getUser(); if (is_null($user) || $name !== $user->getUID()) { // a user is only allowed to see their own home contents, so in case another collection // is accessed, we return a simple empty collection for now diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index fac66a4bbcf67..a5648cdef9377 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -28,6 +28,7 @@ */ namespace OCA\DAV; +use OC\EventDispatcher\SymfonyAdapter; use OC\KnownUser\KnownUserService; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\CalDavBackend; @@ -46,37 +47,46 @@ use OCA\DAV\Upload\CleanupService; use OCP\App\IAppManager; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use Psr\Log\LoggerInterface; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\L10N\IFactory; +use OCP\Security\ISecureRandom; +use OCP\Share\IManager; +use OCP\SystemTag\ISystemTagManager; +use OCP\SystemTag\ISystemTagObjectMapper; use Sabre\DAV\SimpleCollection; class RootCollection extends SimpleCollection { public function __construct() { - $l10n = \OC::$server->getL10N('dav'); - $random = \OC::$server->getSecureRandom(); + $l10n = \OC::$server->get(IFactory::class)->get('dav'); + $random = \OC::$server->get(ISecureRandom::class); $logger = \OC::$server->getLogger(); $psrLogger = \OC::$server->get(LoggerInterface::class); - $userManager = \OC::$server->getUserManager(); - $userSession = \OC::$server->getUserSession(); - $groupManager = \OC::$server->getGroupManager(); - $shareManager = \OC::$server->getShareManager(); - $db = \OC::$server->getDatabaseConnection(); + $userManager = \OC::$server->get(IUserManager::class); + $userSession = \OC::$server->get(IUserSession::class); + $groupManager = \OC::$server->get(IGroupManager::class); + $shareManager = \OC::$server->get(IManager::class); + $db = \OC::$server->get(IDBConnection::class); $dispatcher = \OC::$server->get(IEventDispatcher::class); - $legacyDispatcher = \OC::$server->getEventDispatcher(); $config = \OC::$server->get(IConfig::class); - $proxyMapper = \OC::$server->query(ProxyMapper::class); + $proxyMapper = \OC::$server->get(ProxyMapper::class); $userPrincipalBackend = new Principal( $userManager, $groupManager, $shareManager, - \OC::$server->getUserSession(), - \OC::$server->getAppManager(), + \OC::$server->get(IUserSession::class), + \OC::$server->get(IAppManager::class), $proxyMapper, \OC::$server->get(KnownUserService::class), - \OC::$server->getConfig(), - \OC::$server->getL10NFactory() + \OC::$server->get(IConfig::class), + \OC::$server->get(IFactory::class) ); $groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager, $config); $calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper); @@ -121,45 +131,45 @@ public function __construct() { $publicCalendarRoot->disableListing = $disableListing; $systemTagCollection = new SystemTag\SystemTagsByIdCollection( - \OC::$server->getSystemTagManager(), - \OC::$server->getUserSession(), + \OC::$server->get(ISystemTagManager::class), + \OC::$server->get(IUserSession::class), $groupManager ); $systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection( - \OC::$server->getSystemTagManager(), - \OC::$server->getSystemTagObjectMapper(), - \OC::$server->getUserSession(), + \OC::$server->get(ISystemTagManager::class), + \OC::$server->get(ISystemTagObjectMapper::class), + \OC::$server->get(IUserSession::class), $groupManager, - \OC::$server->getEventDispatcher() + \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class) ); $commentsCollection = new Comments\RootCollection( - \OC::$server->getCommentsManager(), + \OC::$server->get(ICommentsManager::class), $userManager, - \OC::$server->getUserSession(), - \OC::$server->getEventDispatcher(), + \OC::$server->get(IUserSession::class), + \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class), \OC::$server->getLogger() ); - $pluginManager = new PluginManager(\OC::$server, \OC::$server->query(IAppManager::class)); - $usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher, $legacyDispatcher); + $pluginManager = new PluginManager(\OC::$server, \OC::$server->get(IAppManager::class)); + $usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher); $usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, $pluginManager, 'principals/users'); $usersAddressBookRoot->disableListing = $disableListing; - $systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher, $legacyDispatcher); + $systemCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher); $systemAddressBookRoot = new AddressBookRoot(new SystemPrincipalBackend(), $systemCardDavBackend, $pluginManager, 'principals/system'); $systemAddressBookRoot->disableListing = $disableListing; $uploadCollection = new Upload\RootCollection( $userPrincipalBackend, 'principals/users', - \OC::$server->query(CleanupService::class)); + \OC::$server->get(CleanupService::class)); $uploadCollection->disableListing = $disableListing; $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users'); $avatarCollection->disableListing = $disableListing; $appleProvisioning = new AppleProvisioningNode( - \OC::$server->query(ITimeFactory::class)); + \OC::$server->get(ITimeFactory::class)); $children = [ new SimpleCollection('principals', [ diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index 759d39c02339d..e52ca1d3a8c65 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -34,8 +34,23 @@ */ namespace OCA\DAV; -use OCA\DAV\Connector\Sabre\RequestIdHeaderPlugin; use OCP\Diagnostics\IEventLogger; +use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; +use OC\Security\Bruteforce\Throttler; +use OCP\App\IAppManager; +use OCP\Comments\ICommentsManager; +use OCP\Files\IRootFolder; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IPreview; +use OCP\ITagManager; +use OCP\IURLGenerator; +use OCP\IUserSession; +use OCP\L10N\IFactory; +use OCP\Share\IManager; +use OCP\SystemTag\ISystemTagManager; +use OCP\SystemTag\ISystemTagObjectMapper; use Psr\Log\LoggerInterface; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\BirthdayService; @@ -58,6 +73,7 @@ use OCA\DAV\Connector\Sabre\FilesReportPlugin; use OCA\DAV\Connector\Sabre\PropfindCompressionPlugin; use OCA\DAV\Connector\Sabre\QuotaPlugin; +use OCA\DAV\Connector\Sabre\RequestIdHeaderPlugin; use OCA\DAV\Connector\Sabre\SharesPlugin; use OCA\DAV\Connector\Sabre\TagsPlugin; use OCA\DAV\DAV\CustomPropertiesBackend; @@ -92,30 +108,30 @@ public function __construct(IRequest $request, $baseUri) { $this->request = $request; $this->baseUri = $baseUri; $logger = \OC::$server->getLogger(); - $dispatcher = \OC::$server->getEventDispatcher(); + $dispatcher = \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class); /** @var IEventDispatcher $newDispatcher */ - $newDispatcher = \OC::$server->query(IEventDispatcher::class); + $newDispatcher = \OC::$server->get(IEventDispatcher::class); $root = new RootCollection(); $this->server = new \OCA\DAV\Connector\Sabre\Server(new CachingTree($root)); // Add maintenance plugin - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin(\OC::$server->getConfig(), \OC::$server->getL10N('dav'))); + $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin(\OC::$server->get(IConfig::class), \OC::$server->get(IFactory::class)->get('dav'))); // Backends $authBackend = new Auth( - \OC::$server->getSession(), - \OC::$server->getUserSession(), - \OC::$server->getRequest(), - \OC::$server->getTwoFactorAuthManager(), - \OC::$server->getBruteForceThrottler() + \OC::$server->get(IUserSession::class)->getSession(), + \OC::$server->get(IUserSession::class), + \OC::$server->get(IRequest::class), + \OC::$server->get(TwoFactorAuthManager::class), + \OC::$server->get(Throttler::class) ); // Set URL explicitly due to reverse-proxy situations $this->server->httpRequest->setUrl($this->request->getRequestUri()); $this->server->setBaseUri($this->baseUri); - $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->getConfig())); + $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->get(IConfig::class))); $this->server->addPlugin(new AnonymousOptionsPlugin()); $authPlugin = new Plugin(); $authPlugin->addBackend(new PublicAuth()); @@ -129,16 +145,16 @@ public function __construct(IRequest $request, $baseUri) { $newDispatcher->dispatchTyped($newAuthEvent); $bearerAuthBackend = new BearerAuth( - \OC::$server->getUserSession(), - \OC::$server->getSession(), - \OC::$server->getRequest() + \OC::$server->get(IUserSession::class), + \OC::$server->get(IUserSession::class)->getSession(), + \OC::$server->get(IRequest::class) ); $authPlugin->addBackend($bearerAuthBackend); // because we are throwing exceptions this plugin has to be the last one $authPlugin->addBackend($authBackend); // debugging - if (\OC::$server->getConfig()->getSystemValue('debug', false)) { + if (\OC::$server->get(IConfig::class)->getSystemValue('debug', false)) { $this->server->addPlugin(new \Sabre\DAV\Browser\Plugin()); } else { $this->server->addPlugin(new DummyGetResponsePlugin()); @@ -161,10 +177,10 @@ public function __construct(IRequest $request, $baseUri) { // calendar plugins if ($this->requestIsForSubtree(['calendars', 'public-calendars', 'system-calendars', 'principals'])) { $this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin()); - $this->server->addPlugin(new \OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin(\OC::$server->getConfig(), \OC::$server->getLogger())); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->getConfig())); - if (\OC::$server->getConfig()->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') { - $this->server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class)); + $this->server->addPlugin(new \OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin(\OC::$server->get(IConfig::class), \OC::$server->getLogger())); + $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); + if (\OC::$server->get(IConfig::class)->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') { + $this->server->addPlugin(\OC::$server->get(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class)); } $this->server->addPlugin(\OC::$server->get(\OCA\DAV\CalDAV\Trashbin\Plugin::class)); @@ -172,16 +188,16 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin()); $this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin()); - $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest(), \OC::$server->getConfig())); + $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->get(IRequest::class), \OC::$server->get(IConfig::class))); $this->server->addPlugin(new \OCA\DAV\CalDAV\Publishing\PublishPlugin( - \OC::$server->getConfig(), - \OC::$server->getURLGenerator() + \OC::$server->get(IConfig::class), + \OC::$server->get(IURLGenerator::class) )); } // addressbook plugins if ($this->requestIsForSubtree(['addressbooks', 'principals'])) { - $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest(), \OC::$server->getConfig())); + $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->get(IRequest::class), \OC::$server->get(IConfig::class))); $this->server->addPlugin(new \OCA\DAV\CardDAV\Plugin()); $this->server->addPlugin(new VCFExportPlugin()); $this->server->addPlugin(new MultiGetExportPlugin()); @@ -194,15 +210,15 @@ public function __construct(IRequest $request, $baseUri) { // system tags plugins $this->server->addPlugin(new SystemTagPlugin( - \OC::$server->getSystemTagManager(), - \OC::$server->getGroupManager(), - \OC::$server->getUserSession() + \OC::$server->get(ISystemTagManager::class), + \OC::$server->get(IGroupManager::class), + \OC::$server->get(IUserSession::class) )); // comments plugin $this->server->addPlugin(new CommentsPlugin( - \OC::$server->getCommentsManager(), - \OC::$server->getUserSession() + \OC::$server->get(ICommentsManager::class), + \OC::$server->get(IUserSession::class) )); $this->server->addPlugin(new CopyEtagHeaderPlugin()); @@ -232,19 +248,19 @@ public function __construct(IRequest $request, $baseUri) { // wait with registering these until auth is handled and the filesystem is setup $this->server->on('beforeMethod:*', function () use ($root, $lazySearchBackend) { // custom properties plugin must be the last one - $userSession = \OC::$server->getUserSession(); + $userSession = \OC::$server->get(IUserSession::class); $user = $userSession->getUser(); if ($user !== null) { $view = \OC\Files\Filesystem::getView(); $this->server->addPlugin( new FilesPlugin( $this->server->tree, - \OC::$server->getConfig(), + \OC::$server->get(IConfig::class), $this->request, - \OC::$server->getPreviewManager(), - \OC::$server->getUserSession(), + \OC::$server->get(IPreview::class), + \OC::$server->get(IUserSession::class), false, - !\OC::$server->getConfig()->getSystemValue('debug', false) + !\OC::$server->get(IConfig::class)->getSystemValue('debug', false) ) ); @@ -252,8 +268,8 @@ public function __construct(IRequest $request, $baseUri) { new \Sabre\DAV\PropertyStorage\Plugin( new CustomPropertiesBackend( $this->server->tree, - \OC::$server->getDatabaseConnection(), - \OC::$server->getUserSession()->getUser() + \OC::$server->get(IDBConnection::class), + \OC::$server->get(IUserSession::class)->getUser() ) ) ); @@ -263,7 +279,7 @@ public function __construct(IRequest $request, $baseUri) { } $this->server->addPlugin( new TagsPlugin( - $this->server->tree, \OC::$server->getTagManager() + $this->server->tree, \OC::$server->get(ITagManager::class) ) ); // TODO: switch to LazyUserFolder @@ -272,10 +288,10 @@ public function __construct(IRequest $request, $baseUri) { $this->server->tree, $userSession, $userFolder, - \OC::$server->getShareManager() + \OC::$server->get(IManager::class) )); $this->server->addPlugin(new CommentPropertiesPlugin( - \OC::$server->getCommentsManager(), + \OC::$server->get(ICommentsManager::class), $userSession )); $this->server->addPlugin(new \OCA\DAV\CalDAV\Search\SearchPlugin()); @@ -283,19 +299,19 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin(new FilesReportPlugin( $this->server->tree, $view, - \OC::$server->getSystemTagManager(), - \OC::$server->getSystemTagObjectMapper(), - \OC::$server->getTagManager(), + \OC::$server->get(ISystemTagManager::class), + \OC::$server->get(ISystemTagObjectMapper::class), + \OC::$server->get(ITagManager::class), $userSession, - \OC::$server->getGroupManager(), + \OC::$server->get(IGroupManager::class), $userFolder, - \OC::$server->getAppManager() + \OC::$server->get(IAppManager::class) )); $lazySearchBackend->setBackend(new \OCA\DAV\Files\FileSearchBackend( $this->server->tree, $user, - \OC::$server->getRootFolder(), - \OC::$server->getShareManager(), + \OC::$server->get(IRootFolder::class), + \OC::$server->get(IManager::class), $view )); $logger = \OC::$server->get(LoggerInterface::class); @@ -304,15 +320,15 @@ public function __construct(IRequest $request, $baseUri) { ); } $this->server->addPlugin(new \OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin( - \OC::$server->getConfig(), - \OC::$server->query(BirthdayService::class) + \OC::$server->get(IConfig::class), + \OC::$server->get(BirthdayService::class) )); $this->server->addPlugin(new AppleProvisioningPlugin( - \OC::$server->getUserSession(), - \OC::$server->getURLGenerator(), + \OC::$server->get(IUserSession::class), + \OC::$server->get(IURLGenerator::class), \OC::$server->getThemingDefaults(), - \OC::$server->getRequest(), - \OC::$server->getL10N('dav'), + \OC::$server->get(IRequest::class), + \OC::$server->get(IFactory::class)->get('dav'), function () { return UUIDUtil::getUUID(); } @@ -322,7 +338,7 @@ function () { // register plugins from apps $pluginManager = new PluginManager( \OC::$server, - \OC::$server->getAppManager() + \OC::$server->get(IAppManager::class) ); foreach ($pluginManager->getAppPlugins() as $appPlugin) { $this->server->addPlugin($appPlugin); diff --git a/apps/dav/lib/Upload/UploadHome.php b/apps/dav/lib/Upload/UploadHome.php index 35d47b6a82aba..ef52c0c15519c 100644 --- a/apps/dav/lib/Upload/UploadHome.php +++ b/apps/dav/lib/Upload/UploadHome.php @@ -28,6 +28,7 @@ use OC\Files\Filesystem; use OC\Files\View; use OCA\DAV\Connector\Sabre\Directory; +use OCP\IUserSession; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\ICollection; @@ -90,7 +91,7 @@ public function getLastModified() { */ private function impl() { $rootView = new View(); - $user = \OC::$server->getUserSession()->getUser(); + $user = \OC::$server->get(IUserSession::class)->getUser(); Filesystem::initMountPoints($user->getUID()); if (!$rootView->file_exists('/' . $user->getUID() . '/uploads')) { $rootView->mkdir('/' . $user->getUID() . '/uploads'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php index 5adfece42e86e..a16718bf46421 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php @@ -28,10 +28,20 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use OC\Files\Storage\Local; use OC\Files\View; use OCA\DAV\Connector\Sabre\Server; use OCA\DAV\Connector\Sabre\ServerFactory; +use OCP\Files\Mount\IMountManager; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IPreview; use OCP\IRequest; +use OCP\ITagManager; +use OCP\ITempManager; +use OCP\IUserSession; +use OCP\L10N\IFactory; +use Psr\Log\LoggerInterface; use Sabre\HTTP\Request; use Test\TestCase; use Test\Traits\MountProviderTrait; @@ -59,25 +69,25 @@ protected function setUp(): void { unset($_SERVER['HTTP_OC_CHUNKED']); $this->serverFactory = new ServerFactory( - \OC::$server->getConfig(), - \OC::$server->getLogger(), - \OC::$server->getDatabaseConnection(), - \OC::$server->getUserSession(), - \OC::$server->getMountManager(), - \OC::$server->getTagManager(), + \OC::$server->get(IConfig::class), + \OC::$server->get(LoggerInterface::class), + \OC::$server->get(IDBConnection::class), + \OC::$server->get(IUserSession::class), + \OC::$server->get(IMountManager::class), + \OC::$server->get(ITagManager::class), $this->getMockBuilder(IRequest::class) ->disableOriginalConstructor() ->getMock(), - \OC::$server->getPreviewManager(), - \OC::$server->getEventDispatcher(), - \OC::$server->getL10N('dav') + \OC::$server->get(IPreview::class), + \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class), + \OC::$server->get(IFactory::class)->get('dav') ); } protected function setupUser($name, $password) { $this->createUser($name, $password); - $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); - $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); + $tmpFolder = \OC::$server->get(ITempManager::class)->getTemporaryFolder(); + $this->registerMount($name, Local::class, '/' . $name, ['datadir' => $tmpFolder]); $this->loginAsUser($name); return new View('/' . $name . '/files'); } From 08abaae9e728f29ea084210d2349af807c8a196a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 19:05:10 +0100 Subject: [PATCH 07/23] Fix doctype of param passed to deleteContact Signed-off-by: Thomas Citharel --- apps/dav/lib/CardDAV/AddressBookImpl.php | 2 +- lib/public/IAddressBook.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/dav/lib/CardDAV/AddressBookImpl.php b/apps/dav/lib/CardDAV/AddressBookImpl.php index 3db20cb4220a3..442d8a5472b0c 100644 --- a/apps/dav/lib/CardDAV/AddressBookImpl.php +++ b/apps/dav/lib/CardDAV/AddressBookImpl.php @@ -206,7 +206,7 @@ public function getPermissions() { } /** - * @param object $id the unique identifier to a contact + * @param int $id the unique identifier to a contact * @return bool successful or not * @since 5.0.0 */ diff --git a/lib/public/IAddressBook.php b/lib/public/IAddressBook.php index 4bb632ae07099..346a1af02b857 100644 --- a/lib/public/IAddressBook.php +++ b/lib/public/IAddressBook.php @@ -98,7 +98,7 @@ public function createOrUpdate($properties); public function getPermissions(); /** - * @param object $id the unique identifier to a contact + * @param int $id the unique identifier to a contact * @return bool successful or not * @since 5.0.0 */ From 4827bc76eec5e88906e39ba9af3ff8384aaec01b Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 19:06:20 +0100 Subject: [PATCH 08/23] Improve OCA\DAV\Connector\Sabre\Principal Signed-off-by: Thomas Citharel --- apps/dav/lib/Connector/Sabre/Principal.php | 51 +++++++++------------ apps/dav/lib/Traits/PrincipalProxyTrait.php | 4 +- 2 files changed, 24 insertions(+), 31 deletions(-) diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 0f7e0ac136e2c..8093fb6f1d4e2 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -235,12 +235,10 @@ public function getGroupMembership($principal, $needGroups = false) { } } - $groups = array_unique(array_merge( + return array_unique(array_merge( $groups, $this->traitGetGroupMembership($principal, $needGroups) )); - - return $groups; } /** @@ -472,25 +470,23 @@ public function findByUri($uri, $principalPrefix) { $restrictGroups = $this->groupManager->getUserGroupIds($user); } - if (strpos($uri, 'mailto:') === 0) { - if ($principalPrefix === 'principals/users') { - $users = $this->userManager->getByEmail(substr($uri, 7)); - if (count($users) !== 1) { - return null; - } - $user = $users[0]; + if ($principalPrefix === 'principals/users' && (strpos($uri, 'mailto:') === 0)) { + $users = $this->userManager->getByEmail(substr($uri, 7)); + if (count($users) !== 1) { + return null; + } + $user = $users[0]; - if ($restrictGroups !== false) { - $userGroups = $this->groupManager->getUserGroupIds($user); - if (count(array_intersect($userGroups, $restrictGroups)) === 0) { - return null; - } + if ($restrictGroups !== false) { + $userGroups = $this->groupManager->getUserGroupIds($user); + if (count(array_intersect($userGroups, $restrictGroups)) === 0) { + return null; } - - return $this->principalPrefix . '/' . $user->getUID(); } + + return $this->principalPrefix . '/' . $user->getUID(); } - if (substr($uri, 0, 10) === 'principal:') { + if (strpos($uri, 'principal:') === 0) { $principal = substr($uri, 10); $principal = $this->getPrincipalByPath($principal); if ($principal !== null) { @@ -505,7 +501,7 @@ public function findByUri($uri, $principalPrefix) { * @param IUser $user * @return array */ - protected function userToPrincipal($user) { + protected function userToPrincipal(IUser $user): array { $userId = $user->getUID(); $displayName = $user->getDisplayName(); $principal = [ @@ -523,7 +519,7 @@ protected function userToPrincipal($user) { return $principal; } - public function getPrincipalPrefix() { + public function getPrincipalPrefix(): string { return $this->principalPrefix; } @@ -531,13 +527,13 @@ public function getPrincipalPrefix() { * @param string $circleUniqueId * @return array|null */ - protected function circleToPrincipal($circleUniqueId) { + protected function circleToPrincipal(string $circleUniqueId): ?array { if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) { return null; } try { - $circle = \OCA\Circles\Api\v1\Circles::detailsCircle($circleUniqueId, true); + $circle = Circles::detailsCircle($circleUniqueId, true); } catch (QueryException $ex) { return null; } catch (CircleNotFoundException $ex) { @@ -562,10 +558,9 @@ protected function circleToPrincipal($circleUniqueId) { * @param string $principal * @return array * @throws Exception - * @throws \OCP\AppFramework\QueryException * @suppress PhanUndeclaredClassMethod */ - public function getCircleMembership($principal):array { + public function getCircleMembership(string $principal):array { if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) { return []; } @@ -577,14 +572,12 @@ public function getCircleMembership($principal):array { throw new Exception('Principal not found'); } - $circles = \OCA\Circles\Api\v1\Circles::joinedCircles($name, true); + $circles = Circles::joinedCircles($name, true); - $circles = array_map(function ($circle) { - /** @var \OCA\Circles\Model\Circle $circle */ + return array_map(static function ($circle) { + /** @var Circle $circle */ return 'principals/circles/' . urlencode($circle->getSingleId()); }, $circles); - - return $circles; } return []; diff --git a/apps/dav/lib/Traits/PrincipalProxyTrait.php b/apps/dav/lib/Traits/PrincipalProxyTrait.php index 6e764cac8c05c..98caa67ae50f1 100644 --- a/apps/dav/lib/Traits/PrincipalProxyTrait.php +++ b/apps/dav/lib/Traits/PrincipalProxyTrait.php @@ -108,7 +108,7 @@ public function getGroupMembership($principal, $needGroups = false) { * * @param string $principal * @param string[] $members - * @throws Exception + * @throws Exception|\OCP\DB\Exception */ public function setGroupMemberSet($principal, array $members) { [$principalUri, $target] = \Sabre\Uri\split($principal); @@ -183,7 +183,7 @@ private function isProxyPrincipal(string $principalUri):bool { [$realPrincipalUri, $proxy] = \Sabre\Uri\split($principalUri); [$prefix, $userId] = \Sabre\Uri\split($realPrincipalUri); - if (!isset($prefix) || !isset($userId)) { + if (!isset($prefix, $userId)) { return false; } if ($prefix !== $this->principalPrefix) { From aa7994f5bdeb362ba7e58acb290ea9246a0f8ff6 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 19:06:42 +0100 Subject: [PATCH 09/23] Improve OCA\DAV\Tests\unit\CardDAV\AddressBookImplTest Signed-off-by: Thomas Citharel --- .../unit/CardDAV/AddressBookImplTest.php | 95 ++++++++++--------- 1 file changed, 51 insertions(+), 44 deletions(-) diff --git a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php index eb87901f3acf3..3cbaf91659851 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php @@ -34,9 +34,10 @@ use OCA\DAV\CardDAV\AddressBookImpl; use OCA\DAV\CardDAV\CardDavBackend; use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\VObject\Component\VCard; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Property\Text; -//use Sabre\VObject\Property\; use Test\TestCase; class AddressBookImplTest extends TestCase { @@ -47,16 +48,16 @@ class AddressBookImplTest extends TestCase { /** @var array */ private $addressBookInfo; - /** @var AddressBook | \PHPUnit\Framework\MockObject\MockObject */ + /** @var AddressBook | MockObject */ private $addressBook; - /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator | MockObject */ private $urlGenerator; - /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject */ + /** @var CardDavBackend | MockObject */ private $backend; - /** @var VCard | \PHPUnit\Framework\MockObject\MockObject */ + /** @var VCard | MockObject */ private $vCard; protected function setUp(): void { @@ -83,19 +84,19 @@ protected function setUp(): void { ); } - public function testGetKey() { + public function testGetKey(): void { $this->assertSame($this->addressBookInfo['id'], $this->addressBookImpl->getKey()); } - public function testGetDisplayName() { + public function testGetDisplayName(): void { $this->assertSame($this->addressBookInfo['{DAV:}displayname'], $this->addressBookImpl->getDisplayName()); } - public function testSearch() { + public function testSearch(): void { - /** @var \PHPUnit\Framework\MockObject\MockObject | AddressBookImpl $addressBookImpl */ + /** @var MockObject | AddressBookImpl $addressBookImpl */ $addressBookImpl = $this->getMockBuilder(AddressBookImpl::class) ->setConstructorArgs( [ @@ -105,11 +106,11 @@ public function testSearch() { $this->urlGenerator, ] ) - ->setMethods(['vCard2Array', 'readCard']) + ->onlyMethods(['vCard2Array', 'readCard']) ->getMock(); $pattern = 'pattern'; - $searchProperties = 'properties'; + $searchProperties = ['properties' => 'value']; $this->backend->expects($this->once())->method('search') ->with($this->addressBookInfo['id'], $pattern, $searchProperties) @@ -130,7 +131,7 @@ public function testSearch() { $result = $addressBookImpl->search($pattern, $searchProperties, []); $this->assertTrue((is_array($result))); - $this->assertSame(2, count($result)); + $this->assertCount(2, $result); } /** @@ -138,10 +139,10 @@ public function testSearch() { * * @param array $properties */ - public function testCreate($properties) { + public function testCreate(array $properties): void { $uid = 'uid'; - /** @var \PHPUnit\Framework\MockObject\MockObject | AddressBookImpl $addressBookImpl */ + /** @var MockObject | AddressBookImpl $addressBookImpl */ $addressBookImpl = $this->getMockBuilder(AddressBookImpl::class) ->setConstructorArgs( [ @@ -151,7 +152,7 @@ public function testCreate($properties) { $this->urlGenerator, ] ) - ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard']) + ->onlyMethods(['vCard2Array', 'createUid', 'createEmptyVCard']) ->getMock(); $expectedProperties = 0; @@ -178,7 +179,7 @@ public function testCreate($properties) { $this->assertTrue($addressBookImpl->createOrUpdate($properties)); } - public function dataTestCreate() { + public function dataTestCreate(): array { return [ [[]], [['FN' => 'John Doe']], @@ -186,12 +187,12 @@ public function dataTestCreate() { ]; } - public function testUpdate() { + public function testUpdate(): void { $uid = 'uid'; $uri = 'bla.vcf'; $properties = ['URI' => $uri, 'UID' => $uid, 'FN' => 'John Doe']; - /** @var \PHPUnit\Framework\MockObject\MockObject | AddressBookImpl $addressBookImpl */ + /** @var MockObject | AddressBookImpl $addressBookImpl */ $addressBookImpl = $this->getMockBuilder(AddressBookImpl::class) ->setConstructorArgs( [ @@ -201,7 +202,7 @@ public function testUpdate() { $this->urlGenerator, ] ) - ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard', 'readCard']) + ->onlyMethods(['vCard2Array', 'createUid', 'createEmptyVCard', 'readCard']) ->getMock(); $addressBookImpl->expects($this->never())->method('createUid'); @@ -221,14 +222,17 @@ public function testUpdate() { $this->assertTrue($addressBookImpl->createOrUpdate($properties)); } - public function testUpdateWithTypes() { + /** + * @throws InvalidDataException + */ + public function testUpdateWithTypes(): void { $uid = 'uid'; $uri = 'bla.vcf'; $properties = ['URI' => $uri, 'UID' => $uid, 'FN' => 'John Doe', 'ADR' => [['type' => 'HOME', 'value' => ';;street;city;;;country']]]; $vCard = new vCard; $textProperty = $vCard->createProperty('KEY','value'); - /** @var \PHPUnit\Framework\MockObject\MockObject | AddressBookImpl $addressBookImpl */ + /** @var MockObject | AddressBookImpl $addressBookImpl */ $addressBookImpl = $this->getMockBuilder(AddressBookImpl::class) ->setConstructorArgs( [ @@ -238,7 +242,7 @@ public function testUpdateWithTypes() { $this->urlGenerator, ] ) - ->setMethods(['vCard2Array', 'createUid', 'createEmptyVCard', 'readCard']) + ->onlyMethods(['vCard2Array', 'createUid', 'createEmptyVCard', 'readCard']) ->getMock(); $this->backend->expects($this->once())->method('getCard') @@ -262,7 +266,7 @@ public function testUpdateWithTypes() { * @param array $permissions * @param int $expected */ - public function testGetPermissions($permissions, $expected) { + public function testGetPermissions(array $permissions, int $expected): void { $this->addressBook->expects($this->once())->method('getACL') ->willReturn($permissions); @@ -271,7 +275,7 @@ public function testGetPermissions($permissions, $expected) { ); } - public function dataTestGetPermissions() { + public function dataTestGetPermissions(): array { return [ [[], 0], [[['privilege' => '{DAV:}read']], 1], @@ -285,7 +289,7 @@ public function dataTestGetPermissions() { ]; } - public function testDelete() { + public function testDelete(): void { $cardId = 1; $cardUri = 'cardUri'; $this->backend->expects($this->once())->method('getCardUri') @@ -297,19 +301,19 @@ public function testDelete() { $this->assertTrue($this->addressBookImpl->delete($cardId)); } - public function testReadCard() { + public function testReadCard(): void { $vCard = new VCard(); $vCard->add(new Text($vCard, 'UID', 'uid')); $vCardSerialized = $vCard->serialize(); - $result = $this->invokePrivate($this->addressBookImpl, 'readCard', [$vCardSerialized]); + $result = self::invokePrivate($this->addressBookImpl, 'readCard', [$vCardSerialized]); $resultSerialized = $result->serialize(); $this->assertSame($vCardSerialized, $resultSerialized); } - public function testCreateUid() { - /** @var \PHPUnit\Framework\MockObject\MockObject | AddressBookImpl $addressBookImpl */ + public function testCreateUid(): void { + /** @var MockObject | AddressBookImpl $addressBookImpl */ $addressBookImpl = $this->getMockBuilder(AddressBookImpl::class) ->setConstructorArgs( [ @@ -319,38 +323,40 @@ public function testCreateUid() { $this->urlGenerator, ] ) - ->setMethods(['getUid']) + ->onlyMethods(['getUid']) ->getMock(); - $addressBookImpl->expects($this->at(0))->method('getUid')->willReturn('uid0'); - $addressBookImpl->expects($this->at(1))->method('getUid')->willReturn('uid1'); + $addressBookImpl->expects($this->exactly(2))->method('getUid')->willReturnOnConsecutiveCalls('uid0', 'uid1'); // simulate that 'uid0' already exists, so the second uid will be returned $this->backend->expects($this->exactly(2))->method('getContact') ->willReturnCallback( function ($id, $uid) { - return ($uid === 'uid0.vcf'); + return ($uid === 'uid0.vcf' ? ['carddata' => 'something'] : []); } ); $this->assertSame('uid1', - $this->invokePrivate($addressBookImpl, 'createUid', []) + self::invokePrivate($addressBookImpl, 'createUid', []) ); } - public function testCreateEmptyVCard() { + public function testCreateEmptyVCard(): void { $uid = 'uid'; $expectedVCard = new VCard(); $expectedVCard->UID = $uid; $expectedVCardSerialized = $expectedVCard->serialize(); - $result = $this->invokePrivate($this->addressBookImpl, 'createEmptyVCard', [$uid]); + $result = self::invokePrivate($this->addressBookImpl, 'createEmptyVCard', [$uid]); $resultSerialized = $result->serialize(); $this->assertSame($expectedVCardSerialized, $resultSerialized); } - public function testVCard2Array() { + /** + * @throws InvalidDataException + */ + public function testVCard2Array(): void { $vCard = new VCard(); $vCard->add($vCard->createProperty('FN', 'Full Name')); @@ -378,9 +384,8 @@ public function testVCard2Array() { $property->add('TYPE', 'facebook'); $vCard->add($property); - $array = $this->invokePrivate($this->addressBookImpl, 'vCard2Array', ['uri', $vCard]); - unset($array['PRODID']); - unset($array['UID']); + $array = self::invokePrivate($this->addressBookImpl, 'vCard2Array', ['uri', $vCard]); + unset($array['PRODID'], $array['UID']); $this->assertEquals([ 'URI' => 'uri', @@ -417,7 +422,10 @@ public function testVCard2Array() { ], $array); } - public function testVCard2ArrayWithTypes() { + /** + * @throws InvalidDataException + */ + public function testVCard2ArrayWithTypes(): void { $vCard = new VCard(); $vCard->add($vCard->createProperty('FN', 'Full Name')); @@ -457,9 +465,8 @@ public function testVCard2ArrayWithTypes() { $property->add('TYPE', 'facebook'); $vCard->add($property); - $array = $this->invokePrivate($this->addressBookImpl, 'vCard2Array', ['uri', $vCard, true]); - unset($array['PRODID']); - unset($array['UID']); + $array = self::invokePrivate($this->addressBookImpl, 'vCard2Array', ['uri', $vCard, true]); + unset($array['PRODID'], $array['UID']); $this->assertEquals([ 'URI' => 'uri', From 3a3a1a02a0215175d0ab00635ba1a149d40e510a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 20:24:19 +0100 Subject: [PATCH 10/23] Move uses of ILogger to LoggerInterface Except for BackgroundJobs Signed-off-by: Thomas Citharel --- apps/dav/lib/AppInfo/Application.php | 10 +++---- .../BuildReminderIndexBackgroundJob.php | 10 +++---- .../lib/BackgroundJob/RefreshWebcalJob.php | 3 +-- apps/dav/lib/CalDAV/CalDavBackend.php | 16 ++++++------ .../ICSExportPlugin/ICSExportPlugin.php | 6 ++--- .../InvitationResponseServer.php | 3 ++- .../NotificationProvider/AbstractProvider.php | 8 +++--- .../NotificationProvider/EmailProvider.php | 8 +++--- .../NotificationProvider/PushProvider.php | 6 ++--- .../AbstractPrincipalBackend.php | 8 +++--- .../ResourcePrincipalBackend.php | 6 ++--- .../ResourceBooking/RoomPrincipalBackend.php | 6 ++--- apps/dav/lib/CalDAV/Schedule/IMipPlugin.php | 10 +++---- .../WebcalCaching/RefreshWebcalService.php | 23 +++++++--------- apps/dav/lib/CardDAV/PhotoCache.php | 16 ++++++------ apps/dav/lib/CardDAV/SyncService.php | 8 +++--- apps/dav/lib/Command/CreateCalendar.php | 3 ++- apps/dav/lib/Comments/CommentNode.php | 12 ++++----- apps/dav/lib/Comments/EntityCollection.php | 8 +++--- .../dav/lib/Comments/EntityTypeCollection.php | 8 +++--- apps/dav/lib/Comments/RootCollection.php | 8 +++--- apps/dav/lib/Connector/Sabre/Auth.php | 3 ++- .../Connector/Sabre/ExceptionLoggerPlugin.php | 14 ++++------ apps/dav/lib/Connector/Sabre/File.php | 17 ++++++------ .../dav/lib/Connector/Sabre/ServerFactory.php | 8 +++--- apps/dav/lib/HookManager.php | 5 ++-- .../BuildCalendarSearchIndexBackgroundJob.php | 8 +++--- .../BuildSocialSearchIndexBackgroundJob.php | 8 +++--- .../lib/Migration/CalDAVRemoveEmptyValue.php | 8 +++--- apps/dav/lib/RootCollection.php | 7 ++++- apps/dav/lib/Server.php | 6 ++--- .../BackgroundJob/RefreshWebcalJobTest.php | 1 - .../unit/CalDAV/AbstractCalDavBackend.php | 6 ++--- .../unit/CalDAV/PublicCalendarRootTest.php | 7 +++-- .../AbstractNotificationProviderTest.php | 6 ++--- .../EmailProviderTest.php | 4 +-- .../NotificationProvider/PushProviderTest.php | 4 +-- .../AbstractPrincipalBackendTest.php | 6 ++--- .../unit/CalDAV/Schedule/IMipPluginTest.php | 6 ++--- .../RefreshWebcalServiceTest.php | 26 +++++++++---------- .../tests/unit/CardDAV/SyncServiceTest.php | 8 +++--- .../tests/unit/Comments/CommentsNodeTest.php | 8 +++--- .../unit/Comments/EntityCollectionTest.php | 6 ++--- .../Comments/EntityTypeCollectionTest.php | 6 ++--- .../unit/Comments/RootCollectionTest.php | 1 - .../Migration/CalDAVRemoveEmptyValueTest.php | 6 ++--- 46 files changed, 187 insertions(+), 184 deletions(-) diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index 5281747a4df24..d2182bdee164a 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -96,12 +96,12 @@ use OCP\BackgroundJob\IJobList; use OCP\Calendar\IManager as ICalendarManager; use OCP\Contacts\IManager as IContactsManager; -use OCP\ILogger; use OCP\IServerContainer; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserSession; use Psr\Container\ContainerInterface; +use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; use Symfony\Component\EventDispatcher\GenericEvent; use Throwable; @@ -122,7 +122,7 @@ public function register(IRegistrationContext $context): void { return new PhotoCache( $server->getAppDataDir('dav-photocache'), - $c->get(ILogger::class) + $c->get(LoggerInterface::class) ); }); @@ -254,7 +254,7 @@ function (GenericEvent $event) { $job->run([]); $serverContainer->get(IJobList::class)->setLastRun($job); } catch (Exception $ex) { - $serverContainer->getLogger()->logException($ex); + $serverContainer->get(LoggerInterface::class)->error('Error while setting last run for UpdateCalendarResourcesRoomsBackgroundJob', ['exception' => $ex]); } }; @@ -308,13 +308,13 @@ private function setupCalendarProvider(ICalendarManager $calendarManager, } public function registerCalendarReminders(NotificationProviderManager $manager, - ILogger $logger): void { + LoggerInterface $logger): void { try { $manager->registerProvider(AudioProvider::class); $manager->registerProvider(EmailProvider::class); $manager->registerProvider(PushProvider::class); } catch (Throwable $ex) { - $logger->logException($ex); + $logger->error('Error while registering calendar reminder provider', ['exception' => $ex]); } } } diff --git a/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php b/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php index 3d4e4dd5e6b99..dfc7521024a14 100644 --- a/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php @@ -32,7 +32,7 @@ use OCP\BackgroundJob\IJobList; use OCP\BackgroundJob\QueuedJob; use OCP\IDBConnection; -use OCP\ILogger; +use Psr\Log\LoggerInterface; /** * Class BuildReminderIndexBackgroundJob @@ -47,7 +47,7 @@ class BuildReminderIndexBackgroundJob extends QueuedJob { /** @var ReminderService */ private $reminderService; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var IJobList */ @@ -61,13 +61,13 @@ class BuildReminderIndexBackgroundJob extends QueuedJob { * * @param IDBConnection $db * @param ReminderService $reminderService - * @param ILogger $logger + * @param LoggerInterface $logger * @param IJobList $jobList * @param ITimeFactory $timeFactory */ public function __construct(IDBConnection $db, ReminderService $reminderService, - ILogger $logger, + LoggerInterface $logger, IJobList $jobList, ITimeFactory $timeFactory) { parent::__construct($timeFactory); @@ -126,7 +126,7 @@ private function buildIndex(int $offset, int $stopAt):int { try { $this->reminderService->onCalendarObjectCreate($row); } catch (\Exception $ex) { - $this->logger->logException($ex); + $this->logger->error('Error while building reminder index', ['exception' => $ex]); } if (($this->timeFactory->getTime() - $startTime) > 15) { diff --git a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php index fbb944159fd3a..fa3a938dead72 100644 --- a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php +++ b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php @@ -95,8 +95,7 @@ public function execute(IJobList $jobList, ILogger $logger = null) { /** @var DateInterval $dateInterval */ $dateInterval = DateTimeParser::parseDuration($refreshRate); } catch (InvalidDataException $ex) { - $this->logger->logException($ex); - $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid"); + $this->logger->warning("Subscription $subscriptionId could not be refreshed, refreshrate in database is invalid", ['exception' => $ex]); return; } diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 2294ba58a9d8b..4610e381275f7 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -69,10 +69,10 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\IGroupManager; -use OCP\ILogger; use OCP\IUser; use OCP\IUserManager; use OCP\Security\ISecureRandom; +use Psr\Log\LoggerInterface; use RuntimeException; use Sabre\CalDAV\Backend\AbstractBackend; use Sabre\CalDAV\Backend\SchedulingSupport; @@ -217,7 +217,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription /** @var ISecureRandom */ private $random; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var IEventDispatcher */ @@ -240,7 +240,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * @param IUserManager $userManager * @param IGroupManager $groupManager * @param ISecureRandom $random - * @param ILogger $logger + * @param LoggerInterface $logger * @param IEventDispatcher $dispatcher * @param bool $legacyEndpoint */ @@ -249,7 +249,7 @@ public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, ISecureRandom $random, - ILogger $logger, + LoggerInterface $logger, IEventDispatcher $dispatcher, IConfig $config, bool $legacyEndpoint = false) { @@ -1705,15 +1705,15 @@ public function calendarQuery($calendarId, array $filters, $calendarType = self: try { $matches = $this->validateFilterForObject($row, $filters); } catch (ParseException $ex) { - $this->logger->logException($ex, [ + $this->logger->error('Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [ 'app' => 'dav', - 'message' => 'Caught parsing exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'] + 'exception' => $ex ]); continue; } catch (InvalidDataException $ex) { - $this->logger->logException($ex, [ + $this->logger->error('Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'], [ 'app' => 'dav', - 'message' => 'Caught invalid data exception for calendar data. This usually indicates invalid calendar data. calendar-id:'.$calendarId.' uri:'.$row['uri'] + 'exception' => $ex ]); continue; } diff --git a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php index ae568720c55b7..fa5a418603436 100644 --- a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php +++ b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php @@ -23,7 +23,7 @@ namespace OCA\DAV\CalDAV\ICSExportPlugin; use OCP\IConfig; -use OCP\ILogger; +use Psr\Log\LoggerInterface; use Sabre\HTTP\ResponseInterface; use Sabre\VObject\DateTimeParser; use Sabre\VObject\InvalidDataException; @@ -39,7 +39,7 @@ class ICSExportPlugin extends \Sabre\CalDAV\ICSExportPlugin { /** @var IConfig */ private $config; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var string */ @@ -50,7 +50,7 @@ class ICSExportPlugin extends \Sabre\CalDAV\ICSExportPlugin { * * @param IConfig $config */ - public function __construct(IConfig $config, ILogger $logger) { + public function __construct(IConfig $config, LoggerInterface $logger) { $this->config = $config; $this->logger = $logger; } diff --git a/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php b/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php index c6d7e03758057..1e35c2f613348 100644 --- a/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php +++ b/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php @@ -41,6 +41,7 @@ use OCP\IConfig; use OCP\IURLGenerator; use OCP\L10N\IFactory; +use Psr\Log\LoggerInterface; use Sabre\VObject\ITip\Message; class InvitationResponseServer { @@ -53,7 +54,7 @@ class InvitationResponseServer { */ public function __construct(bool $public = true) { $baseUri = \OC::$WEBROOT . '/remote.php/dav/'; - $logger = \OC::$server->getLogger(); + $logger = \OC::$server->get(LoggerInterface::class); /** @var IEventDispatcher $dispatcher */ $dispatcher = \OC::$server->get(IEventDispatcher::class); diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php index 044e5fac4e237..ed9c156b44910 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php @@ -32,10 +32,10 @@ use OCA\DAV\CalDAV\Reminder\INotificationProvider; use OCP\IConfig; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; +use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VEvent; use Sabre\VObject\DateTimeParser; use Sabre\VObject\Property; @@ -50,7 +50,7 @@ abstract class AbstractProvider implements INotificationProvider { /** @var string */ public const NOTIFICATION_TYPE = ''; - /** @var ILogger */ + /** @var LoggerInterface */ protected $logger; /** @var L10NFactory */ @@ -69,12 +69,12 @@ abstract class AbstractProvider implements INotificationProvider { protected $config; /** - * @param ILogger $logger + * @param LoggerInterface $logger * @param L10NFactory $l10nFactory * @param IConfig $config * @param IUrlGenerator $urlGenerator */ - public function __construct(ILogger $logger, + public function __construct(LoggerInterface $logger, L10NFactory $l10nFactory, IURLGenerator $urlGenerator, IConfig $config) { diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php index 456b9f8b42dcf..4a5a32805efe5 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php @@ -34,11 +34,11 @@ use DateTime; use OCP\IConfig; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\L10N\IFactory as L10NFactory; use OCP\Mail\IEMailTemplate; use OCP\Mail\IMailer; +use Psr\Log\LoggerInterface; use Sabre\VObject; use Sabre\VObject\Component\VEvent; use Sabre\VObject\Parameter; @@ -60,13 +60,13 @@ class EmailProvider extends AbstractProvider { /** * @param IConfig $config * @param IMailer $mailer - * @param ILogger $logger + * @param LoggerInterface $logger * @param L10NFactory $l10nFactory * @param IUrlGenerator $urlGenerator */ public function __construct(IConfig $config, IMailer $mailer, - ILogger $logger, + LoggerInterface $logger, L10NFactory $l10nFactory, IURLGenerator $urlGenerator) { parent::__construct($logger, $l10nFactory, $urlGenerator, $config); @@ -133,7 +133,7 @@ public function send(VEvent $vevent, $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]); } } catch (\Exception $ex) { - $this->logger->logException($ex, ['app' => 'dav']); + $this->logger->error('Unable to deliver reminder message', ['app' => 'dav', 'exception' => $ex]); } } } diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php index fb123960df825..03c749ac2c18d 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php @@ -32,12 +32,12 @@ use OCA\DAV\AppInfo\Application; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; use OCP\Notification\IManager; use OCP\Notification\INotification; +use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VEvent; use Sabre\VObject\Property; @@ -60,14 +60,14 @@ class PushProvider extends AbstractProvider { /** * @param IConfig $config * @param IManager $manager - * @param ILogger $logger + * @param LoggerInterface $logger * @param L10NFactory $l10nFactory * @param IUrlGenerator $urlGenerator * @param ITimeFactory $timeFactory */ public function __construct(IConfig $config, IManager $manager, - ILogger $logger, + LoggerInterface $logger, L10NFactory $l10nFactory, IURLGenerator $urlGenerator, ITimeFactory $timeFactory) { diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php index aebb5a24f0e5d..e8f92e90e2f29 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php @@ -33,8 +33,8 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; use OCP\IGroupManager; -use OCP\ILogger; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\PropPatch; use Sabre\DAVACL\PrincipalBackend\BackendInterface; use function array_intersect; @@ -54,7 +54,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { /** @var IGroupManager */ private $groupManager; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var ProxyMapper */ @@ -79,7 +79,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { * @param IDBConnection $dbConnection * @param IUserSession $userSession * @param IGroupManager $groupManager - * @param ILogger $logger + * @param LoggerInterface $logger * @param string $principalPrefix * @param string $dbPrefix * @param string $cuType @@ -87,7 +87,7 @@ abstract class AbstractPrincipalBackend implements BackendInterface { public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, - ILogger $logger, + LoggerInterface $logger, ProxyMapper $proxyMapper, string $principalPrefix, string $dbPrefix, diff --git a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php index 65203e24da591..7c920de45dbfb 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php @@ -25,8 +25,8 @@ use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCP\IDBConnection; use OCP\IGroupManager; -use OCP\ILogger; use OCP\IUserSession; +use Psr\Log\LoggerInterface; /** * Class ResourcePrincipalBackend @@ -41,13 +41,13 @@ class ResourcePrincipalBackend extends AbstractPrincipalBackend { * @param IDBConnection $dbConnection * @param IUserSession $userSession * @param IGroupManager $groupManager - * @param ILogger $logger + * @param LoggerInterface $logger * @param ProxyMapper $proxyMapper */ public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, - ILogger $logger, + LoggerInterface $logger, ProxyMapper $proxyMapper) { parent::__construct($dbConnection, $userSession, $groupManager, $logger, $proxyMapper, 'principals/calendar-resources', 'resource', 'RESOURCE'); diff --git a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php index ca78ebd4bc432..fdc19ff74307f 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php @@ -25,8 +25,8 @@ use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCP\IDBConnection; use OCP\IGroupManager; -use OCP\ILogger; use OCP\IUserSession; +use Psr\Log\LoggerInterface; /** * Class RoomPrincipalBackend @@ -41,13 +41,13 @@ class RoomPrincipalBackend extends AbstractPrincipalBackend { * @param IDBConnection $dbConnection * @param IUserSession $userSession * @param IGroupManager $groupManager - * @param ILogger $logger + * @param LoggerInterface $logger * @param ProxyMapper $proxyMapper */ public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, - ILogger $logger, + LoggerInterface $logger, ProxyMapper $proxyMapper) { parent::__construct($dbConnection, $userSession, $groupManager, $logger, $proxyMapper, 'principals/calendar-rooms', 'room', 'ROOM'); diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index 8aacc33bb46a4..663779fb69750 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -39,7 +39,6 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUserManager; use OCP\L10N\IFactory as L10NFactory; @@ -47,6 +46,7 @@ use OCP\Mail\IMailer; use OCP\Security\ISecureRandom; use OCP\Util; +use Psr\Log\LoggerInterface; use Sabre\CalDAV\Schedule\IMipPlugin as SabreIMipPlugin; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\Component\VEvent; @@ -81,7 +81,7 @@ class IMipPlugin extends SabreIMipPlugin { /** @var IMailer */ private $mailer; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var ITimeFactory */ @@ -115,7 +115,7 @@ class IMipPlugin extends SabreIMipPlugin { /** * @param IConfig $config * @param IMailer $mailer - * @param ILogger $logger + * @param LoggerInterface $logger * @param ITimeFactory $timeFactory * @param L10NFactory $l10nFactory * @param IUrlGenerator $urlGenerator @@ -124,7 +124,7 @@ class IMipPlugin extends SabreIMipPlugin { * @param IDBConnection $db * @param string $userId */ - public function __construct(IConfig $config, IMailer $mailer, ILogger $logger, + public function __construct(IConfig $config, IMailer $mailer, LoggerInterface $logger, ITimeFactory $timeFactory, L10NFactory $l10nFactory, IURLGenerator $urlGenerator, Defaults $defaults, ISecureRandom $random, IDBConnection $db, IUserManager $userManager, @@ -306,7 +306,7 @@ public function schedule(Message $iTipMessage) { $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } } catch (\Exception $ex) { - $this->logger->logException($ex, ['app' => 'dav']); + $this->logger->error('Unable to deliver message', ['app' => 'dav', 'exception' => $ex]); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } } diff --git a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php index 543d15e0179b0..1d07ac8248204 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php @@ -37,9 +37,9 @@ use OCP\Http\Client\IClientService; use OCP\Http\Client\LocalServerException; use OCP\IConfig; -use OCP\ILogger; use Psr\Http\Message\RequestInterface; use Psr\Http\Message\ResponseInterface; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\PropPatch; use Sabre\DAV\Xml\Property\Href; @@ -64,7 +64,7 @@ class RefreshWebcalService { /** @var IConfig */ private $config; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate'; @@ -78,9 +78,9 @@ class RefreshWebcalService { * @param CalDavBackend $calDavBackend * @param IClientService $clientService * @param IConfig $config - * @param ILogger $logger + * @param LoggerInterface $logger */ - public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, ILogger $logger) { + public function __construct(CalDavBackend $calDavBackend, IClientService $clientService, IConfig $config, LoggerInterface $logger) { $this->calDavBackend = $calDavBackend; $this->clientService = $clientService; $this->config = $config; @@ -143,7 +143,7 @@ public function refreshSubscription(string $principalUri, string $uri) { try { $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); } catch (NoInstancesException | BadRequest $ex) { - $this->logger->logException($ex); + $this->logger->error('Error while creating calendar object from subscription', ['exception' => $ex]); } } @@ -156,8 +156,7 @@ public function refreshSubscription(string $principalUri, string $uri) { } catch (ParseException $ex) { $subscriptionId = $subscription['id']; - $this->logger->logException($ex); - $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error"); + $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a parsing error", ['exception' => $ex]); } } @@ -279,16 +278,14 @@ private function queryWebcalFeed(array $subscription, array &$mutations) { return $vCalendar->serialize(); } } catch (LocalServerException $ex) { - $this->logger->logException($ex, [ - 'message' => "Subscription $subscriptionId was not refreshed because it violates local access rules", - 'level' => ILogger::WARN, + $this->logger->warning("Subscription $subscriptionId was not refreshed because it violates local access rules", [ + 'exception' => $ex, ]); return null; } catch (Exception $ex) { - $this->logger->logException($ex, [ - 'message' => "Subscription $subscriptionId could not be refreshed due to a network error", - 'level' => ILogger::WARN, + $this->logger->warning("Subscription $subscriptionId could not be refreshed due to a network error", [ + 'exception' => $ex, ]); return null; diff --git a/apps/dav/lib/CardDAV/PhotoCache.php b/apps/dav/lib/CardDAV/PhotoCache.php index d3e4b2450d372..42271c3b58c21 100644 --- a/apps/dav/lib/CardDAV/PhotoCache.php +++ b/apps/dav/lib/CardDAV/PhotoCache.php @@ -34,7 +34,7 @@ use OCP\Files\NotPermittedException; use OCP\Files\SimpleFS\ISimpleFile; use OCP\Files\SimpleFS\ISimpleFolder; -use OCP\ILogger; +use Psr\Log\LoggerInterface; use Sabre\CardDAV\Card; use Sabre\VObject\Document; use Sabre\VObject\Parameter; @@ -54,16 +54,16 @@ class PhotoCache { /** @var IAppData */ protected $appData; - /** @var ILogger */ + /** @var LoggerInterface */ protected $logger; /** * PhotoCache constructor. * * @param IAppData $appData - * @param ILogger $logger + * @param LoggerInterface $logger */ - public function __construct(IAppData $appData, ILogger $logger) { + public function __construct(IAppData $appData, LoggerInterface $logger) { $this->appData = $appData; $this->logger = $logger; } @@ -216,8 +216,8 @@ private function getPhoto(Card $node) { $vObject = $this->readCard($node->get()); return $this->getPhotoFromVObject($vObject); } catch (\Exception $e) { - $this->logger->logException($e, [ - 'message' => 'Exception during vcard photo parsing' + $this->logger->error('Exception during vcard photo parsing', [ + 'exception' => $e ]); } return false; @@ -262,8 +262,8 @@ public function getPhotoFromVObject(Document $vObject) { 'body' => $val ]; } catch (\Exception $e) { - $this->logger->logException($e, [ - 'message' => 'Exception during vcard photo parsing' + $this->logger->error('Exception during vcard photo parsing', [ + 'exception' => $e ]); } return false; diff --git a/apps/dav/lib/CardDAV/SyncService.php b/apps/dav/lib/CardDAV/SyncService.php index 73bfaf01b604e..d7cc01c7d861f 100644 --- a/apps/dav/lib/CardDAV/SyncService.php +++ b/apps/dav/lib/CardDAV/SyncService.php @@ -30,9 +30,9 @@ use OC\Accounts\AccountManager; use OCP\AppFramework\Http; -use OCP\ILogger; use OCP\IUser; use OCP\IUserManager; +use Psr\Log\LoggerInterface; use Sabre\DAV\Client; use Sabre\DAV\Xml\Response\MultiStatus; use Sabre\DAV\Xml\Service; @@ -47,7 +47,7 @@ class SyncService { /** @var IUserManager */ private $userManager; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var array */ @@ -64,10 +64,10 @@ class SyncService { * * @param CardDavBackend $backend * @param IUserManager $userManager - * @param ILogger $logger + * @param LoggerInterface $logger * @param AccountManager $accountManager */ - public function __construct(CardDavBackend $backend, IUserManager $userManager, ILogger $logger, Converter $converter) { + public function __construct(CardDavBackend $backend, IUserManager $userManager, LoggerInterface $logger, Converter $converter) { $this->backend = $backend; $this->userManager = $userManager; $this->logger = $logger; diff --git a/apps/dav/lib/Command/CreateCalendar.php b/apps/dav/lib/Command/CreateCalendar.php index c923a8d760285..cae3528cad782 100644 --- a/apps/dav/lib/Command/CreateCalendar.php +++ b/apps/dav/lib/Command/CreateCalendar.php @@ -39,6 +39,7 @@ use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; use OCP\Share\IManager; +use Psr\Log\LoggerInterface; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; @@ -96,7 +97,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int \OC::$server->get(IFactory::class), ); $random = \OC::$server->get(ISecureRandom::class); - $logger = \OC::$server->getLogger(); + $logger = \OC::$server->get(LoggerInterface::class); $dispatcher = \OC::$server->get(IEventDispatcher::class); $config = \OC::$server->get(IConfig::class); diff --git a/apps/dav/lib/Comments/CommentNode.php b/apps/dav/lib/Comments/CommentNode.php index af76027671e06..c4b9d886e6b3f 100644 --- a/apps/dav/lib/Comments/CommentNode.php +++ b/apps/dav/lib/Comments/CommentNode.php @@ -26,9 +26,9 @@ use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; use OCP\Comments\MessageTooLongException; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\MethodNotAllowed; @@ -52,7 +52,7 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { /** @var ICommentsManager */ protected $commentsManager; - /** @var ILogger */ + /** @var LoggerInterface */ protected $logger; /** @var array list of properties with key being their name and value their setter */ @@ -71,14 +71,14 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { * @param IComment $comment * @param IUserManager $userManager * @param IUserSession $userSession - * @param ILogger $logger + * @param LoggerInterface $logger */ public function __construct( ICommentsManager $commentsManager, IComment $comment, IUserManager $userManager, IUserSession $userSession, - ILogger $logger + LoggerInterface $logger ) { $this->commentsManager = $commentsManager; $this->comment = $comment; @@ -194,7 +194,7 @@ public function updateComment($propertyValue) { $this->commentsManager->save($this->comment); return true; } catch (\Exception $e) { - $this->logger->logException($e, ['app' => 'dav/comments']); + $this->logger->error('Failed to update comment', ['app' => 'dav/comments', 'exception' => $e]); if ($e instanceof MessageTooLongException) { $msg = 'Message exceeds allowed character limit of '; throw new BadRequest($msg . IComment::MAX_MESSAGE_LENGTH, 0, $e); @@ -287,7 +287,7 @@ protected function composeMentionsPropertyValue() { try { $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']); } catch (\OutOfBoundsException $e) { - $this->logger->logException($e); + $this->logger->error('Unable to resolve display name', ['exception' => $e]); // No displayname, upon client's discretion what to display. $displayName = ''; } diff --git a/apps/dav/lib/Comments/EntityCollection.php b/apps/dav/lib/Comments/EntityCollection.php index d9b06e1240c70..c3769282b0c64 100644 --- a/apps/dav/lib/Comments/EntityCollection.php +++ b/apps/dav/lib/Comments/EntityCollection.php @@ -25,9 +25,9 @@ use OCP\Comments\ICommentsManager; use OCP\Comments\NotFoundException; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\IProperties; use Sabre\DAV\PropPatch; @@ -46,7 +46,7 @@ class EntityCollection extends RootCollection implements IProperties { /** @var string */ protected $id; - /** @var ILogger */ + /** @var LoggerInterface */ protected $logger; /** @@ -55,7 +55,7 @@ class EntityCollection extends RootCollection implements IProperties { * @param ICommentsManager $commentsManager * @param IUserManager $userManager * @param IUserSession $userSession - * @param ILogger $logger + * @param LoggerInterface $logger */ public function __construct( $id, @@ -63,7 +63,7 @@ public function __construct( ICommentsManager $commentsManager, IUserManager $userManager, IUserSession $userSession, - ILogger $logger + LoggerInterface $logger ) { foreach (['id', 'name'] as $property) { $$property = trim($$property); diff --git a/apps/dav/lib/Comments/EntityTypeCollection.php b/apps/dav/lib/Comments/EntityTypeCollection.php index c9df2a068d78a..6cd2c43c1d25a 100644 --- a/apps/dav/lib/Comments/EntityTypeCollection.php +++ b/apps/dav/lib/Comments/EntityTypeCollection.php @@ -24,9 +24,9 @@ namespace OCA\DAV\Comments; use OCP\Comments\ICommentsManager; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; @@ -43,7 +43,7 @@ */ class EntityTypeCollection extends RootCollection { - /** @var ILogger */ + /** @var LoggerInterface */ protected $logger; /** @var IUserManager */ @@ -57,7 +57,7 @@ class EntityTypeCollection extends RootCollection { * @param ICommentsManager $commentsManager * @param IUserManager $userManager * @param IUserSession $userSession - * @param ILogger $logger + * @param LoggerInterface $logger * @param \Closure $childExistsFunction */ public function __construct( @@ -65,7 +65,7 @@ public function __construct( ICommentsManager $commentsManager, IUserManager $userManager, IUserSession $userSession, - ILogger $logger, + LoggerInterface $logger, \Closure $childExistsFunction ) { $name = trim($name); diff --git a/apps/dav/lib/Comments/RootCollection.php b/apps/dav/lib/Comments/RootCollection.php index e8e890696ebd3..c5e978f7f9659 100644 --- a/apps/dav/lib/Comments/RootCollection.php +++ b/apps/dav/lib/Comments/RootCollection.php @@ -26,9 +26,9 @@ use OCP\Comments\CommentsEntityEvent; use OCP\Comments\ICommentsManager; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Exception\NotFound; @@ -46,7 +46,7 @@ class RootCollection implements ICollection { /** @var string */ protected $name = 'comments'; - /** @var ILogger */ + /** @var LoggerInterface */ protected $logger; /** @var IUserManager */ @@ -63,14 +63,14 @@ class RootCollection implements ICollection { * @param IUserManager $userManager * @param IUserSession $userSession * @param EventDispatcherInterface $dispatcher - * @param ILogger $logger + * @param LoggerInterface $logger */ public function __construct( ICommentsManager $commentsManager, IUserManager $userManager, IUserSession $userSession, EventDispatcherInterface $dispatcher, - ILogger $logger) { + LoggerInterface $logger) { $this->commentsManager = $commentsManager; $this->logger = $logger; $this->userManager = $userManager; diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index df4e3c65ce0a8..6a339062951e7 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -41,6 +41,7 @@ use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden; use OCP\IRequest; use OCP\ISession; +use Psr\Log\LoggerInterface; use Sabre\DAV\Auth\Backend\AbstractBasic; use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Exception\ServiceUnavailable; @@ -157,7 +158,7 @@ public function check(RequestInterface $request, ResponseInterface $response) { } catch (Exception $e) { $class = get_class($e); $msg = $e->getMessage(); - \OC::$server->getLogger()->logException($e); + \OC::$server->get(LoggerInterface::class)->error('Unable to check auth in Sabre Connector', ['exception' => $e]); throw new ServiceUnavailable("$class: $msg"); } } diff --git a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php index b4df1f582dbe7..a56c11bfa0d25 100644 --- a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php @@ -30,7 +30,7 @@ use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden; use OCP\Files\StorageNotAvailableException; -use OCP\ILogger; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\Conflict; use Sabre\DAV\Exception\Forbidden; @@ -86,12 +86,12 @@ class ExceptionLoggerPlugin extends \Sabre\DAV\ServerPlugin { /** @var string */ private $appName; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** * @param string $loggerAppName app name to use when logging - * @param ILogger $logger + * @param LoggerInterface $logger */ public function __construct($loggerAppName, $logger) { $this->appName = $loggerAppName; @@ -119,19 +119,15 @@ public function initialize(\Sabre\DAV\Server $server) { */ public function logException(\Throwable $ex) { $exceptionClass = get_class($ex); - $level = ILogger::FATAL; if (isset($this->nonFatalExceptions[$exceptionClass]) || ( $exceptionClass === ServiceUnavailable::class && $ex->getMessage() === 'System in maintenance mode.' ) ) { - $level = ILogger::DEBUG; + $this->logger->debug('Sabre has thrown an exception', ['exception' => $ex, 'app' => $this->appName]); } - $this->logger->logException($ex, [ - 'app' => $this->appName, - 'level' => $level, - ]); + $this->logger->critical('Sabre has thrown an exception', ['exception' => $ex, 'app' => $this->appName]); } } diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index 91af83db0e3b0..afcb9becad875 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -63,13 +63,13 @@ use OCP\Files\Storage; use OCP\Files\StorageNotAvailableException; use OCP\IL10N; -use OCP\ILogger; use OCP\L10N\IFactory as IL10NFactory; use OCP\IConfig; use OCP\IRequest; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Share\IManager; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\Forbidden; @@ -250,7 +250,7 @@ public function put($data) { } else { $target = $partStorage->fopen($internalPartPath, 'wb'); if ($target === false) { - \OC::$server->getLogger()->error('\OC\Files\Filesystem::fopen() failed', ['app' => 'webdav']); + \OC::$server->get(LoggerInterface::class)->error('\OC\Files\Filesystem::fopen() failed', ['app' => 'webdav']); // because we have no clue about the cause we can only throw back a 500/Internal Server Error throw new Exception($this->l10n->t('Could not write file contents')); } @@ -294,13 +294,14 @@ public function put($data) { } } } catch (\Exception $e) { - $context = []; + /** @var LoggerInterface $logger */ + $logger = \OC::$server->get(LoggerInterface::class); if ($e instanceof LockedException) { - $context['level'] = ILogger::DEBUG; + $logger->debug('Unable to PUT file', ['exception' => $e]); + } else { + $logger->error('Unable to PUT file', ['exception' => $e]); } - - \OC::$server->getLogger()->logException($e, $context); if ($needsPartFile) { $partStorage->unlink($internalPartPath); } @@ -339,7 +340,7 @@ public function put($data) { $renameOkay = $storage->moveFromStorage($partStorage, $internalPartPath, $internalPath); $fileExists = $storage->file_exists($internalPath); if ($renameOkay === false || $fileExists === false) { - \OC::$server->getLogger()->error('renaming part file to final file failed $renameOkay: ' . ($renameOkay ? 'true' : 'false') . ', $fileExists: ' . ($fileExists ? 'true' : 'false') . ')', ['app' => 'webdav']); + \OC::$server->get(LoggerInterface::class)->error('renaming part file to final file failed $renameOkay: ' . ($renameOkay ? 'true' : 'false') . ', $fileExists: ' . ($fileExists ? 'true' : 'false') . ')', ['app' => 'webdav']); throw new Exception($this->l10n->t('Could not rename part file to final file')); } } catch (ForbiddenException $ex) { @@ -627,7 +628,7 @@ private function createFileChunked($data) { $renameOkay = $targetStorage->moveFromStorage($partStorage, $partInternalPath, $targetInternalPath); $fileExists = $targetStorage->file_exists($targetInternalPath); if ($renameOkay === false || $fileExists === false) { - \OC::$server->getLogger()->error('\OC\Files\Filesystem::rename() failed', ['app' => 'webdav']); + \OC::$server->get(LoggerInterface::class)->error('\OC\Files\Filesystem::rename() failed', ['app' => 'webdav']); // only delete if an error occurred and the target file was already created if ($fileExists) { // set to null to avoid double-deletion when handling exception diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index 02a2e284ce159..5e4e350eb6898 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -41,7 +41,6 @@ use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IL10N; -use OCP\ILogger; use OCP\IPreview; use OCP\IRequest; use OCP\ITagManager; @@ -50,13 +49,14 @@ use OCP\Share\IManager; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; +use Psr\Log\LoggerInterface; use Sabre\DAV\Auth\Plugin; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class ServerFactory { /** @var IConfig */ private $config; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var IDBConnection */ private $databaseConnection; @@ -77,7 +77,7 @@ class ServerFactory { /** * @param IConfig $config - * @param ILogger $logger + * @param LoggerInterface $logger * @param IDBConnection $databaseConnection * @param IUserSession $userSession * @param IMountManager $mountManager @@ -87,7 +87,7 @@ class ServerFactory { */ public function __construct( IConfig $config, - ILogger $logger, + LoggerInterface $logger, IDBConnection $databaseConnection, IUserSession $userSession, IMountManager $mountManager, diff --git a/apps/dav/lib/HookManager.php b/apps/dav/lib/HookManager.php index 1287104fd10ca..3f008b6cdd58e 100644 --- a/apps/dav/lib/HookManager.php +++ b/apps/dav/lib/HookManager.php @@ -35,6 +35,7 @@ use OCP\IUser; use OCP\IUserManager; use OCP\Util; +use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; class HookManager { @@ -177,7 +178,7 @@ public function firstLogin(IUser $user = null) { 'components' => 'VEVENT' ]); } catch (\Exception $ex) { - \OC::$server->getLogger()->logException($ex); + \OC::$server->get(LoggerInterface::class)->error('Error creating initial calendar for user', ['exception' => $ex]); } } if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) { @@ -186,7 +187,7 @@ public function firstLogin(IUser $user = null) { '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME, ]); } catch (\Exception $ex) { - \OC::$server->getLogger()->logException($ex); + \OC::$server->get(LoggerInterface::class)->logException('Error creating initial addressbook for user', ['exception' => $ex]); } } } diff --git a/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php b/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php index 6a315f2a1505c..b9b973e9fb50f 100644 --- a/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php @@ -28,7 +28,7 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; use OCP\IDBConnection; -use OCP\ILogger; +use Psr\Log\LoggerInterface; class BuildCalendarSearchIndexBackgroundJob extends QueuedJob { @@ -38,7 +38,7 @@ class BuildCalendarSearchIndexBackgroundJob extends QueuedJob { /** @var CalDavBackend */ private $calDavBackend; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var IJobList */ @@ -50,13 +50,13 @@ class BuildCalendarSearchIndexBackgroundJob extends QueuedJob { /** * @param IDBConnection $db * @param CalDavBackend $calDavBackend - * @param ILogger $logger + * @param LoggerInterface $logger * @param IJobList $jobList * @param ITimeFactory $timeFactory */ public function __construct(IDBConnection $db, CalDavBackend $calDavBackend, - ILogger $logger, + LoggerInterface $logger, IJobList $jobList, ITimeFactory $timeFactory) { $this->db = $db; diff --git a/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php b/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php index 98afecc3b7d45..50666921296f6 100644 --- a/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php @@ -27,7 +27,7 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; use OCP\IDBConnection; -use OCP\ILogger; +use Psr\Log\LoggerInterface; class BuildSocialSearchIndexBackgroundJob extends QueuedJob { @@ -37,7 +37,7 @@ class BuildSocialSearchIndexBackgroundJob extends QueuedJob { /** @var CardDavBackend */ private $davBackend; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** @var IJobList */ @@ -49,13 +49,13 @@ class BuildSocialSearchIndexBackgroundJob extends QueuedJob { /** * @param IDBConnection $db * @param CardDavBackend $davBackend - * @param ILogger $logger + * @param LoggerInterface $logger * @param IJobList $jobList * @param ITimeFactory $timeFactory */ public function __construct(IDBConnection $db, CardDavBackend $davBackend, - ILogger $logger, + LoggerInterface $logger, IJobList $jobList, ITimeFactory $timeFactory) { $this->db = $db; diff --git a/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php b/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php index 5e575347d95f7..f22ca9ccde017 100644 --- a/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php +++ b/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php @@ -28,9 +28,9 @@ use OCA\DAV\CalDAV\CalDavBackend; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; -use OCP\ILogger; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use Psr\Log\LoggerInterface; use Sabre\VObject\InvalidDataException; class CalDAVRemoveEmptyValue implements IRepairStep { @@ -41,15 +41,15 @@ class CalDAVRemoveEmptyValue implements IRepairStep { /** @var CalDavBackend */ private $calDavBackend; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; /** * @param IDBConnection $db * @param CalDavBackend $calDavBackend - * @param ILogger $logger + * @param LoggerInterface $logger */ - public function __construct(IDBConnection $db, CalDavBackend $calDavBackend, ILogger $logger) { + public function __construct(IDBConnection $db, CalDavBackend $calDavBackend, LoggerInterface $logger) { $this->db = $db; $this->calDavBackend = $calDavBackend; $this->logger = $logger; diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index a5648cdef9377..8c31886773179 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -60,14 +60,19 @@ use OCP\Share\IManager; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; +use Psr\Log\LoggerInterface; use Sabre\DAV\SimpleCollection; class RootCollection extends SimpleCollection { public function __construct() { $l10n = \OC::$server->get(IFactory::class)->get('dav'); $random = \OC::$server->get(ISecureRandom::class); +<<<<<<< HEAD $logger = \OC::$server->getLogger(); $psrLogger = \OC::$server->get(LoggerInterface::class); +======= + $logger = \OC::$server->get(LoggerInterface::class); +>>>>>>> 4565b23b66 (Move uses of ILogger to LoggerInterface) $userManager = \OC::$server->get(IUserManager::class); $userSession = \OC::$server->get(IUserSession::class); $groupManager = \OC::$server->get(IGroupManager::class); @@ -147,7 +152,7 @@ public function __construct() { $userManager, \OC::$server->get(IUserSession::class), \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class), - \OC::$server->getLogger() + \OC::$server->get(LoggerInterface::class) ); $pluginManager = new PluginManager(\OC::$server, \OC::$server->get(IAppManager::class)); diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index e52ca1d3a8c65..d89e15d3a204d 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -107,7 +107,7 @@ class Server { public function __construct(IRequest $request, $baseUri) { $this->request = $request; $this->baseUri = $baseUri; - $logger = \OC::$server->getLogger(); + $logger = \OC::$server->get(LoggerInterface::class); $dispatcher = \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class); /** @var IEventDispatcher $newDispatcher */ $newDispatcher = \OC::$server->get(IEventDispatcher::class); @@ -177,7 +177,7 @@ public function __construct(IRequest $request, $baseUri) { // calendar plugins if ($this->requestIsForSubtree(['calendars', 'public-calendars', 'system-calendars', 'principals'])) { $this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin()); - $this->server->addPlugin(new \OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin(\OC::$server->get(IConfig::class), \OC::$server->getLogger())); + $this->server->addPlugin(new \OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin(\OC::$server->get(IConfig::class), \OC::$server->get(LoggerInterface::class))); $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); if (\OC::$server->get(IConfig::class)->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') { $this->server->addPlugin(\OC::$server->get(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class)); @@ -204,7 +204,7 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin(new HasPhotoPlugin()); $this->server->addPlugin(new ImageExportPlugin(new PhotoCache( \OC::$server->getAppDataDir('dav-photocache'), - \OC::$server->getLogger()) + \OC::$server->get(LoggerInterface::class)) )); } diff --git a/apps/dav/tests/unit/BackgroundJob/RefreshWebcalJobTest.php b/apps/dav/tests/unit/BackgroundJob/RefreshWebcalJobTest.php index 360c4c791c704..7d77acd070f5b 100644 --- a/apps/dav/tests/unit/BackgroundJob/RefreshWebcalJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/RefreshWebcalJobTest.php @@ -35,7 +35,6 @@ use OCP\IConfig; use OCP\ILogger; use PHPUnit\Framework\MockObject\MockObject; - use Test\TestCase; class RefreshWebcalJobTest extends TestCase { diff --git a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php index e0ae86a89016e..ec2acf44608e6 100644 --- a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php +++ b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php @@ -35,12 +35,12 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; use OCP\IGroupManager; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; use OCP\Share\IManager as ShareManager; +use Psr\Log\LoggerInterface; use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet; use Sabre\DAV\Xml\Property\Href; use Test\TestCase; @@ -68,7 +68,7 @@ abstract class AbstractCalDavBackend extends TestCase { /** @var ISecureRandom */ private $random; - /** @var ILogger */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $logger; public const UNIT_TEST_USER = 'principals/users/caldav-unit-test'; @@ -107,7 +107,7 @@ protected function setUp(): void { $db = \OC::$server->getDatabaseConnection(); $this->random = \OC::$server->getSecureRandom(); - $this->logger = $this->createMock(ILogger::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->config = $this->createMock(IConfig::class); $this->backend = new CalDavBackend( $db, diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php index 2bcb3940911a7..a5716e1b83f3b 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php @@ -39,7 +39,6 @@ use OCP\IConfig; use OCP\IGroupManager; use OCP\IL10N; -use OCP\ILogger; use OCP\IUserManager; use OCP\Security\ISecureRandom; use Psr\Log\LoggerInterface; @@ -71,7 +70,7 @@ class PublicCalendarRootTest extends TestCase { /** @var ISecureRandom */ private $random; - /** @var ILogger */ + /** @var LoggerInterface */ private $logger; protected function setUp(): void { @@ -82,8 +81,12 @@ protected function setUp(): void { $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->random = \OC::$server->getSecureRandom(); +<<<<<<< HEAD $this->logger = $this->createMock(ILogger::class); $this->psrLogger = $this->createMock(LoggerInterface::class); +======= + $this->logger = $this->createMock(LoggerInterface::class); +>>>>>>> 4565b23b66 (Move uses of ILogger to LoggerInterface) $dispatcher = $this->createMock(IEventDispatcher::class); $config = $this->createMock(IConfig::class); diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php index 8335428c6d58a..ae272e6b1a9e9 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php @@ -30,16 +30,16 @@ use OCA\DAV\CalDAV\Reminder\NotificationProvider\AbstractProvider; use OCP\IConfig; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; +use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VCalendar; use Test\TestCase; abstract class AbstractNotificationProviderTest extends TestCase { - /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $logger; /** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */ @@ -75,7 +75,7 @@ abstract class AbstractNotificationProviderTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock(ILogger::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->l10nFactory = $this->createMock(L10NFactory::class); $this->l10n = $this->createMock(IL10N::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php index 0352827aa5c76..ededcf819bb0c 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php @@ -34,7 +34,6 @@ use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; use OCP\IConfig; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; @@ -42,12 +41,13 @@ use OCP\Mail\IMailer; use OCP\Mail\IMessage; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VCalendar; class EmailProviderTest extends AbstractNotificationProviderTest { public const USER_EMAIL = 'frodo@hobb.it'; - /** @var ILogger|MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; /** @var L10NFactory|MockObject */ diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php index 9e9759f5eb884..b1f76fe9448bc 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php @@ -33,16 +33,16 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; use OCP\Notification\IManager; use OCP\Notification\INotification; +use Psr\Log\LoggerInterface; class PushProviderTest extends AbstractNotificationProviderTest { - /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $logger; /** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */ diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php index 5f49028634757..0fffbc2cd1070 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php @@ -28,9 +28,9 @@ use OCA\DAV\CalDAV\Proxy\Proxy; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCP\IGroupManager; -use OCP\ILogger; use OCP\IUser; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\PropPatch; use Test\TestCase; @@ -45,7 +45,7 @@ abstract class AbstractPrincipalBackendTest extends TestCase { /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ protected $groupManager; - /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $logger; /** @var ProxyMapper|\PHPUnit\Framework\MockObject\MockObject */ @@ -71,7 +71,7 @@ protected function setUp(): void { $this->userSession = $this->createMock(IUserSession::class); $this->groupManager = $this->createMock(IGroupManager::class); - $this->logger = $this->createMock(ILogger::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->proxyMapper = $this->createMock(ProxyMapper::class); } diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php index a81aac52fbb36..0d8076f7aa455 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php @@ -36,7 +36,6 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\IL10N; -use OCP\ILogger; use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserManager; @@ -47,6 +46,7 @@ use OCP\Mail\IMessage; use OCP\Security\ISecureRandom; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\ITip\Message; use Test\TestCase; @@ -95,8 +95,8 @@ protected function setUp(): void { $this->emailAttachment = $this->createMock(IAttachment::class); $this->mailer->method('createAttachment')->willReturn($this->emailAttachment); - /** @var ILogger|MockObject $logger */ - $logger = $this->getMockBuilder(ILogger::class)->disableOriginalConstructor()->getMock(); + /** @var LoggerInterface|MockObject $logger */ + $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); $this->timeFactory = $this->getMockBuilder(ITimeFactory::class)->disableOriginalConstructor()->getMock(); $this->timeFactory->method('getTime')->willReturn(1496912528); // 2017-01-01 diff --git a/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php b/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php index 12e913457097e..00a9dbcf8f4af 100644 --- a/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php +++ b/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php @@ -34,8 +34,8 @@ use OCP\Http\Client\IResponse; use OCP\Http\Client\LocalServerException; use OCP\IConfig; -use OCP\ILogger; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\VObject; use Sabre\VObject\Recur\NoInstancesException; @@ -53,7 +53,7 @@ class RefreshWebcalServiceTest extends TestCase { /** @var IConfig | MockObject */ private $config; - /** @var ILogger | MockObject */ + /** @var LoggerInterface | MockObject */ private $logger; protected function setUp(): void { @@ -62,7 +62,7 @@ protected function setUp(): void { $this->caldavBackend = $this->createMock(CalDavBackend::class); $this->clientService = $this->createMock(IClientService::class); $this->config = $this->createMock(IConfig::class); - $this->logger = $this->createMock(ILogger::class); + $this->logger = $this->createMock(LoggerInterface::class); } /** @@ -144,7 +144,7 @@ public function testRun(string $body, string $contentType, string $result) { $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123'); } - + /** * @param string $body * @param string $contentType @@ -209,15 +209,15 @@ public function testRunCreateCalendarNoException(string $body, string $contentTy $this->caldavBackend->expects($this->once()) ->method('createCalendarObject') ->with(42, 'uri-1.ics', $result, 1); - + $noInstanceException = new NoInstancesException("can't add calendar object"); $this->caldavBackend->expects($this->once()) ->method("createCalendarObject") ->willThrowException($noInstanceException); - + $this->logger->expects($this->once()) - ->method('logException') - ->with($noInstanceException); + ->method('error') + ->with('Error while creating calendar object from subscription', ['exception' => $noInstanceException]); $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123'); } @@ -286,14 +286,14 @@ public function testRunCreateCalendarBadRequest(string $body, string $contentTyp $this->caldavBackend->expects($this->once()) ->method('createCalendarObject') ->with(42, 'uri-1.ics', $result, 1); - + $badRequestException = new BadRequest("can't add reach calendar url"); $this->caldavBackend->expects($this->once()) ->method("createCalendarObject") ->willThrowException($badRequestException); - + $this->logger->expects($this->once()) - ->method('logException') + ->method('error') ->with($badRequestException); $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123'); @@ -366,8 +366,8 @@ public function testRunLocalURL($source) { ->willThrowException(new LocalServerException()); $this->logger->expects($this->once()) - ->method('logException') - ->with($this->isInstanceOf(LocalServerException::class), $this->anything()); + ->method('warning') + ->with($this->anything(), $this->isInstanceOf(LocalServerException::class)); $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123'); } diff --git a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php index d22a246bbece0..58af8a64d0b4e 100644 --- a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php +++ b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php @@ -30,9 +30,9 @@ use OCA\DAV\CardDAV\CardDavBackend; use OCA\DAV\CardDAV\Converter; use OCA\DAV\CardDAV\SyncService; -use OCP\ILogger; use OCP\IUser; use OCP\IUserManager; +use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VCard; use Test\TestCase; @@ -80,7 +80,7 @@ public function testEnsureSystemAddressBookExists() { /** @var IUserManager $userManager */ $userManager = $this->getMockBuilder(IUserManager::class)->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder(ILogger::class)->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); $converter = $this->createMock(Converter::class); $ss = new SyncService($backend, $userManager, $logger, $converter); @@ -106,7 +106,7 @@ public function dataActivatedUsers() { public function testUpdateAndDeleteUser($activated, $createCalls, $updateCalls, $deleteCalls) { /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backend */ $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder(ILogger::class)->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); $backend->expects($this->exactly($createCalls))->method('createCard'); $backend->expects($this->exactly($updateCalls))->method('updateCard'); @@ -166,7 +166,7 @@ private function getBackendMock($createCount, $updateCount, $deleteCount) { */ private function getSyncServiceMock($backend, $response) { $userManager = $this->getMockBuilder(IUserManager::class)->disableOriginalConstructor()->getMock(); - $logger = $this->getMockBuilder(ILogger::class)->disableOriginalConstructor()->getMock(); + $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); $converter = $this->createMock(Converter::class); /** @var SyncService | \PHPUnit\Framework\MockObject\MockObject $ss */ $ss = $this->getMockBuilder(SyncService::class) diff --git a/apps/dav/tests/unit/Comments/CommentsNodeTest.php b/apps/dav/tests/unit/Comments/CommentsNodeTest.php index f085ace9d8931..ea3a1952e45e9 100644 --- a/apps/dav/tests/unit/Comments/CommentsNodeTest.php +++ b/apps/dav/tests/unit/Comments/CommentsNodeTest.php @@ -30,10 +30,10 @@ use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; use OCP\Comments\MessageTooLongException; -use OCP\ILogger; use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; use Sabre\DAV\PropPatch; class CommentsNodeTest extends \Test\TestCase { @@ -62,7 +62,7 @@ protected function setUp(): void { $this->userSession = $this->getMockBuilder(IUserSession::class) ->disableOriginalConstructor() ->getMock(); - $this->logger = $this->getMockBuilder(ILogger::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMock(); @@ -230,7 +230,7 @@ public function testUpdateCommentLogException() { ->method('save'); $this->logger->expects($this->once()) - ->method('logException'); + ->method('error'); $this->node->updateComment($msg); } @@ -268,7 +268,7 @@ public function testUpdateCommentMessageTooLongException() { ->method('save'); $this->logger->expects($this->once()) - ->method('logException'); + ->method('error'); // imagine 'foo' has >1k characters. comment is mocked anyway. $this->node->updateComment('foo'); diff --git a/apps/dav/tests/unit/Comments/EntityCollectionTest.php b/apps/dav/tests/unit/Comments/EntityCollectionTest.php index 4466b0a63074b..f95dbf839ee8f 100644 --- a/apps/dav/tests/unit/Comments/EntityCollectionTest.php +++ b/apps/dav/tests/unit/Comments/EntityCollectionTest.php @@ -28,9 +28,9 @@ use OCA\DAV\Comments\EntityCollection; use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; class EntityCollectionTest extends \Test\TestCase { @@ -38,7 +38,7 @@ class EntityCollectionTest extends \Test\TestCase { protected $commentsManager; /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ protected $userManager; - /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $logger; /** @var EntityCollection */ protected $collection; @@ -57,7 +57,7 @@ protected function setUp(): void { $this->userSession = $this->getMockBuilder(IUserSession::class) ->disableOriginalConstructor() ->getMock(); - $this->logger = $this->getMockBuilder(ILogger::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php b/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php index f49b2c39857ce..89f84fb6ad422 100644 --- a/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php +++ b/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php @@ -26,9 +26,9 @@ use OCA\DAV\Comments\EntityCollection as EntityCollectionImplemantation; use OCP\Comments\ICommentsManager; -use OCP\ILogger; use OCP\IUserManager; use OCP\IUserSession; +use Psr\Log\LoggerInterface; class EntityTypeCollectionTest extends \Test\TestCase { @@ -36,7 +36,7 @@ class EntityTypeCollectionTest extends \Test\TestCase { protected $commentsManager; /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject */ protected $userManager; - /** @var \OCP\ILogger|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ protected $logger; /** @var \OCA\DAV\Comments\EntityTypeCollection */ protected $collection; @@ -57,7 +57,7 @@ protected function setUp(): void { $this->userSession = $this->getMockBuilder(IUserSession::class) ->disableOriginalConstructor() ->getMock(); - $this->logger = $this->getMockBuilder(ILogger::class) + $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/dav/tests/unit/Comments/RootCollectionTest.php b/apps/dav/tests/unit/Comments/RootCollectionTest.php index 8537eb9ab174f..b379dcb7e45df 100644 --- a/apps/dav/tests/unit/Comments/RootCollectionTest.php +++ b/apps/dav/tests/unit/Comments/RootCollectionTest.php @@ -30,7 +30,6 @@ use OCA\DAV\Comments\EntityTypeCollection as EntityTypeCollectionImplementation; use OCP\Comments\CommentsEntityEvent; use OCP\Comments\ICommentsManager; -use OCP\ILogger; use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; diff --git a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php index 478be5b42946a..0adabd2388f04 100644 --- a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php +++ b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php @@ -27,8 +27,8 @@ use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\Migration\CalDAVRemoveEmptyValue; -use OCP\ILogger; use OCP\Migration\IOutput; +use Psr\Log\LoggerInterface; use Sabre\VObject\InvalidDataException; use Test\TestCase; @@ -40,7 +40,7 @@ */ class CalDAVRemoveEmptyValueTest extends TestCase { - /** @var ILogger|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ private $logger; /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */ @@ -94,7 +94,7 @@ class CalDAVRemoveEmptyValueTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->logger = $this->createMock(ILogger::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->backend = $this->createMock(CalDavBackend::class); $this->output = $this->createMock(IOutput::class); } From fed15f9e1e2986ac3431744fa86419633dc84f6a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 19 Dec 2021 20:29:03 +0100 Subject: [PATCH 11/23] Move some events to IEventDispatcher Signed-off-by: Thomas Citharel --- apps/comments/lib/AppInfo/Application.php | 2 +- apps/dav/appinfo/v1/webdav.php | 4 ++ apps/dav/lib/Comments/RootCollection.php | 12 ++-- .../dav/lib/Connector/Sabre/ServerFactory.php | 10 ++-- apps/dav/lib/Events/SabreAddPluginEvent.php | 55 +++++++++++++++++++ apps/dav/lib/RootCollection.php | 1 - apps/dav/lib/Server.php | 6 +- .../SystemTagsRelationsCollection.php | 8 +-- .../unit/Comments/RootCollectionTest.php | 18 ++---- 9 files changed, 85 insertions(+), 31 deletions(-) create mode 100644 apps/dav/lib/Events/SabreAddPluginEvent.php diff --git a/apps/comments/lib/AppInfo/Application.php b/apps/comments/lib/AppInfo/Application.php index 527c5d99fc347..fbf51c2a869c6 100644 --- a/apps/comments/lib/AppInfo/Application.php +++ b/apps/comments/lib/AppInfo/Application.php @@ -69,7 +69,7 @@ public function register(IRegistrationContext $context): void { LoadSidebarScripts::class ); $context->registerEventListener( - CommentsEntityEvent::EVENT_ENTITY, + CommentsEntityEvent::class, CommentsEntityEventListener::class ); $context->registerSearchProvider(CommentsSearchProvider::class); diff --git a/apps/dav/appinfo/v1/webdav.php b/apps/dav/appinfo/v1/webdav.php index 7b0a0ae11df99..44130da0f28e7 100644 --- a/apps/dav/appinfo/v1/webdav.php +++ b/apps/dav/appinfo/v1/webdav.php @@ -29,6 +29,8 @@ * */ // no php execution timeout for webdav +use OCA\DAV\Events\SabreAddPluginEvent; + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { @set_time_limit(0); } @@ -75,7 +77,9 @@ }); $dispatcher = \OC::$server->getEventDispatcher(); +$newDispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class); // allow setup of additional plugins +$newDispatcher->dispatchTyped(new SabreAddPluginEvent($server)); $event = new \OCP\SabrePluginEvent($server); $dispatcher->dispatch('OCA\DAV\Connector\Sabre::addPlugin', $event); diff --git a/apps/dav/lib/Comments/RootCollection.php b/apps/dav/lib/Comments/RootCollection.php index c5e978f7f9659..af92157f4c1a5 100644 --- a/apps/dav/lib/Comments/RootCollection.php +++ b/apps/dav/lib/Comments/RootCollection.php @@ -26,6 +26,7 @@ use OCP\Comments\CommentsEntityEvent; use OCP\Comments\ICommentsManager; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IUserManager; use OCP\IUserSession; use Psr\Log\LoggerInterface; @@ -33,7 +34,6 @@ use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\ICollection; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; class RootCollection implements ICollection { @@ -55,21 +55,21 @@ class RootCollection implements ICollection { /** @var IUserSession */ protected $userSession; - /** @var EventDispatcherInterface */ + /** @var IEventDispatcher */ protected $dispatcher; /** * @param ICommentsManager $commentsManager * @param IUserManager $userManager * @param IUserSession $userSession - * @param EventDispatcherInterface $dispatcher + * @param IEventDispatcher $dispatcher * @param LoggerInterface $logger */ public function __construct( ICommentsManager $commentsManager, IUserManager $userManager, IUserSession $userSession, - EventDispatcherInterface $dispatcher, + IEventDispatcher $dispatcher, LoggerInterface $logger) { $this->commentsManager = $commentsManager; $this->logger = $logger; @@ -94,8 +94,8 @@ protected function initCollections() { throw new NotAuthenticated(); } - $event = new CommentsEntityEvent(CommentsEntityEvent::EVENT_ENTITY); - $this->dispatcher->dispatch(CommentsEntityEvent::EVENT_ENTITY, $event); + $event = new CommentsEntityEvent(CommentsEntityEvent::class); + $this->dispatcher->dispatchTyped($event); $this->entityTypeCollections = []; foreach ($event->getEntityCollections() as $entity => $entityExistsFunction) { diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index 5e4e350eb6898..eedb657f2ddb4 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -36,6 +36,7 @@ use OCA\DAV\Files\BrowserErrorPagePlugin; use OCP\App\IAppManager; use OCP\Comments\ICommentsManager; +use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\Mount\IMountManager; use OCP\IConfig; use OCP\IDBConnection; @@ -51,7 +52,6 @@ use OCP\SystemTag\ISystemTagObjectMapper; use Psr\Log\LoggerInterface; use Sabre\DAV\Auth\Plugin; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; class ServerFactory { /** @var IConfig */ @@ -70,7 +70,7 @@ class ServerFactory { private $request; /** @var IPreview */ private $previewManager; - /** @var EventDispatcherInterface */ + /** @var IEventDispatcher */ private $eventDispatcher; /** @var IL10N */ private $l10n; @@ -84,6 +84,8 @@ class ServerFactory { * @param ITagManager $tagManager * @param IRequest $request * @param IPreview $previewManager + * @param IEventDispatcher $eventDispatcher + * @param IL10N $l10n */ public function __construct( IConfig $config, @@ -94,7 +96,7 @@ public function __construct( ITagManager $tagManager, IRequest $request, IPreview $previewManager, - EventDispatcherInterface $eventDispatcher, + IEventDispatcher $eventDispatcher, IL10N $l10n ) { $this->config = $config; @@ -222,7 +224,7 @@ public function createServer($baseUri, // Load dav plugins from apps $event = new SabrePluginEvent($server); - $this->eventDispatcher->dispatch($event); + $this->eventDispatcher->dispatchTyped($event); $pluginManager = new PluginManager( \OC::$server, \OC::$server->get(IAppManager::class) diff --git a/apps/dav/lib/Events/SabreAddPluginEvent.php b/apps/dav/lib/Events/SabreAddPluginEvent.php new file mode 100644 index 0000000000000..a434d94066a58 --- /dev/null +++ b/apps/dav/lib/Events/SabreAddPluginEvent.php @@ -0,0 +1,55 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Events; + +use OCP\EventDispatcher\Event; +use Sabre\DAV\Server; + +/** + * This event is triggered during the setup of the SabreDAV server to allow the + * registration of additional Sabre plugins + * + * @since 24.0.0 + */ +class SabreAddPluginEvent extends Event { + + /** @var Server */ + private $server; + + /** + * @since 20.0.0 + */ + public function __construct(Server $server) { + $this->server = $server; + } + + /** + * @since 20.0.0 + */ + public function getServer(): Server { + return $this->server; + } +} diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index 8c31886773179..4ef799668d28b 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -28,7 +28,6 @@ */ namespace OCA\DAV; -use OC\EventDispatcher\SymfonyAdapter; use OC\KnownUser\KnownUserService; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\CalDavBackend; diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index d89e15d3a204d..da7c08bb9cedd 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -37,6 +37,7 @@ use OCP\Diagnostics\IEventLogger; use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; use OC\Security\Bruteforce\Throttler; +use OCA\DAV\Events\SabreAddPluginEvent; use OCP\App\IAppManager; use OCP\Comments\ICommentsManager; use OCP\Files\IRootFolder; @@ -87,7 +88,6 @@ use OCA\DAV\Upload\ChunkingPlugin; use OCP\EventDispatcher\IEventDispatcher; use OCP\IRequest; -use OCP\SabrePluginEvent; use Sabre\CardDAV\VCFExportPlugin; use Sabre\DAV\Auth\Plugin; use Sabre\DAV\UUIDUtil; @@ -138,8 +138,6 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin($authPlugin); // allow setup of additional auth backends - $event = new SabrePluginEvent($this->server); - $dispatcher->dispatch('OCA\DAV\Connector\Sabre::authInit', $event); $newAuthEvent = new SabrePluginAuthInitEvent($this->server); $newDispatcher->dispatchTyped($newAuthEvent); @@ -226,6 +224,8 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin(new ChunkingPlugin()); // allow setup of additional plugins + $newDispatcher->dispatchTyped(new SabreAddPluginEvent($this->server)); + $event = new \OCP\SabrePluginEvent($this->server); $dispatcher->dispatch('OCA\DAV\Connector\Sabre::addPlugin', $event); // Some WebDAV clients do require Class 2 WebDAV support (locking), since diff --git a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php index 4c179d5f0f661..74dfe4a2cddde 100644 --- a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\SystemTag; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IGroupManager; use OCP\IUserSession; use OCP\SystemTag\ISystemTagManager; @@ -33,7 +34,6 @@ use OCP\SystemTag\SystemTagsEntityEvent; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\SimpleCollection; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; class SystemTagsRelationsCollection extends SimpleCollection { @@ -44,14 +44,14 @@ class SystemTagsRelationsCollection extends SimpleCollection { * @param ISystemTagObjectMapper $tagMapper * @param IUserSession $userSession * @param IGroupManager $groupManager - * @param EventDispatcherInterface $dispatcher + * @param IEventDispatcher $dispatcher */ public function __construct( ISystemTagManager $tagManager, ISystemTagObjectMapper $tagMapper, IUserSession $userSession, IGroupManager $groupManager, - EventDispatcherInterface $dispatcher + IEventDispatcher $dispatcher ) { $children = [ new SystemTagsObjectTypeCollection( @@ -68,7 +68,7 @@ function ($name) { ]; $event = new SystemTagsEntityEvent(SystemTagsEntityEvent::EVENT_ENTITY); - $dispatcher->dispatch(SystemTagsEntityEvent::EVENT_ENTITY, $event); + $dispatcher->dispatchTyped($event); foreach ($event->getEntityCollections() as $entity => $entityExistsFunction) { $children[] = new SystemTagsObjectTypeCollection( diff --git a/apps/dav/tests/unit/Comments/RootCollectionTest.php b/apps/dav/tests/unit/Comments/RootCollectionTest.php index b379dcb7e45df..51777c96db7c1 100644 --- a/apps/dav/tests/unit/Comments/RootCollectionTest.php +++ b/apps/dav/tests/unit/Comments/RootCollectionTest.php @@ -25,11 +25,10 @@ */ namespace OCA\DAV\Tests\unit\Comments; -use OC\EventDispatcher\EventDispatcher; -use OC\EventDispatcher\SymfonyAdapter; use OCA\DAV\Comments\EntityTypeCollection as EntityTypeCollectionImplementation; use OCP\Comments\CommentsEntityEvent; use OCP\Comments\ICommentsManager; +use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; @@ -72,21 +71,16 @@ protected function setUp(): void { $this->logger = $this->getMockBuilder(LoggerInterface::class) ->disableOriginalConstructor() ->getMock(); - $this->dispatcher = new SymfonyAdapter( - new EventDispatcher( - new \Symfony\Component\EventDispatcher\EventDispatcher(), - \OC::$server, - $this->logger - ), - $this->logger - ); + $this->dispatcher = $this->getMockBuilder(IEventDispatcher::class) + ->disableOriginalConstructor() + ->getMock(); $this->collection = new \OCA\DAV\Comments\RootCollection( $this->commentsManager, $this->userManager, $this->userSession, $this->dispatcher, - $this->createMock(ILogger::class) + $this->logger ); } @@ -99,7 +93,7 @@ protected function prepareForInitCollections() { ->method('getUser') ->willReturn($this->user); - $this->dispatcher->addListener(CommentsEntityEvent::EVENT_ENTITY, function (CommentsEntityEvent $event) { + $this->dispatcher->addListener(CommentsEntityEvent::class, function (CommentsEntityEvent $event) { $event->addEntityCollection('files', function () { return true; }); From c304561353b821fdd6d3758d69586017decffacb Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Sun, 16 Jan 2022 16:56:31 +0100 Subject: [PATCH 12/23] Replace calls to Sabre's depreciated getPropertiesForPath with getPropertiesIteratorForPath Signed-off-by: Thomas Citharel --- apps/dav/lib/CalDAV/Schedule/Plugin.php | 6 +++--- apps/dav/lib/CalDAV/Search/SearchPlugin.php | 4 ++-- apps/dav/lib/Comments/CommentsPlugin.php | 6 +++--- apps/dav/lib/Connector/Sabre/FilesReportPlugin.php | 2 +- apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php | 14 ++++++++++++-- 5 files changed, 21 insertions(+), 11 deletions(-) diff --git a/apps/dav/lib/CalDAV/Schedule/Plugin.php b/apps/dav/lib/CalDAV/Schedule/Plugin.php index 96bacce4454b6..bb41391275442 100644 --- a/apps/dav/lib/CalDAV/Schedule/Plugin.php +++ b/apps/dav/lib/CalDAV/Schedule/Plugin.php @@ -321,12 +321,12 @@ public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) { ]); } - $result = $this->server->getPropertiesForPath($calendarHomePath . '/' . $uri, [], 1); - if (empty($result)) { + $result = $this->server->getPropertiesIteratorForPath($calendarHomePath . '/' . $uri, [], 1); + if (!$result->valid()) { return null; } - return new LocalHref($result[0]['href']); + return new LocalHref($result->current()['href']); }); } } diff --git a/apps/dav/lib/CalDAV/Search/SearchPlugin.php b/apps/dav/lib/CalDAV/Search/SearchPlugin.php index d08a5749ab20b..21b2899eeacce 100644 --- a/apps/dav/lib/CalDAV/Search/SearchPlugin.php +++ b/apps/dav/lib/CalDAV/Search/SearchPlugin.php @@ -145,10 +145,10 @@ private function calendarSearch($report) { $nodePaths = $node->calendarSearch($report->filters, $report->limit, $report->offset); foreach ($nodePaths as $path) { - [$properties] = $this->server->getPropertiesForPath( + $properties = $this->server->getPropertiesIteratorForPath( $this->server->getRequestUri() . '/' . $path, $report->properties); - $result[] = $properties; + $result[] = $properties->current(); } } diff --git a/apps/dav/lib/Comments/CommentsPlugin.php b/apps/dav/lib/Comments/CommentsPlugin.php index a49327518979c..68c437cca46c0 100644 --- a/apps/dav/lib/Comments/CommentsPlugin.php +++ b/apps/dav/lib/Comments/CommentsPlugin.php @@ -184,11 +184,11 @@ public function onReport($reportName, $report, $uri) { $responses = []; foreach ($results as $node) { $nodePath = $this->server->getRequestUri() . '/' . $node->comment->getId(); - $resultSet = $this->server->getPropertiesForPath($nodePath, CommentNode::getPropertyNames()); - if (isset($resultSet[0]) && isset($resultSet[0][200])) { + $resultSet = $this->server->getPropertiesIteratorForPath($nodePath, CommentNode::getPropertyNames()); + if ($resultSet->valid() && isset($resultSet->current()[200])) { $responses[] = new Response( $this->server->getBaseUri() . $nodePath, - [200 => $resultSet[0][200]], + [200 => $resultSet->current()[200]], 200 ); } diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 4876e9ad8f3d7..50222fdf3c92a 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -381,7 +381,7 @@ public function prepareResponses($filesUri, $requestedProps, $nodes) { $propFind = new PropFind($filesUri . $node->getPath(), $requestedProps); $this->server->getPropertiesByNode($propFind, $node); - // copied from Sabre Server's getPropertiesForPath + // copied from Sabre Server's getPropertiesIteratorForPath $result = $propFind->getResultForMultiStatus(); $result['href'] = $propFind->getPath(); diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php index 2518cc3d91af4..2aa873b6fa4ec 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php @@ -32,6 +32,7 @@ use OCA\DAV\CalDAV\Schedule\Plugin; use OCP\IConfig; use PHPUnit\Framework\MockObject\MockObject; +use PHPUnit\Framework\MockObject\Stub\ReturnCallback; use Sabre\DAV\PropFind; use Sabre\DAV\Server; use Sabre\DAV\Tree; @@ -330,9 +331,9 @@ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $ca ] : []; $this->server->expects($this->once()) - ->method('getPropertiesForPath') + ->method('getPropertiesIteratorForPath') ->with($calendarHome .'/' . $calendarUri, [], 1) - ->willReturn($properties); + ->willReturn($this->generate($properties)); $this->plugin->propFindDefaultCalendarUrl($propFind, $node); @@ -345,4 +346,13 @@ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $ca $result = $propFind->get(Plugin::SCHEDULE_DEFAULT_CALENDAR_URL); $this->assertEquals('/remote.php/dav/'. $calendarHome . '/' . $calendarUri, $result->getHref()); } + + // https://stackoverflow.com/a/56763373/10204399 + protected function generate(array $yield_values): ReturnCallback { + return $this->returnCallback(function() use ($yield_values) { + foreach ($yield_values as $value) { + yield $value; + } + }); + } } From 981b99c5b2152ddd34418c3f0be123408c8d1df0 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 07:24:15 +0100 Subject: [PATCH 13/23] Remove more depreciated calls Signed-off-by: Thomas Citharel --- apps/dav/lib/AppInfo/PluginManager.php | 4 ++-- apps/dav/lib/CalDAV/Search/SearchPlugin.php | 2 +- apps/dav/lib/Connector/Sabre/File.php | 3 ++- apps/dav/lib/Connector/Sabre/Principal.php | 4 ++-- apps/dav/lib/Files/RootCollection.php | 5 ++++- .../tests/unit/CalDAV/AbstractCalDavBackend.php | 5 +++-- .../unit/CalDAV/Activity/Filter/GenericTest.php | 14 +++++++------- .../unit/CalDAV/Activity/Setting/GenericTest.php | 16 ++++++++-------- .../tests/unit/CalDAV/PublicCalendarRootTest.php | 14 +++++--------- .../tests/unit/CalDAV/Schedule/PluginTest.php | 3 +-- .../unit/Command/RemoveInvalidSharesTest.php | 5 +++-- .../Sabre/CustomPropertiesBackendTest.php | 5 +++-- apps/dav/tests/unit/Connector/Sabre/FileTest.php | 14 ++++++++------ apps/dav/tests/unit/Connector/Sabre/NodeTest.php | 4 ++-- .../unit/Connector/Sabre/RequestTest/Auth.php | 16 ++++++++++------ .../EncryptionMasterKeyUploadTest.php | 6 ++++-- .../Sabre/RequestTest/EncryptionUploadTest.php | 6 ++++-- .../RequestTest/PartFileInRootUploadTest.php | 2 +- .../Sabre/RequestTest/RequestTestCase.php | 2 +- apps/dav/tests/unit/DAV/AnonymousOptionsTest.php | 2 +- .../unit/DAV/CustomPropertiesBackendTest.php | 2 +- .../Migration/CalDAVRemoveEmptyValueTest.php | 9 +++++---- 22 files changed, 78 insertions(+), 65 deletions(-) diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index dc67f9ca73c14..bed6963f8879b 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -32,7 +32,7 @@ use OCA\DAV\CalDAV\Integration\ICalendarProvider; use OCA\DAV\CardDAV\Integration\IAddressBookProvider; use OCP\App\IAppManager; -use OCP\AppFramework\QueryException; +use Psr\Container\ContainerExceptionInterface; use Sabre\DAV\Collection; use Sabre\DAV\ServerPlugin; use function array_map; @@ -254,7 +254,7 @@ private function extractCalendarPluginList(array $array): array { private function createClass(string $className): object { try { return $this->container->get($className); - } catch (QueryException $e) { + } catch (ContainerExceptionInterface $e) { if (class_exists($className)) { return new $className(); } diff --git a/apps/dav/lib/CalDAV/Search/SearchPlugin.php b/apps/dav/lib/CalDAV/Search/SearchPlugin.php index 21b2899eeacce..a9ca977277cc6 100644 --- a/apps/dav/lib/CalDAV/Search/SearchPlugin.php +++ b/apps/dav/lib/CalDAV/Search/SearchPlugin.php @@ -132,7 +132,7 @@ public function getSupportedReportSet($uri) { * @param Xml\Request\CalendarSearchReport $report * @return void */ - private function calendarSearch($report) { + private function calendarSearch(CalendarSearchReport $report): void { $node = $this->server->tree->getNodeForPath($this->server->getRequestUri()); $depth = $this->server->getHTTPDepth(2); diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index afcb9becad875..58f4be241170e 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -49,6 +49,7 @@ use OCA\DAV\Connector\Sabre\Exception\Forbidden as DAVForbiddenException; use OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType; use OCA\DAV\Connector\Sabre\Exception\BadGateway; +use OCP\App\IAppManager; use OCP\Encryption\Exceptions\GenericEncryptionException; use OCP\Files\EntityTooLargeException; use OCP\Files\FileInfo; @@ -545,7 +546,7 @@ public function getContentType() { * @return array|bool */ public function getDirectDownload() { - if (\OCP\App::isEnabled('encryption')) { + if (\OC::$server->get(IAppManager::class)->isEnabledForUser('encryption')) { return []; } /** @var \OCP\Files\Storage $storage */ diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 8093fb6f1d4e2..293013df1fa90 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -44,7 +44,6 @@ use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\Traits\PrincipalProxyTrait; use OCP\App\IAppManager; -use OCP\AppFramework\QueryException; use OCP\Constants; use OCP\IConfig; use OCP\IGroup; @@ -54,6 +53,7 @@ use OCP\IUserSession; use OCP\L10N\IFactory; use OCP\Share\IManager as IShareManager; +use Psr\Container\ContainerExceptionInterface; use Sabre\DAV\Exception; use Sabre\DAV\PropPatch; use Sabre\DAVACL\PrincipalBackend\BackendInterface; @@ -534,7 +534,7 @@ protected function circleToPrincipal(string $circleUniqueId): ?array { try { $circle = Circles::detailsCircle($circleUniqueId, true); - } catch (QueryException $ex) { + } catch (ContainerExceptionInterface $ex) { return null; } catch (CircleNotFoundException $ex) { return null; diff --git a/apps/dav/lib/Files/RootCollection.php b/apps/dav/lib/Files/RootCollection.php index 897c8ed5b875f..09f53c9ed089e 100644 --- a/apps/dav/lib/Files/RootCollection.php +++ b/apps/dav/lib/Files/RootCollection.php @@ -26,6 +26,7 @@ namespace OCA\DAV\Files; use OCP\Files\FileInfo; +use OCP\Files\IRootFolder; use OCP\IUserSession; use Sabre\DAV\INode; use Sabre\DAV\SimpleCollection; @@ -52,7 +53,9 @@ public function getChildForPrincipal(array $principalInfo) { // in the future this could be considered to be used for accessing shared files return new SimpleCollection($name); } - $userFolder = \OC::$server->getUserFolder(); + /** @var IRootFolder $root */ + $root = \OC::$server->get(IRootFolder::class); + $userFolder = $root->getUserFolder($user->getUID()); if (!($userFolder instanceof FileInfo)) { throw new \Exception('Home does not exist'); } diff --git a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php index ec2acf44608e6..fbd96eb169f1b 100644 --- a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php +++ b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php @@ -34,6 +34,7 @@ use OCP\App\IAppManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; +use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IUserManager; use OCP\IUserSession; @@ -105,8 +106,8 @@ protected function setUp(): void { ->withAnyParameters() ->willReturn([self::UNIT_TEST_GROUP, self::UNIT_TEST_GROUP2]); - $db = \OC::$server->getDatabaseConnection(); - $this->random = \OC::$server->getSecureRandom(); + $db = \OC::$server->get(IDBConnection::class); + $this->random = \OC::$server->get(ISecureRandom::class); $this->logger = $this->createMock(LoggerInterface::class); $this->config = $this->createMock(IConfig::class); $this->backend = new CalDavBackend( diff --git a/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php b/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php index af4c87c354bbb..4cfc7ef7144ca 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php @@ -44,7 +44,7 @@ public function dataFilters() { * @param string $filterClass */ public function testImplementsInterface($filterClass) { - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $this->assertInstanceOf(IFilter::class, $filter); } @@ -54,7 +54,7 @@ public function testImplementsInterface($filterClass) { */ public function testGetIdentifier($filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $this->assertIsString($filter->getIdentifier()); } @@ -64,7 +64,7 @@ public function testGetIdentifier($filterClass) { */ public function testGetName($filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $this->assertIsString($filter->getName()); } @@ -74,7 +74,7 @@ public function testGetName($filterClass) { */ public function testGetPriority($filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $priority = $filter->getPriority(); $this->assertIsInt($filter->getPriority()); $this->assertGreaterThanOrEqual(0, $priority); @@ -87,7 +87,7 @@ public function testGetPriority($filterClass) { */ public function testGetIcon($filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $this->assertIsString($filter->getIcon()); $this->assertStringStartsWith('http', $filter->getIcon()); } @@ -98,7 +98,7 @@ public function testGetIcon($filterClass) { */ public function testFilterTypes($filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $this->assertIsArray($filter->filterTypes([])); } @@ -108,7 +108,7 @@ public function testFilterTypes($filterClass) { */ public function testAllowedApps($filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->query($filterClass); + $filter = \OC::$server->get($filterClass); $this->assertIsArray($filter->allowedApps()); } } diff --git a/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php b/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php index b4c3506565ab9..582885c5ea59d 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php @@ -43,7 +43,7 @@ public function dataSettings() { * @param string $settingClass */ public function testImplementsInterface($settingClass) { - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertInstanceOf(ISetting::class, $setting); } @@ -53,7 +53,7 @@ public function testImplementsInterface($settingClass) { */ public function testGetIdentifier($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertIsString($setting->getIdentifier()); } @@ -63,7 +63,7 @@ public function testGetIdentifier($settingClass) { */ public function testGetName($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertIsString($setting->getName()); } @@ -73,7 +73,7 @@ public function testGetName($settingClass) { */ public function testGetPriority($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $priority = $setting->getPriority(); $this->assertIsInt($setting->getPriority()); $this->assertGreaterThanOrEqual(0, $priority); @@ -86,7 +86,7 @@ public function testGetPriority($settingClass) { */ public function testCanChangeStream($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertIsBool($setting->canChangeStream()); } @@ -96,7 +96,7 @@ public function testCanChangeStream($settingClass) { */ public function testIsDefaultEnabledStream($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertIsBool($setting->isDefaultEnabledStream()); } @@ -106,7 +106,7 @@ public function testIsDefaultEnabledStream($settingClass) { */ public function testCanChangeMail($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertIsBool($setting->canChangeMail()); } @@ -116,7 +116,7 @@ public function testCanChangeMail($settingClass) { */ public function testIsDefaultEnabledMail($settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->query($settingClass); + $setting = \OC::$server->get($settingClass); $this->assertIsBool($setting->isDefaultEnabledMail()); } } diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php index a5716e1b83f3b..758e5ee1b20a4 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php @@ -37,6 +37,7 @@ use OCA\DAV\Connector\Sabre\Principal; use OCP\EventDispatcher\IEventDispatcher; use OCP\IConfig; +use OCP\IDBConnection; use OCP\IGroupManager; use OCP\IL10N; use OCP\IUserManager; @@ -76,17 +77,12 @@ class PublicCalendarRootTest extends TestCase { protected function setUp(): void { parent::setUp(); - $db = \OC::$server->getDatabaseConnection(); - $this->principal = $this->createMock('OCA\DAV\Connector\Sabre\Principal'); + $db = \OC::$server->get(IDBConnection::class); + $this->principal = $this->createMock(Principal::class); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); - $this->random = \OC::$server->getSecureRandom(); -<<<<<<< HEAD - $this->logger = $this->createMock(ILogger::class); - $this->psrLogger = $this->createMock(LoggerInterface::class); -======= + $this->random = \OC::$server->get(ISecureRandom::class); $this->logger = $this->createMock(LoggerInterface::class); ->>>>>>> 4565b23b66 (Move uses of ILogger to LoggerInterface) $dispatcher = $this->createMock(IEventDispatcher::class); $config = $this->createMock(IConfig::class); @@ -113,7 +109,7 @@ protected function setUp(): void { $this->config = $this->createMock(IConfig::class); $this->publicCalendarRoot = new PublicCalendarRoot($this->backend, - $this->l10n, $this->config, $this->psrLogger); + $this->l10n, $this->config, $this->logger); } protected function tearDown(): void { diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php index 2aa873b6fa4ec..972a77873b8ab 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php @@ -241,7 +241,7 @@ public function propFindDefaultCalendarUrlProvider(): array { /** * @dataProvider propFindDefaultCalendarUrlProvider * @param string $principalUri - * @param string $calendarHome + * @param string|null $calendarHome * @param bool $isResource * @param string $calendarUri * @param string $displayName @@ -249,7 +249,6 @@ public function propFindDefaultCalendarUrlProvider(): array { * @param bool $propertiesForPath */ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $calendarHome, bool $isResource, string $calendarUri, string $displayName, bool $exists, bool $propertiesForPath = true) { - /** @var PropFind $propFind */ $propFind = new PropFind( $principalUri, [ diff --git a/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php b/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php index 66ac40eff83ae..61c79a32c12f7 100644 --- a/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php +++ b/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php @@ -24,6 +24,7 @@ use OCA\DAV\Command\RemoveInvalidShares; use OCA\DAV\Connector\Sabre\Principal; +use OCP\IDBConnection; use OCP\Migration\IOutput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; @@ -38,7 +39,7 @@ class RemoveInvalidSharesTest extends TestCase { protected function setUp(): void { parent::setUp(); - $db = \OC::$server->getDatabaseConnection(); + $db = \OC::$server->get(IDBConnection::class); $db->insertIfNotExist('*PREFIX*dav_shares', [ 'principaluri' => 'principal:unknown', @@ -49,7 +50,7 @@ protected function setUp(): void { } public function test() { - $db = \OC::$server->getDatabaseConnection(); + $db = \OC::$server->get(IDBConnection::class); /** @var Principal | \PHPUnit\Framework\MockObject\MockObject $principal */ $principal = $this->createMock(Principal::class); diff --git a/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php b/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php index 48658f3ffa36f..a7b1225bdc052 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php @@ -38,6 +38,7 @@ use OCA\DAV\Connector\Sabre\Directory; use OCA\DAV\Connector\Sabre\File; +use OCP\IDBConnection; use OCP\IUser; use Sabre\DAV\Tree; @@ -88,13 +89,13 @@ protected function setUp(): void { $this->plugin = new \OCA\DAV\DAV\CustomPropertiesBackend( $this->tree, - \OC::$server->getDatabaseConnection(), + \OC::$server->get(IDBConnection::class), $this->user ); } protected function tearDown(): void { - $connection = \OC::$server->getDatabaseConnection(); + $connection = \OC::$server->get(IDBConnection::class); $deleteStatement = $connection->prepare( 'DELETE FROM `*PREFIX*properties`' . ' WHERE `userid` = ?' diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index d12a86f6e8dee..050fa029784d3 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -38,9 +38,11 @@ use OCA\DAV\Connector\Sabre\File; use OCP\Constants; use OCP\Files\ForbiddenException; -use OCP\Files\Storage; +use OCP\Files\Storage\IStorage; use OCP\IConfig; use OCP\IRequestId; +use OCP\ITempManager; +use OCP\IUserManager; use OCP\Lock\ILockingProvider; use PHPUnit\Framework\MockObject\MockObject; use Test\HookHelper; @@ -88,7 +90,7 @@ protected function setUp(): void { } protected function tearDown(): void { - $userManager = \OC::$server->getUserManager(); + $userManager = \OC::$server->get(IUserManager::class); $userManager->get($this->user)->delete(); unset($_SERVER['HTTP_OC_CHUNKED']); @@ -96,10 +98,10 @@ protected function tearDown(): void { } /** - * @return MockObject|Storage + * @return MockObject|IStorage */ private function getMockStorage() { - $storage = $this->getMockBuilder(Storage::class) + $storage = $this->getMockBuilder(IStorage::class) ->disableOriginalConstructor() ->getMock(); $storage->method('getId') @@ -181,7 +183,7 @@ public function testSimplePutFails($thrownException, $expectedException, $checkP // setup $storage = $this->getMockBuilder(Local::class) ->setMethods(['writeStream']) - ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]]) + ->setConstructorArgs([['datadir' => \OC::$server->get(ITempManager::class)->getTemporaryFolder()]]) ->getMock(); \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); /** @var View | MockObject $view */ @@ -241,7 +243,7 @@ public function testChunkedPutFails($thrownException, $expectedException, $check // setup $storage = $this->getMockBuilder(Local::class) ->setMethods(['fopen']) - ->setConstructorArgs([['datadir' => \OC::$server->getTempManager()->getTemporaryFolder()]]) + ->setConstructorArgs([['datadir' => \OC::$server->get(ITempManager::class)->getTemporaryFolder()]]) ->getMock(); \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); $view = $this->getMockBuilder(View::class) diff --git a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php index 00fd0ebd8aa2a..9889dcbe3bd9c 100644 --- a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php @@ -30,7 +30,7 @@ use OC\Files\FileInfo; use OC\Files\View; use OCP\Files\Mount\IMountPoint; -use OCP\Files\Storage; +use OCP\Files\Storage\IStorage; use OCP\Share\IManager; use OCP\Share\IShare; @@ -129,7 +129,7 @@ public function sharePermissionsProvider() { * @dataProvider sharePermissionsProvider */ public function testSharePermissions($type, $user, $permissions, $expected) { - $storage = $this->getMockBuilder(Storage::class) + $storage = $this->getMockBuilder(IStorage::class) ->disableOriginalConstructor() ->getMock(); $storage->method('getPermissions')->willReturn($permissions); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php index 917c63038cb88..eb159b15d2b09 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php @@ -24,6 +24,8 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use OCP\Files\IRootFolder; +use OCP\IUserSession; use Sabre\DAV\Auth\Backend\BackendInterface; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -79,15 +81,17 @@ public function __construct($user, $password) { * @return array */ public function check(RequestInterface $request, ResponseInterface $response) { - $userSession = \OC::$server->getUserSession(); + /** @var IUserSession $userSession */ + $userSession = \OC::$server->get(IUserSession::class); $result = $userSession->login($this->user, $this->password); - if ($result) { + if ($result && $user = $userSession->getUser()) { //we need to pass the user name, which may differ from login name - $user = $userSession->getUser()->getUID(); - \OC_Util::setupFS($user); + $userId = $user->getUID(); + \OC_Util::setupFS($userId); //trigger creation of user home and /files folder - \OC::$server->getUserFolder($user); - return [true, "principals/$user"]; + $root = \OC::$server->get(IRootFolder::class); + $root->getUserFolder($userId); + return [true, "principals/$userId"]; } return [false, "login failed"]; } diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php index f0fd9e5a8333b..abf8165f0ac09 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php @@ -22,6 +22,8 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; use OC\Files\View; +use OCP\IConfig; +use OCP\ITempManager; use Test\Traits\EncryptionTrait; /** @@ -36,10 +38,10 @@ class EncryptionMasterKeyUploadTest extends UploadTest { protected function setupUser($name, $password) { $this->createUser($name, $password); - $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmpFolder = \OC::$server->get(ITempManager::class)->getTemporaryFolder(); $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); // we use the master key - \OC::$server->getConfig()->setAppValue('encryption', 'useMasterKey', '1'); + \OC::$server->get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '1'); $this->setupForUser($name, $password); $this->loginWithEncryption($name); return new View('/' . $name . '/files'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php index da7c35560cbd3..f29f5debe8f78 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php @@ -25,6 +25,8 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; use OC\Files\View; +use OCP\IConfig; +use OCP\ITempManager; use Test\Traits\EncryptionTrait; /** @@ -39,10 +41,10 @@ class EncryptionUploadTest extends UploadTest { protected function setupUser($name, $password) { $this->createUser($name, $password); - $tmpFolder = \OC::$server->getTempManager()->getTemporaryFolder(); + $tmpFolder = \OC::$server->get(ITempManager::class)->getTemporaryFolder(); $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); // we use per-user keys - \OC::$server->getConfig()->setAppValue('encryption', 'useMasterKey', '0'); + \OC::$server->get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '0'); $this->setupForUser($name, $password); $this->loginWithEncryption($name); return new View('/' . $name . '/files'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php index 88ec848ad8955..7ec9e0d4054aa 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php @@ -36,7 +36,7 @@ */ class PartFileInRootUploadTest extends UploadTest { protected function setUp(): void { - $config = \OC::$server->getConfig(); + $config = \OC::$server->get(IConfig::class); $mockConfig = $this->getMockBuilder(IConfig::class) ->disableOriginalConstructor() ->getMock(); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php index a16718bf46421..45da9cf17c5b7 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php @@ -140,7 +140,7 @@ protected function makeRequest(Server $server, Request $request) { $sapi = new Sapi($request); $server->sapi = $sapi; $server->httpRequest = $request; - $server->exec(); + $server->start(); return $sapi->getResponse(); } diff --git a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php index 8c178ba8e4483..537c22e74a2d1 100644 --- a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php +++ b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php @@ -46,7 +46,7 @@ private function sendRequest($method, $path, $userAgent = '') { $server->httpRequest->setHeader('User-Agent', $userAgent); $server->sapi = new SapiMock(); - $server->exec(); + $server->start(); return $server->httpResponse; } diff --git a/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php b/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php index 2e7939aa6144f..3ac34d2a18a12 100644 --- a/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php @@ -60,7 +60,7 @@ protected function setUp(): void { $this->user->method('getUID') ->with() ->willReturn('dummy_user_42'); - $this->dbConnection = \OC::$server->getDatabaseConnection(); + $this->dbConnection = \OC::$server->get(IDBConnection::class); $this->backend = new CustomPropertiesBackend( $this->tree, diff --git a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php index 0adabd2388f04..e8a9a617fe233 100644 --- a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php +++ b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php @@ -27,6 +27,7 @@ use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\Migration\CalDAVRemoveEmptyValue; +use OCP\IDBConnection; use OCP\Migration\IOutput; use Psr\Log\LoggerInterface; use Sabre\VObject\InvalidDataException; @@ -103,7 +104,7 @@ public function testRunAllValid() { /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->getDatabaseConnection(), + \OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) @@ -127,7 +128,7 @@ public function testRunInvalid() { /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->getDatabaseConnection(), + \OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) @@ -170,7 +171,7 @@ public function testRunValid() { /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->getDatabaseConnection(), + \OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) @@ -212,7 +213,7 @@ public function testRunStillInvalid() { /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->getDatabaseConnection(), + \OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) From dcc9c703913f5612b677953973b42bea742071d7 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 08:56:55 +0100 Subject: [PATCH 14/23] Remove HookManager and replace with UserChangeListener Signed-off-by: Thomas Citharel --- .../composer/composer/autoload_classmap.php | 3 +- .../dav/composer/composer/autoload_static.php | 3 +- apps/dav/composer/composer/installed.php | 4 +- apps/dav/lib/AppInfo/Application.php | 19 +- apps/dav/lib/HookManager.php | 195 -------------- apps/dav/lib/Listener/UserChangeListener.php | 194 ++++++++++++++ apps/dav/tests/unit/DAV/HookManagerTest.php | 250 ------------------ .../unit/Listener/UserChangeListenerTest.php | 161 +++++++++++ 8 files changed, 375 insertions(+), 454 deletions(-) delete mode 100644 apps/dav/lib/HookManager.php create mode 100644 apps/dav/lib/Listener/UserChangeListener.php delete mode 100644 apps/dav/tests/unit/DAV/HookManagerTest.php create mode 100644 apps/dav/tests/unit/Listener/UserChangeListenerTest.php diff --git a/apps/dav/composer/composer/autoload_classmap.php b/apps/dav/composer/composer/autoload_classmap.php index 96a81218e6a30..d038943a9b729 100644 --- a/apps/dav/composer/composer/autoload_classmap.php +++ b/apps/dav/composer/composer/autoload_classmap.php @@ -220,6 +220,7 @@ 'OCA\\DAV\\Events\\CardCreatedEvent' => $baseDir . '/../lib/Events/CardCreatedEvent.php', 'OCA\\DAV\\Events\\CardDeletedEvent' => $baseDir . '/../lib/Events/CardDeletedEvent.php', 'OCA\\DAV\\Events\\CardUpdatedEvent' => $baseDir . '/../lib/Events/CardUpdatedEvent.php', + 'OCA\\DAV\\Events\\SabreAddPluginEvent' => $baseDir . '/../lib/Events/SabreAddPluginEvent.php', 'OCA\\DAV\\Events\\SabrePluginAuthInitEvent' => $baseDir . '/../lib/Events/SabrePluginAuthInitEvent.php', 'OCA\\DAV\\Events\\SubscriptionCreatedEvent' => $baseDir . '/../lib/Events/SubscriptionCreatedEvent.php', 'OCA\\DAV\\Events\\SubscriptionDeletedEvent' => $baseDir . '/../lib/Events/SubscriptionDeletedEvent.php', @@ -232,7 +233,6 @@ 'OCA\\DAV\\Files\\RootCollection' => $baseDir . '/../lib/Files/RootCollection.php', 'OCA\\DAV\\Files\\Sharing\\FilesDropPlugin' => $baseDir . '/../lib/Files/Sharing/FilesDropPlugin.php', 'OCA\\DAV\\Files\\Sharing\\PublicLinkCheckPlugin' => $baseDir . '/../lib/Files/Sharing/PublicLinkCheckPlugin.php', - 'OCA\\DAV\\HookManager' => $baseDir . '/../lib/HookManager.php', 'OCA\\DAV\\Listener\\ActivityUpdaterListener' => $baseDir . '/../lib/Listener/ActivityUpdaterListener.php', 'OCA\\DAV\\Listener\\AddressbookListener' => $baseDir . '/../lib/Listener/AddressbookListener.php', 'OCA\\DAV\\Listener\\BirthdayListener' => $baseDir . '/../lib/Listener/BirthdayListener.php', @@ -246,6 +246,7 @@ 'OCA\\DAV\\Listener\\ClearPhotoCacheListener' => $baseDir . '/../lib/Listener/ClearPhotoCacheListener.php', 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => $baseDir . '/../lib/Listener/SubscriptionCreationListener.php', 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => $baseDir . '/../lib/Listener/SubscriptionDeletionListener.php', + 'OCA\\DAV\\Listener\\UserChangeListener' => $baseDir . '/../lib/Listener/UserChangeListener.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndex.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndexBackgroundJob' => $baseDir . '/../lib/Migration/BuildCalendarSearchIndexBackgroundJob.php', 'OCA\\DAV\\Migration\\BuildSocialSearchIndex' => $baseDir . '/../lib/Migration/BuildSocialSearchIndex.php', diff --git a/apps/dav/composer/composer/autoload_static.php b/apps/dav/composer/composer/autoload_static.php index 7c6bae0d4c2b0..7beafe9a86e90 100644 --- a/apps/dav/composer/composer/autoload_static.php +++ b/apps/dav/composer/composer/autoload_static.php @@ -235,6 +235,7 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Events\\CardCreatedEvent' => __DIR__ . '/..' . '/../lib/Events/CardCreatedEvent.php', 'OCA\\DAV\\Events\\CardDeletedEvent' => __DIR__ . '/..' . '/../lib/Events/CardDeletedEvent.php', 'OCA\\DAV\\Events\\CardUpdatedEvent' => __DIR__ . '/..' . '/../lib/Events/CardUpdatedEvent.php', + 'OCA\\DAV\\Events\\SabreAddPluginEvent' => __DIR__ . '/..' . '/../lib/Events/SabreAddPluginEvent.php', 'OCA\\DAV\\Events\\SabrePluginAuthInitEvent' => __DIR__ . '/..' . '/../lib/Events/SabrePluginAuthInitEvent.php', 'OCA\\DAV\\Events\\SubscriptionCreatedEvent' => __DIR__ . '/..' . '/../lib/Events/SubscriptionCreatedEvent.php', 'OCA\\DAV\\Events\\SubscriptionDeletedEvent' => __DIR__ . '/..' . '/../lib/Events/SubscriptionDeletedEvent.php', @@ -247,7 +248,6 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Files\\RootCollection' => __DIR__ . '/..' . '/../lib/Files/RootCollection.php', 'OCA\\DAV\\Files\\Sharing\\FilesDropPlugin' => __DIR__ . '/..' . '/../lib/Files/Sharing/FilesDropPlugin.php', 'OCA\\DAV\\Files\\Sharing\\PublicLinkCheckPlugin' => __DIR__ . '/..' . '/../lib/Files/Sharing/PublicLinkCheckPlugin.php', - 'OCA\\DAV\\HookManager' => __DIR__ . '/..' . '/../lib/HookManager.php', 'OCA\\DAV\\Listener\\ActivityUpdaterListener' => __DIR__ . '/..' . '/../lib/Listener/ActivityUpdaterListener.php', 'OCA\\DAV\\Listener\\AddressbookListener' => __DIR__ . '/..' . '/../lib/Listener/AddressbookListener.php', 'OCA\\DAV\\Listener\\BirthdayListener' => __DIR__ . '/..' . '/../lib/Listener/BirthdayListener.php', @@ -261,6 +261,7 @@ class ComposerStaticInitDAV 'OCA\\DAV\\Listener\\ClearPhotoCacheListener' => __DIR__ . '/..' . '/../lib/Listener/ClearPhotoCacheListener.php', 'OCA\\DAV\\Listener\\SubscriptionCreationListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionCreationListener.php', 'OCA\\DAV\\Listener\\SubscriptionDeletionListener' => __DIR__ . '/..' . '/../lib/Listener/SubscriptionDeletionListener.php', + 'OCA\\DAV\\Listener\\UserChangeListener' => __DIR__ . '/..' . '/../lib/Listener/UserChangeListener.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndex' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndex.php', 'OCA\\DAV\\Migration\\BuildCalendarSearchIndexBackgroundJob' => __DIR__ . '/..' . '/../lib/Migration/BuildCalendarSearchIndexBackgroundJob.php', 'OCA\\DAV\\Migration\\BuildSocialSearchIndex' => __DIR__ . '/..' . '/../lib/Migration/BuildSocialSearchIndex.php', diff --git a/apps/dav/composer/composer/installed.php b/apps/dav/composer/composer/installed.php index baf72c4fb3446..b05cf6c285fc4 100644 --- a/apps/dav/composer/composer/installed.php +++ b/apps/dav/composer/composer/installed.php @@ -5,7 +5,7 @@ 'type' => 'library', 'install_path' => __DIR__ . '/../', 'aliases' => array(), - 'reference' => 'e2c675724fc4ea50f1275bf0027b96f277c32578', + 'reference' => 'a25928fb43d5f308719762b57ad826135d91c3f1', 'name' => '__root__', 'dev' => false, ), @@ -16,7 +16,7 @@ 'type' => 'library', 'install_path' => __DIR__ . '/../', 'aliases' => array(), - 'reference' => 'e2c675724fc4ea50f1275bf0027b96f277c32578', + 'reference' => 'a25928fb43d5f308719762b57ad826135d91c3f1', 'dev_requirement' => false, ), ), diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index d2182bdee164a..d268c1e10e91d 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -70,7 +70,6 @@ use OCA\DAV\Events\CardUpdatedEvent; use OCA\DAV\Events\SubscriptionCreatedEvent; use OCA\DAV\Events\SubscriptionDeletedEvent; -use OCA\DAV\HookManager; use OCA\DAV\Listener\ActivityUpdaterListener; use OCA\DAV\Listener\AddressbookListener; use OCA\DAV\Listener\BirthdayListener; @@ -84,6 +83,7 @@ use OCA\DAV\Listener\ClearPhotoCacheListener; use OCA\DAV\Listener\SubscriptionCreationListener; use OCA\DAV\Listener\SubscriptionDeletionListener; +use OCA\DAV\Listener\UserChangeListener; use OCA\DAV\Search\ContactsSearchProvider; use OCA\DAV\Search\EventsSearchProvider; use OCA\DAV\Search\TasksSearchProvider; @@ -100,6 +100,10 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserSession; +use OCP\User\Events\BeforeUserDeletedEvent; +use OCP\User\Events\UserChangedEvent; +use OCP\User\Events\UserCreatedEvent; +use OCP\User\Events\UserDeletedEvent; use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; use Symfony\Component\EventDispatcher\EventDispatcherInterface; @@ -184,6 +188,11 @@ public function register(IRegistrationContext $context): void { $context->registerEventListener(CardDeletedEvent::class, ClearPhotoCacheListener::class); $context->registerEventListener(CardUpdatedEvent::class, ClearPhotoCacheListener::class); + $context->registerEventListener(UserCreatedEvent::class, UserChangeListener::class); + $context->registerEventListener(BeforeUserDeletedEvent::class, UserChangeListener::class); + $context->registerEventListener(UserDeletedEvent::class, UserChangeListener::class); + $context->registerEventListener(UserChangedEvent::class, UserChangeListener::class); + $context->registerNotifierService(Notifier::class); $context->registerCalendarProvider(CalendarProvider::class); @@ -201,16 +210,16 @@ public function boot(IBootContext $context): void { $context->injectFn([$this, 'registerCalendarReminders']); } - public function registerHooks(HookManager $hm, + public function registerHooks(UserChangeListener $userChangeListener, EventDispatcherInterface $dispatcher, IAppContainer $container, IServerContainer $serverContainer) { - $hm->setup(); + $userChangeListener->setupLegacyHooks(); // first time login event setup - $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($hm) { + $dispatcher->addListener(IUser::class . '::firstLogin', function ($event) use ($userChangeListener) { if ($event instanceof GenericEvent) { - $hm->firstLogin($event->getSubject()); + $userChangeListener->firstLogin($event->getSubject()); } }); diff --git a/apps/dav/lib/HookManager.php b/apps/dav/lib/HookManager.php deleted file mode 100644 index 3f008b6cdd58e..0000000000000 --- a/apps/dav/lib/HookManager.php +++ /dev/null @@ -1,195 +0,0 @@ - - * @author Bjoern Schiessle - * @author Christoph Wurst - * @author Joas Schilling - * @author John Molakvoæ - * @author Robin Appelman - * @author Thomas Citharel - * @author Thomas Müller - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * 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, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV; - -use OCA\DAV\CalDAV\CalDavBackend; -use OCA\DAV\CardDAV\CardDavBackend; -use OCA\DAV\CardDAV\SyncService; -use OCP\Defaults; -use OCP\IUser; -use OCP\IUserManager; -use OCP\Util; -use Psr\Log\LoggerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; - -class HookManager { - - /** @var IUserManager */ - private $userManager; - - /** @var SyncService */ - private $syncService; - - /** @var IUser[] */ - private $usersToDelete = []; - - /** @var CalDavBackend */ - private $calDav; - - /** @var CardDavBackend */ - private $cardDav; - - /** @var array */ - private $calendarsToDelete = []; - - /** @var array */ - private $subscriptionsToDelete = []; - - /** @var array */ - private $addressBooksToDelete = []; - - /** @var Defaults */ - private $themingDefaults; - - /** @var EventDispatcherInterface */ - private $eventDispatcher; - - public function __construct(IUserManager $userManager, - SyncService $syncService, - CalDavBackend $calDav, - CardDavBackend $cardDav, - Defaults $themingDefaults, - EventDispatcherInterface $eventDispatcher) { - $this->userManager = $userManager; - $this->syncService = $syncService; - $this->calDav = $calDav; - $this->cardDav = $cardDav; - $this->themingDefaults = $themingDefaults; - $this->eventDispatcher = $eventDispatcher; - } - - public function setup() { - Util::connectHook('OC_User', - 'post_createUser', - $this, - 'postCreateUser'); - \OC::$server->getUserManager()->listen('\OC\User', 'assignedUserId', function ($uid) { - $this->postCreateUser(['uid' => $uid]); - }); - Util::connectHook('OC_User', - 'pre_deleteUser', - $this, - 'preDeleteUser'); - \OC::$server->getUserManager()->listen('\OC\User', 'preUnassignedUserId', [$this, 'preUnassignedUserId']); - Util::connectHook('OC_User', - 'post_deleteUser', - $this, - 'postDeleteUser'); - \OC::$server->getUserManager()->listen('\OC\User', 'postUnassignedUserId', function ($uid) { - $this->postDeleteUser(['uid' => $uid]); - }); - \OC::$server->getUserManager()->listen('\OC\User', 'postUnassignedUserId', [$this, 'postUnassignedUserId']); - Util::connectHook('OC_User', - 'changeUser', - $this, - 'changeUser'); - } - - public function postCreateUser($params) { - $user = $this->userManager->get($params['uid']); - if ($user instanceof IUser) { - $this->syncService->updateUser($user); - } - } - - public function preDeleteUser($params) { - $uid = $params['uid']; - $userPrincipalUri = 'principals/users/' . $uid; - $this->usersToDelete[$uid] = $this->userManager->get($uid); - $this->calendarsToDelete = $this->calDav->getUsersOwnCalendars($userPrincipalUri); - $this->subscriptionsToDelete = $this->calDav->getSubscriptionsForUser($userPrincipalUri); - $this->addressBooksToDelete = $this->cardDav->getUsersOwnAddressBooks($userPrincipalUri); - } - - public function preUnassignedUserId($uid) { - $this->usersToDelete[$uid] = $this->userManager->get($uid); - } - - public function postDeleteUser($params) { - $uid = $params['uid']; - if (isset($this->usersToDelete[$uid])) { - $this->syncService->deleteUser($this->usersToDelete[$uid]); - } - - foreach ($this->calendarsToDelete as $calendar) { - $this->calDav->deleteCalendar( - $calendar['id'], - true // Make sure the data doesn't go into the trashbin, a new user with the same UID would later see it otherwise - ); - } - - foreach ($this->subscriptionsToDelete as $subscription) { - $this->calDav->deleteSubscription( - $subscription['id'], - ); - } - $this->calDav->deleteAllSharesByUser('principals/users/' . $uid); - - foreach ($this->addressBooksToDelete as $addressBook) { - $this->cardDav->deleteAddressBook($addressBook['id']); - } - } - - public function postUnassignedUserId($uid) { - if (isset($this->usersToDelete[$uid])) { - $this->syncService->deleteUser($this->usersToDelete[$uid]); - } - } - - public function changeUser($params) { - $user = $params['user']; - $this->syncService->updateUser($user); - } - - public function firstLogin(IUser $user = null) { - if (!is_null($user)) { - $principal = 'principals/users/' . $user->getUID(); - if ($this->calDav->getCalendarsForUserCount($principal) === 0) { - try { - $this->calDav->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [ - '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME, - '{http://apple.com/ns/ical/}calendar-color' => $this->themingDefaults->getColorPrimary(), - 'components' => 'VEVENT' - ]); - } catch (\Exception $ex) { - \OC::$server->get(LoggerInterface::class)->error('Error creating initial calendar for user', ['exception' => $ex]); - } - } - if ($this->cardDav->getAddressBooksForUserCount($principal) === 0) { - try { - $this->cardDav->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [ - '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME, - ]); - } catch (\Exception $ex) { - \OC::$server->get(LoggerInterface::class)->logException('Error creating initial addressbook for user', ['exception' => $ex]); - } - } - } - } -} diff --git a/apps/dav/lib/Listener/UserChangeListener.php b/apps/dav/lib/Listener/UserChangeListener.php new file mode 100644 index 0000000000000..d985a5d519163 --- /dev/null +++ b/apps/dav/lib/Listener/UserChangeListener.php @@ -0,0 +1,194 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Listener; + +use Exception; +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\CardDAV\SyncService; +use OCP\Defaults; +use OCP\EventDispatcher\Event; +use OCP\EventDispatcher\IEventListener; +use OCP\IUser; +use OCP\IUserManager; +use OCP\User\Events\BeforeUserDeletedEvent; +use OCP\User\Events\UserChangedEvent; +use OCP\User\Events\UserCreatedEvent; +use OCP\User\Events\UserDeletedEvent; +use Psr\Log\LoggerInterface; + +/** + * @template-implements IEventListener + */ +class UserChangeListener implements IEventListener { + + /** @var IUserManager */ + private $userManager; + + /** @var CalDavBackend */ + private $calDavBackend; + + /** @var CardDavBackend */ + private $cardDavBackend; + + /** @var Defaults */ + private $defaults; + + /** @var SyncService */ + private $syncService; + + /** @var LoggerInterface */ + private $logger; + + /** @var IUser[] */ + private $usersToDelete = []; + + /** @var array */ + private $calendarsToDelete = []; + + /** @var array */ + private $subscriptionsToDelete = []; + + /** @var array */ + private $addressBooksToDelete = []; + + private const USERS_PRINCIPAL_PREFIX = 'principals/users/'; + + public function __construct(IUserManager $userManager, CalDavBackend $calDavBackend, CardDavBackend $cardDavBackend, Defaults $defaults, SyncService $syncService, LoggerInterface $logger) { + $this->userManager = $userManager; + $this->calDavBackend = $calDavBackend; + $this->cardDavBackend = $cardDavBackend; + $this->defaults = $defaults; + $this->syncService = $syncService; + $this->logger = $logger; + } + + public function setupLegacyHooks(): void { + $this->userManager->listen('\OC\User', 'assignedUserId', function ($uid) { + $user = $this->userManager->get($uid); + if ($user) { + $this->postCreateUser($user); + } + }); + $this->userManager->listen('\OC\User', 'preUnassignedUserId', function ($uid): void { + if ($user = $this->userManager->get($uid)) { + $this->usersToDelete[$uid] = $user; + } + }); + $this->userManager->listen('\OC\User', 'postUnassignedUserId', function ($uid) { + $this->postDeleteUser($uid); + }); + } + + /** + * @throws \OCP\DB\Exception + */ + public function handle(Event $event): void { + if ($event instanceof UserCreatedEvent) { + $this->postCreateUser($event->getUser()); + } + if ($event instanceof BeforeUserDeletedEvent) { + $this->preDeleteUser($event->getUser()); + } + if ($event instanceof UserDeletedEvent) { + $this->postDeleteUser($event->getUser()->getUID()); + } + if ($event instanceof UserChangedEvent) { + $this->syncService->updateUser($event->getUser()); + } + } + + private function postCreateUser(IUser $user): void { + $this->syncService->updateUser($user); + } + + /** + * @throws \OCP\DB\Exception + */ + private function preDeleteUser(IUser $user): void { + $userPrincipalUri = self::USERS_PRINCIPAL_PREFIX . $user->getUID(); + $this->usersToDelete[$user->getUID()] = $user; + $this->calendarsToDelete = $this->calDavBackend->getUsersOwnCalendars($userPrincipalUri); + $this->subscriptionsToDelete = $this->calDavBackend->getSubscriptionsForUser($userPrincipalUri); + $this->addressBooksToDelete = $this->cardDavBackend->getUsersOwnAddressBooks($userPrincipalUri); + } + + /** + * @throws \OCP\DB\Exception + */ + private function postDeleteUser(string $uid): void { + if (isset($this->usersToDelete[$uid])) { + $this->syncService->deleteUser($this->usersToDelete[$uid]); + } + + foreach ($this->calendarsToDelete as $calendar) { + $this->calDavBackend->deleteCalendar( + $calendar['id'], + true // Make sure the data doesn't go into the trashbin, a new user with the same UID would later see it otherwise + ); + } + + foreach ($this->subscriptionsToDelete as $subscription) { + $this->calDavBackend->deleteSubscription( + $subscription['id'], + ); + } + $this->calDavBackend->deleteAllSharesByUser(self::USERS_PRINCIPAL_PREFIX . $uid); + + foreach ($this->addressBooksToDelete as $addressBook) { + $this->cardDavBackend->deleteAddressBook($addressBook['id']); + } + } + + /** + * @throws \OCP\DB\Exception + */ + public function firstLogin(IUser $user = null): void { + if (!is_null($user)) { + $principal = self::USERS_PRINCIPAL_PREFIX . $user->getUID(); + if ($this->calDavBackend->getCalendarsForUserCount($principal) === 0) { + try { + $this->calDavBackend->createCalendar($principal, CalDavBackend::PERSONAL_CALENDAR_URI, [ + '{DAV:}displayname' => CalDavBackend::PERSONAL_CALENDAR_NAME, + '{http://apple.com/ns/ical/}calendar-color' => $this->defaults->getColorPrimary(), + 'components' => 'VEVENT' + ]); + } catch (Exception $ex) { + $this->logger->error('Error creating initial calendar for user', ['exception' => $ex]); + } + } + if ($this->cardDavBackend->getAddressBooksForUserCount($principal) === 0) { + try { + $this->cardDavBackend->createAddressBook($principal, CardDavBackend::PERSONAL_ADDRESSBOOK_URI, [ + '{DAV:}displayname' => CardDavBackend::PERSONAL_ADDRESSBOOK_NAME, + ]); + } catch (Exception $ex) { + $this->logger->error('Error creating initial addressbook for user', ['exception' => $ex]); + } + } + } + } +} diff --git a/apps/dav/tests/unit/DAV/HookManagerTest.php b/apps/dav/tests/unit/DAV/HookManagerTest.php deleted file mode 100644 index 503062c75db40..0000000000000 --- a/apps/dav/tests/unit/DAV/HookManagerTest.php +++ /dev/null @@ -1,250 +0,0 @@ - - * @author Christoph Wurst - * @author Joas Schilling - * @author John Molakvoæ - * @author Lukas Reschke - * @author Morris Jobke - * @author Robin Appelman - * @author Roeland Jago Douma - * @author Thomas Citharel - * @author Thomas Müller - * - * @license AGPL-3.0 - * - * This code is free software: you can redistribute it and/or modify - * it under the terms of the GNU Affero General Public License, version 3, - * as published by the Free Software Foundation. - * - * 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, version 3, - * along with this program. If not, see - * - */ -namespace OCA\DAV\Tests\unit\DAV; - -use OCA\DAV\CalDAV\CalDavBackend; -use OCA\DAV\CardDAV\CardDavBackend; -use OCA\DAV\CardDAV\SyncService; -use OCA\DAV\HookManager; -use OCP\Defaults; -use OCP\IL10N; -use OCP\IUser; -use OCP\IUserManager; -use PHPUnit\Framework\MockObject\MockObject; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; -use Test\TestCase; - -class HookManagerTest extends TestCase { - /** @var IL10N */ - private $l10n; - - /** @var EventDispatcherInterface | MockObject */ - private $eventDispatcher; - - protected function setUp(): void { - parent::setUp(); - $this->eventDispatcher = $this->createMock(EventDispatcherInterface::class); - $this->l10n = $this->createMock(IL10N::class); - $this->l10n - ->expects($this->any()) - ->method('t') - ->willReturnCallback(function ($text, $parameters = []) { - return vsprintf($text, $parameters); - }); - } - - public function test() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once())->method('getUID')->willReturn('newUser'); - - /** @var IUserManager | MockObject $userManager */ - $userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var SyncService | MockObject $syncService */ - $syncService = $this->getMockBuilder(SyncService::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var Defaults | MockObject $syncService */ - $defaults = $this->getMockBuilder(Defaults::class) - ->disableOriginalConstructor() - ->getMock(); - - $defaults->expects($this->once())->method('getColorPrimary')->willReturn('#745bca'); - - /** @var CalDavBackend | MockObject $cal */ - $cal = $this->getMockBuilder(CalDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getCalendarsForUserCount')->willReturn(0); - $cal->expects($this->once())->method('createCalendar')->with( - 'principals/users/newUser', - 'personal', [ - '{DAV:}displayname' => 'Personal', - '{http://apple.com/ns/ical/}calendar-color' => '#745bca', - 'components' => 'VEVENT' - ]); - - /** @var CardDavBackend | MockObject $card */ - $card = $this->getMockBuilder(CardDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getAddressBooksForUserCount')->willReturn(0); - $card->expects($this->once())->method('createAddressBook')->with( - 'principals/users/newUser', - 'contacts', ['{DAV:}displayname' => 'Contacts']); - - $hm = new HookManager($userManager, $syncService, $cal, $card, $defaults, $this->eventDispatcher); - $hm->firstLogin($user); - } - - public function testWithExisting() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once())->method('getUID')->willReturn('newUser'); - - /** @var IUserManager | MockObject $userManager */ - $userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var SyncService | MockObject $syncService */ - $syncService = $this->getMockBuilder(SyncService::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var Defaults | MockObject $syncService */ - $defaults = $this->getMockBuilder(Defaults::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var CalDavBackend | MockObject $cal */ - $cal = $this->getMockBuilder(CalDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getCalendarsForUserCount')->willReturn(1); - $cal->expects($this->never())->method('createCalendar'); - - /** @var CardDavBackend | MockObject $card */ - $card = $this->getMockBuilder(CardDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getAddressBooksForUserCount')->willReturn(1); - $card->expects($this->never())->method('createAddressBook'); - - $hm = new HookManager($userManager, $syncService, $cal, $card, $defaults, $this->eventDispatcher); - $hm->firstLogin($user); - } - - public function testWithBirthdayCalendar() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - $user->expects($this->once())->method('getUID')->willReturn('newUser'); - - /** @var IUserManager | MockObject $userManager */ - $userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var SyncService | MockObject $syncService */ - $syncService = $this->getMockBuilder(SyncService::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var Defaults | MockObject $syncService */ - $defaults = $this->getMockBuilder(Defaults::class) - ->disableOriginalConstructor() - ->getMock(); - $defaults->expects($this->once())->method('getColorPrimary')->willReturn('#745bca'); - - /** @var CalDavBackend | MockObject $cal */ - $cal = $this->getMockBuilder(CalDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getCalendarsForUserCount')->willReturn(0); - $cal->expects($this->once())->method('createCalendar')->with( - 'principals/users/newUser', - 'personal', [ - '{DAV:}displayname' => 'Personal', - '{http://apple.com/ns/ical/}calendar-color' => '#745bca', - 'components' => 'VEVENT' - ]); - - /** @var CardDavBackend | MockObject $card */ - $card = $this->getMockBuilder(CardDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getAddressBooksForUserCount')->willReturn(0); - $card->expects($this->once())->method('createAddressBook')->with( - 'principals/users/newUser', - 'contacts', ['{DAV:}displayname' => 'Contacts']); - - $hm = new HookManager($userManager, $syncService, $cal, $card, $defaults, $this->eventDispatcher); - $hm->firstLogin($user); - } - - public function testDeleteCalendar() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var IUserManager | MockObject $userManager */ - $userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - $userManager->expects($this->once())->method('get')->willReturn($user); - - /** @var SyncService | MockObject $syncService */ - $syncService = $this->getMockBuilder(SyncService::class) - ->disableOriginalConstructor() - ->getMock(); - $syncService->expects($this->once()) - ->method('deleteUser'); - - /** @var Defaults | MockObject $syncService */ - $defaults = $this->getMockBuilder(Defaults::class) - ->disableOriginalConstructor() - ->getMock(); - - /** @var CalDavBackend | MockObject $cal */ - $cal = $this->getMockBuilder(CalDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $cal->expects($this->once())->method('getUsersOwnCalendars')->willReturn([ - ['id' => 'personal'] - ]); - $cal->expects($this->once())->method('getSubscriptionsForUser')->willReturn([ - ['id' => 'some-subscription'] - ]); - $cal->expects($this->once())->method('deleteCalendar')->with('personal'); - $cal->expects($this->once())->method('deleteSubscription')->with('some-subscription'); - $cal->expects($this->once())->method('deleteAllSharesByUser'); - - /** @var CardDavBackend | MockObject $card */ - $card = $this->getMockBuilder(CardDavBackend::class) - ->disableOriginalConstructor() - ->getMock(); - $card->expects($this->once())->method('getUsersOwnAddressBooks')->willReturn([ - ['id' => 'personal'] - ]); - $card->expects($this->once())->method('deleteAddressBook'); - - $hm = new HookManager($userManager, $syncService, $cal, $card, $defaults, $this->eventDispatcher); - $hm->preDeleteUser(['uid' => 'newUser']); - $hm->postDeleteUser(['uid' => 'newUser']); - } -} diff --git a/apps/dav/tests/unit/Listener/UserChangeListenerTest.php b/apps/dav/tests/unit/Listener/UserChangeListenerTest.php new file mode 100644 index 0000000000000..6f55980867839 --- /dev/null +++ b/apps/dav/tests/unit/Listener/UserChangeListenerTest.php @@ -0,0 +1,161 @@ + + * + * @author Thomas Citharel + * + * @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\DAV\Tests\Unit\Listener; + +use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\CardDAV\SyncService; +use OCA\DAV\Listener\UserChangeListener; +use OCP\DB\Exception; +use OCP\Defaults; +use OCP\IUser; +use OCP\IUserManager; +use OCP\User\Events\BeforeUserDeletedEvent; +use OCP\User\Events\UserDeletedEvent; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\LoggerInterface; +use Test\TestCase; + +class UserChangeListenerTest extends TestCase { + + /** @var IUserManager|MockObject */ + private $userManager; + + /** @var CalDavBackend|MockObject */ + private $calDavBackend; + + /** @var CardDavBackend|MockObject */ + private $cardDavBackend; + + /** @var LoggerInterface|MockObject */ + private $logger; + + /** @var Defaults|MockObject */ + private $defaults; + + /** @var SyncService|MockObject */ + private $syncService; + + /** @var UserChangeListener */ + private $listener; + + protected function setUp(): void { + parent::setUp(); + + $this->userManager = $this->createMock(IUserManager::class); + $this->calDavBackend = $this->createMock(CalDavBackend::class); + $this->cardDavBackend = $this->createMock(CardDavBackend::class); + $this->defaults = $this->createMock(Defaults::class); + $this->syncService = $this->createMock(SyncService::class); + $this->logger = $this->createMock(LoggerInterface::class); + + $this->listener = new UserChangeListener( + $this->userManager, + $this->calDavBackend, + $this->cardDavBackend, + $this->defaults, + $this->syncService, + $this->logger + ); + } + + /** + * @throws Exception + */ + public function testFirstLoginWithExisting() { + $this->calDavBackend->expects($this->once())->method('getCalendarsForUserCount')->willReturn(1); + $this->calDavBackend->expects($this->never())->method('createCalendar'); + + + $this->cardDavBackend->expects($this->once())->method('getAddressBooksForUserCount')->willReturn(1); + $this->cardDavBackend->expects($this->never())->method('createAddressBook'); + + $this->listener->firstLogin($this->createMockUser()); + } + + /** + * @throws Exception + */ + public function testFirstLoginWithBirthdayCalendar() { + $this->setupDefaultPrimaryColor(); + + $this->calDavBackend->expects($this->once())->method('getCalendarsForUserCount')->willReturn(0); + $this->calDavBackend->expects($this->once())->method('createCalendar')->with( + 'principals/users/newUser', + 'personal', [ + '{DAV:}displayname' => 'Personal', + '{http://apple.com/ns/ical/}calendar-color' => '#745bca', + 'components' => 'VEVENT' + ]); + + $this->cardDavBackend->expects($this->once())->method('getAddressBooksForUserCount')->willReturn(0); + $this->cardDavBackend->expects($this->once())->method('createAddressBook')->with( + 'principals/users/newUser', + 'contacts', ['{DAV:}displayname' => 'Contacts']); + + $this->listener->firstLogin($this->createMockUser()); + } + + /** + * @throws Exception + */ + public function testDeleteCalendar() { + $user = $this->createMock(IUser::class); + $user->expects($this->any())->method('getUID')->willReturn('newUser'); + + $this->syncService->expects($this->once())->method('deleteUser'); + + $this->calDavBackend->expects($this->once())->method('getUsersOwnCalendars')->willReturn([ + ['id' => 'personal'] + ]); + $this->calDavBackend->expects($this->once())->method('getSubscriptionsForUser')->willReturn([ + ['id' => 'some-subscription'] + ]); + $this->calDavBackend->expects($this->once())->method('deleteCalendar')->with('personal'); + $this->calDavBackend->expects($this->once())->method('deleteSubscription')->with('some-subscription'); + $this->calDavBackend->expects($this->once())->method('deleteAllSharesByUser'); + + $this->cardDavBackend->expects($this->once())->method('getUsersOwnAddressBooks')->willReturn([ + ['id' => 'personal'] + ]); + $this->cardDavBackend->expects($this->once())->method('deleteAddressBook'); + + $preDeleteEvent = new BeforeUserDeletedEvent($user); + $postDeleteEvent = new UserDeletedEvent($user); + $this->listener->handle($preDeleteEvent); + $this->listener->handle($postDeleteEvent); + } + + private function createMockUser() { + $user = $this->createMock(IUser::class); + $user->expects($this->once())->method('getUID')->willReturn('newUser'); + return $user; + } + + private function setupDefaultPrimaryColor(): void { + $this->defaults->expects($this->once())->method('getColorPrimary')->willReturn('#745bca'); + } +} From 7a5f4afd3285727ae7f51b83fb9ca2129aca2cc9 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 10:40:24 +0100 Subject: [PATCH 15/23] Modernize endpoints Signed-off-by: Thomas Citharel --- apps/dav/appinfo/v1/caldav.php | 108 +++++++++++++++++--------- apps/dav/appinfo/v1/carddav.php | 98 ++++++++++++++++------- apps/dav/appinfo/v1/publicwebdav.php | 96 +++++++++++++++-------- apps/dav/appinfo/v1/webdav.php | 76 +++++++++++------- apps/dav/appinfo/v2/direct.php | 28 ++++--- apps/dav/appinfo/v2/remote.php | 9 ++- apps/dav/bin/chunkperf.php | 17 ++-- apps/dav/lib/Connector/Sabre/Auth.php | 5 +- apps/dav/lib/Server.php | 59 +++++++++----- 9 files changed, 326 insertions(+), 170 deletions(-) diff --git a/apps/dav/appinfo/v1/caldav.php b/apps/dav/appinfo/v1/caldav.php index 260192b4d9b08..4caa355ac21a8 100644 --- a/apps/dav/appinfo/v1/caldav.php +++ b/apps/dav/appinfo/v1/caldav.php @@ -26,8 +26,13 @@ * */ // Backends +use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; use OC\KnownUser\KnownUserService; +use OC\Security\Bruteforce\Throttler; use OCA\DAV\CalDAV\CalDavBackend; +use OCA\DAV\CalDAV\Proxy\ProxyMapper; +use OCA\DAV\CalDAV\Schedule\IMipPlugin; +use OCA\DAV\CalDAV\Schedule\Plugin as SchedulePlugin; use OCA\DAV\Connector\LegacyDAVACL; use OCA\DAV\CalDAV\CalendarRoot; use OCA\DAV\Connector\Sabre\Auth; @@ -35,51 +40,78 @@ use OCA\DAV\Connector\Sabre\MaintenancePlugin; use OCA\DAV\Connector\Sabre\Principal; use Psr\Log\LoggerInterface; +use OCP\App\IAppManager; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IRequest; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\L10N\IFactory as IL10NFactory; +use OCP\Security\ISecureRandom; +use OCP\Share\IManager as IShareManager; +use Sabre\CalDAV\ICSExportPlugin; +use Sabre\CalDAV\Plugin as CalDAVPlugin; +use Sabre\CalDAV\Principal\Collection; +use Sabre\DAV\Auth\Plugin as AuthPlugin; +use Sabre\DAV\Browser\Plugin as BrowserPlugin; +use Sabre\DAV\Server; +use Sabre\DAV\Sync\Plugin as SyncPlugin; + +/** @var IUserSession $userSession */ +$userSession = \OC::$server->get(IUserSession::class); +/** @var IRequest $request */ +$request = \OC::$server->get(IRequest::class); +/** @var IUserManager $userManager */ +$userManager = \OC::$server->get(IUserManager::class); +/** @var IGroupManager $groupManager */ +$groupManager = \OC::$server->get(IGroupManager::class); +/** @var IConfig $config */ +$config = \OC::$server->get(IConfig::class); +/** @var IL10NFactory $l10nFactory */ +$l10nFactory = \OC::$server->get(IL10NFactory::class); +/** @var LoggerInterface $logger */ +$logger = \OC::$server->get(LoggerInterface::class); $authBackend = new Auth( - \OC::$server->getSession(), - \OC::$server->getUserSession(), - \OC::$server->getRequest(), - \OC::$server->getTwoFactorAuthManager(), - \OC::$server->getBruteForceThrottler(), + $userSession->getSession(), + $userSession, + $request, + \OC::$server->get(TwoFactorAuthManager::class), + \OC::$server->get(Throttler::class), 'principals/' ); $principalBackend = new Principal( - \OC::$server->getUserManager(), - \OC::$server->getGroupManager(), - \OC::$server->getShareManager(), - \OC::$server->getUserSession(), - \OC::$server->getAppManager(), - \OC::$server->query(\OCA\DAV\CalDAV\Proxy\ProxyMapper::class), + $userManager, + $groupManager, + \OC::$server->get(IShareManager::class), + $userSession, + \OC::$server->get(IAppManager::class), + \OC::$server->get(ProxyMapper::class), \OC::$server->get(KnownUserService::class), - \OC::$server->getConfig(), - \OC::$server->getL10NFactory(), + $config, + $l10nFactory, 'principals/' ); -$db = \OC::$server->getDatabaseConnection(); -$userManager = \OC::$server->getUserManager(); -$random = \OC::$server->getSecureRandom(); -$logger = \OC::$server->getLogger(); -$dispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class); -$config = \OC::$server->get(\OCP\IConfig::class); $calDavBackend = new CalDavBackend( - $db, + \OC::$server->get(IDBConnection::class), $principalBackend, $userManager, - \OC::$server->getGroupManager(), - $random, + $groupManager, + \OC::$server->get(ISecureRandom::class), $logger, - $dispatcher, + \OC::$server->get(IEventDispatcher::class), $config, true ); -$debugging = \OC::$server->getConfig()->getSystemValue('debug', false); -$sendInvitations = \OC::$server->getConfig()->getAppValue('dav', 'sendInvitations', 'yes') === 'yes'; +$debugging = $config->getSystemValue('debug', false); +$sendInvitations = $config->getAppValue('dav', 'sendInvitations', 'yes') === 'yes'; // Root nodes -$principalCollection = new \Sabre\CalDAV\Principal\Collection($principalBackend); +$principalCollection = new Collection($principalBackend); $principalCollection->disableListing = !$debugging; // Disable listing $addressBookRoot = new CalendarRoot($principalBackend, $calDavBackend, 'principals', \OC::$server->get(LoggerInterface::class)); @@ -91,29 +123,29 @@ ]; // Fire up server -$server = new \Sabre\DAV\Server($nodes); +$server = new Server($nodes); $server::$exposeVersion = false; -$server->httpRequest->setUrl(\OC::$server->getRequest()->getRequestUri()); +$server->httpRequest->setUrl($request->getRequestUri()); $server->setBaseUri($baseuri); // Add plugins -$server->addPlugin(new MaintenancePlugin(\OC::$server->getConfig(), \OC::$server->getL10N('dav'))); -$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend, 'ownCloud')); -$server->addPlugin(new \Sabre\CalDAV\Plugin()); +$server->addPlugin(new MaintenancePlugin($config, $l10nFactory->get('dav'))); +$server->addPlugin(new AuthPlugin($authBackend)); +$server->addPlugin(new CalDAVPlugin()); $server->addPlugin(new LegacyDAVACL()); if ($debugging) { - $server->addPlugin(new Sabre\DAV\Browser\Plugin()); + $server->addPlugin(new BrowserPlugin()); } -$server->addPlugin(new \Sabre\DAV\Sync\Plugin()); -$server->addPlugin(new \Sabre\CalDAV\ICSExportPlugin()); -$server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->getConfig())); +$server->addPlugin(new SyncPlugin()); +$server->addPlugin(new ICSExportPlugin()); +$server->addPlugin(new SchedulePlugin($config)); if ($sendInvitations) { - $server->addPlugin(\OC::$server->query(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class)); + $server->addPlugin(\OC::$server->get(IMipPlugin::class)); } -$server->addPlugin(new ExceptionLoggerPlugin('caldav', \OC::$server->getLogger())); +$server->addPlugin(new ExceptionLoggerPlugin('caldav', $logger)); // And off we go! -$server->exec(); +$server->start(); diff --git a/apps/dav/appinfo/v1/carddav.php b/apps/dav/appinfo/v1/carddav.php index 1b694f84d1db9..3474d61c2727a 100644 --- a/apps/dav/appinfo/v1/carddav.php +++ b/apps/dav/appinfo/v1/carddav.php @@ -8,6 +8,7 @@ * @author John Molakvoæ * @author Lukas Reschke * @author Morris Jobke + * @author Thomas Citharel * @author Thomas Müller * * @license AGPL-3.0 @@ -26,48 +27,85 @@ * */ // Backends +use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; +use OC\Files\AppData\Factory as AppDataFactory; use OC\KnownUser\KnownUserService; +use OC\Security\Bruteforce\Throttler; use OCA\DAV\AppInfo\PluginManager; +use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\CardDAV\AddressBookRoot; use OCA\DAV\CardDAV\CardDavBackend; +use OCA\DAV\CardDAV\ImageExportPlugin; +use OCA\DAV\CardDAV\PhotoCache; use OCA\DAV\Connector\LegacyDAVACL; use OCA\DAV\Connector\Sabre\Auth; use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin; use OCA\DAV\Connector\Sabre\MaintenancePlugin; use OCA\DAV\Connector\Sabre\Principal; use OCP\App\IAppManager; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IGroupManager; +use OCP\IRequest; +use OCP\IUserManager; +use OCP\IUserSession; +use OCP\L10N\IFactory as IL10NFactory; +use OCP\Share\IManager as IShareManager; +use Psr\Log\LoggerInterface; +use Sabre\CalDAV\Principal\Collection; use Sabre\CardDAV\Plugin; +use Sabre\CardDAV\VCFExportPlugin; +use Sabre\DAV\Auth\Plugin as AuthPlugin; +use Sabre\DAV\Browser\Plugin as BrowserPlugin; +use Sabre\DAV\Server; +use Sabre\DAV\Sync\Plugin as SyncPlugin; + +/** @var IUserSession $userSession */ +$userSession = \OC::$server->get(IUserSession::class); +/** @var IRequest $request */ +$request = \OC::$server->get(IRequest::class); +/** @var IUserManager $userManager */ +$userManager = \OC::$server->get(IUserManager::class); +/** @var IGroupManager $groupManager */ +$groupManager = \OC::$server->get(IGroupManager::class); +/** @var IConfig $config */ +$config = \OC::$server->get(IConfig::class); +/** @var IL10NFactory $l10nFactory */ +$l10nFactory = \OC::$server->get(IL10NFactory::class); +/** @var LoggerInterface $logger */ +$logger = \OC::$server->get(LoggerInterface::class); $authBackend = new Auth( - \OC::$server->getSession(), - \OC::$server->getUserSession(), - \OC::$server->getRequest(), - \OC::$server->getTwoFactorAuthManager(), - \OC::$server->getBruteForceThrottler(), + $userSession->getSession(), + $userSession, + $request, + \OC::$server->get(TwoFactorAuthManager::class), + \OC::$server->get(Throttler::class), 'principals/' ); $principalBackend = new Principal( - \OC::$server->getUserManager(), - \OC::$server->getGroupManager(), - \OC::$server->getShareManager(), - \OC::$server->getUserSession(), - \OC::$server->getAppManager(), - \OC::$server->query(\OCA\DAV\CalDAV\Proxy\ProxyMapper::class), + $userManager, + $groupManager, + \OC::$server->get(IShareManager::class), + $userSession, + \OC::$server->get(IAppManager::class), + \OC::$server->get(ProxyMapper::class), \OC::$server->get(KnownUserService::class), - \OC::$server->getConfig(), - \OC::$server->getL10NFactory(), + $config, + $l10nFactory, 'principals/' ); -$db = \OC::$server->getDatabaseConnection(); -$cardDavBackend = new CardDavBackend($db, $principalBackend, \OC::$server->getUserManager(), \OC::$server->getGroupManager(), \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class)); -$debugging = \OC::$server->getConfig()->getSystemValue('debug', false); +$cardDavBackend = new CardDavBackend(\OC::$server->get(IDBConnection::class), $principalBackend, $userManager, $groupManager, \OC::$server->get(IEventDispatcher::class)); + +$debugging = $config->getSystemValue('debug', false); // Root nodes -$principalCollection = new \Sabre\CalDAV\Principal\Collection($principalBackend); +$principalCollection = new Collection($principalBackend); $principalCollection->disableListing = !$debugging; // Disable listing -$pluginManager = new PluginManager(\OC::$server, \OC::$server->query(IAppManager::class)); +$pluginManager = new PluginManager(\OC::$server, \OC::$server->get(IAppManager::class)); $addressBookRoot = new AddressBookRoot($principalBackend, $cardDavBackend, $pluginManager); $addressBookRoot->disableListing = !$debugging; // Disable listing @@ -77,27 +115,27 @@ ]; // Fire up server -$server = new \Sabre\DAV\Server($nodes); +$server = new Server($nodes); $server::$exposeVersion = false; -$server->httpRequest->setUrl(\OC::$server->getRequest()->getRequestUri()); +$server->httpRequest->setUrl($request->getRequestUri()); $server->setBaseUri($baseuri); // Add plugins -$server->addPlugin(new MaintenancePlugin(\OC::$server->getConfig(), \OC::$server->getL10N('dav'))); -$server->addPlugin(new \Sabre\DAV\Auth\Plugin($authBackend, 'ownCloud')); +$server->addPlugin(new MaintenancePlugin($config, $l10nFactory->get('dav'))); +$server->addPlugin(new AuthPlugin($authBackend)); $server->addPlugin(new Plugin()); $server->addPlugin(new LegacyDAVACL()); if ($debugging) { - $server->addPlugin(new Sabre\DAV\Browser\Plugin()); + $server->addPlugin(new BrowserPlugin()); } -$server->addPlugin(new \Sabre\DAV\Sync\Plugin()); -$server->addPlugin(new \Sabre\CardDAV\VCFExportPlugin()); -$server->addPlugin(new \OCA\DAV\CardDAV\ImageExportPlugin(new \OCA\DAV\CardDAV\PhotoCache( - \OC::$server->getAppDataDir('dav-photocache'), - \OC::$server->getLogger() +$server->addPlugin(new SyncPlugin()); +$server->addPlugin(new VCFExportPlugin()); +$server->addPlugin(new ImageExportPlugin(new PhotoCache( + \OC::$server->get(AppDataFactory::class)->get('dav-photocache'), + $logger ))); -$server->addPlugin(new ExceptionLoggerPlugin('carddav', \OC::$server->getLogger())); +$server->addPlugin(new ExceptionLoggerPlugin('carddav', $logger)); // And off we go! -$server->exec(); +$server->start(); diff --git a/apps/dav/appinfo/v1/publicwebdav.php b/apps/dav/appinfo/v1/publicwebdav.php index c99c5bcd83399..3585f490ca4da 100644 --- a/apps/dav/appinfo/v1/publicwebdav.php +++ b/apps/dav/appinfo/v1/publicwebdav.php @@ -11,6 +11,7 @@ * @author Morris Jobke * @author Robin Appelman * @author Roeland Jago Douma + * @author Thomas Citharel * @author Thomas Müller * @author Vincent Petry * @@ -29,68 +30,97 @@ * along with this program. If not, see * */ + +use OC\Files\Filesystem; +use OC\Files\Storage\Wrapper\PermissionsMask; +use OC\Files\View; +use OC\Security\Bruteforce\Throttler; +use OCA\DAV\Files\Sharing\FilesDropPlugin; +use OCA\DAV\Files\Sharing\PublicLinkCheckPlugin; +use OCA\DAV\Storage\PublicOwnerWrapper; +use OCA\FederatedFileSharing\FederatedShareProvider; +use OCP\Constants; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\Mount\IMountManager; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IPreview; +use OCP\IRequest; +use OCP\ITagManager; +use OCP\IUserSession; +use OCP\L10N\IFactory as IL10NFactory; +use OCP\Share\IManager as IShareManager; +use Psr\Log\LoggerInterface; +use Sabre\DAV\Auth\Plugin as AuthPlugin; +use Sabre\DAV\Exception\NotAuthenticated; +use Sabre\DAV\Server; + // load needed apps $RUNTIME_APPTYPES = ['filesystem', 'authentication', 'logging']; +/** @var IUserSession $userSession */ +$userSession = \OC::$server->get(IUserSession::class); +/** @var IRequest $request */ +$request = \OC::$server->get(IRequest::class); + OC_App::loadApps($RUNTIME_APPTYPES); OC_Util::obEnd(); -\OC::$server->getSession()->close(); +$userSession->getSession()->close(); // Backends $authBackend = new OCA\DAV\Connector\PublicAuth( - \OC::$server->getRequest(), - \OC::$server->getShareManager(), - \OC::$server->getSession(), - \OC::$server->getBruteForceThrottler() + $request, + \OC::$server->get(IShareManager::class), + $userSession->getSession(), + \OC::$server->get(Throttler::class) ); -$authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend); +$authPlugin = new AuthPlugin($authBackend); $serverFactory = new OCA\DAV\Connector\Sabre\ServerFactory( - \OC::$server->getConfig(), - \OC::$server->getLogger(), - \OC::$server->getDatabaseConnection(), - \OC::$server->getUserSession(), - \OC::$server->getMountManager(), - \OC::$server->getTagManager(), - \OC::$server->getRequest(), - \OC::$server->getPreviewManager(), - \OC::$server->getEventDispatcher(), - \OC::$server->getL10N('dav') + \OC::$server->get(IConfig::class), + \OC::$server->get(LoggerInterface::class), + \OC::$server->get(IDBConnection::class), + $userSession, + \OC::$server->get(IMountManager::class), + \OC::$server->get(ITagManager::class), + $request, + \OC::$server->get(IPreview::class), + \OC::$server->get(IEventDispatcher::class), + \OC::$server->get(IL10NFactory::class)->get('dav') ); -$requestUri = \OC::$server->getRequest()->getRequestUri(); -$linkCheckPlugin = new \OCA\DAV\Files\Sharing\PublicLinkCheckPlugin(); -$filesDropPlugin = new \OCA\DAV\Files\Sharing\FilesDropPlugin(); +$linkCheckPlugin = new PublicLinkCheckPlugin(); +$filesDropPlugin = new FilesDropPlugin(); -$server = $serverFactory->createServer($baseuri, $requestUri, $authPlugin, function (\Sabre\DAV\Server $server) use ($authBackend, $linkCheckPlugin, $filesDropPlugin) { +$server = $serverFactory->createServer($baseuri, $request->getRequestUri(), $authPlugin, function (Server $server) use ($authBackend, $linkCheckPlugin, $filesDropPlugin) { $isAjax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest'); - /** @var \OCA\FederatedFileSharing\FederatedShareProvider $shareProvider */ - $federatedShareProvider = \OC::$server->query(\OCA\FederatedFileSharing\FederatedShareProvider::class); + /** @var FederatedShareProvider $shareProvider */ + $federatedShareProvider = \OC::$server->get(FederatedShareProvider::class); if ($federatedShareProvider->isOutgoingServer2serverShareEnabled() === false && !$isAjax) { // this is what is thrown when trying to access a non-existing share - throw new \Sabre\DAV\Exception\NotAuthenticated(); + throw new NotAuthenticated(); } $share = $authBackend->getShare(); $owner = $share->getShareOwner(); - $isReadable = $share->getPermissions() & \OCP\Constants::PERMISSION_READ; + $isReadable = $share->getPermissions() & Constants::PERMISSION_READ; $fileId = $share->getNodeId(); // FIXME: should not add storage wrappers outside of preSetup, need to find a better way - $previousLog = \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper(false); - \OC\Files\Filesystem::addStorageWrapper('sharePermissions', function ($mountPoint, $storage) use ($share) { - return new \OC\Files\Storage\Wrapper\PermissionsMask(['storage' => $storage, 'mask' => $share->getPermissions() | \OCP\Constants::PERMISSION_SHARE]); + $previousLog = Filesystem::logWarningWhenAddingStorageWrapper(false); + Filesystem::addStorageWrapper('sharePermissions', function ($mountPoint, $storage) use ($share) { + return new PermissionsMask(['storage' => $storage, 'mask' => $share->getPermissions() | Constants::PERMISSION_SHARE]); }); - \OC\Files\Filesystem::addStorageWrapper('shareOwner', function ($mountPoint, $storage) use ($share) { - return new \OCA\DAV\Storage\PublicOwnerWrapper(['storage' => $storage, 'owner' => $share->getShareOwner()]); + Filesystem::addStorageWrapper('shareOwner', function ($mountPoint, $storage) use ($share) { + return new PublicOwnerWrapper(['storage' => $storage, 'owner' => $share->getShareOwner()]); }); - \OC\Files\Filesystem::logWarningWhenAddingStorageWrapper($previousLog); + Filesystem::logWarningWhenAddingStorageWrapper($previousLog); OC_Util::tearDownFS(); OC_Util::setupFS($owner); - $ownerView = new \OC\Files\View('/'. $owner . '/files'); + $ownerView = new View('/'. $owner . '/files'); $path = $ownerView->getPath($fileId); $fileInfo = $ownerView->getFileInfo($path); $linkCheckPlugin->setFileInfo($fileInfo); @@ -100,7 +130,7 @@ $filesDropPlugin->enable(); } - $view = new \OC\Files\View($ownerView->getAbsolutePath($path)); + $view = new View($ownerView->getAbsolutePath($path)); $filesDropPlugin->setView($view); return $view; @@ -110,4 +140,4 @@ $server->addPlugin($filesDropPlugin); // And off we go! -$server->exec(); +$server->start(); diff --git a/apps/dav/appinfo/v1/webdav.php b/apps/dav/appinfo/v1/webdav.php index 44130da0f28e7..729cda1a7f737 100644 --- a/apps/dav/appinfo/v1/webdav.php +++ b/apps/dav/appinfo/v1/webdav.php @@ -10,6 +10,7 @@ * @author Morris Jobke * @author Robin Appelman * @author Roeland Jago Douma + * @author Thomas Citharel * @author Thomas Müller * @author Vincent Petry * @@ -29,7 +30,23 @@ * */ // no php execution timeout for webdav +use OC\Authentication\TwoFactorAuth\Manager; +use OC\Files\Filesystem; +use OC\Security\Bruteforce\Throttler; +use OCA\DAV\Connector\Sabre\BearerAuth; use OCA\DAV\Events\SabreAddPluginEvent; +use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\Mount\IMountManager; +use OCP\IConfig; +use OCP\IDBConnection; +use OCP\IPreview; +use OCP\IRequest; +use OCP\ITagManager; +use OCP\IUserSession; +use OCP\L10N\IFactory as IL10NFactory; +use OCP\SabrePluginEvent; +use Psr\Log\LoggerInterface; +use Sabre\DAV\Auth\Plugin as AuthPlugin; if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { @set_time_limit(0); @@ -39,49 +56,52 @@ // Turn off output buffering to prevent memory problems \OC_Util::obEnd(); -$serverFactory = new \OCA\DAV\Connector\Sabre\ServerFactory( - \OC::$server->getConfig(), - \OC::$server->getLogger(), - \OC::$server->getDatabaseConnection(), - \OC::$server->getUserSession(), - \OC::$server->getMountManager(), - \OC::$server->getTagManager(), - \OC::$server->getRequest(), - \OC::$server->getPreviewManager(), - \OC::$server->getEventDispatcher(), - \OC::$server->getL10N('dav') +/** @var IUserSession $userSession */ +$userSession = \OC::$server->get(IUserSession::class); +/** @var IRequest $request */ +$request = \OC::$server->get(IRequest::class); + +$serverFactory = new OCA\DAV\Connector\Sabre\ServerFactory( + \OC::$server->get(IConfig::class), + \OC::$server->get(LoggerInterface::class), + \OC::$server->get(IDBConnection::class), + $userSession, + \OC::$server->get(IMountManager::class), + \OC::$server->get(ITagManager::class), + $request, + \OC::$server->get(IPreview::class), + \OC::$server->get(IEventDispatcher::class), + \OC::$server->get(IL10NFactory::class)->get('dav') ); // Backends $authBackend = new \OCA\DAV\Connector\Sabre\Auth( - \OC::$server->getSession(), - \OC::$server->getUserSession(), - \OC::$server->getRequest(), - \OC::$server->getTwoFactorAuthManager(), - \OC::$server->getBruteForceThrottler(), + $userSession->getSession(), + $userSession, + $request, + \OC::$server->get(Manager::class), + \OC::$server->get(Throttler::class), 'principals/' ); -$authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend); -$bearerAuthPlugin = new \OCA\DAV\Connector\Sabre\BearerAuth( - \OC::$server->getUserSession(), - \OC::$server->getSession(), - \OC::$server->getRequest() +$authPlugin = new AuthPlugin($authBackend); +$bearerAuthPlugin = new BearerAuth( + $userSession, + $userSession->getSession(), + $request ); $authPlugin->addBackend($bearerAuthPlugin); -$requestUri = \OC::$server->getRequest()->getRequestUri(); - -$server = $serverFactory->createServer($baseuri, $requestUri, $authPlugin, function () { +$server = $serverFactory->createServer($baseuri, $request->getRequestUri(), $authPlugin, function () { // use the view for the logged in user - return \OC\Files\Filesystem::getView(); + return Filesystem::getView(); }); $dispatcher = \OC::$server->getEventDispatcher(); -$newDispatcher = \OC::$server->get(\OCP\EventDispatcher\IEventDispatcher::class); +$newDispatcher = \OC::$server->get(IEventDispatcher::class); // allow setup of additional plugins $newDispatcher->dispatchTyped(new SabreAddPluginEvent($server)); -$event = new \OCP\SabrePluginEvent($server); +$event = new SabrePluginEvent($server); $dispatcher->dispatch('OCA\DAV\Connector\Sabre::addPlugin', $event); // And off we go! -$server->exec(); +$server->start(); diff --git a/apps/dav/appinfo/v2/direct.php b/apps/dav/appinfo/v2/direct.php index cab6109e5e62d..9073b561b1a13 100644 --- a/apps/dav/appinfo/v2/direct.php +++ b/apps/dav/appinfo/v2/direct.php @@ -7,6 +7,7 @@ * * @author Robin Appelman * @author Roeland Jago Douma + * @author Thomas Citharel * * @license GNU AGPL version 3 or any later version * @@ -24,7 +25,13 @@ * along with this program. If not, see . * */ -use \OCA\DAV\Direct\ServerFactory; + +use OC\Security\Bruteforce\Throttler; +use OCA\DAV\Db\DirectMapper; +use OCA\DAV\Direct\ServerFactory; +use OCP\AppFramework\Utility\ITimeFactory; +use OCP\Files\IRootFolder; +use OCP\IRequest; // no php execution timeout for webdav if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { @@ -35,18 +42,19 @@ // Turn off output buffering to prevent memory problems \OC_Util::obEnd(); -$requestUri = \OC::$server->getRequest()->getRequestUri(); +/** @var IRequest $request */ +$request = \OC::$server->get(IRequest::class); /** @var ServerFactory $serverFactory */ -$serverFactory = \OC::$server->query(ServerFactory::class); +$serverFactory = \OC::$server->get(ServerFactory::class); $server = $serverFactory->createServer( $baseuri, - $requestUri, - \OC::$server->getRootFolder(), - \OC::$server->query(\OCA\DAV\Db\DirectMapper::class), - \OC::$server->query(\OCP\AppFramework\Utility\ITimeFactory::class), - \OC::$server->getBruteForceThrottler(), - \OC::$server->getRequest() + $request->getRequestUri(), + \OC::$server->get(IRootFolder::class), + \OC::$server->get(DirectMapper::class), + \OC::$server->get(ITimeFactory::class), + \OC::$server->get(Throttler::class), + $request ); -$server->exec(); +$server->start(); diff --git a/apps/dav/appinfo/v2/remote.php b/apps/dav/appinfo/v2/remote.php index de2ba989f8dab..9eb424c987167 100644 --- a/apps/dav/appinfo/v2/remote.php +++ b/apps/dav/appinfo/v2/remote.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Ko- + * @author Thomas Citharel * @author Thomas Müller * @author Vincent Petry * @@ -22,6 +23,9 @@ * */ // no php execution timeout for webdav +use OCA\DAV\Server; +use OCP\IRequest; + if (strpos(@ini_get('disable_functions'), 'set_time_limit') === false) { @set_time_limit(0); } @@ -30,6 +34,5 @@ // Turn off output buffering to prevent memory problems \OC_Util::obEnd(); -$request = \OC::$server->getRequest(); -$server = new \OCA\DAV\Server($request, $baseuri); -$server->exec(); +$server = new Server(\OC::$server->get(IRequest::class), $baseuri); +$server->start(); diff --git a/apps/dav/bin/chunkperf.php b/apps/dav/bin/chunkperf.php index a8652654bca07..72a204d15eea3 100644 --- a/apps/dav/bin/chunkperf.php +++ b/apps/dav/bin/chunkperf.php @@ -3,6 +3,7 @@ * @copyright Copyright (c) 2016, ownCloud, Inc. * * @author Christoph Wurst + * @author Thomas Citharel * @author Thomas Müller * * @license AGPL-3.0 @@ -20,6 +21,9 @@ * along with this program. If not, see * */ + +use Sabre\DAV\Client; + require '../../../../3rdparty/autoload.php'; if ($argc !== 6) { @@ -28,11 +32,14 @@ } /** - * @param \Sabre\DAV\Client $client - * @param $uploadUrl - * @return mixed + * @param Client $client + * @param string $method + * @param string $uploadUrl + * @param string|null $data + * @param array $headers + * @return array */ -function request($client, $method, $uploadUrl, $data = null, $headers = []) { +function request(Client $client, string $method, string $uploadUrl, string $data = null, array $headers = []): array { echo "$method $uploadUrl ... "; $t0 = microtime(true); $result = $client->request($method, $uploadUrl, $data, $headers); @@ -50,7 +57,7 @@ function request($client, $method, $uploadUrl, $data = null, $headers = []) { $file = $argv[4]; $chunkSize = $argv[5] * 1024 * 1024; -$client = new \Sabre\DAV\Client([ +$client = new Client([ 'baseUri' => $baseUri, 'userName' => $userName, 'password' => $password diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index 6a339062951e7..fb314f514fb84 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -41,6 +41,7 @@ use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden; use OCP\IRequest; use OCP\ISession; +use OCP\IUserSession; use Psr\Log\LoggerInterface; use Sabre\DAV\Auth\Backend\AbstractBasic; use Sabre\DAV\Exception\NotAuthenticated; @@ -73,11 +74,11 @@ class Auth extends AbstractBasic { * @param string $principalPrefix */ public function __construct(ISession $session, - Session $userSession, + IUserSession $userSession, IRequest $request, Manager $twoFactorManager, Throttler $throttler, - $principalPrefix = 'principals/users/') { + string $principalPrefix = 'principals/users/') { $this->session = $session; $this->userSession = $userSession; $this->twoFactorManager = $twoFactorManager; diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index da7c08bb9cedd..eb994a3471987 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -36,8 +36,17 @@ use OCP\Diagnostics\IEventLogger; use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; +use OC\EventDispatcher\SymfonyAdapter; use OC\Security\Bruteforce\Throttler; +use OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin; +use OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin; +use OCA\DAV\CalDAV\Publishing\PublishPlugin; +use OCA\DAV\CalDAV\Schedule\IMipPlugin; +use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin; +use OCA\DAV\Connector\Sabre\LockPlugin; +use OCA\DAV\Connector\Sabre\MaintenancePlugin; use OCA\DAV\Events\SabreAddPluginEvent; +use OCA\DAV\Files\FileSearchBackend; use OCP\App\IAppManager; use OCP\Comments\ICommentsManager; use OCP\Files\IRootFolder; @@ -49,6 +58,7 @@ use OCP\IURLGenerator; use OCP\IUserSession; use OCP\L10N\IFactory; +use OCP\SabrePluginEvent; use OCP\Share\IManager; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; @@ -108,15 +118,15 @@ public function __construct(IRequest $request, $baseUri) { $this->request = $request; $this->baseUri = $baseUri; $logger = \OC::$server->get(LoggerInterface::class); - $dispatcher = \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class); + $dispatcher = \OC::$server->get(SymfonyAdapter::class); /** @var IEventDispatcher $newDispatcher */ $newDispatcher = \OC::$server->get(IEventDispatcher::class); $root = new RootCollection(); - $this->server = new \OCA\DAV\Connector\Sabre\Server(new CachingTree($root)); + $this->server = new Connector\Sabre\Server(new CachingTree($root)); // Add maintenance plugin - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin(\OC::$server->get(IConfig::class), \OC::$server->get(IFactory::class)->get('dav'))); + $this->server->addPlugin(new MaintenancePlugin(\OC::$server->get(IConfig::class), \OC::$server->get(IFactory::class)->get('dav'))); // Backends $authBackend = new Auth( @@ -158,8 +168,8 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin(new DummyGetResponsePlugin()); } - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $logger)); - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin()); + $this->server->addPlugin(new ExceptionLoggerPlugin('webdav', $logger)); + $this->server->addPlugin(new LockPlugin()); $this->server->addPlugin(new \Sabre\DAV\Sync\Plugin()); // acl @@ -174,20 +184,20 @@ public function __construct(IRequest $request, $baseUri) { // calendar plugins if ($this->requestIsForSubtree(['calendars', 'public-calendars', 'system-calendars', 'principals'])) { - $this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin()); - $this->server->addPlugin(new \OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin(\OC::$server->get(IConfig::class), \OC::$server->get(LoggerInterface::class))); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); + $this->server->addPlugin(new CalDAV\Plugin()); + $this->server->addPlugin(new ICSExportPlugin(\OC::$server->get(IConfig::class), \OC::$server->get(LoggerInterface::class))); + $this->server->addPlugin(new CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); if (\OC::$server->get(IConfig::class)->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') { - $this->server->addPlugin(\OC::$server->get(\OCA\DAV\CalDAV\Schedule\IMipPlugin::class)); + $this->server->addPlugin(\OC::$server->get(IMipPlugin::class)); } - $this->server->addPlugin(\OC::$server->get(\OCA\DAV\CalDAV\Trashbin\Plugin::class)); - $this->server->addPlugin(new \OCA\DAV\CalDAV\WebcalCaching\Plugin($request)); + $this->server->addPlugin(\OC::$server->get(CalDAV\Trashbin\Plugin::class)); + $this->server->addPlugin(new CalDAV\WebcalCaching\Plugin($request)); $this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin()); $this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin()); $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->get(IRequest::class), \OC::$server->get(IConfig::class))); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Publishing\PublishPlugin( + $this->server->addPlugin(new PublishPlugin( \OC::$server->get(IConfig::class), \OC::$server->get(IURLGenerator::class) )); @@ -196,7 +206,7 @@ public function __construct(IRequest $request, $baseUri) { // addressbook plugins if ($this->requestIsForSubtree(['addressbooks', 'principals'])) { $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->get(IRequest::class), \OC::$server->get(IConfig::class))); - $this->server->addPlugin(new \OCA\DAV\CardDAV\Plugin()); + $this->server->addPlugin(new CardDAV\Plugin()); $this->server->addPlugin(new VCFExportPlugin()); $this->server->addPlugin(new MultiGetExportPlugin()); $this->server->addPlugin(new HasPhotoPlugin()); @@ -225,7 +235,7 @@ public function __construct(IRequest $request, $baseUri) { // allow setup of additional plugins $newDispatcher->dispatchTyped(new SabreAddPluginEvent($this->server)); - $event = new \OCP\SabrePluginEvent($this->server); + $event = new SabrePluginEvent($this->server); $dispatcher->dispatch('OCA\DAV\Connector\Sabre::addPlugin', $event); // Some WebDAV clients do require Class 2 WebDAV support (locking), since @@ -294,7 +304,7 @@ public function __construct(IRequest $request, $baseUri) { \OC::$server->get(ICommentsManager::class), $userSession )); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Search\SearchPlugin()); + $this->server->addPlugin(new CalDAV\Search\SearchPlugin()); if ($view !== null) { $this->server->addPlugin(new FilesReportPlugin( $this->server->tree, @@ -307,7 +317,7 @@ public function __construct(IRequest $request, $baseUri) { $userFolder, \OC::$server->get(IAppManager::class) )); - $lazySearchBackend->setBackend(new \OCA\DAV\Files\FileSearchBackend( + $lazySearchBackend->setBackend(new FileSearchBackend( $this->server->tree, $user, \OC::$server->get(IRootFolder::class), @@ -319,14 +329,14 @@ public function __construct(IRequest $request, $baseUri) { new BulkUploadPlugin($userFolder, $logger) ); } - $this->server->addPlugin(new \OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin( + $this->server->addPlugin(new EnablePlugin( \OC::$server->get(IConfig::class), \OC::$server->get(BirthdayService::class) )); $this->server->addPlugin(new AppleProvisioningPlugin( \OC::$server->get(IUserSession::class), \OC::$server->get(IURLGenerator::class), - \OC::$server->getThemingDefaults(), + \OC::$server->get('ThemingDefaults'), \OC::$server->get(IRequest::class), \OC::$server->get(IFactory::class)->get('dav'), function () { @@ -353,12 +363,19 @@ function () { ); } + /** + * @deprecated + */ public function exec() { + $this->start(); + } + + public function start() { /** @var IEventLogger $eventLogger */ $eventLogger = \OC::$server->get(IEventLogger::class); - $eventLogger->start('dav_server_exec', ''); - $this->server->exec(); - $eventLogger->end('dav_server_exec'); + $eventLogger->start('dav_server_start', ''); + $this->server->start(); + $eventLogger->end('dav_server_start'); } private function requestIsForSubtree(array $subTrees): bool { From d739f925a998ca046e2b3a4fd8d5a8a4a53d4ac8 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 10:40:43 +0100 Subject: [PATCH 16/23] Modernize Sabre Connector Signed-off-by: Thomas Citharel --- apps/dav/lib/Connector/LegacyDAVACL.php | 7 +- apps/dav/lib/Connector/PublicAuth.php | 15 ++- .../Sabre/AnonymousOptionsPlugin.php | 8 +- .../lib/Connector/Sabre/AppEnabledPlugin.php | 10 +- apps/dav/lib/Connector/Sabre/Auth.php | 18 ++-- apps/dav/lib/Connector/Sabre/BearerAuth.php | 7 +- .../Sabre/BlockLegacyClientPlugin.php | 5 +- apps/dav/lib/Connector/Sabre/CachingTree.php | 4 +- apps/dav/lib/Connector/Sabre/ChecksumList.php | 2 +- .../Sabre/CommentPropertiesPlugin.php | 14 +-- .../Connector/Sabre/CopyEtagHeaderPlugin.php | 7 +- apps/dav/lib/Connector/Sabre/DavAclPlugin.php | 12 +++ apps/dav/lib/Connector/Sabre/Directory.php | 23 +++-- .../Sabre/DummyGetResponsePlugin.php | 5 +- .../Connector/Sabre/ExceptionLoggerPlugin.php | 8 +- .../lib/Connector/Sabre/FakeLockerPlugin.php | 6 +- apps/dav/lib/Connector/Sabre/File.php | 96 ++++++++++--------- apps/dav/lib/Connector/Sabre/FilesPlugin.php | 57 +++++------ .../lib/Connector/Sabre/FilesReportPlugin.php | 22 +++-- apps/dav/lib/Connector/Sabre/LockPlugin.php | 6 ++ .../lib/Connector/Sabre/MaintenancePlugin.php | 4 +- apps/dav/lib/Connector/Sabre/Node.php | 89 ++++++++++------- apps/dav/lib/Connector/Sabre/ObjectTree.php | 64 +++++++------ apps/dav/lib/Connector/Sabre/Principal.php | 35 ++++--- .../Sabre/PropfindCompressionPlugin.php | 4 +- apps/dav/lib/Connector/Sabre/QuotaPlugin.php | 38 +++++--- apps/dav/lib/Connector/Sabre/Server.php | 3 + .../dav/lib/Connector/Sabre/ServerFactory.php | 74 +++++++------- .../dav/lib/Connector/Sabre/ShareTypeList.php | 14 ++- apps/dav/lib/Connector/Sabre/SharesPlugin.php | 30 +++--- apps/dav/lib/Connector/Sabre/TagList.php | 14 ++- apps/dav/lib/Connector/Sabre/TagsPlugin.php | 46 +++++---- 32 files changed, 421 insertions(+), 326 deletions(-) diff --git a/apps/dav/lib/Connector/LegacyDAVACL.php b/apps/dav/lib/Connector/LegacyDAVACL.php index da570b235de92..1c76c37d8e99b 100644 --- a/apps/dav/lib/Connector/LegacyDAVACL.php +++ b/apps/dav/lib/Connector/LegacyDAVACL.php @@ -42,7 +42,7 @@ public function getCurrentUserPrincipals() { return []; } - $principalV1 = $this->convertPrincipal($principalV2, false); + $principalV1 = $this->convertPrincipal($principalV2); return array_merge( [ $principalV2, @@ -52,11 +52,8 @@ public function getCurrentUserPrincipals() { ); } - private function convertPrincipal($principal, $toV2) { + private function convertPrincipal(string $principal): string { [, $name] = \Sabre\Uri\split($principal); - if ($toV2) { - return "principals/users/$name"; - } return "principals/$name"; } diff --git a/apps/dav/lib/Connector/PublicAuth.php b/apps/dav/lib/Connector/PublicAuth.php index 426cbf871d71c..f6c185907086e 100644 --- a/apps/dav/lib/Connector/PublicAuth.php +++ b/apps/dav/lib/Connector/PublicAuth.php @@ -30,12 +30,14 @@ namespace OCA\DAV\Connector; use OC\Security\Bruteforce\Throttler; +use OCP\Defaults; use OCP\IRequest; use OCP\ISession; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IShare; use Sabre\DAV\Auth\Backend\AbstractBasic; +use Sabre\DAV\Exception\NotAuthenticated; /** * Class PublicAuth @@ -45,7 +47,7 @@ class PublicAuth extends AbstractBasic { private const BRUTEFORCE_ACTION = 'public_webdav_auth'; - /** @var \OCP\Share\IShare */ + /** @var IShare */ private $share; /** @var IManager */ @@ -76,7 +78,7 @@ public function __construct(IRequest $request, $this->throttler = $throttler; // setup realm - $defaults = new \OCP\Defaults(); + $defaults = new Defaults(); $this->realm = $defaults->getName(); } @@ -90,7 +92,7 @@ public function __construct(IRequest $request, * @param string $password * * @return bool - * @throws \Sabre\DAV\Exception\NotAuthenticated + * @throws NotAuthenticated */ protected function validateUserPass($username, $password) { $this->throttler->sleepDelayOrThrowOnMax($this->request->getRemoteAddress(), self::BRUTEFORCE_ACTION); @@ -121,7 +123,7 @@ protected function validateUserPass($username, $password) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup http_response_code(401); header('WWW-Authenticate: DummyBasic realm="' . $this->realm . '"'); - throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); + throw new NotAuthenticated('Cannot authenticate over ajax calls'); } $this->throttler->registerAttempt(self::BRUTEFORCE_ACTION, $this->request->getRemoteAddress()); @@ -138,10 +140,7 @@ protected function validateUserPass($username, $password) { } } - /** - * @return \OCP\Share\IShare - */ - public function getShare() { + public function getShare(): IShare { return $this->share; } } diff --git a/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php b/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php index 6c3600fa5eb52..ade63b706c15a 100644 --- a/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php @@ -51,15 +51,17 @@ public function initialize(\Sabre\DAV\Server $server) { } /** + * @param $path * @return bool */ - public function isRequestInRoot($path) { + public function isRequestInRoot($path): bool { return $path === '' || (is_string($path) && strpos($path, '/') === false); } /** - * @throws \Sabre\DAV\Exception\Forbidden - * @return bool + * @param RequestInterface $request + * @param ResponseInterface $response + * @return false|void */ public function handleAnonymousOptions(RequestInterface $request, ResponseInterface $response) { $isOffice = preg_match('/Microsoft Office/i', $request->getHeader('User-Agent') ?? ''); diff --git a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php index 244e5de0683ea..e56371f504e25 100644 --- a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php @@ -45,13 +45,13 @@ class AppEnabledPlugin extends ServerPlugin { private $app; /** - * @var \OCP\App\IAppManager + * @var IAppManager */ private $appManager; /** * @param string $app - * @param \OCP\App\IAppManager $appManager + * @param IAppManager $appManager */ public function __construct($app, IAppManager $appManager) { $this->app = $app; @@ -77,10 +77,10 @@ public function initialize(\Sabre\DAV\Server $server) { /** * This method is called before any HTTP after auth and checks if the user has access to the app * - * @throws \Sabre\DAV\Exception\Forbidden - * @return bool + * @return void + * @throws Forbidden */ - public function checkAppEnabled() { + public function checkAppEnabled(): void { if (!$this->appManager->isEnabledForUser($this->app)) { throw new Forbidden(); } diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index fb314f514fb84..7057e92d3bbfe 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -37,8 +37,10 @@ use OC\Authentication\Exceptions\PasswordLoginForbiddenException; use OC\Authentication\TwoFactorAuth\Manager; use OC\Security\Bruteforce\Throttler; +use OC\User\LoginException; use OC\User\Session; use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden; +use OCP\Defaults; use OCP\IRequest; use OCP\ISession; use OCP\IUserSession; @@ -87,7 +89,7 @@ public function __construct(ISession $session, $this->principalPrefix = $principalPrefix; // setup realm - $defaults = new \OCP\Defaults(); + $defaults = new Defaults(); $this->realm = $defaults->getName(); } @@ -102,7 +104,7 @@ public function __construct(ISession $session, * @param string $username * @return bool */ - public function isDavAuthenticated($username) { + public function isDavAuthenticated(string $username): bool { return !is_null($this->session->get(self::DAV_AUTHENTICATED)) && $this->session->get(self::DAV_AUTHENTICATED) === $username; } @@ -116,7 +118,7 @@ public function isDavAuthenticated($username) { * @param string $username * @param string $password * @return bool - * @throws PasswordLoginForbidden + * @throws PasswordLoginForbidden|LoginException */ protected function validateUserPass($username, $password) { if ($this->userSession->isLoggedIn() && @@ -169,7 +171,7 @@ public function check(RequestInterface $request, ResponseInterface $response) { * * @return bool */ - private function requiresCSRFCheck() { + private function requiresCSRFCheck(): bool { // GET requires no check at all if ($this->request->getMethod() === 'GET') { return false; @@ -209,7 +211,7 @@ private function requiresCSRFCheck() { * @return array * @throws NotAuthenticated */ - private function auth(RequestInterface $request, ResponseInterface $response) { + private function auth(RequestInterface $request, ResponseInterface $response): array { $forcedLogout = false; if (!$this->request->passesCSRFCheck() && @@ -219,7 +221,7 @@ private function auth(RequestInterface $request, ResponseInterface $response) { $forcedLogout = true; } else { $response->setStatus(401); - throw new \Sabre\DAV\Exception\NotAuthenticated('CSRF check not passed.'); + throw new NotAuthenticated('CSRF check not passed.'); } } @@ -227,7 +229,7 @@ private function auth(RequestInterface $request, ResponseInterface $response) { $this->userSession->logout(); } else { if ($this->twoFactorManager->needsSecondFactor($this->userSession->getUser())) { - throw new \Sabre\DAV\Exception\NotAuthenticated('2FA challenge not passed.'); + throw new NotAuthenticated('2FA challenge not passed.'); } if ( //Fix for broken webdav clients @@ -247,7 +249,7 @@ private function auth(RequestInterface $request, ResponseInterface $response) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup $response->addHeader('WWW-Authenticate','DummyBasic realm="' . $this->realm . '"'); $response->setStatus(401); - throw new \Sabre\DAV\Exception\NotAuthenticated('Cannot authenticate over ajax calls'); + throw new NotAuthenticated('Cannot authenticate over ajax calls'); } $data = parent::check($request, $response); diff --git a/apps/dav/lib/Connector/Sabre/BearerAuth.php b/apps/dav/lib/Connector/Sabre/BearerAuth.php index d28a9cfdb84db..e5e423ead43ae 100644 --- a/apps/dav/lib/Connector/Sabre/BearerAuth.php +++ b/apps/dav/lib/Connector/Sabre/BearerAuth.php @@ -23,6 +23,7 @@ */ namespace OCA\DAV\Connector\Sabre; +use OCP\Defaults; use OCP\IRequest; use OCP\ISession; use OCP\IUserSession; @@ -49,18 +50,18 @@ class BearerAuth extends AbstractBearer { public function __construct(IUserSession $userSession, ISession $session, IRequest $request, - $principalPrefix = 'principals/users/') { + string $principalPrefix = 'principals/users/') { $this->userSession = $userSession; $this->session = $session; $this->request = $request; $this->principalPrefix = $principalPrefix; // setup realm - $defaults = new \OCP\Defaults(); + $defaults = new Defaults(); $this->realm = $defaults->getName(); } - private function setupUserFs($userId) { + private function setupUserFs(string $userId): string { \OC_Util::setupFS($userId); $this->session->close(); return $this->principalPrefix . $userId; diff --git a/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php b/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php index 8e2ea4d4e161b..15d4b690d1e87 100644 --- a/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php +++ b/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php @@ -26,6 +26,7 @@ namespace OCA\DAV\Connector\Sabre; use OCP\IConfig; +use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; @@ -61,7 +62,7 @@ public function initialize(\Sabre\DAV\Server $server) { * Detects all unsupported clients and throws a \Sabre\DAV\Exception\Forbidden * exception which will result in a 403 to them. * @param RequestInterface $request - * @throws \Sabre\DAV\Exception\Forbidden If the client version is not supported + * @throws Forbidden If the client version is not supported */ public function beforeHandler(RequestInterface $request) { $userAgent = $request->getHeader('User-Agent'); @@ -76,7 +77,7 @@ public function beforeHandler(RequestInterface $request) { preg_match("/(?:mirall\\/)([\d.]+)/i", $userAgent, $versionMatches); if (isset($versionMatches[1]) && version_compare($versionMatches[1], $minimumSupportedDesktopVersion) === -1) { - throw new \Sabre\DAV\Exception\Forbidden('Unsupported client version.'); + throw new Forbidden('Unsupported client version.'); } } } diff --git a/apps/dav/lib/Connector/Sabre/CachingTree.php b/apps/dav/lib/Connector/Sabre/CachingTree.php index eb1233d35408b..3462a354e8084 100644 --- a/apps/dav/lib/Connector/Sabre/CachingTree.php +++ b/apps/dav/lib/Connector/Sabre/CachingTree.php @@ -30,9 +30,9 @@ class CachingTree extends Tree { * Store a node in the cache * * @param Node $node - * @param null|string $path + * @param string|null $path */ - public function cacheNode(Node $node, $path = null) { + public function cacheNode(Node $node, string $path = null) { if (is_null($path)) { $path = $node->getPath(); } diff --git a/apps/dav/lib/Connector/Sabre/ChecksumList.php b/apps/dav/lib/Connector/Sabre/ChecksumList.php index 74cdc98ef4f91..636d2821349e3 100644 --- a/apps/dav/lib/Connector/Sabre/ChecksumList.php +++ b/apps/dav/lib/Connector/Sabre/ChecksumList.php @@ -40,7 +40,7 @@ class ChecksumList implements XmlSerializable { /** * @param string $checksum */ - public function __construct($checksum) { + public function __construct(string $checksum) { $this->checksums = explode(',', $checksum); } diff --git a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php index 82980553fa8f1..ea51695dc6ca4 100644 --- a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php @@ -27,6 +27,7 @@ use OCP\Comments\ICommentsManager; use OCP\IUserSession; +use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\ServerPlugin; @@ -97,19 +98,19 @@ private function cacheDirectory(Directory $directory) { * if requested. * * @param PropFind $propFind - * @param \Sabre\DAV\INode $node + * @param INode $node * @return void */ public function handleGetProperties( PropFind $propFind, - \Sabre\DAV\INode $node + INode $node ) { if (!($node instanceof File) && !($node instanceof Directory)) { return; } // need prefetch ? - if ($node instanceof \OCA\DAV\Connector\Sabre\Directory + if ($node instanceof Directory && $propFind->getDepth() !== 0 && !is_null($propFind->getStatus(self::PROPERTY_NAME_UNREAD)) ) { @@ -136,7 +137,7 @@ public function handleGetProperties( * returns a reference to the comments node * * @param Node $node - * @return mixed|string + * @return array|string|string[]|null */ public function getCommentsLink(Node $node) { $href = $this->server->getBaseUri(); @@ -146,8 +147,7 @@ public function getCommentsLink(Node $node) { return null; } $commentsPart = 'dav/comments/files/' . rawurldecode($node->getId()); - $href = substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/')); - return $href; + return substr_replace($href, $commentsPart, $entryPoint + strlen('/remote.php/')); } /** @@ -157,7 +157,7 @@ public function getCommentsLink(Node $node) { * @param Node $node * @return Int|null */ - public function getUnreadCount(Node $node) { + public function getUnreadCount(Node $node): ?int { $user = $this->userSession->getUser(); if (is_null($user)) { return null; diff --git a/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php b/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php index 029e631f4d90e..08ed3da027884 100644 --- a/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php @@ -25,6 +25,7 @@ namespace OCA\DAV\Connector\Sabre; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -33,7 +34,7 @@ * This is a workaround for setups that automatically strip * or mangle Etag headers. */ -class CopyEtagHeaderPlugin extends \Sabre\DAV\ServerPlugin { +class CopyEtagHeaderPlugin extends ServerPlugin { /** @var \Sabre\DAV\Server */ private $server; @@ -57,7 +58,7 @@ public function initialize(\Sabre\DAV\Server $server) { * @param RequestInterface $request request * @param ResponseInterface $response response */ - public function afterMethod(RequestInterface $request, ResponseInterface $response) { + public function afterMethod(RequestInterface $request, ResponseInterface $response): void { $eTag = $response->getHeader('Etag'); if (!empty($eTag)) { $response->setHeader('OC-ETag', $eTag); @@ -73,7 +74,7 @@ public function afterMethod(RequestInterface $request, ResponseInterface $respon * @param string $destination * @return void */ - public function afterMove($source, $destination) { + public function afterMove(string $source, string $destination): void { try { $node = $this->server->tree->getNodeForPath($destination); } catch (NotFound $e) { diff --git a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php index 6842975835dfd..d2a04bde7e984 100644 --- a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php +++ b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php @@ -28,9 +28,11 @@ use OCA\DAV\CardDAV\AddressBook; use Sabre\CalDAV\Principal\User; +use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\INode; use Sabre\DAV\PropFind; +use Sabre\DAVACL\Exception\NeedPrivileges; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -48,6 +50,11 @@ public function __construct() { $this->allowUnauthenticatedAccess = false; } + /** + * @throws NeedPrivileges + * @throws NotAuthenticated + * @throws NotFound + */ public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, $throwExceptions = true) { $access = parent::checkPrivileges($uri, $privileges, $recursion, false); if ($access === false && $throwExceptions) { @@ -74,6 +81,11 @@ public function checkPrivileges($uri, $privileges, $recursion = self::R_PARENT, return $access; } + /** + * @throws NotAuthenticated + * @throws NotFound + * @throws NeedPrivileges + */ public function propFind(PropFind $propFind, INode $node) { // If the node is neither readable nor writable then fail unless its of // the standard user-principal diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index 08406e4cfb09c..f287fd98acc1e 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -45,19 +45,24 @@ use OCP\Files\StorageNotAvailableException; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; +use OCP\Share\IManager; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\Locked; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Exception\ServiceUnavailable; +use Sabre\DAV\ICollection; +use Sabre\DAV\ICopyTarget; use Sabre\DAV\IFile; +use Sabre\DAV\IMoveTarget; use Sabre\DAV\INode; +use Sabre\DAV\IQuota; -class Directory extends \OCA\DAV\Connector\Sabre\Node implements \Sabre\DAV\ICollection, \Sabre\DAV\IQuota, \Sabre\DAV\IMoveTarget, \Sabre\DAV\ICopyTarget { +class Directory extends Node implements ICollection, IQuota, IMoveTarget, ICopyTarget { /** * Cached directory content * - * @var \OCP\Files\FileInfo[] + * @var FileInfo[] */ private $dirContent; @@ -76,12 +81,12 @@ class Directory extends \OCA\DAV\Connector\Sabre\Node implements \Sabre\DAV\ICol /** * Sets up the node, expects a full path name * - * @param \OC\Files\View $view - * @param \OCP\Files\FileInfo $info + * @param View $view + * @param FileInfo $info * @param ObjectTree|null $tree - * @param \OCP\Share\IManager $shareManager + * @param IManager|null $shareManager */ - public function __construct(View $view, FileInfo $info, $tree = null, $shareManager = null) { + public function __construct(View $view, FileInfo $info, ObjectTree $tree = null, IManager $shareManager = null) { parent::__construct($view, $info, $shareManager); $this->tree = $tree; } @@ -204,7 +209,7 @@ public function createDirectory($name) { * Returns a specific child node, referenced by its name * * @param string $name - * @param \OCP\Files\FileInfo $info + * @param FileInfo $info * @return \Sabre\DAV\INode * @throws InvalidPath * @throws \Sabre\DAV\Exception\NotFound @@ -330,8 +335,8 @@ public function getQuotaInfo() { try { $info = $this->fileView->getFileInfo($this->path, false); $storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $info); - if ($storageInfo['quota'] === \OCP\Files\FileInfo::SPACE_UNLIMITED) { - $free = \OCP\Files\FileInfo::SPACE_UNLIMITED; + if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) { + $free = FileInfo::SPACE_UNLIMITED; } else { $free = $storageInfo['free']; } diff --git a/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php b/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php index 3a8469e99b423..13b79aa39c434 100644 --- a/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php +++ b/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\Connector\Sabre; +use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -42,7 +43,7 @@ * * @package OCA\DAV\Connector\Sabre */ -class DummyGetResponsePlugin extends \Sabre\DAV\ServerPlugin { +class DummyGetResponsePlugin extends ServerPlugin { /** @var \Sabre\DAV\Server */ protected $server; @@ -60,7 +61,7 @@ public function initialize(\Sabre\DAV\Server $server) { * @param ResponseInterface $response * @return false */ - public function httpGet(RequestInterface $request, ResponseInterface $response) { + public function httpGet(RequestInterface $request, ResponseInterface $response): bool { $string = 'This is the WebDAV interface. It can only be accessed by ' . 'WebDAV clients such as the Nextcloud desktop sync client.'; $stream = fopen('php://memory','r+'); diff --git a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php index a56c11bfa0d25..18e95df42f17d 100644 --- a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php @@ -42,8 +42,9 @@ use Sabre\DAV\Exception\PreconditionFailed; use Sabre\DAV\Exception\RequestedRangeNotSatisfiable; use Sabre\DAV\Exception\ServiceUnavailable; +use Sabre\DAV\ServerPlugin; -class ExceptionLoggerPlugin extends \Sabre\DAV\ServerPlugin { +class ExceptionLoggerPlugin extends ServerPlugin { protected $nonFatalExceptions = [ NotAuthenticated::class => true, // If tokenauth can throw this exception (which is basically as @@ -93,7 +94,7 @@ class ExceptionLoggerPlugin extends \Sabre\DAV\ServerPlugin { * @param string $loggerAppName app name to use when logging * @param LoggerInterface $logger */ - public function __construct($loggerAppName, $logger) { + public function __construct(string $loggerAppName, LoggerInterface $logger) { $this->appName = $loggerAppName; $this->logger = $logger; } @@ -115,9 +116,8 @@ public function initialize(\Sabre\DAV\Server $server) { /** * Log exception - * */ - public function logException(\Throwable $ex) { + public function logException(\Throwable $ex): void { $exceptionClass = get_class($ex); if (isset($this->nonFatalExceptions[$exceptionClass]) || ( diff --git a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php index d05cd6d2e6d35..8ed7ae13c6597 100644 --- a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php @@ -103,7 +103,7 @@ public function propFind(PropFind $propFind, INode $node) { * @param RequestInterface $request * @param array $conditions */ - public function validateTokens(RequestInterface $request, &$conditions) { + public function validateTokens(RequestInterface $request, array &$conditions) { foreach ($conditions as &$fileCondition) { if (isset($fileCondition['tokens'])) { foreach ($fileCondition['tokens'] as &$token) { @@ -125,7 +125,7 @@ public function validateTokens(RequestInterface $request, &$conditions) { * @return bool */ public function fakeLockProvider(RequestInterface $request, - ResponseInterface $response) { + ResponseInterface $response): bool { $lockInfo = new LockInfo(); $lockInfo->token = md5($request->getPath()); $lockInfo->uri = $request->getPath(); @@ -151,7 +151,7 @@ public function fakeLockProvider(RequestInterface $request, * @return bool */ public function fakeUnlockProvider(RequestInterface $request, - ResponseInterface $response) { + ResponseInterface $response): bool { $response->setStatus(204); $response->setHeader('Content-Length', '0'); return false; diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index 58f4be241170e..d45de9b718339 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -44,9 +44,11 @@ use OC\Files\Stream\HashWrapper; use OC\Files\View; use OCA\DAV\AppInfo\Application; +use OC\ServerNotAvailableException; use OCA\DAV\Connector\Sabre\Exception\EntityTooLarge; use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCA\DAV\Connector\Sabre\Exception\Forbidden as DAVForbiddenException; +use OCA\DAV\Connector\Sabre\Exception\InvalidPath; use OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType; use OCA\DAV\Connector\Sabre\Exception\BadGateway; use OCP\App\IAppManager; @@ -65,6 +67,7 @@ use OCP\Files\StorageNotAvailableException; use OCP\IL10N; use OCP\L10N\IFactory as IL10NFactory; +use OCP\HintException; use OCP\IConfig; use OCP\IRequest; use OCP\Lock\ILockingProvider; @@ -87,10 +90,10 @@ class File extends Node implements IFile { /** * Sets up the node, expects a full path name * - * @param \OC\Files\View $view - * @param \OCP\Files\FileInfo $info - * @param \OCP\Share\IManager $shareManager - * @param \OC\AppFramework\Http\Request $request + * @param View $view + * @param FileInfo $info + * @param IManager|null $shareManager + * @param Request|null $request */ public function __construct(View $view, FileInfo $info, IManager $shareManager = null, Request $request = null) { parent::__construct($view, $info, $shareManager); @@ -126,18 +129,17 @@ public function __construct(View $view, FileInfo $info, IManager $shareManager = * * @param resource $data * - * @throws Forbidden - * @throws UnsupportedMediaType - * @throws BadRequest + * @return string|null + * @throws DAVForbiddenException * @throws Exception - * @throws EntityTooLarge - * @throws ServiceUnavailable + * @throws InvalidPath * @throws FileLocked - * @return string|null + * @throws Forbidden + * @throws ServiceUnavailable */ public function put($data) { try { - $exists = $this->fileView->file_exists($this->path); + $exists = (bool) $this->fileView->file_exists($this->path); if ($this->info && $exists && !$this->info->isUpdateable()) { throw new Forbidden(); } @@ -161,7 +163,7 @@ public function put($data) { [$partStorage] = $this->fileView->resolvePath($this->path); $needsPartFile = $partStorage->needsPartFile() && (strlen($this->path) > 1); - $view = \OC\Files\Filesystem::getView(); + $view = Filesystem::getView(); if ($needsPartFile) { // mark file as partial while uploading (ignored by the scanner) @@ -329,9 +331,7 @@ public function put($data) { try { $this->acquireLock(ILockingProvider::LOCK_EXCLUSIVE); } catch (LockedException $ex) { - if ($needsPartFile) { - $partStorage->unlink($internalPartPath); - } + $partStorage->unlink($internalPartPath); throw new FileLocked($e->getMessage(), $e->getCode(), $e); } } @@ -406,7 +406,7 @@ public function put($data) { return '"' . $this->info->getEtag() . '"'; } - private function getPartFileBasePath($path) { + private function getPartFileBasePath(string $path): string { $partFileInStorage = \OC::$server->get(IConfig::class)->getSystemValue('part_file_in_storage', true); if ($partFileInStorage) { return $path; @@ -416,9 +416,13 @@ private function getPartFileBasePath($path) { } /** - * @param string $path + * @param bool $exists + * @param string|null $path + * @return bool|mixed + * @throws HintException + * @throws ServerNotAvailableException */ - private function emitPreHooks($exists, $path = null) { + private function emitPreHooks(bool $exists, string $path = null): bool { if (is_null($path)) { $path = $this->path; } @@ -426,42 +430,45 @@ private function emitPreHooks($exists, $path = null) { $run = true; if (!$exists) { - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_create, [ - \OC\Files\Filesystem::signal_param_path => $hookPath, - \OC\Files\Filesystem::signal_param_run => &$run, + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [ + Filesystem::signal_param_path => $hookPath, + Filesystem::signal_param_run => &$run, ]); } else { - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_update, [ - \OC\Files\Filesystem::signal_param_path => $hookPath, - \OC\Files\Filesystem::signal_param_run => &$run, + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [ + Filesystem::signal_param_path => $hookPath, + Filesystem::signal_param_run => &$run, ]); } - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_write, [ - \OC\Files\Filesystem::signal_param_path => $hookPath, - \OC\Files\Filesystem::signal_param_run => &$run, + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [ + Filesystem::signal_param_path => $hookPath, + Filesystem::signal_param_run => &$run, ]); return $run; } /** - * @param string $path + * @param bool $exists + * @param string|null $path + * @throws HintException + * @throws ServerNotAvailableException */ - private function emitPostHooks($exists, $path = null) { + private function emitPostHooks(bool $exists, string $path = null): void { if (is_null($path)) { $path = $this->path; } $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path)); if (!$exists) { - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_create, [ - \OC\Files\Filesystem::signal_param_path => $hookPath + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [ + Filesystem::signal_param_path => $hookPath ]); } else { - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_update, [ - \OC\Files\Filesystem::signal_param_path => $hookPath + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [ + Filesystem::signal_param_path => $hookPath ]); } - \OC_Hook::emit(\OC\Files\Filesystem::CLASSNAME, \OC\Files\Filesystem::signal_post_write, [ - \OC\Files\Filesystem::signal_param_path => $hookPath + \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [ + Filesystem::signal_param_path => $hookPath ]); } @@ -469,7 +476,10 @@ private function emitPostHooks($exists, $path = null) { * Returns the data * * @return resource - * @throws Forbidden + * @throws DAVForbiddenException + * @throws Exception + * @throws FileLocked + * @throws NotFound * @throws ServiceUnavailable */ public function get() { @@ -504,7 +514,7 @@ public function get() { * Delete the current file * * @throws Forbidden - * @throws ServiceUnavailable + * @throws ServiceUnavailable|FileLocked */ public function delete() { if (!$this->info->isDeletable()) { @@ -566,7 +576,7 @@ public function getDirectDownload() { * @throws NotImplemented * @throws ServiceUnavailable */ - private function createFileChunked($data) { + private function createFileChunked($data): ?string { [$path, $name] = \Sabre\Uri\split($this->path); $info = \OC_FileChunking::decodeName($name); @@ -606,7 +616,7 @@ private function createFileChunked($data) { /** @var \OC\Files\Storage\Storage $targetStorage */ [$targetStorage, $targetInternalPath] = $this->fileView->resolvePath($targetPath); - $exists = $this->fileView->file_exists($targetPath); + $exists = (bool) $this->fileView->file_exists($targetPath); try { $this->fileView->lockFile($targetPath, ILockingProvider::LOCK_SHARED); @@ -689,10 +699,10 @@ private function createFileChunked($data) { * * @param \Exception $e * - * @throws \Sabre\DAV\Exception + * @throws Exception */ private function convertToSabreException(\Exception $e) { - if ($e instanceof \Sabre\DAV\Exception) { + if ($e instanceof Exception) { throw $e; } if ($e instanceof NotPermittedException) { @@ -731,7 +741,7 @@ private function convertToSabreException(\Exception $e) { throw new NotFound($this->l10n->t('File not found: %1$s', [$e->getMessage()]), 0, $e); } - throw new \Sabre\DAV\Exception($e->getMessage(), 0, $e); + throw new Exception($e->getMessage(), 0, $e); } /** @@ -739,7 +749,7 @@ private function convertToSabreException(\Exception $e) { * * @return string|null */ - public function getChecksum() { + public function getChecksum(): ?string { if (!$this->info) { return null; } diff --git a/apps/dav/lib/Connector/Sabre/FilesPlugin.php b/apps/dav/lib/Connector/Sabre/FilesPlugin.php index 017b1d31841c6..5daaea87d2d20 100644 --- a/apps/dav/lib/Connector/Sabre/FilesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesPlugin.php @@ -44,6 +44,7 @@ use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\IFile; +use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; use Sabre\DAV\ServerPlugin; @@ -138,8 +139,8 @@ public function __construct(Tree $tree, IRequest $request, IPreview $previewManager, IUserSession $userSession, - $isPublic = false, - $downloadAttachment = true) { + bool $isPublic = false, + bool $downloadAttachment = true) { $this->tree = $tree; $this->config = $config; $this->request = $request; @@ -207,7 +208,7 @@ public function initialize(\Sabre\DAV\Server $server) { * @throws Forbidden * @throws NotFound */ - public function checkMove($source, $destination) { + public function checkMove(string $source, string $destination) { $sourceNode = $this->tree->getNodeForPath($source); if (!$sourceNode instanceof Node) { return; @@ -217,10 +218,6 @@ public function checkMove($source, $destination) { if ($sourceDir !== $destinationDir) { $sourceNodeFileInfo = $sourceNode->getFileInfo(); - if ($sourceNodeFileInfo === null) { - throw new NotFound($source . ' does not exist'); - } - if (!$sourceNodeFileInfo->isDeletable()) { throw new Forbidden($source . " cannot be deleted"); } @@ -258,6 +255,7 @@ public function handleDownloadToken(RequestInterface $request, ResponseInterface * * @param RequestInterface $request * @param ResponseInterface $response + * @throws NotFound */ public function httpGet(RequestInterface $request, ResponseInterface $response) { // Only handle valid files @@ -284,7 +282,7 @@ public function httpGet(RequestInterface $request, ResponseInterface $response) } } - if ($node instanceof \OCA\DAV\Connector\Sabre\File) { + if ($node instanceof File) { //Add OC-Checksum header $checksum = $node->getChecksum(); if ($checksum !== null && $checksum !== '') { @@ -297,13 +295,13 @@ public function httpGet(RequestInterface $request, ResponseInterface $response) * Adds all ownCloud-specific properties * * @param PropFind $propFind - * @param \Sabre\DAV\INode $node + * @param INode $node * @return void */ - public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) { + public function handleGetProperties(PropFind $propFind, INode $node) { $httpRequest = $this->server->httpRequest; - if ($node instanceof \OCA\DAV\Connector\Sabre\Node) { + if ($node instanceof Node) { /** * This was disabled, because it made dir listing throw an exception, * so users were unable to navigate into folders where one subitem @@ -359,20 +357,10 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) }); $propFind->handle(self::OWNER_ID_PROPERTYNAME, function () use ($node) { - $owner = $node->getOwner(); - if (!$owner) { - return null; - } else { - return $owner->getUID(); - } + return $node->getOwner()->getUID(); }); $propFind->handle(self::OWNER_DISPLAY_NAME_PROPERTYNAME, function () use ($node) { - $owner = $node->getOwner(); - if (!$owner) { - return null; - } else { - return $owner->getDisplayName(); - } + return $node->getOwner()->getDisplayName(); }); $propFind->handle(self::HAS_PREVIEW_PROPERTYNAME, function () use ($node) { @@ -408,16 +396,14 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) }); } - if ($node instanceof \OCA\DAV\Connector\Sabre\File) { + if ($node instanceof File) { $propFind->handle(self::DOWNLOADURL_PROPERTYNAME, function () use ($node) { try { $directDownloadUrl = $node->getDirectDownload(); if (isset($directDownloadUrl['url'])) { return $directDownloadUrl['url']; } - } catch (StorageNotAvailableException $e) { - return false; - } catch (ForbiddenException $e) { + } catch (StorageNotAvailableException|ForbiddenException $e) { return false; } return false; @@ -468,10 +454,10 @@ public function handleGetProperties(PropFind $propFind, \Sabre\DAV\INode $node) /** * translate Nextcloud permissions to OCM Permissions * - * @param $ncPermissions + * @param int $ncPermissions * @return array */ - protected function ncPermissions2ocmPermissions($ncPermissions) { + protected function ncPermissions2ocmPermissions(int $ncPermissions): array { $ocmPermissions = []; if ($ncPermissions & Constants::PERMISSION_SHARE) { @@ -497,10 +483,11 @@ protected function ncPermissions2ocmPermissions($ncPermissions) { * @param PropPatch $propPatch * * @return void + * @throws NotFound */ - public function handleUpdateProperties($path, PropPatch $propPatch) { + public function handleUpdateProperties(string $path, PropPatch $propPatch) { $node = $this->tree->getNodeForPath($path); - if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) { + if (!($node instanceof Node)) { return; } @@ -539,10 +526,10 @@ public function handleUpdateProperties($path, PropPatch $propPatch) { /** * @param string $filePath - * @param \Sabre\DAV\INode $node - * @throws \Sabre\DAV\Exception\BadRequest + * @param INode|null $node + * @throws NotFound */ - public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) { + public function sendFileIdHeader(string $filePath, INode $node = null) { // chunked upload handling if (isset($_SERVER['HTTP_OC_CHUNKED'])) { [$path, $name] = \Sabre\Uri\split($filePath); @@ -557,7 +544,7 @@ public function sendFileIdHeader($filePath, \Sabre\DAV\INode $node = null) { return; } $node = $this->server->tree->getNodeForPath($filePath); - if ($node instanceof \OCA\DAV\Connector\Sabre\Node) { + if ($node instanceof Node) { $fileId = $node->getFileId(); if (!is_null($fileId)) { $this->server->httpResponse->setHeader('OC-FileId', $fileId); diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 50222fdf3c92a..982237019b8e2 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -30,6 +30,7 @@ use OC\Files\View; use OCP\App\IAppManager; use OCP\Files\Folder; +use OCP\Files\NotFoundException; use OCP\IGroupManager; use OCP\ITagManager; use OCP\IUserSession; @@ -37,6 +38,7 @@ use OCP\SystemTag\ISystemTagObjectMapper; use OCP\SystemTag\TagNotFoundException; use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Exception\PreconditionFailed; use Sabre\DAV\PropFind; use Sabre\DAV\ServerPlugin; @@ -172,14 +174,15 @@ public function getSupportedReportSet($uri) { * REPORT operations to look for files * * @param string $reportName - * @param $report + * @param array $report * @param string $uri - * @return bool + * @return bool|void * @throws BadRequest + * @throws NotFound * @throws PreconditionFailed * @internal param $ [] $report */ - public function onReport($reportName, $report, $uri) { + public function onReport(string $reportName, array $report, string $uri) { $reportTargetNode = $this->server->tree->getNodeForPath($uri); if (!$reportTargetNode instanceof Directory || $reportName !== self::REPORT_NAME) { return; @@ -264,7 +267,7 @@ private function getFilesBaseUri(string $uri, string $subPath): string { * * @throws TagNotFoundException whenever a tag was not found */ - protected function processFilterRules($filterRules) { + protected function processFilterRules(array $filterRules): array { $ns = '{' . $this::NS_OWNCLOUD . '}'; $resultFileIds = null; $systemTagIds = []; @@ -310,7 +313,7 @@ protected function processFilterRules($filterRules) { return $resultFileIds; } - private function getSystemTagFileIds($systemTagIds) { + private function getSystemTagFileIds(array $systemTagIds): ?array { $resultFileIds = null; // check user permissions, if applicable @@ -358,7 +361,7 @@ private function getSystemTagFileIds($systemTagIds) { * @param array $circlesIds * @return array */ - private function getCirclesFileIds(array $circlesIds) { + private function getCirclesFileIds(array $circlesIds): array { if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) { return []; } @@ -375,7 +378,7 @@ private function getCirclesFileIds(array $circlesIds) { * @param Node[] nodes nodes for which to fetch and prepare responses * @return Response[] */ - public function prepareResponses($filesUri, $requestedProps, $nodes) { + public function prepareResponses(string $filesUri, array $requestedProps, array $nodes): array { $responses = []; foreach ($nodes as $node) { $propFind = new PropFind($filesUri . $node->getPath(), $requestedProps); @@ -405,8 +408,9 @@ public function prepareResponses($filesUri, $requestedProps, $nodes) { * @param Node $rootNode root node for search * @param array $fileIds file ids * @return Node[] array of Sabre nodes + * @throws NotFoundException */ - public function findNodesByFileIds($rootNode, $fileIds) { + public function findNodesByFileIds(Node $rootNode, array $fileIds): array { $folder = $this->userFolder; if (trim($rootNode->getPath(), '/') !== '') { $folder = $folder->get($rootNode->getPath()); @@ -431,7 +435,7 @@ public function findNodesByFileIds($rootNode, $fileIds) { /** * Returns whether the currently logged in user is an administrator */ - private function isAdmin() { + private function isAdmin(): bool { $user = $this->userSession->getUser(); if ($user !== null) { return $this->groupManager->isAdmin($user->getUID()); diff --git a/apps/dav/lib/Connector/Sabre/LockPlugin.php b/apps/dav/lib/Connector/Sabre/LockPlugin.php index 6305b0ec1380a..805b98c91e7bd 100644 --- a/apps/dav/lib/Connector/Sabre/LockPlugin.php +++ b/apps/dav/lib/Connector/Sabre/LockPlugin.php @@ -58,6 +58,9 @@ public function initialize(\Sabre\DAV\Server $server) { $this->isLocked = false; } + /** + * @throws FileLocked + */ public function getLock(RequestInterface $request) { // we can't listen on 'beforeMethod:PUT' due to order of operations with setting up the tree // so instead we limit ourselves to the PUT method manually @@ -79,6 +82,9 @@ public function getLock(RequestInterface $request) { } } + /** + * @throws LockedException + */ public function releaseLock(RequestInterface $request) { // don't try to release the lock if we never locked one if ($this->isLocked === false) { diff --git a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php index ca0e649bf5908..87b99158405c3 100644 --- a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php +++ b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php @@ -39,7 +39,7 @@ class MaintenancePlugin extends ServerPlugin { /** @var IConfig */ private $config; - /** @var \OCP\IL10N */ + /** @var IL10N */ private $l10n; /** @@ -81,7 +81,7 @@ public function initialize(\Sabre\DAV\Server $server) { * @throws ServiceUnavailable * @return bool */ - public function checkMaintenanceMode() { + public function checkMaintenanceMode(): bool { if ($this->config->getSystemValueBool('maintenance')) { throw new ServiceUnavailable($this->l10n->t('System is in maintenance mode.')); } diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php index 69c691b2860c1..ff52d9b18f0fc 100644 --- a/apps/dav/lib/Connector/Sabre/Node.php +++ b/apps/dav/lib/Connector/Sabre/Node.php @@ -38,16 +38,25 @@ use OC\Files\Mount\MoveableMount; use OC\Files\View; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCP\Constants; use OCP\Files\FileInfo; +use OCP\Files\InvalidPathException; use OCP\Files\StorageNotAvailableException; +use OCP\IUser; +use OCP\Lock\LockedException; use OCP\Share\IShare; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use Sabre\DAV\Exception; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\INode; -abstract class Node implements \Sabre\DAV\INode { +abstract class Node implements INode { /** - * @var \OC\Files\View + * @var View */ protected $fileView; @@ -66,7 +75,7 @@ abstract class Node implements \Sabre\DAV\INode { protected $property_cache = null; /** - * @var \OCP\Files\FileInfo + * @var FileInfo */ protected $info; @@ -78,9 +87,9 @@ abstract class Node implements \Sabre\DAV\INode { /** * Sets up the node, expects a full path name * - * @param \OC\Files\View $view - * @param \OCP\Files\FileInfo $info - * @param IManager $shareManager + * @param View $view + * @param FileInfo $info + * @param IManager|null $shareManager */ public function __construct(View $view, FileInfo $info, IManager $shareManager = null) { $this->fileView = $view; @@ -111,7 +120,7 @@ public function getName() { * * @return string */ - public function getPath() { + public function getPath(): string { return $this->path; } @@ -119,14 +128,16 @@ public function getPath() { * Renames the node * * @param string $name The new name - * @throws \Sabre\DAV\Exception\BadRequest - * @throws \Sabre\DAV\Exception\Forbidden + * @throws InvalidPath + * @throws LockedException + * @throws Exception + * @throws Forbidden */ public function setName($name) { // rename is only allowed if the update privilege is granted if (!($this->info->isUpdateable() || ($this->info->getMountPoint() instanceof MoveableMount && $this->info->getInternalPath() === ''))) { - throw new \Sabre\DAV\Exception\Forbidden(); + throw new Forbidden(); } [$parentPath,] = \Sabre\Uri\split($this->path); @@ -138,7 +149,7 @@ public function setName($name) { $newPath = $parentPath . '/' . $newName; if (!$this->fileView->rename($this->path, $newPath)) { - throw new \Sabre\DAV\Exception('Failed to rename '. $this->path . ' to ' . $newPath); + throw new Exception('Failed to rename '. $this->path . ' to ' . $newPath); } $this->path = $newPath; @@ -168,7 +179,7 @@ public function getLastModified() { * in the second parameter or to now if the second param is empty. * Even if the modification time is set to a custom value the access time is set to now. */ - public function touch($mtime) { + public function touch(string $mtime): void { $mtime = $this->sanitizeMtime($mtime); $this->fileView->touch($this->path, $mtime); $this->refreshInfo(); @@ -185,7 +196,7 @@ public function touch($mtime) { * * @return string */ - public function getETag() { + public function getETag(): string { return '"' . $this->info->getEtag() . '"'; } @@ -196,15 +207,15 @@ public function getETag() { * * @return int file id of updated file or -1 on failure */ - public function setETag($etag) { + public function setETag(string $etag): int { return $this->fileView->putFileInfo($this->path, ['etag' => $etag]); } - public function setCreationTime(int $time) { + public function setCreationTime(int $time): int { return $this->fileView->putFileInfo($this->path, ['creation_time' => $time]); } - public function setUploadTime(int $time) { + public function setUploadTime(int $time): int { return $this->fileView->putFileInfo($this->path, ['upload_time' => $time]); } @@ -213,7 +224,7 @@ public function setUploadTime(int $time) { * * @return integer */ - public function getSize() { + public function getSize(): int { return $this->info->getSize(); } @@ -222,14 +233,14 @@ public function getSize() { * * @return int */ - public function getId() { + public function getId(): int { return $this->info->getId(); } /** * @return string|null */ - public function getFileId() { + public function getFileId(): ?string { if ($this->info->getId()) { $instanceId = \OC_Util::getInstanceId(); $id = sprintf('%08d', $this->info->getId()); @@ -242,15 +253,15 @@ public function getFileId() { /** * @return integer */ - public function getInternalFileId() { + public function getInternalFileId(): int { return $this->info->getId(); } /** - * @param string $user + * @param string|null $user * @return int */ - public function getSharePermissions($user) { + public function getSharePermissions(?string $user): int { // check of we access a federated share if ($user !== null) { @@ -287,25 +298,25 @@ public function getSharePermissions($user) { } if (!$mountpoint->getOption('readonly', false) && $mountpointpath === $this->info->getPath()) { - $permissions |= \OCP\Constants::PERMISSION_DELETE | \OCP\Constants::PERMISSION_UPDATE; + $permissions |= Constants::PERMISSION_DELETE | Constants::PERMISSION_UPDATE; } } /* * Files can't have create or delete permissions */ - if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) { - $permissions &= ~(\OCP\Constants::PERMISSION_CREATE | \OCP\Constants::PERMISSION_DELETE); + if ($this->info->getType() === FileInfo::TYPE_FILE) { + $permissions &= ~(Constants::PERMISSION_CREATE | Constants::PERMISSION_DELETE); } return $permissions; } /** - * @param string $user + * @param string|null $user * @return string */ - public function getNoteFromShare($user) { + public function getNoteFromShare(?string $user): string { if ($user === null) { return ''; } @@ -333,7 +344,7 @@ public function getNoteFromShare($user) { /** * @return string */ - public function getDavPermissions() { + public function getDavPermissions(): string { $p = ''; if ($this->info->isShared()) { $p .= 'S'; @@ -353,7 +364,7 @@ public function getDavPermissions() { if ($this->info->isUpdateable()) { $p .= 'NV'; // Renameable, Moveable } - if ($this->info->getType() === \OCP\Files\FileInfo::TYPE_FILE) { + if ($this->info->getType() === FileInfo::TYPE_FILE) { if ($this->info->isUpdateable()) { $p .= 'W'; } @@ -365,45 +376,51 @@ public function getDavPermissions() { return $p; } - public function getOwner() { + public function getOwner(): IUser { return $this->info->getOwner(); } + /** + * @throws InvalidPath + */ protected function verifyPath() { try { $fileName = basename($this->info->getPath()); $this->fileView->verifyPath($this->path, $fileName); - } catch (\OCP\Files\InvalidPathException $ex) { + } catch (InvalidPathException $ex) { throw new InvalidPath($ex->getMessage()); } } /** * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE + * @throws LockedException */ - public function acquireLock($type) { + public function acquireLock(int $type) { $this->fileView->lockFile($this->path, $type); } /** * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE + * @throws LockedException */ - public function releaseLock($type) { + public function releaseLock(int $type) { $this->fileView->unlockFile($this->path, $type); } /** * @param int $type \OCP\Lock\ILockingProvider::LOCK_SHARED or \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE + * @throws LockedException */ - public function changeLock($type) { + public function changeLock(int $type) { $this->fileView->changeLock($this->path, $type); } - public function getFileInfo() { + public function getFileInfo(): FileInfo { return $this->info; } - protected function sanitizeMtime($mtimeFromRequest) { + protected function sanitizeMtime($mtimeFromRequest): int { return MtimeSanitizer::sanitizeMtime($mtimeFromRequest); } } diff --git a/apps/dav/lib/Connector/Sabre/ObjectTree.php b/apps/dav/lib/Connector/Sabre/ObjectTree.php index c129371e37632..ab296fdccbb5e 100644 --- a/apps/dav/lib/Connector/Sabre/ObjectTree.php +++ b/apps/dav/lib/Connector/Sabre/ObjectTree.php @@ -28,40 +28,42 @@ */ namespace OCA\DAV\Connector\Sabre; +use Exception; use OC\Files\FileInfo; use OC\Files\Storage\FailedStorage; +use OC\Files\Storage\Storage; +use OC\Files\View; use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCA\DAV\Connector\Sabre\Exception\Forbidden; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; use OCP\Files\ForbiddenException; +use OCP\Files\Mount\IMountManager; use OCP\Files\StorageInvalidException; use OCP\Files\StorageNotAvailableException; use OCP\Lock\LockedException; +use Sabre\DAV\Exception\Locked; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\ServiceUnavailable; +use Sabre\DAV\INode; class ObjectTree extends CachingTree { /** - * @var \OC\Files\View + * @var View */ protected $fileView; /** - * @var \OCP\Files\Mount\IMountManager + * @var IMountManager */ protected $mountManager; /** - * Creates the object + * @param INode $rootNode + * @param View $view + * @param IMountManager $mountManager */ - public function __construct() { - } - - /** - * @param \Sabre\DAV\INode $rootNode - * @param \OC\Files\View $view - * @param \OCP\Files\Mount\IMountManager $mountManager - */ - public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\Files\Mount\IMountManager $mountManager) { + public function init(INode $rootNode, View $view, IMountManager $mountManager) { $this->rootNode = $rootNode; $this->fileView = $view; $this->mountManager = $mountManager; @@ -76,7 +78,7 @@ public function init(\Sabre\DAV\INode $rootNode, \OC\Files\View $view, \OCP\File * * @return string path to real file */ - private function resolveChunkFile($path) { + private function resolveChunkFile(string $path): string { if (isset($_SERVER['HTTP_OC_CHUNKED'])) { // resolve to real file name to find the proper node [$dir, $name] = \Sabre\Uri\split($path); @@ -100,15 +102,15 @@ private function resolveChunkFile($path) { * Returns the INode object for the requested path * * @param string $path - * @return \Sabre\DAV\INode + * @return INode * @throws InvalidPath - * @throws \Sabre\DAV\Exception\Locked - * @throws \Sabre\DAV\Exception\NotFound - * @throws \Sabre\DAV\Exception\ServiceUnavailable + * @throws Locked + * @throws NotFound + * @throws ServiceUnavailable|\Sabre\DAV\Exception\Forbidden */ public function getNodeForPath($path) { if (!$this->fileView) { - throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup'); + throw new ServiceUnavailable('filesystem not setup'); } $path = trim($path, '/'); @@ -138,7 +140,7 @@ public function getNodeForPath($path) { $internalPath = $mount->getInternalPath($absPath); if ($storage && $storage->file_exists($internalPath)) { /** - * @var \OC\Files\Storage\Storage $storage + * @var Storage $storage */ // get data directly $data = $storage->getMetaData($internalPath); @@ -158,24 +160,24 @@ public function getNodeForPath($path) { throw new StorageNotAvailableException(); } } catch (StorageNotAvailableException $e) { - throw new \Sabre\DAV\Exception\ServiceUnavailable('Storage is temporarily not available', 0, $e); + throw new ServiceUnavailable('Storage is temporarily not available', 0, $e); } catch (StorageInvalidException $e) { - throw new \Sabre\DAV\Exception\NotFound('Storage ' . $path . ' is invalid'); + throw new NotFound('Storage ' . $path . ' is invalid'); } catch (LockedException $e) { - throw new \Sabre\DAV\Exception\Locked(); + throw new Locked(); } catch (ForbiddenException $e) { throw new \Sabre\DAV\Exception\Forbidden(); } } if (!$info) { - throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located'); + throw new NotFound('File with name ' . $path . ' could not be located'); } if ($info->getType() === 'dir') { - $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this); + $node = new Directory($this->fileView, $info, $this); } else { - $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info); + $node = new File($this->fileView, $info); } $this->cache[$path] = $node; @@ -193,16 +195,16 @@ public function getNodeForPath($path) { * @throws FileLocked * @throws Forbidden * @throws InvalidPath - * @throws \Exception + * @throws Exception * @throws \Sabre\DAV\Exception\Forbidden - * @throws \Sabre\DAV\Exception\Locked - * @throws \Sabre\DAV\Exception\NotFound - * @throws \Sabre\DAV\Exception\ServiceUnavailable + * @throws Locked + * @throws NotFound + * @throws ServiceUnavailable * @return void */ public function copy($sourcePath, $destinationPath) { if (!$this->fileView) { - throw new \Sabre\DAV\Exception\ServiceUnavailable('filesystem not setup'); + throw new ServiceUnavailable('filesystem not setup'); } @@ -229,7 +231,7 @@ public function copy($sourcePath, $destinationPath) { try { $this->fileView->copy($sourcePath, $destinationPath); } catch (StorageNotAvailableException $e) { - throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage()); + throw new ServiceUnavailable($e->getMessage()); } catch (ForbiddenException $ex) { throw new Forbidden($ex->getMessage(), $ex->getRetry()); } catch (LockedException $e) { diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 293013df1fa90..8c9696f2850ee 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -40,6 +40,12 @@ use OC\KnownUser\KnownUserService; use OCA\Circles\Api\v1\Circles; use OCA\Circles\Exceptions\CircleNotFoundException; +use OCA\Circles\Exceptions\FederatedUserException; +use OCA\Circles\Exceptions\FederatedUserNotFoundException; +use OCA\Circles\Exceptions\InitiatorNotFoundException; +use OCA\Circles\Exceptions\InvalidIdException; +use OCA\Circles\Exceptions\RequestBuilderException; +use OCA\Circles\Exceptions\SingleCircleNotFoundException; use OCA\Circles\Model\Circle; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\Traits\PrincipalProxyTrait; @@ -257,7 +263,7 @@ public function updatePrincipal($path, PropPatch $propPatch) { * @param string $test * @return array */ - protected function searchUserPrincipals(array $searchProperties, $test = 'allof') { + protected function searchUserPrincipals(array $searchProperties, string $test = 'allof'): array { $results = []; // If sharing is disabled, return the empty array @@ -449,7 +455,7 @@ public function searchPrincipals($prefixPath, array $searchProperties, $test = ' /** * @param string $uri * @param string $principalPrefix - * @return string + * @return string|null */ public function findByUri($uri, $principalPrefix) { // If sharing is disabled, return the empty array @@ -526,6 +532,12 @@ public function getPrincipalPrefix(): string { /** * @param string $circleUniqueId * @return array|null + * @throws FederatedUserException + * @throws FederatedUserNotFoundException + * @throws InitiatorNotFoundException + * @throws InvalidIdException + * @throws RequestBuilderException + * @throws SingleCircleNotFoundException */ protected function circleToPrincipal(string $circleUniqueId): ?array { if (!$this->appManager->isEnabledForUser('circles') || !class_exists('\OCA\Circles\Api\v1\Circles')) { @@ -534,22 +546,14 @@ protected function circleToPrincipal(string $circleUniqueId): ?array { try { $circle = Circles::detailsCircle($circleUniqueId, true); - } catch (ContainerExceptionInterface $ex) { - return null; - } catch (CircleNotFoundException $ex) { - return null; - } - - if (!$circle) { + } catch (ContainerExceptionInterface|CircleNotFoundException $ex) { return null; } - $principal = [ + return [ 'uri' => 'principals/circles/' . $circleUniqueId, '{DAV:}displayname' => $circle->getDisplayName(), ]; - - return $principal; } /** @@ -558,6 +562,12 @@ protected function circleToPrincipal(string $circleUniqueId): ?array { * @param string $principal * @return array * @throws Exception + * @throws FederatedUserException + * @throws FederatedUserNotFoundException + * @throws InitiatorNotFoundException + * @throws InvalidIdException + * @throws RequestBuilderException + * @throws SingleCircleNotFoundException * @suppress PhanUndeclaredClassMethod */ public function getCircleMembership(string $principal):array { @@ -575,7 +585,6 @@ public function getCircleMembership(string $principal):array { $circles = Circles::joinedCircles($name, true); return array_map(static function ($circle) { - /** @var Circle $circle */ return 'principals/circles/' . urlencode($circle->getSingleId()); }, $circles); } diff --git a/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php b/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php index d0251b2755fcd..5c47d2f68f3fa 100644 --- a/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php +++ b/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php @@ -51,10 +51,10 @@ class PropfindCompressionPlugin extends ServerPlugin { */ public function initialize(\Sabre\DAV\Server $server) { $this->server = $server; - $this->server->on('afterMethod:PROPFIND', [$this, 'compressResponse'], 100); + $this->server->on('afterMethod:PROPFIND', [$this, 'compressResponse']); } - public function compressResponse(Request $request, Response $response) { + public function compressResponse(Request $request, Response $response): Response { $header = $request->getHeader('Accept-Encoding'); if ($header === null) { diff --git a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php index f2b652e33201a..7e1f849b6372d 100644 --- a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php +++ b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php @@ -30,11 +30,15 @@ */ namespace OCA\DAV\Connector\Sabre; +use OC\Files\View; use OCA\DAV\Upload\FutureFile; +use OCP\Files\InvalidPathException; use OCP\Files\StorageNotAvailableException; use Sabre\DAV\Exception\InsufficientStorage; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\INode; +use Sabre\DAV\ServerPlugin; /** * This plugin check user quota and deny creating files when they exceeds the quota. @@ -43,9 +47,9 @@ * @copyright Copyright (C) 2012 entreCables S.L. All rights reserved. * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ -class QuotaPlugin extends \Sabre\DAV\ServerPlugin { +class QuotaPlugin extends ServerPlugin { - /** @var \OC\Files\View */ + /** @var View */ private $view; /** @@ -56,9 +60,9 @@ class QuotaPlugin extends \Sabre\DAV\ServerPlugin { private $server; /** - * @param \OC\Files\View $view + * @param View $view */ - public function __construct($view) { + public function __construct(View $view) { $this->view = $view; } @@ -88,8 +92,10 @@ public function initialize(\Sabre\DAV\Server $server) { * @param resource $data data * @param INode $parent Sabre Node * @param bool $modified modified + * @throws InsufficientStorage + * @return bool|void */ - public function beforeCreateFile($uri, $data, INode $parent, $modified) { + public function beforeCreateFile(string $uri, $data, INode $parent, bool $modified) { if (!$parent instanceof Node) { return; } @@ -104,8 +110,9 @@ public function beforeCreateFile($uri, $data, INode $parent, $modified) { * @param INode $node Sabre Node * @param resource $data data * @param bool $modified modified + * @return bool|void */ - public function beforeWriteContent($uri, INode $node, $data, $modified) { + public function beforeWriteContent(string $uri, INode $node, $data, bool $modified) { if (!$node instanceof Node) { return; } @@ -119,8 +126,10 @@ public function beforeWriteContent($uri, INode $node, $data, $modified) { * * @param string $source source path * @param string $destination destination path + * @return bool|void + * @throws NotFound|InsufficientStorage */ - public function beforeMove($source, $destination) { + public function beforeMove(string $source, string $destination) { $sourceNode = $this->server->tree->getNodeForPath($source); if (!$sourceNode instanceof FutureFile) { return; @@ -143,11 +152,11 @@ public function beforeMove($source, $destination) { * This method is called before any HTTP method and validates there is enough free space to store the file * * @param string $path relative to the users home - * @param int $length - * @throws InsufficientStorage + * @param int|null $length * @return bool + *@throws InsufficientStorage|ServiceUnavailable */ - public function checkQuota($path, $length = null) { + public function checkQuota(string $path, int $length = null): bool { if ($length === null) { $length = $this->getLength(); } @@ -178,7 +187,7 @@ public function checkQuota($path, $length = null) { return true; } - public function getFileChunking($info) { + public function getFileChunking($info): \OC_FileChunking { // FIXME: need a factory for better mocking support return new \OC_FileChunking($info); } @@ -202,12 +211,11 @@ public function getLength() { /** * @param string $uri * @return mixed - * @throws ServiceUnavailable + * @throws ServiceUnavailable|InvalidPathException */ - public function getFreeSpace($uri) { + public function getFreeSpace(string $uri) { try { - $freeSpace = $this->view->free_space(ltrim($uri, '/')); - return $freeSpace; + return $this->view->free_space(ltrim($uri, '/')); } catch (StorageNotAvailableException $e) { throw new ServiceUnavailable($e->getMessage()); } diff --git a/apps/dav/lib/Connector/Sabre/Server.php b/apps/dav/lib/Connector/Sabre/Server.php index 6cf6fa954c8db..2545e3205ba19 100644 --- a/apps/dav/lib/Connector/Sabre/Server.php +++ b/apps/dav/lib/Connector/Sabre/Server.php @@ -25,6 +25,8 @@ */ namespace OCA\DAV\Connector\Sabre; +use Sabre\DAV\Exception; + /** * Class \OCA\DAV\Connector\Sabre\Server * @@ -36,6 +38,7 @@ class Server extends \Sabre\DAV\Server { /** @var CachingTree $tree */ /** + * @throws Exception * @see \Sabre\DAV\Server */ public function __construct($treeOrNode = null) { diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index eedb657f2ddb4..7d0b0fc7fd8de 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -31,12 +31,14 @@ */ namespace OCA\DAV\Connector\Sabre; -use OCP\Files\Folder; +use OC\Files\View; use OCA\DAV\AppInfo\PluginManager; +use OCA\DAV\DAV\CustomPropertiesBackend; use OCA\DAV\Files\BrowserErrorPagePlugin; use OCP\App\IAppManager; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; +use OCP\Files\IRootFolder; use OCP\Files\Mount\IMountManager; use OCP\IConfig; use OCP\IDBConnection; @@ -45,6 +47,7 @@ use OCP\IPreview; use OCP\IRequest; use OCP\ITagManager; +use OCP\IUser; use OCP\IUserSession; use OCP\SabrePluginEvent; use OCP\Share\IManager; @@ -52,6 +55,7 @@ use OCP\SystemTag\ISystemTagObjectMapper; use Psr\Log\LoggerInterface; use Sabre\DAV\Auth\Plugin; +use Sabre\DAV\Exception; class ServerFactory { /** @var IConfig */ @@ -117,30 +121,29 @@ public function __construct( * @param Plugin $authPlugin * @param callable $viewCallBack callback that should return the view for the dav endpoint * @return Server + * @throws Exception */ - public function createServer($baseUri, - $requestUri, - Plugin $authPlugin, - callable $viewCallBack) { + public function createServer(string $baseUri, + string $requestUri, + Plugin $authPlugin, + callable $viewCallBack): Server { // Fire up server - $objectTree = new \OCA\DAV\Connector\Sabre\ObjectTree(); - $server = new \OCA\DAV\Connector\Sabre\Server($objectTree); + $objectTree = new ObjectTree(); + $server = new Server($objectTree); // Set URL explicitly due to reverse-proxy situations $server->httpRequest->setUrl($requestUri); $server->setBaseUri($baseUri); // Load plugins - $server->addPlugin(new \OCA\DAV\Connector\Sabre\MaintenancePlugin($this->config, $this->l10n)); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin($this->config)); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\AnonymousOptionsPlugin()); + $server->addPlugin(new MaintenancePlugin($this->config, $this->l10n)); + $server->addPlugin(new BlockLegacyClientPlugin($this->config)); + $server->addPlugin(new AnonymousOptionsPlugin()); $server->addPlugin($authPlugin); // FIXME: The following line is a workaround for legacy components relying on being able to send a GET to / - $server->addPlugin(new \OCA\DAV\Connector\Sabre\DummyGetResponsePlugin()); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $this->logger)); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin()); - - $server->addPlugin(new RequestIdHeaderPlugin(\OC::$server->get(IRequest::class))); - + $server->addPlugin(new DummyGetResponsePlugin()); + $server->addPlugin(new ExceptionLoggerPlugin('webdav', $this->logger)); + $server->addPlugin(new LockPlugin()); + $server->addPlugin(new RequestIdHeaderPlugin($this->request)); // Some WebDAV clients do require Class 2 WebDAV support (locking), since // we do not provide locking we emulate it using a fake locking plugin. if ($this->request->isUserAgent([ @@ -148,7 +151,7 @@ public function createServer($baseUri, '/OneNote/', '/Microsoft-WebDAV-MiniRedir/', ])) { - $server->addPlugin(new \OCA\DAV\Connector\Sabre\FakeLockerPlugin()); + $server->addPlugin(new FakeLockerPlugin()); } if (BrowserErrorPagePlugin::isBrowserRequest($this->request)) { @@ -158,26 +161,29 @@ public function createServer($baseUri, // wait with registering these until auth is handled and the filesystem is setup $server->on('beforeMethod:*', function () use ($server, $objectTree, $viewCallBack) { // ensure the skeleton is copied - $userFolder = \OC::$server->getUserFolder(); - - /** @var \OC\Files\View $view */ - $view = $viewCallBack($server); - if ($userFolder instanceof Folder && $userFolder->getPath() === $view->getRoot()) { - $rootInfo = $userFolder; + $userFolder = null; + $root = \OC::$server->get(IRootFolder::class); + /** @var IUser $user */ + if ($user = \OC::$server->get(IUserSession::class)->getUser()) { + /** @var IRootFolder $root */ + $rootInfo = $root->getUserFolder($user->getUID()); } else { - $rootInfo = $view->getFileInfo(''); + $rootInfo = $root; } + /** @var View $view */ + $view = $viewCallBack($server); + // Create Nextcloud Dir if ($rootInfo->getType() === 'dir') { - $root = new \OCA\DAV\Connector\Sabre\Directory($view, $rootInfo, $objectTree); + $root = new Directory($view, $rootInfo, $objectTree); } else { - $root = new \OCA\DAV\Connector\Sabre\File($view, $rootInfo); + $root = new File($view, $rootInfo); } $objectTree->init($root, $view, $this->mountManager); $server->addPlugin( - new \OCA\DAV\Connector\Sabre\FilesPlugin( + new FilesPlugin( $objectTree, $this->config, $this->request, @@ -187,18 +193,18 @@ public function createServer($baseUri, !$this->config->getSystemValue('debug', false) ) ); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\QuotaPlugin($view, true)); + $server->addPlugin(new QuotaPlugin($view, true)); if ($this->userSession->isLoggedIn()) { - $server->addPlugin(new \OCA\DAV\Connector\Sabre\TagsPlugin($objectTree, $this->tagManager)); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\SharesPlugin( + $server->addPlugin(new TagsPlugin($objectTree, $this->tagManager)); + $server->addPlugin(new SharesPlugin( $objectTree, $this->userSession, $userFolder, \OC::$server->get(IManager::class) )); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\CommentPropertiesPlugin(\OC::$server->get(ICommentsManager::class), $this->userSession)); - $server->addPlugin(new \OCA\DAV\Connector\Sabre\FilesReportPlugin( + $server->addPlugin(new CommentPropertiesPlugin(\OC::$server->get(ICommentsManager::class), $this->userSession)); + $server->addPlugin(new FilesReportPlugin( $objectTree, $view, \OC::$server->get(ISystemTagManager::class), @@ -212,7 +218,7 @@ public function createServer($baseUri, // custom properties plugin must be the last one $server->addPlugin( new \Sabre\DAV\PropertyStorage\Plugin( - new \OCA\DAV\DAV\CustomPropertiesBackend( + new CustomPropertiesBackend( $objectTree, $this->databaseConnection, $this->userSession->getUser() @@ -220,7 +226,7 @@ public function createServer($baseUri, ) ); } - $server->addPlugin(new \OCA\DAV\Connector\Sabre\CopyEtagHeaderPlugin()); + $server->addPlugin(new CopyEtagHeaderPlugin()); // Load dav plugins from apps $event = new SabrePluginEvent($server); diff --git a/apps/dav/lib/Connector/Sabre/ShareTypeList.php b/apps/dav/lib/Connector/Sabre/ShareTypeList.php index 6fbae0dee4aa2..df5caf705ebb3 100644 --- a/apps/dav/lib/Connector/Sabre/ShareTypeList.php +++ b/apps/dav/lib/Connector/Sabre/ShareTypeList.php @@ -23,6 +23,8 @@ namespace OCA\DAV\Connector\Sabre; use Sabre\Xml\Element; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\Writer; @@ -44,7 +46,7 @@ class ShareTypeList implements Element { /** * @param int[] $shareTypes */ - public function __construct($shareTypes) { + public function __construct(array $shareTypes) { $this->shareTypes = $shareTypes; } @@ -53,7 +55,7 @@ public function __construct($shareTypes) { * * @return int[] */ - public function getShareTypes() { + public function getShareTypes(): array { return $this->shareTypes; } @@ -61,9 +63,11 @@ public function getShareTypes() { * The deserialize method is called during xml parsing. * * @param Reader $reader - * @return mixed + * @return ShareTypeList|null + * @throws LibXMLException + * @throws ParseException */ - public static function xmlDeserialize(Reader $reader) { + public static function xmlDeserialize(Reader $reader): ?ShareTypeList { $shareTypes = []; $tree = $reader->parseInnerTree(); @@ -79,7 +83,7 @@ public static function xmlDeserialize(Reader $reader) { } /** - * The xmlSerialize metod is called during xml writing. + * The xmlSerialize method is called during xml writing. * * @param Writer $writer * @return void diff --git a/apps/dav/lib/Connector/Sabre/SharesPlugin.php b/apps/dav/lib/Connector/Sabre/SharesPlugin.php index d482aa4b51091..1687ecda81d33 100644 --- a/apps/dav/lib/Connector/Sabre/SharesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/SharesPlugin.php @@ -32,13 +32,17 @@ use OCP\Files\Folder; use OCP\Files\NotFoundException; use OCP\IUserSession; +use OCP\Share\IManager; use OCP\Share\IShare; +use Sabre\DAV\INode; use Sabre\DAV\PropFind; +use Sabre\DAV\ServerPlugin; +use Sabre\DAV\Tree; /** * Sabre Plugin to provide share-related properties */ -class SharesPlugin extends \Sabre\DAV\ServerPlugin { +class SharesPlugin extends ServerPlugin { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; public const NS_NEXTCLOUD = 'http://nextcloud.org/ns'; public const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types'; @@ -51,16 +55,16 @@ class SharesPlugin extends \Sabre\DAV\ServerPlugin { */ private $server; - /** @var \OCP\Share\IManager */ + /** @var IManager */ private $shareManager; - /** @var \Sabre\DAV\Tree */ + /** @var Tree */ private $tree; /** @var string */ private $userId; - /** @var \OCP\Files\Folder */ + /** @var Folder */ private $userFolder; /** @var IShare[][] */ @@ -70,16 +74,16 @@ class SharesPlugin extends \Sabre\DAV\ServerPlugin { private $cachedFolders = []; /** - * @param \Sabre\DAV\Tree $tree tree + * @param Tree $tree tree * @param IUserSession $userSession user session - * @param \OCP\Files\Folder $userFolder user home folder - * @param \OCP\Share\IManager $shareManager share manager + * @param Folder $userFolder user home folder + * @param IManager $shareManager share manager */ public function __construct( - \Sabre\DAV\Tree $tree, + Tree $tree, IUserSession $userSession, - \OCP\Files\Folder $userFolder, - \OCP\Share\IManager $shareManager + Folder $userFolder, + IManager $shareManager ) { $this->tree = $tree; $this->shareManager = $shareManager; @@ -163,7 +167,7 @@ private function getShares(DavNode $sabreNode): array { $parentPath = '/'; } // if we already cached the folder this file is in we know there are no shares for this file - if (array_search($parentPath, $this->cachedFolders) === false) { + if (!in_array($parentPath, $this->cachedFolders)) { try { $node = $this->userFolder->get($sabreNode->getPath()); } catch (NotFoundException $e) { @@ -183,11 +187,11 @@ private function getShares(DavNode $sabreNode): array { * Adds shares to propfind response * * @param PropFind $propFind propfind object - * @param \Sabre\DAV\INode $sabreNode sabre node + * @param INode $sabreNode sabre node */ public function handleGetProperties( PropFind $propFind, - \Sabre\DAV\INode $sabreNode + INode $sabreNode ) { if (!($sabreNode instanceof DavNode)) { return; diff --git a/apps/dav/lib/Connector/Sabre/TagList.php b/apps/dav/lib/Connector/Sabre/TagList.php index bbb938fb27d2c..a89fdc6f00682 100644 --- a/apps/dav/lib/Connector/Sabre/TagList.php +++ b/apps/dav/lib/Connector/Sabre/TagList.php @@ -24,6 +24,8 @@ namespace OCA\DAV\Connector\Sabre; use Sabre\Xml\Element; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\Writer; @@ -54,14 +56,14 @@ public function __construct(array $tags) { * * @return array */ - public function getTags() { + public function getTags(): array { return $this->tags; } /** * The deserialize method is called during xml parsing. * - * This method is called statictly, this is because in theory this method + * This method is called statically, this is because in theory this method * may be used as a type of constructor, or factory method. * * Often you want to return an instance of the current class, but you are @@ -77,9 +79,11 @@ public function getTags() { * the next element. * * @param Reader $reader - * @return mixed + * @return TagList|null + * @throws LibXMLException + * @throws ParseException */ - public static function xmlDeserialize(Reader $reader) { + public static function xmlDeserialize(Reader $reader): ?TagList { $tags = []; $tree = $reader->parseInnerTree(); @@ -95,7 +99,7 @@ public static function xmlDeserialize(Reader $reader) { } /** - * The xmlSerialize metod is called during xml writing. + * The xmlSerialize method is called during xml writing. * * Use the $writer argument to write its own xml serialization. * diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index da5dd8749052e..9af78eb6ab878 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -50,10 +50,17 @@ * */ +use OCP\ITagManager; +use OCP\ITags; +use Sabre\DAV\Exception\Locked; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; +use Sabre\DAV\ServerPlugin; +use Sabre\DAV\Tree; -class TagsPlugin extends \Sabre\DAV\ServerPlugin { +class TagsPlugin extends ServerPlugin { // namespace public const NS_OWNCLOUD = 'http://owncloud.org/ns'; @@ -69,12 +76,12 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin { private $server; /** - * @var \OCP\ITagManager + * @var ITagManager */ private $tagManager; /** - * @var \OCP\ITags + * @var ITags */ private $tagger; @@ -87,15 +94,15 @@ class TagsPlugin extends \Sabre\DAV\ServerPlugin { private $cachedTags; /** - * @var \Sabre\DAV\Tree + * @var Tree */ private $tree; /** - * @param \Sabre\DAV\Tree $tree tree - * @param \OCP\ITagManager $tagManager tag manager + * @param Tree $tree tree + * @param ITagManager $tagManager tag manager */ - public function __construct(\Sabre\DAV\Tree $tree, \OCP\ITagManager $tagManager) { + public function __construct(Tree $tree, ITagManager $tagManager) { $this->tree = $tree; $this->tagManager = $tagManager; $this->tagger = null; @@ -125,9 +132,9 @@ public function initialize(\Sabre\DAV\Server $server) { /** * Returns the tagger * - * @return \OCP\ITags tagger + * @return ITags tagger */ - private function getTagger() { + private function getTagger(): ITags { if (!$this->tagger) { $this->tagger = $this->tagManager->load('files'); } @@ -141,7 +148,7 @@ private function getTagger() { * @return array list($tags, $favorite) with $tags as tag array * and $favorite is a boolean whether the file was favorited */ - private function getTagsAndFav($fileId) { + private function getTagsAndFav(int $fileId): array { $isFav = false; $tags = $this->getTags($fileId); if ($tags) { @@ -160,7 +167,7 @@ private function getTagsAndFav($fileId) { * @param integer $fileId file id * @return array list of tags for that file */ - private function getTags($fileId) { + private function getTags(int $fileId): ?array { if (isset($this->cachedTags[$fileId])) { return $this->cachedTags[$fileId]; } else { @@ -181,7 +188,7 @@ private function getTags($fileId) { * @param int $fileId * @param array $tags array of tag strings */ - private function updateTags($fileId, $tags) { + private function updateTags(int $fileId, array $tags): void { $tagger = $this->getTagger(); $currentTags = $this->getTags($fileId); @@ -206,19 +213,21 @@ private function updateTags($fileId, $tags) { * if requested. * * @param PropFind $propFind - * @param \Sabre\DAV\INode $node + * @param INode $node * @return void + * @throws Exception\Forbidden + * @throws Locked */ public function handleGetProperties( PropFind $propFind, - \Sabre\DAV\INode $node + INode $node ) { - if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) { + if (!($node instanceof Node)) { return; } // need prefetch ? - if ($node instanceof \OCA\DAV\Connector\Sabre\Directory + if ($node instanceof Directory && $propFind->getDepth() !== 0 && (!is_null($propFind->getStatus(self::TAGS_PROPERTYNAME)) || !is_null($propFind->getStatus(self::FAVORITE_PROPERTYNAME)) @@ -269,10 +278,11 @@ public function handleGetProperties( * @param PropPatch $propPatch * * @return void + * @throws NotFound */ - public function handleUpdateProperties($path, PropPatch $propPatch) { + public function handleUpdateProperties(string $path, PropPatch $propPatch) { $node = $this->tree->getNodeForPath($path); - if (!($node instanceof \OCA\DAV\Connector\Sabre\Node)) { + if (!($node instanceof Node)) { return; } From 244aaa7faf8d6287801dbf444529597889bb76a7 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 14:47:01 +0100 Subject: [PATCH 17/23] Add @template-implements metadata for listeners Signed-off-by: Thomas Citharel --- apps/dav/lib/Listener/ActivityUpdaterListener.php | 3 +++ apps/dav/lib/Listener/AddressbookListener.php | 3 +++ apps/dav/lib/Listener/BirthdayListener.php | 3 +++ apps/dav/lib/Listener/CalendarContactInteractionListener.php | 3 +++ .../dav/lib/Listener/CalendarObjectReminderUpdaterListener.php | 3 +++ apps/dav/lib/Listener/CardListener.php | 3 +++ apps/dav/lib/Listener/ClearPhotoCacheListener.php | 3 +++ 7 files changed, 21 insertions(+) diff --git a/apps/dav/lib/Listener/ActivityUpdaterListener.php b/apps/dav/lib/Listener/ActivityUpdaterListener.php index 371912ff035b7..2d06004793c0a 100644 --- a/apps/dav/lib/Listener/ActivityUpdaterListener.php +++ b/apps/dav/lib/Listener/ActivityUpdaterListener.php @@ -43,6 +43,9 @@ use Throwable; use function sprintf; +/** + * @template-implements IEventListener + */ class ActivityUpdaterListener implements IEventListener { /** @var ActivityBackend */ diff --git a/apps/dav/lib/Listener/AddressbookListener.php b/apps/dav/lib/Listener/AddressbookListener.php index 3c17d399d4eb1..e367fe762de78 100644 --- a/apps/dav/lib/Listener/AddressbookListener.php +++ b/apps/dav/lib/Listener/AddressbookListener.php @@ -36,6 +36,9 @@ use Throwable; use function sprintf; +/** + * @template-implements IEventListener + */ class AddressbookListener implements IEventListener { /** @var ActivityBackend */ private $activityBackend; diff --git a/apps/dav/lib/Listener/BirthdayListener.php b/apps/dav/lib/Listener/BirthdayListener.php index 5861d5313cbde..43e0f5c6274fb 100644 --- a/apps/dav/lib/Listener/BirthdayListener.php +++ b/apps/dav/lib/Listener/BirthdayListener.php @@ -32,6 +32,9 @@ use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; +/** + * @template-implements IEventListener + */ class BirthdayListener implements IEventListener { /** @var BirthdayService */ private $birthdayService; diff --git a/apps/dav/lib/Listener/CalendarContactInteractionListener.php b/apps/dav/lib/Listener/CalendarContactInteractionListener.php index 04c759d5c3c67..b31788e7079c7 100644 --- a/apps/dav/lib/Listener/CalendarContactInteractionListener.php +++ b/apps/dav/lib/Listener/CalendarContactInteractionListener.php @@ -46,6 +46,9 @@ use function strpos; use function substr; +/** + * @template-implements IEventListener + */ class CalendarContactInteractionListener implements IEventListener { private const URI_USERS = 'principals/users/'; diff --git a/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php b/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php index 3c168f6105c23..67b38457436ea 100644 --- a/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php +++ b/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php @@ -42,6 +42,9 @@ use Throwable; use function sprintf; +/** + * @template-implements IEventListener + */ class CalendarObjectReminderUpdaterListener implements IEventListener { /** @var ReminderBackend */ diff --git a/apps/dav/lib/Listener/CardListener.php b/apps/dav/lib/Listener/CardListener.php index 0281127c8588e..759b47c051c42 100644 --- a/apps/dav/lib/Listener/CardListener.php +++ b/apps/dav/lib/Listener/CardListener.php @@ -36,6 +36,9 @@ use Throwable; use function sprintf; +/** + * @template-implements IEventListener + */ class CardListener implements IEventListener { /** @var ActivityBackend */ private $activityBackend; diff --git a/apps/dav/lib/Listener/ClearPhotoCacheListener.php b/apps/dav/lib/Listener/ClearPhotoCacheListener.php index f7fbb9d9eb674..1a3ffa2b82686 100644 --- a/apps/dav/lib/Listener/ClearPhotoCacheListener.php +++ b/apps/dav/lib/Listener/ClearPhotoCacheListener.php @@ -31,6 +31,9 @@ use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; +/** + * @template-implements IEventListener + */ class ClearPhotoCacheListener implements IEventListener { /** @var PhotoCache */ private $photoCache; From 57ddf28c823f32e57fce3c3209b46ef0a6821ab6 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 14:48:40 +0100 Subject: [PATCH 18/23] Remove CalendarManager registration registerCalendarProvider is now used Signed-off-by: Thomas Citharel --- apps/dav/lib/AppInfo/Application.php | 20 -------------------- 1 file changed, 20 deletions(-) diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index d268c1e10e91d..7ff2f52e43e88 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -35,7 +35,6 @@ use Exception; use OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob; use OCA\DAV\CalDAV\Activity\Backend; -use OCA\DAV\CalDAV\CalendarManager; use OCA\DAV\CalDAV\CalendarProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\AudioProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; @@ -94,7 +93,6 @@ use OCP\AppFramework\Bootstrap\IRegistrationContext; use OCP\AppFramework\IAppContainer; use OCP\BackgroundJob\IJobList; -use OCP\Calendar\IManager as ICalendarManager; use OCP\Contacts\IManager as IContactsManager; use OCP\IServerContainer; use OCP\IURLGenerator; @@ -206,7 +204,6 @@ public function boot(IBootContext $context): void { $context->injectFn([$this, 'registerHooks']); $context->injectFn([$this, 'registerContactsManager']); - $context->injectFn([$this, 'registerCalendarManager']); $context->injectFn([$this, 'registerCalendarReminders']); } @@ -299,23 +296,6 @@ private function setupSystemContactsProvider(IContactsManager $contactsManager, $cm->setupSystemContactsProvider($contactsManager, $urlGenerator); } - public function registerCalendarManager(ICalendarManager $calendarManager, - IAppContainer $container): void { - $calendarManager->register(function () use ($container, $calendarManager) { - $user = \OC::$server->get(IUserSession::class)->getUser(); - if ($user !== null) { - $this->setupCalendarProvider($calendarManager, $container, $user->getUID()); - } - }); - } - - private function setupCalendarProvider(ICalendarManager $calendarManager, - IAppContainer $container, - $userId) { - $cm = $container->query(CalendarManager::class); - $cm->setupCalendarProvider($calendarManager, $userId); - } - public function registerCalendarReminders(NotificationProviderManager $manager, LoggerInterface $logger): void { try { From fccc89db0fe58d9fe71f7fb3ed018d77835f9d65 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 20 Jan 2022 14:49:49 +0100 Subject: [PATCH 19/23] Various fixes Signed-off-by: Thomas Citharel --- apps/dav/lib/AppInfo/Application.php | 13 +- apps/dav/lib/AppInfo/PluginManager.php | 29 ++-- apps/dav/lib/CalDAV/PublicCalendarRoot.php | 4 +- .../Reminder/NotificationProviderManager.php | 12 +- apps/dav/lib/CalDAV/Schedule/IMipPlugin.php | 102 ++++++-------- apps/dav/lib/CalDAV/Schedule/Plugin.php | 20 +-- apps/dav/lib/CardDAV/CardDavBackend.php | 8 +- apps/dav/lib/CardDAV/ContactsManager.php | 2 +- apps/dav/lib/CardDAV/UserAddressBooks.php | 12 +- apps/dav/lib/Comments/RootCollection.php | 12 +- apps/dav/lib/Connector/Sabre/Directory.php | 92 ++++++++----- .../Connector/Sabre/ExceptionLoggerPlugin.php | 18 +-- .../lib/Connector/Sabre/FakeLockerPlugin.php | 2 +- apps/dav/lib/Connector/Sabre/File.php | 2 +- apps/dav/lib/Connector/Sabre/FilesPlugin.php | 4 + .../lib/Connector/Sabre/FilesReportPlugin.php | 10 +- apps/dav/lib/Connector/Sabre/Node.php | 21 +-- apps/dav/lib/Connector/Sabre/QuotaPlugin.php | 2 +- .../dav/lib/Connector/Sabre/ServerFactory.php | 6 +- apps/dav/lib/Connector/Sabre/SharesPlugin.php | 11 +- .../InvitationResponseController.php | 19 ++- apps/dav/lib/DAV/Sharing/Backend.php | 2 +- apps/dav/lib/Files/FileSearchBackend.php | 72 +++++----- apps/dav/lib/Files/RootCollection.php | 7 +- .../Migration/RefreshWebcalJobRegistrar.php | 2 +- apps/dav/lib/RootCollection.php | 80 +++++------ apps/dav/lib/Server.php | 126 ++++++++++-------- apps/dav/lib/Traits/PrincipalProxyTrait.php | 19 +-- apps/dav/lib/Upload/ChunkingPlugin.php | 10 +- .../Connector/Sabre/FilesReportPluginTest.php | 6 + remote.php | 6 +- 31 files changed, 409 insertions(+), 322 deletions(-) diff --git a/apps/dav/lib/AppInfo/Application.php b/apps/dav/lib/AppInfo/Application.php index 7ff2f52e43e88..2d91442064147 100644 --- a/apps/dav/lib/AppInfo/Application.php +++ b/apps/dav/lib/AppInfo/Application.php @@ -33,6 +33,7 @@ namespace OCA\DAV\AppInfo; use Exception; +use OC\Files\AppData\Factory as AppDataFactory; use OCA\DAV\BackgroundJob\UpdateCalendarResourcesRoomsBackgroundJob; use OCA\DAV\CalDAV\Activity\Backend; use OCA\DAV\CalDAV\CalendarProvider; @@ -123,7 +124,7 @@ public function register(IRegistrationContext $context): void { $server = $c->get(IServerContainer::class); return new PhotoCache( - $server->getAppDataDir('dav-photocache'), + $server->get(AppDataFactory::class)->get('dav-photocache'), $c->get(LoggerInterface::class) ); }); @@ -283,16 +284,18 @@ private function setupContactsProvider(IContactsManager $contactsManager, IAppContainer $container, string $userID): void { /** @var ContactsManager $cm */ - $cm = $container->query(ContactsManager::class); - $urlGenerator = $container->getServer()->get(IURLGenerator::class); + $cm = $container->get(ContactsManager::class); + /** @var IURLGenerator $urlGenerator */ + $urlGenerator = $container->get(IURLGenerator::class); $cm->setupContactsProvider($contactsManager, $userID, $urlGenerator); } private function setupSystemContactsProvider(IContactsManager $contactsManager, IAppContainer $container): void { /** @var ContactsManager $cm */ - $cm = $container->query(ContactsManager::class); - $urlGenerator = $container->getServer()->get(IURLGenerator::class); + $cm = $container->get(ContactsManager::class); + /** @var IURLGenerator $urlGenerator */ + $urlGenerator = $container->get(IURLGenerator::class); $cm->setupSystemContactsProvider($contactsManager, $urlGenerator); } diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index bed6963f8879b..65c1fc189af11 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -28,6 +28,7 @@ */ namespace OCA\DAV\AppInfo; +use Exception; use OC\ServerContainer; use OCA\DAV\CalDAV\Integration\ICalendarProvider; use OCA\DAV\CardDAV\Integration\IAddressBookProvider; @@ -101,8 +102,9 @@ public function __construct(ServerContainer $container, IAppManager $appManager) * Returns an array of app-registered plugins * * @return ServerPlugin[] + * @throws Exception */ - public function getAppPlugins() { + public function getAppPlugins(): array { $this->populate(); return $this->plugins; } @@ -111,14 +113,16 @@ public function getAppPlugins() { * Returns an array of app-registered collections * * @return array + * @throws Exception */ - public function getAppCollections() { + public function getAppCollections(): array { $this->populate(); return $this->collections; } /** * @return IAddressBookProvider[] + * @throws Exception */ public function getAddressBookPlugins(): array { $this->populate(); @@ -129,6 +133,7 @@ public function getAddressBookPlugins(): array { * Returns an array of app-registered calendar plugins * * @return ICalendarProvider[] + * @throws Exception */ public function getCalendarPlugins():array { $this->populate(); @@ -137,6 +142,8 @@ public function getCalendarPlugins():array { /** * Retrieve plugin and collection list and populate attributes + * + * @throws Exception */ private function populate(): void { if ($this->populated) { @@ -251,6 +258,9 @@ private function extractCalendarPluginList(array $array): array { return []; } + /** + * @throws Exception + */ private function createClass(string $className): object { try { return $this->container->get($className); @@ -260,20 +270,20 @@ private function createClass(string $className): object { } } - throw new \Exception('Could not load ' . $className, 0, $e); + throw new Exception('Could not load ' . $className, 0, $e); } /** * @param string[] $classes * @return ServerPlugin[] - * @throws \Exception + * @throws Exception */ private function loadSabrePluginsFromInfoXml(array $classes): array { return array_map(function (string $className): ServerPlugin { $instance = $this->createClass($className); if (!($instance instanceof ServerPlugin)) { - throw new \Exception('Sabre server plugin ' . $className . ' does not implement the ' . ServerPlugin::class . ' interface'); + throw new Exception('Sabre server plugin ' . $className . ' does not implement the ' . ServerPlugin::class . ' interface'); } return $instance; }, $classes); @@ -282,12 +292,13 @@ private function loadSabrePluginsFromInfoXml(array $classes): array { /** * @param string[] $classes * @return Collection[] + * @throws Exception */ private function loadSabreCollectionsFromInfoXml(array $classes): array { return array_map(function (string $className): Collection { $instance = $this->createClass($className); if (!($instance instanceof Collection)) { - throw new \Exception('Sabre collection plugin ' . $className . ' does not implement the ' . Collection::class . ' interface'); + throw new Exception('Sabre collection plugin ' . $className . ' does not implement the ' . Collection::class . ' interface'); } return $instance; }, $classes); @@ -296,12 +307,13 @@ private function loadSabreCollectionsFromInfoXml(array $classes): array { /** * @param string[] $classes * @return IAddressBookProvider[] + * @throws Exception */ private function loadSabreAddressBookPluginsFromInfoXml(array $classes): array { return array_map(function (string $className): IAddressBookProvider { $instance = $this->createClass($className); if (!($instance instanceof IAddressBookProvider)) { - throw new \Exception('Sabre address book plugin class ' . $className . ' does not implement the ' . IAddressBookProvider::class . ' interface'); + throw new Exception('Sabre address book plugin class ' . $className . ' does not implement the ' . IAddressBookProvider::class . ' interface'); } return $instance; }, $classes); @@ -310,12 +322,13 @@ private function loadSabreAddressBookPluginsFromInfoXml(array $classes): array { /** * @param string[] $classes * @return ICalendarProvider[] + * @throws Exception */ private function loadSabreCalendarPluginsFromInfoXml(array $classes): array { return array_map(function (string $className): ICalendarProvider { $instance = $this->createClass($className); if (!($instance instanceof ICalendarProvider)) { - throw new \Exception('Sabre calendar plugin class ' . $className . ' does not implement the ' . ICalendarProvider::class . ' interface'); + throw new Exception('Sabre calendar plugin class ' . $className . ' does not implement the ' . ICalendarProvider::class . ' interface'); } return $instance; }, $classes); diff --git a/apps/dav/lib/CalDAV/PublicCalendarRoot.php b/apps/dav/lib/CalDAV/PublicCalendarRoot.php index 4f7dfea268227..55f48b982018f 100644 --- a/apps/dav/lib/CalDAV/PublicCalendarRoot.php +++ b/apps/dav/lib/CalDAV/PublicCalendarRoot.php @@ -35,10 +35,10 @@ class PublicCalendarRoot extends Collection { /** @var CalDavBackend */ protected $caldavBackend; - /** @var \OCP\IL10N */ + /** @var IL10N */ protected $l10n; - /** @var \OCP\IConfig */ + /** @var IConfig */ protected $config; /** @var LoggerInterface */ diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php b/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php index 9cab336fd6d65..cb11c7d3e2c16 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php @@ -27,6 +27,11 @@ */ namespace OCA\DAV\CalDAV\Reminder; +use InvalidArgumentException; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use function in_array; + /** * Class NotificationProviderManager * @@ -44,7 +49,7 @@ class NotificationProviderManager { * @return bool */ public function hasProvider(string $type):bool { - return (\in_array($type, ReminderService::REMINDER_TYPES, true) + return (in_array($type, ReminderService::REMINDER_TYPES, true) && isset($this->providers[$type])); } @@ -70,13 +75,14 @@ public function getProvider(string $type):INotificationProvider { * Registers a new provider * * @param string $providerClassName - * @throws \OCP\AppFramework\QueryException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function registerProvider(string $providerClassName):void { $provider = \OC::$server->get($providerClassName); if (!$provider instanceof INotificationProvider) { - throw new \InvalidArgumentException('Invalid notification provider registered'); + throw new InvalidArgumentException('Invalid notification provider registered'); } $this->providers[$provider::NOTIFICATION_TYPE] = $provider; diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index 663779fb69750..67c1bba219fe2 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -34,6 +34,10 @@ */ namespace OCA\DAV\CalDAV\Schedule; +use DateTime; +use DateTimeImmutable; +use DateTimeInterface; +use Exception; use OCP\AppFramework\Utility\ITimeFactory; use OCP\Defaults; use OCP\IConfig; @@ -55,6 +59,8 @@ use Sabre\VObject\Parameter; use Sabre\VObject\Property; use Sabre\VObject\Recur\EventIterator; +use Sabre\VObject\Recur\MaxInstancesExceededException; +use Sabre\VObject\Recur\NoInstancesException; /** * iMIP handler. @@ -112,23 +118,11 @@ class IMipPlugin extends SabreIMipPlugin { public const METHOD_CANCEL = 'cancel'; public const IMIP_INDENT = 15; // Enough for the length of all body bullet items, in all languages - /** - * @param IConfig $config - * @param IMailer $mailer - * @param LoggerInterface $logger - * @param ITimeFactory $timeFactory - * @param L10NFactory $l10nFactory - * @param IUrlGenerator $urlGenerator - * @param Defaults $defaults - * @param ISecureRandom $random - * @param IDBConnection $db - * @param string $userId - */ public function __construct(IConfig $config, IMailer $mailer, LoggerInterface $logger, ITimeFactory $timeFactory, L10NFactory $l10nFactory, IURLGenerator $urlGenerator, Defaults $defaults, ISecureRandom $random, IDBConnection $db, IUserManager $userManager, - $userId) { + string $userId) { parent::__construct(''); $this->userId = $userId; $this->config = $config; @@ -148,6 +142,7 @@ public function __construct(IConfig $config, IMailer $mailer, LoggerInterface $l * * @param Message $iTipMessage * @return void + * @throws Exception */ public function schedule(Message $iTipMessage) { @@ -305,7 +300,7 @@ public function schedule(Message $iTipMessage) { $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } - } catch (\Exception $ex) { + } catch (Exception $ex) { $this->logger->error('Unable to deliver message', ['app' => 'dav', 'exception' => $ex]); $iTipMessage->scheduleStatus = '5.0; EMail delivery failed'; } @@ -313,10 +308,11 @@ public function schedule(Message $iTipMessage) { /** * check if event took place in the past already - * @param VCalendar $vObject - * @return int + * + * @throws MaxInstancesExceededException + * @throws NoInstancesException */ - private function getLastOccurrence(VCalendar $vObject) { + private function getLastOccurrence(VCalendar $vObject): int { /** @var VEvent $component */ $component = $vObject->VEVENT; @@ -326,13 +322,13 @@ private function getLastOccurrence(VCalendar $vObject) { if (isset($component->DTEND)) { $lastOccurrence = $component->DTEND->getDateTime()->getTimeStamp(); } elseif (isset($component->DURATION)) { - /** @var \DateTime $endDate */ + /** @var DateTime $endDate */ $endDate = clone $component->DTSTART->getDateTime(); // $component->DTEND->getDateTime() returns DateTimeImmutable $endDate = $endDate->add(DateTimeParser::parse($component->DURATION->getValue())); $lastOccurrence = $endDate->getTimestamp(); } elseif (!$component->DTSTART->hasTime()) { - /** @var \DateTime $endDate */ + /** @var DateTime $endDate */ $endDate = clone $component->DTSTART->getDateTime(); // $component->DTSTART->getDateTime() returns DateTimeImmutable $endDate = $endDate->modify('+1 day'); @@ -342,7 +338,7 @@ private function getLastOccurrence(VCalendar $vObject) { } } else { $it = new EventIterator($vObject, (string)$component->UID); - $maxDate = new \DateTime(self::MAX_DATE); + $maxDate = new DateTime(self::MAX_DATE); if ($it->isInfinite()) { $lastOccurrence = $maxDate->getTimestamp(); } else { @@ -358,11 +354,7 @@ private function getLastOccurrence(VCalendar $vObject) { return $lastOccurrence; } - /** - * @param Message $iTipMessage - * @return null|Property - */ - private function getCurrentAttendee(Message $iTipMessage) { + private function getCurrentAttendee(Message $iTipMessage): ?Property { /** @var VEvent $vevent */ $vevent = $iTipMessage->message->VEVENT; $attendees = $vevent->select('ATTENDEE'); @@ -375,12 +367,7 @@ private function getCurrentAttendee(Message $iTipMessage) { return null; } - /** - * @param string $default - * @param Property|null $attendee - * @return string - */ - private function getAttendeeLangOrDefault($default, Property $attendee = null) { + private function getAttendeeLangOrDefault(string $default, Property $attendee = null): string { if ($attendee !== null) { $lang = $attendee->offsetGet('LANGUAGE'); if ($lang instanceof Parameter) { @@ -390,11 +377,7 @@ private function getAttendeeLangOrDefault($default, Property $attendee = null) { return $default; } - /** - * @param Property|null $attendee - * @return bool - */ - private function getAttendeeRsvpOrReqForParticipant(Property $attendee = null) { + private function getAttendeeRsvpOrReqForParticipant(Property $attendee = null): bool { if ($attendee !== null) { $rsvp = $attendee->offsetGet('RSVP'); if (($rsvp instanceof Parameter) && (strcasecmp($rsvp->getValue(), 'TRUE') === 0)) { @@ -415,8 +398,7 @@ private function getAttendeeRsvpOrReqForParticipant(Property $attendee = null) { } /** - * @param IL10N $l10n - * @param VEvent $vevent + * @throws Exception */ private function generateWhenString(IL10N $l10n, VEvent $vevent) { $dtstart = $vevent->DTSTART; @@ -442,15 +424,15 @@ private function generateWhenString(IL10N $l10n, VEvent $vevent) { /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */ /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */ - /** @var \DateTimeImmutable $dtstartDt */ + /** @var DateTimeImmutable $dtstartDt */ $dtstartDt = $dtstart->getDateTime(); - /** @var \DateTimeImmutable $dtendDt */ + /** @var DateTimeImmutable $dtendDt */ $dtendDt = $dtend->getDateTime(); $diff = $dtstartDt->diff($dtendDt); - $dtstartDt = new \DateTime($dtstartDt->format(\DateTimeInterface::ATOM)); - $dtendDt = new \DateTime($dtendDt->format(\DateTimeInterface::ATOM)); + $dtstartDt = new DateTime($dtstartDt->format(DateTimeInterface::ATOM)); + $dtendDt = new DateTime($dtendDt->format(DateTimeInterface::ATOM)); if ($isAllDay) { // One day event @@ -508,11 +490,11 @@ private function generateWhenString(IL10N $l10n, VEvent $vevent) { } /** - * @param \DateTime $dtStart - * @param \DateTime $dtEnd + * @param DateTime $dtStart + * @param DateTime $dtEnd * @return bool */ - private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) { + private function isDayEqual(DateTime $dtStart, DateTime $dtEnd): bool { return $dtStart->format('Y-m-d') === $dtEnd->format('Y-m-d'); } @@ -522,8 +504,7 @@ private function isDayEqual(\DateTime $dtStart, \DateTime $dtEnd) { * @param string $method * @param string $summary */ - private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, - $method, $summary) { + private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, string $method, string $summary): void { if ($method === self::METHOD_CANCEL) { // TRANSLATORS Subject for email, when an invitation is cancelled. Ex: "Cancelled: {{Event Name}}" $template->setSubject($l10n->t('Cancelled: %1$s', [$summary])); @@ -543,8 +524,9 @@ private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, * @param IEMailTemplate $template * @param IL10N $l10n * @param VEVENT $vevent + * @throws Exception */ - private function addBulletList(IEMailTemplate $template, IL10N $l10n, $vevent) { + private function addBulletList(IEMailTemplate $template, IL10N $l10n, VEvent $vevent) { if ($vevent->SUMMARY) { $template->addBodyListItem($vevent->SUMMARY, $l10n->t('Title:'), $this->getAbsoluteImagePath('caldav/title.png'),'','',self::IMIP_INDENT); @@ -589,11 +571,9 @@ private function addBulletList(IEMailTemplate $template, IL10N $l10n, $vevent) { * * @param IEMailTemplate $template * @param IL10N $l10n - * @param Message $iTipMessage - * @param int $lastOccurrence + * @param VEvent $vevent * @author brad2014 on github.com */ - private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vevent) { if ($this->config->getAppValue('dav', 'invitation_list_attendees', 'no') === 'no') { return; @@ -603,7 +583,7 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev /** @var Property\ICalendar\CalAddress $organizer */ $organizer = $vevent->ORGANIZER; $organizerURI = $organizer->getNormalizedValue(); - [$scheme,$organizerEmail] = explode(':',$organizerURI,2); # strip off scheme mailto: + [,$organizerEmail] = explode(':',$organizerURI,2); # strip off scheme mailto: /** @var string|null $organizerName */ $organizerName = isset($organizer['CN']) ? $organizer['CN'] : null; $organizerHTML = sprintf('%s', @@ -632,8 +612,8 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev $attendeesText = []; foreach ($attendees as $attendee) { $attendeeURI = $attendee->getNormalizedValue(); - [$scheme,$attendeeEmail] = explode(':',$attendeeURI,2); # strip off scheme mailto: - $attendeeName = isset($attendee['CN']) ? $attendee['CN'] : null; + [,$attendeeEmail] = explode(':',$attendeeURI,2); # strip off scheme mailto: + $attendeeName = $attendee['CN'] ?? null; $attendeeHTML = sprintf('%s', htmlspecialchars($attendeeURI), htmlspecialchars($attendeeName ?: $attendeeEmail)); @@ -657,9 +637,9 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev * @param IL10N $l10n * @param Message $iTipMessage * @param int $lastOccurrence + * @throws \OCP\DB\Exception */ - private function addResponseButtons(IEMailTemplate $template, IL10N $l10n, - Message $iTipMessage, $lastOccurrence) { + private function addResponseButtons(IEMailTemplate $template, IL10N $l10n, Message $iTipMessage, int $lastOccurrence): void { $token = $this->createInvitationToken($iTipMessage, $lastOccurrence); $template->addBodyButtonGroup( @@ -688,18 +668,16 @@ private function addResponseButtons(IEMailTemplate $template, IL10N $l10n, * @param string $path * @return string */ - private function getAbsoluteImagePath($path) { + private function getAbsoluteImagePath(string $path): string { return $this->urlGenerator->getAbsoluteURL( $this->urlGenerator->imagePath('core', $path) ); } /** - * @param Message $iTipMessage - * @param int $lastOccurrence - * @return string + * @throws \OCP\DB\Exception */ - private function createInvitationToken(Message $iTipMessage, $lastOccurrence):string { + private function createInvitationToken(Message $iTipMessage, int $lastOccurrence):string { $token = $this->random->generate(60, ISecureRandom::CHAR_ALPHANUMERIC); /** @var VEvent $vevent */ @@ -722,7 +700,7 @@ private function createInvitationToken(Message $iTipMessage, $lastOccurrence):st 'expiration' => $query->createNamedParameter($lastOccurrence), 'uid' => $query->createNamedParameter($uid) ]) - ->execute(); + ->executeStatement(); return $token; } diff --git a/apps/dav/lib/CalDAV/Schedule/Plugin.php b/apps/dav/lib/CalDAV/Schedule/Plugin.php index bb41391275442..921eb4e87de12 100644 --- a/apps/dav/lib/CalDAV/Schedule/Plugin.php +++ b/apps/dav/lib/CalDAV/Schedule/Plugin.php @@ -28,11 +28,13 @@ */ namespace OCA\DAV\CalDAV\Schedule; +use DateTimeInterface; use DateTimeZone; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\CalendarHome; use OCP\IConfig; use Sabre\CalDAV\ICalendar; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\INode; use Sabre\DAV\IProperties; use Sabre\DAV\PropFind; @@ -66,7 +68,7 @@ class Plugin extends \Sabre\CalDAV\Schedule\Plugin { private $pathOfCalendarObjectChange = null; public const CALENDAR_USER_TYPE = '{' . self::NS_CALDAV . '}calendar-user-type'; - public const SCHEDULE_DEFAULT_CALENDAR_URL = '{' . Plugin::NS_CALDAV . '}schedule-default-calendar-URL'; + public const SCHEDULE_DEFAULT_CALENDAR_URL = '{' . self::NS_CALDAV . '}schedule-default-calendar-URL'; /** * @param IConfig $config @@ -178,7 +180,7 @@ public function scheduleLocalDelivery(ITip\Message $iTipMessage):void { // If parent::scheduleLocalDelivery set scheduleStatus to 1.2, // it means that it was successfully delivered locally. - // Meaning that the ACL plugin is loaded and that a principial + // Meaning that the ACL plugin is loaded and that a principal // exists for the given recipient id, no need to double check /** @var \Sabre\DAVACL\Plugin $aclPlugin */ $aclPlugin = $this->server->getPlugin('acl'); @@ -208,10 +210,10 @@ public function scheduleLocalDelivery(ITip\Message $iTipMessage):void { return; } - /** @var Component $vevent */ + /** @var VEvent $vevent */ $vevent = $vcalendar->VEVENT; - // We don't support autoresponses for recurrencing events for now + // We don't support auto-responses for recurring events for now if (isset($vevent->RRULE) || isset($vevent->RDATE)) { return; } @@ -286,6 +288,7 @@ public function dispatchSchedulingResponses(string $uri):void { * @param PropFind $propFind * @param INode $node * @return void + * @throws NotFound */ public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) { if ($node instanceof IPrincipal) { @@ -337,7 +340,7 @@ public function propFindDefaultCalendarUrl(PropFind $propFind, INode $node) { * @param string $principal * @return string|null */ - protected function getCalendarUserTypeForPrincipal($principal):?string { + protected function getCalendarUserTypeForPrincipal(string $principal):?string { $calendarUserType = '{' . self::NS_CALDAV . '}calendar-user-type'; $properties = $this->server->getProperties( $principal, @@ -418,12 +421,13 @@ private function getDTEndFromVEvent(VEvent $vevent):Property\ICalendar\DateTime /** * @param string $email - * @param \DateTimeInterface $start - * @param \DateTimeInterface $end + * @param DateTimeInterface $start + * @param DateTimeInterface $end * @param string $ignoreUID * @return bool + * @throws NotFound */ - private function isAvailableAtTime(string $email, \DateTimeInterface $start, \DateTimeInterface $end, string $ignoreUID):bool { + private function isAvailableAtTime(string $email, DateTimeInterface $start, DateTimeInterface $end, string $ignoreUID):bool { // This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery // and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail diff --git a/apps/dav/lib/CardDAV/CardDavBackend.php b/apps/dav/lib/CardDAV/CardDavBackend.php index 1845345f89bfe..ac41c4663060a 100644 --- a/apps/dav/lib/CardDAV/CardDavBackend.php +++ b/apps/dav/lib/CardDAV/CardDavBackend.php @@ -226,7 +226,7 @@ public function getAddressBooksForUser($principalUri) { /** * @throws Exception */ - public function getUsersOwnAddressBooks($principalUri): array { + public function getUsersOwnAddressBooks(string $principalUri): array { return array_values($this->getUserAddressBooks($principalUri)); } @@ -377,10 +377,10 @@ public function updateAddressBook($addressBookId, PropPatch $propPatch) { $query->where($query->expr()->eq('id', $query->createNamedParameter($addressBookId))) ->executeStatement(); - $this->addChange($addressBookId, "", 2); + $this->addChange((int) $addressBookId, "", 2); $addressBookRow = $this->getAddressBookById((int)$addressBookId); - $shares = $this->getShares($addressBookId); + $shares = $this->getShares((int) $addressBookId); $this->dispatcher->dispatchTyped(new AddressBookUpdatedEvent((int)$addressBookId, $addressBookRow, $shares, $mutations)); return true; @@ -536,7 +536,7 @@ public function getCards($addressBookId) { * * @param mixed $addressBookId * @param string $cardUri - * @return array|false + * @return array * @throws Exception */ public function getCard($addressBookId, $cardUri) { diff --git a/apps/dav/lib/CardDAV/ContactsManager.php b/apps/dav/lib/CardDAV/ContactsManager.php index bed1e676337dd..37a361b017b5e 100644 --- a/apps/dav/lib/CardDAV/ContactsManager.php +++ b/apps/dav/lib/CardDAV/ContactsManager.php @@ -74,7 +74,7 @@ public function setupSystemContactsProvider(IManager $cm, IURLGenerator $urlGene */ private function register(IManager $cm, $addressBooks, $urlGenerator) { foreach ($addressBooks as $addressBookInfo) { - $addressBook = new \OCA\DAV\CardDAV\AddressBook($this->backend, $addressBookInfo, $this->l10n); + $addressBook = new AddressBook($this->backend, $addressBookInfo, $this->l10n); $cm->registerAddressBook( new AddressBookImpl( $addressBook, diff --git a/apps/dav/lib/CardDAV/UserAddressBooks.php b/apps/dav/lib/CardDAV/UserAddressBooks.php index fa3168f396598..8d2f66b3b1647 100644 --- a/apps/dav/lib/CardDAV/UserAddressBooks.php +++ b/apps/dav/lib/CardDAV/UserAddressBooks.php @@ -33,18 +33,20 @@ use OCP\IConfig; use OCP\IL10N; use OCP\L10N\IFactory; +use Sabre\CardDAV\AddressBookHome; use Sabre\CardDAV\Backend; +use Sabre\DAV\Exception\InvalidResourceType; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\CardDAV\IAddressBook; use function array_map; use Sabre\DAV\MkCol; -class UserAddressBooks extends \Sabre\CardDAV\AddressBookHome { +class UserAddressBooks extends AddressBookHome { - /** @var IL10N */ + /** @var IL10N|null */ protected $l10n; - /** @var IConfig */ + /** @var IConfig|null */ protected $config; /** @var PluginManager */ @@ -87,6 +89,10 @@ public function getChildren() { return array_merge($objects, ...$objectsFromPlugins); } + /** + * @throws InvalidResourceType + * @throws MethodNotAllowed + */ public function createExtendedCollection($name, MkCol $mkCol) { if (ExternalAddressBook::doesViolateReservedName($name)) { throw new MethodNotAllowed('The resource you tried to create has a reserved name'); diff --git a/apps/dav/lib/Comments/RootCollection.php b/apps/dav/lib/Comments/RootCollection.php index af92157f4c1a5..d38790d61ef57 100644 --- a/apps/dav/lib/Comments/RootCollection.php +++ b/apps/dav/lib/Comments/RootCollection.php @@ -34,6 +34,7 @@ use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\ICollection; +use Sabre\DAV\INode; class RootCollection implements ICollection { @@ -94,10 +95,10 @@ protected function initCollections() { throw new NotAuthenticated(); } - $event = new CommentsEntityEvent(CommentsEntityEvent::class); + $this->entityTypeCollections = []; + $event = new CommentsEntityEvent(); $this->dispatcher->dispatchTyped($event); - $this->entityTypeCollections = []; foreach ($event->getEntityCollections() as $entity => $entityExistsFunction) { $this->entityTypeCollections[$entity] = new EntityTypeCollection( $entity, @@ -139,8 +140,9 @@ public function createDirectory($name) { * exist. * * @param string $name - * @return \Sabre\DAV\INode + * @return INode * @throws NotFound + * @throws NotAuthenticated */ public function getChild($name) { $this->initCollections(); @@ -153,7 +155,8 @@ public function getChild($name) { /** * Returns an array with all the child nodes * - * @return \Sabre\DAV\INode[] + * @return INode[] + * @throws NotAuthenticated */ public function getChildren() { $this->initCollections(); @@ -165,6 +168,7 @@ public function getChildren() { * * @param string $name * @return bool + * @throws NotAuthenticated */ public function childExists($name) { $this->initCollections(); diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index f287fd98acc1e..6611efca8b7af 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -32,20 +32,29 @@ */ namespace OCA\DAV\Connector\Sabre; +use Exception; +use OC; use OC\Files\Mount\MoveableMount; use OC\Files\View; +use OC_FileChunking; +use OC_Helper; +use OCA\DAV\Connector\Sabre\Exception\EntityTooLarge; use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCA\DAV\Connector\Sabre\Exception\Forbidden; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType; use OCP\Files\FileInfo; use OCP\Files\ForbiddenException; use OCP\Files\InvalidPathException; use OCP\Files\Mount\IMountManager; +use OCP\Files\NotFoundException; use OCP\Files\NotPermittedException; use OCP\Files\StorageNotAvailableException; use OCP\Lock\ILockingProvider; use OCP\Lock\LockedException; use OCP\Share\IManager; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\Locked; use Sabre\DAV\Exception\NotFound; @@ -81,12 +90,10 @@ class Directory extends Node implements ICollection, IQuota, IMoveTarget, ICopyT /** * Sets up the node, expects a full path name * - * @param View $view - * @param FileInfo $info - * @param ObjectTree|null $tree - * @param IManager|null $shareManager + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function __construct(View $view, FileInfo $info, ObjectTree $tree = null, IManager $shareManager = null) { + public function __construct(View $view, FileInfo $info, $tree = null, IManager $shareManager = null) { parent::__construct($view, $info, $shareManager); $this->tree = $tree; } @@ -114,14 +121,14 @@ public function __construct(View $view, FileInfo $info, ObjectTree $tree = null, * @param string $name Name of the file * @param resource|string $data Initial payload * @return null|string - * @throws Exception\EntityTooLarge - * @throws Exception\UnsupportedMediaType + * @throws EntityTooLarge + * @throws UnsupportedMediaType * @throws FileLocked * @throws InvalidPath * @throws \Sabre\DAV\Exception - * @throws \Sabre\DAV\Exception\BadRequest + * @throws BadRequest * @throws \Sabre\DAV\Exception\Forbidden - * @throws \Sabre\DAV\Exception\ServiceUnavailable + * @throws ServiceUnavailable */ public function createFile($name, $data = null) { try { @@ -130,7 +137,7 @@ public function createFile($name, $data = null) { if (isset($_SERVER['HTTP_OC_CHUNKED'])) { // exit if we can't create a new file and we don't updatable existing file - $chunkInfo = \OC_FileChunking::decodeName($name); + $chunkInfo = OC_FileChunking::decodeName($name); if (!$this->fileView->isCreatable($this->path) && !$this->fileView->isUpdatable($this->path . '/' . $chunkInfo['name']) ) { @@ -152,7 +159,7 @@ public function createFile($name, $data = null) { // use a dummy FileInfo which is acceptable here since it will be refreshed after the put is complete $info = new \OC\Files\FileInfo($path, null, null, [], null); } - $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info); + $node = new File($this->fileView, $info); // only allow 1 process to upload a file at once but still allow reading the file while writing the part file $node->acquireLock(ILockingProvider::LOCK_SHARED); @@ -163,8 +170,8 @@ public function createFile($name, $data = null) { $this->fileView->unlockFile($path . '.upload.part', ILockingProvider::LOCK_EXCLUSIVE); $node->releaseLock(ILockingProvider::LOCK_SHARED); return $result; - } catch (\OCP\Files\StorageNotAvailableException $e) { - throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage(), $e->getCode(), $e); + } catch (StorageNotAvailableException $e) { + throw new ServiceUnavailable($e->getMessage(), $e->getCode(), $e); } catch (InvalidPathException $ex) { throw new InvalidPath($ex->getMessage(), false, $ex); } catch (ForbiddenException $ex) { @@ -181,7 +188,7 @@ public function createFile($name, $data = null) { * @throws FileLocked * @throws InvalidPath * @throws \Sabre\DAV\Exception\Forbidden - * @throws \Sabre\DAV\Exception\ServiceUnavailable + * @throws ServiceUnavailable */ public function createDirectory($name) { try { @@ -194,8 +201,8 @@ public function createDirectory($name) { if (!$this->fileView->mkdir($newPath)) { throw new \Sabre\DAV\Exception\Forbidden('Could not create directory ' . $newPath); } - } catch (\OCP\Files\StorageNotAvailableException $e) { - throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage()); + } catch (StorageNotAvailableException $e) { + throw new ServiceUnavailable($e->getMessage()); } catch (InvalidPathException $ex) { throw new InvalidPath($ex->getMessage()); } catch (ForbiddenException $ex) { @@ -209,11 +216,14 @@ public function createDirectory($name) { * Returns a specific child node, referenced by its name * * @param string $name - * @param FileInfo $info - * @return \Sabre\DAV\INode + * @param null $info + * @return INode + * @throws ContainerExceptionInterface * @throws InvalidPath - * @throws \Sabre\DAV\Exception\NotFound - * @throws \Sabre\DAV\Exception\ServiceUnavailable + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \Sabre\DAV\Exception\Forbidden */ public function getChild($name, $info = null) { if (!$this->info->isReadable()) { @@ -226,8 +236,8 @@ public function getChild($name, $info = null) { try { $this->fileView->verifyPath($this->path, $name); $info = $this->fileView->getFileInfo($path); - } catch (\OCP\Files\StorageNotAvailableException $e) { - throw new \Sabre\DAV\Exception\ServiceUnavailable($e->getMessage()); + } catch (StorageNotAvailableException $e) { + throw new ServiceUnavailable($e->getMessage()); } catch (InvalidPathException $ex) { throw new InvalidPath($ex->getMessage()); } catch (ForbiddenException $e) { @@ -236,13 +246,13 @@ public function getChild($name, $info = null) { } if (!$info) { - throw new \Sabre\DAV\Exception\NotFound('File with name ' . $path . ' could not be located'); + throw new NotFound('File with name ' . $path . ' could not be located'); } if ($info['mimetype'] === 'httpd/unix-directory') { - $node = new \OCA\DAV\Connector\Sabre\Directory($this->fileView, $info, $this->tree, $this->shareManager); + $node = new Directory($this->fileView, $info, $this->tree, $this->shareManager); } else { - $node = new \OCA\DAV\Connector\Sabre\File($this->fileView, $info, $this->shareManager); + $node = new File($this->fileView, $info, $this->shareManager); } if ($this->tree) { $this->tree->cacheNode($node); @@ -253,9 +263,15 @@ public function getChild($name, $info = null) { /** * Returns an array with all the child nodes * - * @return \Sabre\DAV\INode[] - * @throws \Sabre\DAV\Exception\Locked - * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden + * @return INode[] + * @throws ContainerExceptionInterface + * @throws Forbidden + * @throws InvalidPath + * @throws Locked + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \Sabre\DAV\Exception\Forbidden */ public function getChildren() { if (!is_null($this->dirContent)) { @@ -334,7 +350,7 @@ public function getQuotaInfo() { } try { $info = $this->fileView->getFileInfo($this->path, false); - $storageInfo = \OC_Helper::getStorageInfo($this->info->getPath(), $info); + $storageInfo = OC_Helper::getStorageInfo($this->info->getPath(), $info); if ($storageInfo['quota'] === FileInfo::SPACE_UNLIMITED) { $free = FileInfo::SPACE_UNLIMITED; } else { @@ -345,9 +361,9 @@ public function getQuotaInfo() { $free ]; return $this->quotaInfo; - } catch (\OCP\Files\NotFoundException $e) { + } catch (NotFoundException $e) { return [0, 0]; - } catch (\OCP\Files\StorageNotAvailableException $e) { + } catch (StorageNotAvailableException $e) { return [0, 0]; } catch (NotPermittedException $e) { return [0, 0]; @@ -374,9 +390,12 @@ public function getQuotaInfo() { * @param INode $sourceNode Source node itself * @return bool * @throws BadRequest - * @throws ServiceUnavailable - * @throws Forbidden + * @throws ContainerExceptionInterface * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable * @throws \Sabre\DAV\Exception\Forbidden */ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) { @@ -410,7 +429,7 @@ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) { $sourcePath = $sourceNode->getPath(); $isMovableMount = false; - $sourceMount = \OC::$server->get(IMountManager::class)->find($this->fileView->getAbsolutePath($sourcePath)); + $sourceMount = OC::$server->get(IMountManager::class)->find($this->fileView->getAbsolutePath($sourcePath)); $internalPath = $sourceMount->getInternalPath($this->fileView->getAbsolutePath($sourcePath)); if ($sourceMount instanceof MoveableMount && $internalPath === '') { $isMovableMount = true; @@ -461,6 +480,11 @@ public function moveInto($targetName, $fullSourcePath, INode $sourceNode) { } + /** + * @throws InvalidPath + * @throws \Sabre\DAV\Exception\Forbidden + * @throws Exception + */ public function copyInto($targetName, $sourcePath, INode $sourceNode) { if ($sourceNode instanceof File || $sourceNode instanceof Directory) { $destinationPath = $this->getPath() . '/' . $targetName; diff --git a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php index 18e95df42f17d..f1b395f6462bb 100644 --- a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php @@ -42,7 +42,9 @@ use Sabre\DAV\Exception\PreconditionFailed; use Sabre\DAV\Exception\RequestedRangeNotSatisfiable; use Sabre\DAV\Exception\ServiceUnavailable; +use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; +use Throwable; class ExceptionLoggerPlugin extends ServerPlugin { protected $nonFatalExceptions = [ @@ -92,9 +94,9 @@ class ExceptionLoggerPlugin extends ServerPlugin { /** * @param string $loggerAppName app name to use when logging - * @param LoggerInterface $logger + * @param LoggerInterface|null $logger */ - public function __construct(string $loggerAppName, LoggerInterface $logger) { + public function __construct(string $loggerAppName, ?LoggerInterface $logger) { $this->appName = $loggerAppName; $this->logger = $logger; } @@ -107,17 +109,17 @@ public function __construct(string $loggerAppName, LoggerInterface $logger) { * * This method should set up the required event subscriptions. * - * @param \Sabre\DAV\Server $server + * @param Server $server * @return void */ - public function initialize(\Sabre\DAV\Server $server) { + public function initialize(Server $server) { $server->on('exception', [$this, 'logException'], 10); } /** * Log exception */ - public function logException(\Throwable $ex): void { + public function logException(Throwable $ex): void { $exceptionClass = get_class($ex); if (isset($this->nonFatalExceptions[$exceptionClass]) || ( @@ -125,9 +127,9 @@ public function logException(\Throwable $ex): void { $ex->getMessage() === 'System in maintenance mode.' ) ) { - $this->logger->debug('Sabre has thrown an exception', ['exception' => $ex, 'app' => $this->appName]); + $this->logger->debug($ex->getMessage(), ['exception' => $ex, 'app' => $this->appName]); + } else { + $this->logger->critical($ex->getMessage(), ['exception' => $ex, 'app' => $this->appName]); } - - $this->logger->critical('Sabre has thrown an exception', ['exception' => $ex, 'app' => $this->appName]); } } diff --git a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php index 8ed7ae13c6597..51b0669975313 100644 --- a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php @@ -90,7 +90,7 @@ public function getFeatures() { */ public function propFind(PropFind $propFind, INode $node) { $propFind->handle('{DAV:}supportedlock', function () { - return new SupportedLock(true); + return new SupportedLock(); }); $propFind->handle('{DAV:}lockdiscovery', function () use ($propFind) { return new LockDiscovery([]); diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index d45de9b718339..e0e34d2200931 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -127,7 +127,7 @@ public function __construct(View $view, FileInfo $info, IManager $shareManager = * different object on a subsequent GET you are strongly recommended to not * return an ETag, and just return null. * - * @param resource $data + * @param resource|string $data * * @return string|null * @throws DAVForbiddenException diff --git a/apps/dav/lib/Connector/Sabre/FilesPlugin.php b/apps/dav/lib/Connector/Sabre/FilesPlugin.php index 5daaea87d2d20..275bc6bd90c95 100644 --- a/apps/dav/lib/Connector/Sabre/FilesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesPlugin.php @@ -218,6 +218,10 @@ public function checkMove(string $source, string $destination) { if ($sourceDir !== $destinationDir) { $sourceNodeFileInfo = $sourceNode->getFileInfo(); + if ($sourceNodeFileInfo === null) { + throw new NotFound($source . ' does not exist'); + } + if (!$sourceNodeFileInfo->isDeletable()) { throw new Forbidden($source . " cannot be deleted"); } diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 982237019b8e2..9aa8205d88bcd 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -166,7 +166,7 @@ public function initialize(\Sabre\DAV\Server $server) { * @param string $uri * @return array */ - public function getSupportedReportSet($uri) { + public function getSupportedReportSet($uri): array { return [self::REPORT_NAME]; } @@ -174,15 +174,15 @@ public function getSupportedReportSet($uri) { * REPORT operations to look for files * * @param string $reportName - * @param array $report + * @param array|object $report * @param string $uri * @return bool|void * @throws BadRequest * @throws NotFound - * @throws PreconditionFailed + * @throws PreconditionFailed|NotFoundException * @internal param $ [] $report */ - public function onReport(string $reportName, array $report, string $uri) { + public function onReport(string $reportName, $report, string $uri) { $reportTargetNode = $this->server->tree->getNodeForPath($uri); if (!$reportTargetNode instanceof Directory || $reportName !== self::REPORT_NAME) { return; @@ -423,7 +423,7 @@ public function findNodesByFileIds(Node $rootNode, array $fileIds): array { $entry = current($entry); if ($entry instanceof \OCP\Files\File) { $results[] = new File($this->fileView, $entry); - } elseif ($entry instanceof \OCP\Files\Folder) { + } elseif ($entry instanceof Folder) { $results[] = new Directory($this->fileView, $entry); } } diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php index ff52d9b18f0fc..dfd0b1214f4e9 100644 --- a/apps/dav/lib/Connector/Sabre/Node.php +++ b/apps/dav/lib/Connector/Sabre/Node.php @@ -38,6 +38,7 @@ use OC\Files\Mount\MoveableMount; use OC\Files\View; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCA\Files_Sharing\SharedStorage; use OCP\Constants; use OCP\Files\FileInfo; use OCP\Files\InvalidPathException; @@ -63,7 +64,7 @@ abstract class Node implements INode { /** * The path to the current node * - * @var string + * @var string|null */ protected $path; @@ -75,7 +76,7 @@ abstract class Node implements INode { protected $property_cache = null; /** - * @var FileInfo + * @var FileInfo|null */ protected $info; @@ -90,6 +91,8 @@ abstract class Node implements INode { * @param View $view * @param FileInfo $info * @param IManager|null $shareManager + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function __construct(View $view, FileInfo $info, IManager $shareManager = null) { $this->fileView = $view; @@ -120,7 +123,7 @@ public function getName() { * * @return string */ - public function getPath(): string { + public function getPath(): ?string { return $this->path; } @@ -224,7 +227,7 @@ public function setUploadTime(int $time): int { * * @return integer */ - public function getSize(): int { + public function getSize(): ?int { return $this->info->getSize(); } @@ -233,7 +236,7 @@ public function getSize(): int { * * @return int */ - public function getId(): int { + public function getId(): ?int { return $this->info->getId(); } @@ -253,7 +256,7 @@ public function getFileId(): ?string { /** * @return integer */ - public function getInternalFileId(): int { + public function getInternalFileId(): ?int { return $this->info->getId(); } @@ -279,8 +282,8 @@ public function getSharePermissions(?string $user): int { $storage = null; } - if ($storage && $storage->instanceOfStorage('\OCA\Files_Sharing\SharedStorage')) { - /** @var \OCA\Files_Sharing\SharedStorage $storage */ + if ($storage && $storage->instanceOfStorage(SharedStorage::class)) { + /** @var SharedStorage $storage */ $permissions = (int)$storage->getShare()->getPermissions(); } else { $permissions = $this->info->getPermissions(); @@ -416,7 +419,7 @@ public function changeLock(int $type) { $this->fileView->changeLock($this->path, $type); } - public function getFileInfo(): FileInfo { + public function getFileInfo(): ?FileInfo { return $this->info; } diff --git a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php index 7e1f849b6372d..398ffd0ac77ee 100644 --- a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php +++ b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php @@ -154,7 +154,7 @@ public function beforeMove(string $source, string $destination) { * @param string $path relative to the users home * @param int|null $length * @return bool - *@throws InsufficientStorage|ServiceUnavailable + * @throws InsufficientStorage|ServiceUnavailable */ public function checkQuota(string $path, int $length = null): bool { if ($length === null) { diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index 7d0b0fc7fd8de..88b8ad91f388b 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -56,6 +56,7 @@ use Psr\Log\LoggerInterface; use Sabre\DAV\Auth\Plugin; use Sabre\DAV\Exception; +use Sabre\DAV\SimpleCollection; class ServerFactory { /** @var IConfig */ @@ -128,7 +129,7 @@ public function createServer(string $baseUri, Plugin $authPlugin, callable $viewCallBack): Server { // Fire up server - $objectTree = new ObjectTree(); + $objectTree = new ObjectTree(new SimpleCollection('root')); $server = new Server($objectTree); // Set URL explicitly due to reverse-proxy situations $server->httpRequest->setUrl($requestUri); @@ -167,6 +168,7 @@ public function createServer(string $baseUri, if ($user = \OC::$server->get(IUserSession::class)->getUser()) { /** @var IRootFolder $root */ $rootInfo = $root->getUserFolder($user->getUID()); + $userFolder = $rootInfo; } else { $rootInfo = $root; } @@ -193,7 +195,7 @@ public function createServer(string $baseUri, !$this->config->getSystemValue('debug', false) ) ); - $server->addPlugin(new QuotaPlugin($view, true)); + $server->addPlugin(new QuotaPlugin($view)); if ($this->userSession->isLoggedIn()) { $server->addPlugin(new TagsPlugin($objectTree, $this->tagManager)); diff --git a/apps/dav/lib/Connector/Sabre/SharesPlugin.php b/apps/dav/lib/Connector/Sabre/SharesPlugin.php index 1687ecda81d33..fb1c429ac1c58 100644 --- a/apps/dav/lib/Connector/Sabre/SharesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/SharesPlugin.php @@ -48,13 +48,6 @@ class SharesPlugin extends ServerPlugin { public const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types'; public const SHAREES_PROPERTYNAME = '{http://nextcloud.org/ns}sharees'; - /** - * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - /** @var IManager */ private $shareManager; @@ -107,8 +100,8 @@ public function initialize(\Sabre\DAV\Server $server) { $server->protectedProperties[] = self::SHARETYPES_PROPERTYNAME; $server->protectedProperties[] = self::SHAREES_PROPERTYNAME; - $this->server = $server; - $this->server->on('propFind', [$this, 'handleGetProperties']); + $server1 = $server; + $server1->on('propFind', [$this, 'handleGetProperties']); } /** diff --git a/apps/dav/lib/Controller/InvitationResponseController.php b/apps/dav/lib/Controller/InvitationResponseController.php index de22e3ba6a9e6..f69ef09485c9a 100644 --- a/apps/dav/lib/Controller/InvitationResponseController.php +++ b/apps/dav/lib/Controller/InvitationResponseController.php @@ -31,10 +31,14 @@ use OCP\AppFramework\Controller; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\DB\Exception; use OCP\IDBConnection; use OCP\IRequest; +use Sabre\VObject\Component\VEvent; use Sabre\VObject\ITip\Message; +use Sabre\VObject\Property\ICalendar\CalAddress; use Sabre\VObject\Reader; +use function in_array; class InvitationResponseController extends Controller { @@ -74,6 +78,7 @@ public function __construct(string $appName, IRequest $request, * * @param string $token * @return TemplateResponse + * @throws Exception */ public function accept(string $token):TemplateResponse { $row = $this->getTokenInformation($token); @@ -98,6 +103,7 @@ public function accept(string $token):TemplateResponse { * * @param string $token * @return TemplateResponse + * @throws Exception */ public function decline(string $token):TemplateResponse { $row = $this->getTokenInformation($token); @@ -137,6 +143,7 @@ public function options(string $token):TemplateResponse { * @param string $token * * @return TemplateResponse + * @throws Exception */ public function processMoreOptionsResult(string $token):TemplateResponse { $partstat = $this->request->getParam('partStat'); @@ -144,7 +151,7 @@ public function processMoreOptionsResult(string $token):TemplateResponse { $comment = $this->request->getParam('comment'); $row = $this->getTokenInformation($token); - if (!$row || !\in_array($partstat, ['ACCEPTED', 'DECLINED', 'TENTATIVE'])) { + if (!$row || !in_array($partstat, ['ACCEPTED', 'DECLINED', 'TENTATIVE'])) { return new TemplateResponse($this->appName, 'schedule-response-error', [], 'guest'); } @@ -162,14 +169,15 @@ public function processMoreOptionsResult(string $token):TemplateResponse { /** * @param string $token * @return array|null + * @throws Exception */ - private function getTokenInformation(string $token) { + private function getTokenInformation(string $token): ?array { $query = $this->db->getQueryBuilder(); $query->select('*') ->from('calendar_invitations') ->where($query->expr()->eq('token', $query->createNamedParameter($token))); - $stmt = $query->execute(); - $row = $stmt->fetch(\PDO::FETCH_ASSOC); + $stmt = $query->executeQuery(); + $row = $stmt->fetch(); if (!$row) { return null; @@ -224,8 +232,9 @@ private function buildITipResponse(array $row, string $partStat, int $guests = n $partStat, $row['attendee'], $row['organizer'], $row['uid'], $row['sequence'] ?? 0, $row['recurrenceid'] ?? '' ])); + /** @var VEvent $vEvent */ $vEvent = $vObject->{'VEVENT'}; - /** @var \Sabre\VObject\Property\ICalendar\CalAddress $attendee */ + /** @var CalAddress $attendee */ $attendee = $vEvent->{'ATTENDEE'}; $vEvent->DTSTAMP = date('Ymd\\THis\\Z', $this->timeFactory->getTime()); diff --git a/apps/dav/lib/DAV/Sharing/Backend.php b/apps/dav/lib/DAV/Sharing/Backend.php index 0f675ea4c1512..27ca79d0e01dd 100644 --- a/apps/dav/lib/DAV/Sharing/Backend.php +++ b/apps/dav/lib/DAV/Sharing/Backend.php @@ -188,7 +188,7 @@ private function unshare($shareable, $element) { * @param int $resourceId * @return array */ - public function getShares($resourceId) { + public function getShares(int $resourceId): array { $query = $this->db->getQueryBuilder(); $result = $query->select(['principaluri', 'access']) ->from('dav_shares') diff --git a/apps/dav/lib/Files/FileSearchBackend.php b/apps/dav/lib/Files/FileSearchBackend.php index 45e911db182a0..7017becc27850 100644 --- a/apps/dav/lib/Files/FileSearchBackend.php +++ b/apps/dav/lib/Files/FileSearchBackend.php @@ -25,6 +25,8 @@ */ namespace OCA\DAV\Files; +use DateTime; +use InvalidArgumentException; use OC\Files\Search\SearchBinaryOperator; use OC\Files\Search\SearchComparison; use OC\Files\Search\SearchOrder; @@ -32,17 +34,21 @@ use OC\Files\View; use OCA\DAV\Connector\Sabre\CachingTree; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\File; use OCA\DAV\Connector\Sabre\FilesPlugin; use OCA\DAV\Connector\Sabre\TagsPlugin; use OCP\Files\Cache\ICacheEntry; use OCP\Files\Folder; use OCP\Files\IRootFolder; use OCP\Files\Node; +use OCP\Files\NotFoundException; use OCP\Files\Search\ISearchOperator; use OCP\Files\Search\ISearchOrder; use OCP\Files\Search\ISearchQuery; use OCP\IUser; use OCP\Share\IManager; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Sabre\DAV\Exception\NotFound; use SearchDAV\Backend\ISearchBackend; use SearchDAV\Backend\SearchPropertyDefinition; @@ -51,6 +57,7 @@ use SearchDAV\Query\Operator; use SearchDAV\Query\Order; use SearchDAV\Query\Query; +use function array_slice; class FileSearchBackend implements ISearchBackend { /** @var CachingTree */ @@ -137,50 +144,53 @@ public function getPropertyDefinitionsForScope($href, $path) { } /** - * @param Query $search + * @param Query $query * @return SearchResult[] + * @throws NotFound + * @throws NotFoundException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function search(Query $search) { - if (count($search->from) !== 1) { - throw new \InvalidArgumentException('Searching more than one folder is not supported'); + public function search(Query $query) { + if (count($query->from) !== 1) { + throw new InvalidArgumentException('Searching more than one folder is not supported'); } - $query = $this->transformQuery($search); - $scope = $search->from[0]; + $transformedQuery = $this->transformQuery($query); + $scope = $query->from[0]; if ($scope->path === null) { - throw new \InvalidArgumentException('Using uri\'s as scope is not supported, please use a path relative to the search arbiter instead'); + throw new InvalidArgumentException('Using uri\'s as scope is not supported, please use a path relative to the search arbiter instead'); } $node = $this->tree->getNodeForPath($scope->path); if (!$node instanceof Directory) { - throw new \InvalidArgumentException('Search is only supported on directories'); + throw new InvalidArgumentException('Search is only supported on directories'); } $fileInfo = $node->getFileInfo(); $folder = $this->rootFolder->get($fileInfo->getPath()); /** @var Folder $folder $results */ - $results = $folder->search($query); + $results = $folder->search($transformedQuery); - /** @var SearchResult[] $nodes */ $nodes = array_map(function (Node $node) { if ($node instanceof Folder) { - $davNode = new \OCA\DAV\Connector\Sabre\Directory($this->view, $node, $this->tree, $this->shareManager); + $davNode = new Directory($this->view, $node, $this->tree, $this->shareManager); } else { - $davNode = new \OCA\DAV\Connector\Sabre\File($this->view, $node, $this->shareManager); + $davNode = new File($this->view, $node, $this->shareManager); } $path = $this->getHrefForNode($node); $this->tree->cacheNode($davNode, $path); return new SearchResult($davNode, $path); }, $results); - if (!$query->limitToHome()) { + if (!$transformedQuery->limitToHome()) { // Sort again, since the result from multiple storages is appended and not sorted - usort($nodes, function (SearchResult $a, SearchResult $b) use ($search) { - return $this->sort($a, $b, $search->orderBy); + usort($nodes, function (SearchResult $a, SearchResult $b) use ($query) { + return $this->sort($a, $b, $query->orderBy); }); } // If a limit is provided use only return that number of files - if ($search->limit->maxResults !== 0) { - $nodes = \array_slice($nodes, 0, $search->limit->maxResults); + if ($query->limit->maxResults !== 0) { + $nodes = array_slice($nodes, 0, $query->limit->maxResults); } return $nodes; @@ -217,7 +227,7 @@ private function sort(SearchResult $a, SearchResult $b, array $orders) { return 0; } - private function compareProperties($a, $b, Order $order) { + private function compareProperties($a, $b, Order $order): int { switch ($order->property->dataType) { case SearchPropertyDefinition::DATATYPE_STRING: return strcmp($a, $b); @@ -262,7 +272,7 @@ private function getSearchResultProperty(SearchResult $result, SearchPropertyDef * @param Node $node * @return string */ - private function getHrefForNode(Node $node) { + private function getHrefForNode(Node $node): string { $base = '/files/' . $this->user->getUID(); return $base . $this->view->getRelativePath($node->getPath()); } @@ -282,7 +292,7 @@ private function transformQuery(Query $query): ISearchQuery { if ($ownerProp === $this->user->getUID()) { $limitHome = true; } else { - throw new \InvalidArgumentException("Invalid search value for '{http://owncloud.org/ns}owner-id', only the current user id is allowed"); + throw new InvalidArgumentException("Invalid search value for '{http://owncloud.org/ns}owner-id', only the current user id is allowed"); } } @@ -323,19 +333,19 @@ private function transformSearchOperation(Operator $operator) { case Operator::OPERATION_LESS_THAN: case Operator::OPERATION_IS_LIKE: if (count($operator->arguments) !== 2) { - throw new \InvalidArgumentException('Invalid number of arguments for ' . $trimmedType . ' operation'); + throw new InvalidArgumentException('Invalid number of arguments for ' . $trimmedType . ' operation'); } if (!($operator->arguments[0] instanceof SearchPropertyDefinition)) { - throw new \InvalidArgumentException('Invalid argument 1 for ' . $trimmedType . ' operation, expected property'); + throw new InvalidArgumentException('Invalid argument 1 for ' . $trimmedType . ' operation, expected property'); } if (!($operator->arguments[1] instanceof Literal)) { - throw new \InvalidArgumentException('Invalid argument 2 for ' . $trimmedType . ' operation, expected literal'); + throw new InvalidArgumentException('Invalid argument 2 for ' . $trimmedType . ' operation, expected literal'); } return new SearchComparison($trimmedType, $this->mapPropertyNameToColumn($operator->arguments[0]), $this->castValue($operator->arguments[0], $operator->arguments[1]->value)); case Operator::OPERATION_IS_COLLECTION: return new SearchComparison('eq', 'mimetype', ICacheEntry::DIRECTORY_MIMETYPE); default: - throw new \InvalidArgumentException('Unsupported operation ' . $trimmedType . ' (' . $operator->type . ')'); + throw new InvalidArgumentException('Unsupported operation ' . $trimmedType . ' (' . $operator->type . ')'); } } @@ -343,7 +353,7 @@ private function transformSearchOperation(Operator $operator) { * @param SearchPropertyDefinition $property * @return string */ - private function mapPropertyNameToColumn(SearchPropertyDefinition $property) { + private function mapPropertyNameToColumn(SearchPropertyDefinition $property): string { switch ($property->name) { case '{DAV:}displayname': return 'name'; @@ -360,7 +370,7 @@ private function mapPropertyNameToColumn(SearchPropertyDefinition $property) { case FilesPlugin::INTERNAL_FILEID_PROPERTYNAME: return 'fileid'; default: - throw new \InvalidArgumentException('Unsupported property for search or order: ' . $property->name); + throw new InvalidArgumentException('Unsupported property for search or order: ' . $property->name); } } @@ -376,8 +386,8 @@ private function castValue(SearchPropertyDefinition $property, $value) { if (is_numeric($value)) { return max(0, 0 + $value); } - $date = \DateTime::createFromFormat(\DateTimeInterface::ATOM, $value); - return ($date instanceof \DateTime && $date->getTimestamp() !== false) ? $date->getTimestamp() : 0; + $date = DateTime::createFromFormat(\DateTimeInterface::ATOM, $value); + return ($date instanceof DateTime && $date->getTimestamp() !== false) ? $date->getTimestamp() : 0; default: return $value; } @@ -415,13 +425,13 @@ private function extractWhereValue(Operator &$operator, string $propertyName, st return $value; } else { - throw new \InvalidArgumentException("searching by '$propertyName' is only allowed with a literal value"); + throw new InvalidArgumentException("searching by '$propertyName' is only allowed with a literal value"); } } else { - throw new \InvalidArgumentException("searching by '$propertyName' is not allowed inside a '{DAV:}or' or '{DAV:}not'"); + throw new InvalidArgumentException("searching by '$propertyName' is not allowed inside a '{DAV:}or' or '{DAV:}not'"); } } else { - throw new \InvalidArgumentException("searching by '$propertyName' is only allowed inside a '$comparison'"); + throw new InvalidArgumentException("searching by '$propertyName' is only allowed inside a '$comparison'"); } } else { return null; diff --git a/apps/dav/lib/Files/RootCollection.php b/apps/dav/lib/Files/RootCollection.php index 09f53c9ed089e..62c01280a49f6 100644 --- a/apps/dav/lib/Files/RootCollection.php +++ b/apps/dav/lib/Files/RootCollection.php @@ -25,12 +25,15 @@ */ namespace OCA\DAV\Files; +use OC\User\NoUserException; use OCP\Files\FileInfo; use OCP\Files\IRootFolder; +use OCP\Files\NotPermittedException; use OCP\IUserSession; use Sabre\DAV\INode; use Sabre\DAV\SimpleCollection; use Sabre\DAVACL\AbstractPrincipalCollection; +use function Sabre\Uri\split; class RootCollection extends AbstractPrincipalCollection { @@ -43,9 +46,11 @@ class RootCollection extends AbstractPrincipalCollection { * * @param array $principalInfo * @return INode + * @throws NotPermittedException + * @throws NoUserException */ public function getChildForPrincipal(array $principalInfo) { - [,$name] = \Sabre\Uri\split($principalInfo['uri']); + [,$name] = split($principalInfo['uri']); $user = \OC::$server->get(IUserSession::class)->getUser(); if (is_null($user) || $name !== $user->getUID()) { // a user is only allowed to see their own home contents, so in case another collection diff --git a/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php b/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php index ae93071285975..a1c196808386f 100644 --- a/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php +++ b/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php @@ -65,7 +65,7 @@ public function run(IOutput $output) { $query = $this->connection->getQueryBuilder(); $query->select(['principaluri', 'uri']) ->from('calendarsubscriptions'); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $count = 0; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index 4ef799668d28b..1721431da9e22 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -28,6 +28,7 @@ */ namespace OCA\DAV; +use OC; use OC\KnownUser\KnownUserService; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\CalDavBackend; @@ -59,38 +60,38 @@ use OCP\Share\IManager; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; -use Psr\Log\LoggerInterface; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Sabre\DAV\SimpleCollection; class RootCollection extends SimpleCollection { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ public function __construct() { - $l10n = \OC::$server->get(IFactory::class)->get('dav'); - $random = \OC::$server->get(ISecureRandom::class); -<<<<<<< HEAD - $logger = \OC::$server->getLogger(); - $psrLogger = \OC::$server->get(LoggerInterface::class); -======= - $logger = \OC::$server->get(LoggerInterface::class); ->>>>>>> 4565b23b66 (Move uses of ILogger to LoggerInterface) - $userManager = \OC::$server->get(IUserManager::class); - $userSession = \OC::$server->get(IUserSession::class); - $groupManager = \OC::$server->get(IGroupManager::class); - $shareManager = \OC::$server->get(IManager::class); - $db = \OC::$server->get(IDBConnection::class); - $dispatcher = \OC::$server->get(IEventDispatcher::class); - $config = \OC::$server->get(IConfig::class); - $proxyMapper = \OC::$server->get(ProxyMapper::class); + $l10n = OC::$server->get(IFactory::class)->get('dav'); + $random = OC::$server->get(ISecureRandom::class); + $logger = OC::$server->get(LoggerInterface::class); + $userManager = OC::$server->get(IUserManager::class); + $userSession = OC::$server->get(IUserSession::class); + $groupManager = OC::$server->get(IGroupManager::class); + $shareManager = OC::$server->get(IManager::class); + $db = OC::$server->get(IDBConnection::class); + $dispatcher = OC::$server->get(IEventDispatcher::class); + $config = OC::$server->get(IConfig::class); + $proxyMapper = OC::$server->get(ProxyMapper::class); $userPrincipalBackend = new Principal( $userManager, $groupManager, $shareManager, - \OC::$server->get(IUserSession::class), - \OC::$server->get(IAppManager::class), + OC::$server->get(IUserSession::class), + OC::$server->get(IAppManager::class), $proxyMapper, - \OC::$server->get(KnownUserService::class), - \OC::$server->get(IConfig::class), - \OC::$server->get(IFactory::class) + OC::$server->get(KnownUserService::class), + OC::$server->get(IConfig::class), + OC::$server->get(IFactory::class) ); $groupPrincipalBackend = new GroupPrincipalBackend($groupManager, $userSession, $shareManager, $config); $calendarResourcePrincipalBackend = new ResourcePrincipalBackend($db, $userSession, $groupManager, $logger, $proxyMapper); @@ -123,38 +124,37 @@ public function __construct() { $dispatcher, $config ); - $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users', $psrLogger); + $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users', $logger); $userCalendarRoot->disableListing = $disableListing; - $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources', $psrLogger); + $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources', $logger); $resourceCalendarRoot->disableListing = $disableListing; - $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $caldavBackend, 'principals/calendar-rooms', $psrLogger); + $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $caldavBackend, 'principals/calendar-rooms', $logger); $roomCalendarRoot->disableListing = $disableListing; - $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config, $psrLogger); - $publicCalendarRoot->disableListing = $disableListing; + $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config, $logger); $systemTagCollection = new SystemTag\SystemTagsByIdCollection( - \OC::$server->get(ISystemTagManager::class), - \OC::$server->get(IUserSession::class), + OC::$server->get(ISystemTagManager::class), + OC::$server->get(IUserSession::class), $groupManager ); $systemTagRelationsCollection = new SystemTag\SystemTagsRelationsCollection( - \OC::$server->get(ISystemTagManager::class), - \OC::$server->get(ISystemTagObjectMapper::class), - \OC::$server->get(IUserSession::class), + OC::$server->get(ISystemTagManager::class), + OC::$server->get(ISystemTagObjectMapper::class), + OC::$server->get(IUserSession::class), $groupManager, - \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class) + OC::$server->get(IEventDispatcher::class) ); $commentsCollection = new Comments\RootCollection( - \OC::$server->get(ICommentsManager::class), + OC::$server->get(ICommentsManager::class), $userManager, - \OC::$server->get(IUserSession::class), - \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class), - \OC::$server->get(LoggerInterface::class) + OC::$server->get(IUserSession::class), + OC::$server->get(IEventDispatcher::class), + OC::$server->get(LoggerInterface::class) ); - $pluginManager = new PluginManager(\OC::$server, \OC::$server->get(IAppManager::class)); + $pluginManager = new PluginManager(OC::$server, OC::$server->get(IAppManager::class)); $usersCardDavBackend = new CardDavBackend($db, $userPrincipalBackend, $userManager, $groupManager, $dispatcher); $usersAddressBookRoot = new AddressBookRoot($userPrincipalBackend, $usersCardDavBackend, $pluginManager, 'principals/users'); $usersAddressBookRoot->disableListing = $disableListing; @@ -166,14 +166,14 @@ public function __construct() { $uploadCollection = new Upload\RootCollection( $userPrincipalBackend, 'principals/users', - \OC::$server->get(CleanupService::class)); + OC::$server->get(CleanupService::class)); $uploadCollection->disableListing = $disableListing; $avatarCollection = new Avatars\RootCollection($userPrincipalBackend, 'principals/users'); $avatarCollection->disableListing = $disableListing; $appleProvisioning = new AppleProvisioningNode( - \OC::$server->get(ITimeFactory::class)); + OC::$server->get(ITimeFactory::class)); $children = [ new SimpleCollection('principals', [ diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index eb994a3471987..994f9727dcac9 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -35,8 +35,10 @@ namespace OCA\DAV; use OCP\Diagnostics\IEventLogger; +use OC; use OC\Authentication\TwoFactorAuth\Manager as TwoFactorAuthManager; use OC\EventDispatcher\SymfonyAdapter; +use OC\Files\AppData\Factory as AppDataFactory; use OC\Security\Bruteforce\Throttler; use OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin; use OCA\DAV\CalDAV\ICSExportPlugin\ICSExportPlugin; @@ -62,6 +64,8 @@ use OCP\Share\IManager; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\BirthdayService; @@ -100,6 +104,7 @@ use OCP\IRequest; use Sabre\CardDAV\VCFExportPlugin; use Sabre\DAV\Auth\Plugin; +use Sabre\DAV\Exception; use Sabre\DAV\UUIDUtil; use SearchDAV\DAV\SearchPlugin; @@ -114,34 +119,39 @@ class Server { /** @var Connector\Sabre\Server */ public $server; + /** + * @throws ContainerExceptionInterface + * @throws Exception + * @throws NotFoundExceptionInterface + */ public function __construct(IRequest $request, $baseUri) { $this->request = $request; $this->baseUri = $baseUri; - $logger = \OC::$server->get(LoggerInterface::class); - $dispatcher = \OC::$server->get(SymfonyAdapter::class); + $logger = OC::$server->get(LoggerInterface::class); + $dispatcher = OC::$server->get(SymfonyAdapter::class); /** @var IEventDispatcher $newDispatcher */ - $newDispatcher = \OC::$server->get(IEventDispatcher::class); + $newDispatcher = OC::$server->get(IEventDispatcher::class); $root = new RootCollection(); $this->server = new Connector\Sabre\Server(new CachingTree($root)); // Add maintenance plugin - $this->server->addPlugin(new MaintenancePlugin(\OC::$server->get(IConfig::class), \OC::$server->get(IFactory::class)->get('dav'))); + $this->server->addPlugin(new MaintenancePlugin(OC::$server->get(IConfig::class), OC::$server->get(IFactory::class)->get('dav'))); // Backends $authBackend = new Auth( - \OC::$server->get(IUserSession::class)->getSession(), - \OC::$server->get(IUserSession::class), - \OC::$server->get(IRequest::class), - \OC::$server->get(TwoFactorAuthManager::class), - \OC::$server->get(Throttler::class) + OC::$server->get(IUserSession::class)->getSession(), + OC::$server->get(IUserSession::class), + OC::$server->get(IRequest::class), + OC::$server->get(TwoFactorAuthManager::class), + OC::$server->get(Throttler::class) ); // Set URL explicitly due to reverse-proxy situations $this->server->httpRequest->setUrl($this->request->getRequestUri()); $this->server->setBaseUri($this->baseUri); - $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->get(IConfig::class))); + $this->server->addPlugin(new BlockLegacyClientPlugin(OC::$server->get(IConfig::class))); $this->server->addPlugin(new AnonymousOptionsPlugin()); $authPlugin = new Plugin(); $authPlugin->addBackend(new PublicAuth()); @@ -153,16 +163,16 @@ public function __construct(IRequest $request, $baseUri) { $newDispatcher->dispatchTyped($newAuthEvent); $bearerAuthBackend = new BearerAuth( - \OC::$server->get(IUserSession::class), - \OC::$server->get(IUserSession::class)->getSession(), - \OC::$server->get(IRequest::class) + OC::$server->get(IUserSession::class), + OC::$server->get(IUserSession::class)->getSession(), + OC::$server->get(IRequest::class) ); $authPlugin->addBackend($bearerAuthBackend); // because we are throwing exceptions this plugin has to be the last one $authPlugin->addBackend($authBackend); // debugging - if (\OC::$server->get(IConfig::class)->getSystemValue('debug', false)) { + if (OC::$server->get(IConfig::class)->getSystemValue('debug', false)) { $this->server->addPlugin(new \Sabre\DAV\Browser\Plugin()); } else { $this->server->addPlugin(new DummyGetResponsePlugin()); @@ -185,48 +195,48 @@ public function __construct(IRequest $request, $baseUri) { // calendar plugins if ($this->requestIsForSubtree(['calendars', 'public-calendars', 'system-calendars', 'principals'])) { $this->server->addPlugin(new CalDAV\Plugin()); - $this->server->addPlugin(new ICSExportPlugin(\OC::$server->get(IConfig::class), \OC::$server->get(LoggerInterface::class))); - $this->server->addPlugin(new CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); - if (\OC::$server->get(IConfig::class)->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') { - $this->server->addPlugin(\OC::$server->get(IMipPlugin::class)); + $this->server->addPlugin(new ICSExportPlugin(OC::$server->get(IConfig::class), OC::$server->get(LoggerInterface::class))); + $this->server->addPlugin(new CalDAV\Schedule\Plugin(OC::$server->get(IConfig::class))); + if (OC::$server->get(IConfig::class)->getAppValue('dav', 'sendInvitations', 'yes') === 'yes') { + $this->server->addPlugin(OC::$server->get(IMipPlugin::class)); } - $this->server->addPlugin(\OC::$server->get(CalDAV\Trashbin\Plugin::class)); + $this->server->addPlugin(OC::$server->get(CalDAV\Trashbin\Plugin::class)); $this->server->addPlugin(new CalDAV\WebcalCaching\Plugin($request)); $this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin()); $this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin()); - $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->get(IRequest::class), \OC::$server->get(IConfig::class))); + $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, OC::$server->get(IRequest::class), OC::$server->get(IConfig::class))); $this->server->addPlugin(new PublishPlugin( - \OC::$server->get(IConfig::class), - \OC::$server->get(IURLGenerator::class) + OC::$server->get(IConfig::class), + OC::$server->get(IURLGenerator::class) )); } // addressbook plugins if ($this->requestIsForSubtree(['addressbooks', 'principals'])) { - $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, \OC::$server->get(IRequest::class), \OC::$server->get(IConfig::class))); + $this->server->addPlugin(new DAV\Sharing\Plugin($authBackend, OC::$server->get(IRequest::class), OC::$server->get(IConfig::class))); $this->server->addPlugin(new CardDAV\Plugin()); $this->server->addPlugin(new VCFExportPlugin()); $this->server->addPlugin(new MultiGetExportPlugin()); $this->server->addPlugin(new HasPhotoPlugin()); $this->server->addPlugin(new ImageExportPlugin(new PhotoCache( - \OC::$server->getAppDataDir('dav-photocache'), - \OC::$server->get(LoggerInterface::class)) + OC::$server->get(AppDataFactory::class)->get('dav-photocache'), + OC::$server->get(LoggerInterface::class)) )); } // system tags plugins $this->server->addPlugin(new SystemTagPlugin( - \OC::$server->get(ISystemTagManager::class), - \OC::$server->get(IGroupManager::class), - \OC::$server->get(IUserSession::class) + OC::$server->get(ISystemTagManager::class), + OC::$server->get(IGroupManager::class), + OC::$server->get(IUserSession::class) )); // comments plugin $this->server->addPlugin(new CommentsPlugin( - \OC::$server->get(ICommentsManager::class), - \OC::$server->get(IUserSession::class) + OC::$server->get(ICommentsManager::class), + OC::$server->get(IUserSession::class) )); $this->server->addPlugin(new CopyEtagHeaderPlugin()); @@ -258,19 +268,19 @@ public function __construct(IRequest $request, $baseUri) { // wait with registering these until auth is handled and the filesystem is setup $this->server->on('beforeMethod:*', function () use ($root, $lazySearchBackend) { // custom properties plugin must be the last one - $userSession = \OC::$server->get(IUserSession::class); + $userSession = OC::$server->get(IUserSession::class); $user = $userSession->getUser(); if ($user !== null) { $view = \OC\Files\Filesystem::getView(); $this->server->addPlugin( new FilesPlugin( $this->server->tree, - \OC::$server->get(IConfig::class), + OC::$server->get(IConfig::class), $this->request, - \OC::$server->get(IPreview::class), - \OC::$server->get(IUserSession::class), + OC::$server->get(IPreview::class), + OC::$server->get(IUserSession::class), false, - !\OC::$server->get(IConfig::class)->getSystemValue('debug', false) + !OC::$server->get(IConfig::class)->getSystemValue('debug', false) ) ); @@ -278,8 +288,8 @@ public function __construct(IRequest $request, $baseUri) { new \Sabre\DAV\PropertyStorage\Plugin( new CustomPropertiesBackend( $this->server->tree, - \OC::$server->get(IDBConnection::class), - \OC::$server->get(IUserSession::class)->getUser() + OC::$server->get(IDBConnection::class), + OC::$server->get(IUserSession::class)->getUser() ) ) ); @@ -289,19 +299,19 @@ public function __construct(IRequest $request, $baseUri) { } $this->server->addPlugin( new TagsPlugin( - $this->server->tree, \OC::$server->get(ITagManager::class) + $this->server->tree, OC::$server->get(ITagManager::class) ) ); // TODO: switch to LazyUserFolder - $userFolder = \OC::$server->getUserFolder(); + $userFolder = OC::$server->getUserFolder(); $this->server->addPlugin(new SharesPlugin( $this->server->tree, $userSession, $userFolder, - \OC::$server->get(IManager::class) + OC::$server->get(IManager::class) )); $this->server->addPlugin(new CommentPropertiesPlugin( - \OC::$server->get(ICommentsManager::class), + OC::$server->get(ICommentsManager::class), $userSession )); $this->server->addPlugin(new CalDAV\Search\SearchPlugin()); @@ -309,36 +319,36 @@ public function __construct(IRequest $request, $baseUri) { $this->server->addPlugin(new FilesReportPlugin( $this->server->tree, $view, - \OC::$server->get(ISystemTagManager::class), - \OC::$server->get(ISystemTagObjectMapper::class), - \OC::$server->get(ITagManager::class), + OC::$server->get(ISystemTagManager::class), + OC::$server->get(ISystemTagObjectMapper::class), + OC::$server->get(ITagManager::class), $userSession, - \OC::$server->get(IGroupManager::class), + OC::$server->get(IGroupManager::class), $userFolder, - \OC::$server->get(IAppManager::class) + OC::$server->get(IAppManager::class) )); $lazySearchBackend->setBackend(new FileSearchBackend( $this->server->tree, $user, - \OC::$server->get(IRootFolder::class), - \OC::$server->get(IManager::class), + OC::$server->get(IRootFolder::class), + OC::$server->get(IManager::class), $view )); - $logger = \OC::$server->get(LoggerInterface::class); + $logger = OC::$server->get(LoggerInterface::class); $this->server->addPlugin( new BulkUploadPlugin($userFolder, $logger) ); } $this->server->addPlugin(new EnablePlugin( - \OC::$server->get(IConfig::class), - \OC::$server->get(BirthdayService::class) + OC::$server->get(IConfig::class), + OC::$server->get(BirthdayService::class) )); $this->server->addPlugin(new AppleProvisioningPlugin( - \OC::$server->get(IUserSession::class), - \OC::$server->get(IURLGenerator::class), - \OC::$server->get('ThemingDefaults'), - \OC::$server->get(IRequest::class), - \OC::$server->get(IFactory::class)->get('dav'), + OC::$server->get(IUserSession::class), + OC::$server->get(IURLGenerator::class), + OC::$server->get('ThemingDefaults'), + OC::$server->get(IRequest::class), + OC::$server->get(IFactory::class)->get('dav'), function () { return UUIDUtil::getUUID(); } @@ -347,8 +357,8 @@ function () { // register plugins from apps $pluginManager = new PluginManager( - \OC::$server, - \OC::$server->get(IAppManager::class) + OC::$server, + OC::$server->get(IAppManager::class) ); foreach ($pluginManager->getAppPlugins() as $appPlugin) { $this->server->addPlugin($appPlugin); diff --git a/apps/dav/lib/Traits/PrincipalProxyTrait.php b/apps/dav/lib/Traits/PrincipalProxyTrait.php index 98caa67ae50f1..f2bd02bf1604d 100644 --- a/apps/dav/lib/Traits/PrincipalProxyTrait.php +++ b/apps/dav/lib/Traits/PrincipalProxyTrait.php @@ -26,6 +26,7 @@ use OCA\DAV\CalDAV\Proxy\Proxy; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use Sabre\DAV\Exception; +use function Sabre\Uri\split; /** * Trait PrincipalTrait @@ -75,7 +76,7 @@ public function getGroupMemberSet($principal) { * @throws Exception */ public function getGroupMembership($principal, $needGroups = false) { - [$prefix, $name] = \Sabre\Uri\split($principal); + [$prefix, $name] = split($principal); if ($prefix !== $this->principalPrefix) { return []; @@ -111,7 +112,7 @@ public function getGroupMembership($principal, $needGroups = false) { * @throws Exception|\OCP\DB\Exception */ public function setGroupMemberSet($principal, array $members) { - [$principalUri, $target] = \Sabre\Uri\split($principal); + [$principalUri, $target] = split($principal); if ($target !== 'calendar-proxy-write' && $target !== 'calendar-proxy-read') { throw new Exception('Setting members of the group is not supported yet'); @@ -127,11 +128,11 @@ public function setGroupMemberSet($principal, array $members) { $permission |= ProxyMapper::PERMISSION_WRITE; } - [$prefix, $owner] = \Sabre\Uri\split($principalUri); + [$prefix, $owner] = split($principalUri); $proxies = $this->proxyMapper->getProxiesOf($principalUri); foreach ($members as $member) { - [$prefix, $name] = \Sabre\Uri\split($member); + [$prefix, $name] = split($member); if ($prefix !== $this->principalPrefix) { throw new Exception('Invalid member group prefix: ' . $prefix); @@ -180,8 +181,8 @@ public function setGroupMemberSet($principal, array $members) { * @return bool */ private function isProxyPrincipal(string $principalUri):bool { - [$realPrincipalUri, $proxy] = \Sabre\Uri\split($principalUri); - [$prefix, $userId] = \Sabre\Uri\split($realPrincipalUri); + [$realPrincipalUri, $proxy] = split($principalUri); + [$prefix, $userId] = split($realPrincipalUri); if (!isset($prefix, $userId)) { return false; @@ -199,7 +200,7 @@ private function isProxyPrincipal(string $principalUri):bool { * @return bool */ private function isReadProxyPrincipal(string $principalUri):bool { - [, $proxy] = \Sabre\Uri\split($principalUri); + [, $proxy] = split($principalUri); return $proxy === 'calendar-proxy-read'; } @@ -208,7 +209,7 @@ private function isReadProxyPrincipal(string $principalUri):bool { * @return bool */ private function isWriteProxyPrincipal(string $principalUri):bool { - [, $proxy] = \Sabre\Uri\split($principalUri); + [, $proxy] = split($principalUri); return $proxy === 'calendar-proxy-write'; } @@ -217,7 +218,7 @@ private function isWriteProxyPrincipal(string $principalUri):bool { * @return string */ private function getPrincipalUriFromProxyPrincipal(string $principalUri):string { - [$realPrincipalUri, ] = \Sabre\Uri\split($principalUri); + [$realPrincipalUri, ] = split($principalUri); return $realPrincipalUri; } } diff --git a/apps/dav/lib/Upload/ChunkingPlugin.php b/apps/dav/lib/Upload/ChunkingPlugin.php index 5a443ee77127a..a0ed998bf17ae 100644 --- a/apps/dav/lib/Upload/ChunkingPlugin.php +++ b/apps/dav/lib/Upload/ChunkingPlugin.php @@ -54,8 +54,9 @@ public function initialize(Server $server) { * @return bool|void * @throws BadRequest * @throws NotFound + * @throws Forbidden */ - public function beforeMove($sourcePath, $destination) { + public function beforeMove(string $sourcePath, string $destination) { $this->sourceNode = $this->server->tree->getNodeForPath($sourcePath); if (!$this->sourceNode instanceof FutureFile) { // skip handling as the source is not a chunked FutureFile @@ -85,9 +86,10 @@ public function beforeMove($sourcePath, $destination) { * * @param string $path source path * @param string $destination destination path - * @return bool|void false to stop handling, void to skip this handler + * @return false + * @throws Forbidden|NotFound */ - public function performMove($path, $destination) { + public function performMove(string $path, string $destination): bool { $fileExists = $this->server->tree->nodeExists($destination); // do a move manually, skipping Sabre's default "delete" for existing nodes try { @@ -124,7 +126,7 @@ private function verifySize() { // casted to string because cast to float cause equality for non equal numbers // and integer has the problem of limited size on 32 bit systems - if ((string)$expectedSize !== (string)$actualSize) { + if ($expectedSize !== (string)$actualSize) { throw new BadRequest("Chunks on server do not sum up to $expectedSize but to $actualSize bytes"); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php index f73434b33b6b1..29852c245ed26 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php @@ -153,6 +153,12 @@ protected function setUp(): void { ); } + /** + * @throws PreconditionFailed + * @throws BadRequest + * @throws NotFound + * @throws NotFoundException + */ public function testOnReportInvalidNode() { $path = 'totally/unrelated/13'; diff --git a/remote.php b/remote.php index 69e3a53eeece7..b678aac7ae36f 100644 --- a/remote.php +++ b/remote.php @@ -34,6 +34,8 @@ require_once __DIR__ . '/lib/versioncheck.php'; use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin; +use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\Server; @@ -57,7 +59,7 @@ function handleException($e) { $server = new Server(); if (!($e instanceof RemoteException)) { // we shall not log on RemoteException - $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->getLogger())); + $server->addPlugin(new ExceptionLoggerPlugin('webdav', \OC::$server->get(LoggerInterface::class))); } $server->on('beforeMethod:*', function () use ($e) { if ($e instanceof RemoteException) { @@ -65,7 +67,7 @@ function handleException($e) { case 503: throw new ServiceUnavailable($e->getMessage()); case 404: - throw new \Sabre\DAV\Exception\NotFound($e->getMessage()); + throw new NotFound($e->getMessage()); } } $class = get_class($e); From 041526d6bbff7d11208aca5ccde8cc01d29b7824 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Wed, 26 Jan 2022 14:51:46 +0100 Subject: [PATCH 20/23] Improve tests Signed-off-by: Thomas Citharel --- .../tests/unit/AppInfo/ApplicationTest.php | 10 +- .../tests/unit/AppInfo/PluginManagerTest.php | 24 +- .../dav/tests/unit/Avatars/AvatarHomeTest.php | 21 +- .../dav/tests/unit/Avatars/AvatarNodeTest.php | 5 +- .../CleanupInvitationTokenJobTest.php | 20 +- .../BackgroundJob/EventReminderJobTest.php | 31 +- ...erateBirthdayCalendarBackgroundJobTest.php | 2 +- ...egisterRegenerateBirthdayCalendarsTest.php | 40 +- ...alendarResourcesRoomsBackgroundJobTest.php | 64 +- .../unit/CalDAV/AbstractCalDavBackend.php | 51 +- .../unit/CalDAV/Activity/BackendTest.php | 29 +- .../CalDAV/Activity/Filter/CalendarTest.php | 9 +- .../CalDAV/Activity/Filter/GenericTest.php | 54 +- .../unit/CalDAV/Activity/Filter/TodoTest.php | 9 +- .../CalDAV/Activity/Provider/BaseTest.php | 12 +- .../CalDAV/Activity/Provider/EventTest.php | 6 +- .../CalDAV/Activity/Setting/GenericTest.php | 61 +- .../BirthdayCalendar/EnablePluginTest.php | 29 +- .../CalDAV/CachedSubscriptionObjectTest.php | 12 +- .../unit/CalDAV/CachedSubscriptionTest.php | 55 +- .../tests/unit/CalDAV/CalDavBackendTest.php | 104 +++- .../tests/unit/CalDAV/CalendarHomeTest.php | 40 +- .../tests/unit/CalDAV/CalendarImplTest.php | 16 +- .../tests/unit/CalDAV/CalendarManagerTest.php | 53 +- apps/dav/tests/unit/CalDAV/CalendarTest.php | 57 +- .../Integration/ExternalCalendarTest.php | 21 +- apps/dav/tests/unit/CalDAV/PluginTest.php | 7 +- .../unit/CalDAV/PublicCalendarRootTest.php | 46 +- .../tests/unit/CalDAV/PublicCalendarTest.php | 16 +- .../unit/CalDAV/Publishing/PublisherTest.php | 2 +- .../unit/CalDAV/Publishing/PublishingTest.php | 33 +- .../unit/CalDAV/Reminder/BackendTest.php | 105 ++-- .../AbstractNotificationProviderTest.php | 15 +- .../EmailProviderTest.php | 304 +++------ .../NotificationProvider/PushProviderTest.php | 55 +- .../NotificationProviderManagerTest.php | 28 +- .../unit/CalDAV/Reminder/NotifierTest.php | 27 +- .../CalDAV/Reminder/ReminderServiceTest.php | 187 +++--- .../AbstractPrincipalBackendTest.php | 143 +++-- .../ResourcePrincipalBackendTest.php | 4 + .../RoomPrincipalBackendTest.php | 4 + .../unit/CalDAV/Schedule/IMipPluginTest.php | 113 ++-- .../tests/unit/CalDAV/Schedule/PluginTest.php | 42 +- .../Request/CalendarSearchReportTest.php | 48 +- .../unit/CalDAV/Search/SearchPluginTest.php | 31 +- .../unit/CalDAV/WebcalCaching/PluginTest.php | 12 +- .../RefreshWebcalServiceTest.php | 12 +- .../unit/CardDAV/AddressBookImplTest.php | 6 +- .../tests/unit/CardDAV/AddressBookTest.php | 29 +- .../unit/CardDAV/BirthdayServiceTest.php | 90 +-- .../unit/CardDAV/ContactsManagerTest.php | 11 +- apps/dav/tests/unit/CardDAV/ConverterTest.php | 30 +- .../unit/CardDAV/ImageExportPluginTest.php | 63 +- .../tests/unit/CardDAV/Sharing/PluginTest.php | 21 +- .../tests/unit/CardDAV/SyncServiceTest.php | 53 +- .../tests/unit/Command/DeleteCalendarTest.php | 21 +- .../tests/unit/Command/ListCalendarsTest.php | 17 +- .../tests/unit/Command/MoveCalendarTest.php | 213 +++---- .../unit/Command/RemoveInvalidSharesTest.php | 24 +- .../tests/unit/Comments/CommentsNodeTest.php | 147 +++-- .../unit/Comments/CommentsPluginTest.php | 236 +++---- .../unit/Comments/EntityCollectionTest.php | 71 +-- .../Comments/EntityTypeCollectionTest.php | 42 +- .../unit/Comments/RootCollectionTest.php | 105 ++-- .../tests/unit/Connector/PublicAuthTest.php | 81 +-- .../tests/unit/Connector/Sabre/AuthTest.php | 293 ++++----- .../unit/Connector/Sabre/BearerAuthTest.php | 30 +- .../Sabre/BlockLegacyClientPluginTest.php | 36 +- .../Sabre/CommentsPropertiesPluginTest.php | 68 +- .../Sabre/CopyEtagHeaderPluginTest.php | 20 +- .../Sabre/CustomPropertiesBackendTest.php | 79 +-- .../unit/Connector/Sabre/DirectoryTest.php | 231 +++++-- .../Sabre/DummyGetResponsePluginTest.php | 19 +- .../Sabre/Exception/ForbiddenTest.php | 20 +- .../Sabre/Exception/InvalidPathTest.php | 20 +- .../Sabre/ExceptionLoggerPluginTest.php | 43 +- .../Connector/Sabre/FakeLockerPluginTest.php | 70 +-- .../tests/unit/Connector/Sabre/FileTest.php | 589 +++++++++++++----- .../unit/Connector/Sabre/FilesPluginTest.php | 126 ++-- .../Connector/Sabre/FilesReportPluginTest.php | 300 ++++----- .../Connector/Sabre/MaintenancePluginTest.php | 12 +- .../tests/unit/Connector/Sabre/NodeTest.php | 94 ++- .../unit/Connector/Sabre/ObjectTreeTest.php | 121 ++-- .../unit/Connector/Sabre/PrincipalTest.php | 148 ++--- .../unit/Connector/Sabre/QuotaPluginTest.php | 67 +- .../unit/Connector/Sabre/RequestTest/Auth.php | 6 +- .../Sabre/RequestTest/DeleteTest.php | 13 +- .../Sabre/RequestTest/DownloadTest.php | 18 +- .../EncryptionMasterKeyUploadTest.php | 18 +- .../RequestTest/EncryptionUploadTest.php | 18 +- .../Sabre/RequestTest/ExceptionPlugin.php | 13 +- .../RequestTest/PartFileInRootUploadTest.php | 16 +- .../Sabre/RequestTest/RequestTestCase.php | 70 ++- .../unit/Connector/Sabre/RequestTest/Sapi.php | 14 +- .../Sabre/RequestTest/UploadTest.php | 76 ++- .../unit/Connector/Sabre/SharesPluginTest.php | 71 +-- .../unit/Connector/Sabre/TagsPluginTest.php | 159 +++-- .../BirthdayCalendarControllerTest.php | 28 +- .../unit/Controller/DirectControllerTest.php | 21 +- .../InvitationResponseControllerTest.php | 84 +-- .../tests/unit/DAV/AnonymousOptionsTest.php | 3 +- .../unit/DAV/BrowserErrorPagePluginTest.php | 25 +- .../unit/DAV/CustomPropertiesBackendTest.php | 50 +- .../dav/tests/unit/DAV/GroupPrincipalTest.php | 24 +- .../dav/tests/unit/DAV/Sharing/PluginTest.php | 23 +- .../unit/DAV/SystemPrincipalBackendTest.php | 37 +- apps/dav/tests/unit/Direct/DirectFileTest.php | 31 +- apps/dav/tests/unit/Direct/DirectHomeTest.php | 40 +- .../unit/Files/FileSearchBackendTest.php | 82 ++- .../unit/Files/MultipartRequestParserTest.php | 54 +- .../Files/Sharing/FilesDropPluginTest.php | 24 +- ...CalendarContactInteractionListenerTest.php | 7 +- .../unit/Listener/UserChangeListenerTest.php | 14 +- .../Migration/CalDAVRemoveEmptyValueTest.php | 55 +- .../RefreshWebcalJobRegistrarTest.php | 134 ++-- .../RegenerateBirthdayCalendarsTest.php | 5 +- ...eDeletedUsersCalendarSubscriptionsTest.php | 5 +- .../Apple/AppleProvisioningNodeTest.php | 15 +- .../Apple/AppleProvisioningPluginTest.php | 81 ++- .../Search/ContactsSearchProviderTest.php | 11 +- .../unit/Search/EventsSearchProviderTest.php | 20 +- .../unit/Search/TasksSearchProviderTest.php | 11 +- apps/dav/tests/unit/ServerTest.php | 10 +- .../SystemTag/SystemTagMappingNodeTest.php | 47 +- .../unit/SystemTag/SystemTagNodeTest.php | 84 ++- .../unit/SystemTag/SystemTagPluginTest.php | 213 +++---- .../SystemTagsByIdCollectionTest.php | 99 +-- .../SystemTagsObjectMappingCollectionTest.php | 121 ++-- .../SystemTagsObjectTypeCollectionTest.php | 75 +-- .../tests/unit/Upload/AssemblyStreamTest.php | 30 +- .../tests/unit/Upload/ChunkingPluginTest.php | 98 +-- apps/dav/tests/unit/Upload/FutureFileTest.php | 25 +- 132 files changed, 4215 insertions(+), 3678 deletions(-) diff --git a/apps/dav/tests/unit/AppInfo/ApplicationTest.php b/apps/dav/tests/unit/AppInfo/ApplicationTest.php index 2e728f8e8723f..5f4dbe75c6311 100644 --- a/apps/dav/tests/unit/AppInfo/ApplicationTest.php +++ b/apps/dav/tests/unit/AppInfo/ApplicationTest.php @@ -25,6 +25,8 @@ use OCA\DAV\AppInfo\Application; use OCA\DAV\CardDAV\CardDavBackend; use OCA\DAV\CardDAV\ContactsManager; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Test\TestCase; /** @@ -35,14 +37,18 @@ * @package OCA\DAV\Tests\Unit\AppInfo */ class ApplicationTest extends TestCase { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ public function test() { $app = new Application(); $c = $app->getContainer(); // assert service instances in the container are properly setup - $s = $c->query(ContactsManager::class); + $s = $c->get(ContactsManager::class); $this->assertInstanceOf(ContactsManager::class, $s); - $s = $c->query(CardDavBackend::class); + $s = $c->get(CardDavBackend::class); $this->assertInstanceOf(CardDavBackend::class, $s); } } diff --git a/apps/dav/tests/unit/AppInfo/PluginManagerTest.php b/apps/dav/tests/unit/AppInfo/PluginManagerTest.php index 53e63269067f5..9191d8187cfb3 100644 --- a/apps/dav/tests/unit/AppInfo/PluginManagerTest.php +++ b/apps/dav/tests/unit/AppInfo/PluginManagerTest.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\Tests\unit\AppInfo; +use Exception; use OC\App\AppManager; use OC\ServerContainer; use OCA\DAV\AppInfo\PluginManager; @@ -40,6 +41,9 @@ * @package OCA\DAV\Tests\Unit\AppInfo */ class PluginManagerTest extends TestCase { + /** + * @throws Exception + */ public function test() { $server = $this->createMock(ServerContainer::class); @@ -106,17 +110,17 @@ public function test() { $dummyCollection2 = $this->createMock(Collection::class); $dummy2Collection1 = $this->createMock(Collection::class); - $server->method('query') + $server->method('get') ->willReturnMap([ - ['\OCA\DAV\ADavApp\PluginOne', true, $dummyPlugin1], - ['\OCA\DAV\ADavApp\PluginTwo', true, $dummyPlugin2], - ['\OCA\DAV\ADavApp\CalendarPluginOne', true, $calendarPlugin1], - ['\OCA\DAV\ADavApp\CalendarPluginTwo', true, $calendarPlugin2], - ['\OCA\DAV\ADavApp\CollectionOne', true, $dummyCollection1], - ['\OCA\DAV\ADavApp\CollectionTwo', true, $dummyCollection2], - ['\OCA\DAV\ADavApp2\PluginOne', true, $dummy2Plugin1], - ['\OCA\DAV\ADavApp2\CalendarPluginOne', true, $calendarPlugin3], - ['\OCA\DAV\ADavApp2\CollectionOne', true, $dummy2Collection1], + ['\OCA\DAV\ADavApp\PluginOne', $dummyPlugin1], + ['\OCA\DAV\ADavApp\PluginTwo', $dummyPlugin2], + ['\OCA\DAV\ADavApp\CalendarPluginOne', $calendarPlugin1], + ['\OCA\DAV\ADavApp\CalendarPluginTwo', $calendarPlugin2], + ['\OCA\DAV\ADavApp\CollectionOne', $dummyCollection1], + ['\OCA\DAV\ADavApp\CollectionTwo', $dummyCollection2], + ['\OCA\DAV\ADavApp2\PluginOne', $dummy2Plugin1], + ['\OCA\DAV\ADavApp2\CalendarPluginOne', $calendarPlugin3], + ['\OCA\DAV\ADavApp2\CollectionOne', $dummy2Collection1], ]); $expectedPlugins = [ diff --git a/apps/dav/tests/unit/Avatars/AvatarHomeTest.php b/apps/dav/tests/unit/Avatars/AvatarHomeTest.php index 9b2d91954de38..3531f91189be2 100644 --- a/apps/dav/tests/unit/Avatars/AvatarHomeTest.php +++ b/apps/dav/tests/unit/Avatars/AvatarHomeTest.php @@ -28,6 +28,8 @@ use OCA\DAV\Avatars\AvatarNode; use OCP\IAvatar; use OCP\IAvatarManager; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; use Test\TestCase; @@ -37,7 +39,7 @@ class AvatarHomeTest extends TestCase { /** @var AvatarHome */ private $home; - /** @var IAvatarManager | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IAvatarManager | MockObject */ private $avatarManager; protected function setUp(): void { @@ -49,13 +51,13 @@ protected function setUp(): void { /** * @dataProvider providesForbiddenMethods */ - public function testForbiddenMethods($method) { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + public function testForbiddenMethods(string $method) { + $this->expectException(Forbidden::class); $this->home->$method(''); } - public function providesForbiddenMethods() { + public function providesForbiddenMethods(): array { return [ ['createFile'], ['createDirectory'], @@ -69,7 +71,7 @@ public function testGetName() { self::assertEquals('admin', $n); } - public function providesTestGetChild() { + public function providesTestGetChild(): array { return [ [MethodNotAllowed::class, false, ''], [MethodNotAllowed::class, false, 'bla.foo'], @@ -81,8 +83,9 @@ public function providesTestGetChild() { /** * @dataProvider providesTestGetChild + * @throws MethodNotAllowed|NotFound */ - public function testGetChild($expectedException, $hasAvatar, $path) { + public function testGetChild(?string $expectedException, bool $hasAvatar, string $path) { if ($expectedException !== null) { $this->expectException($expectedException); } @@ -97,19 +100,19 @@ public function testGetChild($expectedException, $hasAvatar, $path) { public function testGetChildren() { $avatarNodes = $this->home->getChildren(); - self::assertEquals(0, count($avatarNodes)); + self::assertCount(0, $avatarNodes); $avatar = $this->createMock(IAvatar::class); $avatar->expects($this->once())->method('exists')->willReturn(true); $this->avatarManager->expects($this->any())->method('getAvatar')->with('admin')->willReturn($avatar); $avatarNodes = $this->home->getChildren(); - self::assertEquals(1, count($avatarNodes)); + self::assertCount(1, $avatarNodes); } /** * @dataProvider providesTestGetChild */ - public function testChildExists($expectedException, $hasAvatar, $path) { + public function testChildExists(?string $expectedException, bool $hasAvatar, string $path) { $avatar = $this->createMock(IAvatar::class); $avatar->method('exists')->willReturn($hasAvatar); diff --git a/apps/dav/tests/unit/Avatars/AvatarNodeTest.php b/apps/dav/tests/unit/Avatars/AvatarNodeTest.php index 5a124d7f15b4d..0713c91bb6962 100644 --- a/apps/dav/tests/unit/Avatars/AvatarNodeTest.php +++ b/apps/dav/tests/unit/Avatars/AvatarNodeTest.php @@ -24,18 +24,19 @@ use OCA\DAV\Avatars\AvatarNode; use OCP\IAvatar; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class AvatarNodeTest extends TestCase { public function testGetName() { - /** @var IAvatar | \PHPUnit\Framework\MockObject\MockObject $a */ + /** @var IAvatar | MockObject $a */ $a = $this->createMock(IAvatar::class); $n = new AvatarNode(1024, 'png', $a); $this->assertEquals('1024.png', $n->getName()); } public function testGetContentType() { - /** @var IAvatar | \PHPUnit\Framework\MockObject\MockObject $a */ + /** @var IAvatar | MockObject $a */ $a = $this->createMock(IAvatar::class); $n = new AvatarNode(1024, 'png', $a); $this->assertEquals('image/png', $n->getContentType()); diff --git a/apps/dav/tests/unit/BackgroundJob/CleanupInvitationTokenJobTest.php b/apps/dav/tests/unit/BackgroundJob/CleanupInvitationTokenJobTest.php index 6233980edbbe7..5a74eead0f8c4 100644 --- a/apps/dav/tests/unit/BackgroundJob/CleanupInvitationTokenJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/CleanupInvitationTokenJobTest.php @@ -29,21 +29,25 @@ */ namespace OCA\DAV\Tests\unit\BackgroundJob; +use Doctrine\DBAL\Driver\Statement; use OCA\DAV\BackgroundJob\CleanupInvitationTokenJob; +use OCA\DAV\BackgroundJob\GenerateBirthdayCalendarBackgroundJob; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\DB\QueryBuilder\IExpressionBuilder; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CleanupInvitationTokenJobTest extends TestCase { - /** @var IDBConnection | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IDBConnection | MockObject */ private $dbConnection; - /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory | MockObject */ private $timeFactory; - /** @var \OCA\DAV\BackgroundJob\GenerateBirthdayCalendarBackgroundJob */ + /** @var GenerateBirthdayCalendarBackgroundJob */ private $backgroundJob; protected function setUp(): void { @@ -63,8 +67,8 @@ public function testRun() { ->willReturn(1337); $queryBuilder = $this->createMock(IQueryBuilder::class); - $expr = $this->createMock(\OCP\DB\QueryBuilder\IExpressionBuilder::class); - $stmt = $this->createMock(\Doctrine\DBAL\Driver\Statement::class); + $expr = $this->createMock(IExpressionBuilder::class); + $stmt = $this->createMock(Statement::class); $this->dbConnection->expects($this->once()) ->method('getQueryBuilder') @@ -87,15 +91,15 @@ public function testRun() { ->with() ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(0)) + $queryBuilder->expects($this->once()) ->method('delete') ->with('calendar_invitations') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(3)) + $queryBuilder->expects($this->once()) ->method('where') ->with('LT STATEMENT') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(4)) + $queryBuilder->expects($this->once()) ->method('execute') ->with() ->willReturn($stmt); diff --git a/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php b/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php index ed3c324e71073..f33961509a7b2 100644 --- a/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/EventReminderJobTest.php @@ -28,7 +28,10 @@ */ namespace OCA\DAV\Tests\unit\BackgroundJob; +use OC\User\NoUserException; use OCA\DAV\BackgroundJob\EventReminderJob; +use OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException; +use OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException; use OCA\DAV\CalDAV\Reminder\ReminderService; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; @@ -75,21 +78,27 @@ public function data(): array { /** * @dataProvider data * - * @param bool $sendEventReminders - * @param bool $sendEventRemindersMode - * @param bool $expectCall + * @throws ProviderNotAvailableException + * @throws NotificationTypeDoesNotExistException + * @throws NoUserException */ public function testRun(bool $sendEventReminders, bool $sendEventRemindersMode, bool $expectCall): void { - $this->config->expects($this->at(0)) - ->method('getAppValue') - ->with('dav', 'sendEventReminders', 'yes') - ->willReturn($sendEventReminders ? 'yes' : 'no'); - if ($sendEventReminders) { - $this->config->expects($this->at(1)) + $this->config->expects($this->exactly(2)) + ->method('getAppValue') + ->withConsecutive( + ['dav', 'sendEventReminders', 'yes'], + ['dav', 'sendEventRemindersMode', 'backgroundjob'] + ) + ->willReturnOnConsecutiveCalls( + 'yes', + $sendEventRemindersMode ? 'backgroundjob' : 'cron' + ); + } else { + $this->config->expects($this->once()) ->method('getAppValue') - ->with('dav', 'sendEventRemindersMode', 'backgroundjob') - ->willReturn($sendEventRemindersMode ? 'backgroundjob' : 'cron'); + ->with('dav', 'sendEventReminders', 'yes') + ->willReturn('no'); } if ($expectCall) { diff --git a/apps/dav/tests/unit/BackgroundJob/GenerateBirthdayCalendarBackgroundJobTest.php b/apps/dav/tests/unit/BackgroundJob/GenerateBirthdayCalendarBackgroundJobTest.php index e0601c5c71ab2..c416970ded913 100644 --- a/apps/dav/tests/unit/BackgroundJob/GenerateBirthdayCalendarBackgroundJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/GenerateBirthdayCalendarBackgroundJobTest.php @@ -46,7 +46,7 @@ class GenerateBirthdayCalendarBackgroundJobTest extends TestCase { /** @var IConfig | MockObject */ private $config; - /** @var \OCA\DAV\BackgroundJob\GenerateBirthdayCalendarBackgroundJob */ + /** @var GenerateBirthdayCalendarBackgroundJob */ private $backgroundJob; protected function setUp(): void { diff --git a/apps/dav/tests/unit/BackgroundJob/RegisterRegenerateBirthdayCalendarsTest.php b/apps/dav/tests/unit/BackgroundJob/RegisterRegenerateBirthdayCalendarsTest.php index 00931d53f64af..570287373b97e 100644 --- a/apps/dav/tests/unit/BackgroundJob/RegisterRegenerateBirthdayCalendarsTest.php +++ b/apps/dav/tests/unit/BackgroundJob/RegisterRegenerateBirthdayCalendarsTest.php @@ -32,20 +32,20 @@ use OCA\DAV\BackgroundJob\RegisterRegenerateBirthdayCalendars; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; -use OCP\IConfig; use OCP\IUser; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RegisterRegenerateBirthdayCalendarsTest extends TestCase { - /** @var ITimeFactory | \PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory | MockObject */ private $time; - /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager | MockObject */ private $userManager; - /** @var IJobList | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IJobList | MockObject */ private $jobList; /** @var RegisterRegenerateBirthdayCalendars */ @@ -81,24 +81,22 @@ public function testRun() { $closure($user3); }); - $this->jobList->expects($this->at(0)) + $this->jobList->expects($this->exactly(3)) ->method('add') - ->with(GenerateBirthdayCalendarBackgroundJob::class, [ - 'userId' => 'uid1', - 'purgeBeforeGenerating' => true - ]); - $this->jobList->expects($this->at(1)) - ->method('add') - ->with(GenerateBirthdayCalendarBackgroundJob::class, [ - 'userId' => 'uid2', - 'purgeBeforeGenerating' => true - ]); - $this->jobList->expects($this->at(2)) - ->method('add') - ->with(GenerateBirthdayCalendarBackgroundJob::class, [ - 'userId' => 'uid3', - 'purgeBeforeGenerating' => true - ]); + ->withConsecutive( + [GenerateBirthdayCalendarBackgroundJob::class, [ + 'userId' => 'uid1', + 'purgeBeforeGenerating' => true + ]], + [GenerateBirthdayCalendarBackgroundJob::class, [ + 'userId' => 'uid2', + 'purgeBeforeGenerating' => true + ]], + [GenerateBirthdayCalendarBackgroundJob::class, [ + 'userId' => 'uid3', + 'purgeBeforeGenerating' => true + ]] + ); $this->backgroundJob->run([]); } diff --git a/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php b/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php index 59b68452862ed..965d8bd6d48c0 100644 --- a/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php +++ b/apps/dav/tests/unit/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJobTest.php @@ -39,6 +39,7 @@ use OCP\Calendar\Resource\IManager as IResourceManager; use OCP\Calendar\Resource\IResource; use OCP\Calendar\Room\IManager as IRoomManager; +use OCP\DB\Exception; use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; @@ -53,12 +54,6 @@ class UpdateCalendarResourcesRoomsBackgroundJobTest extends TestCase { /** @var IResourceManager|MockObject */ private $resourceManager; - /** @var IRoomManager|MockObject */ - private $roomManager; - - /** @var CalDavBackend|MockObject */ - private $calDavBackend; - /** @var UpdateCalendarResourcesRoomsBackgroundJob */ private $backgroundJob; @@ -66,25 +61,27 @@ protected function setUp(): void { parent::setUp(); $this->time = $this->createMock(ITimeFactory::class); - $this->resourceManager = $this->createMock(IResourceManager::class); - $this->roomManager = $this->createMock(IRoomManager::class); - $this->calDavBackend = $this->createMock(CalDavBackend::class); + $roomManager = $this->createMock(IRoomManager::class); + $calDavBackend = $this->createMock(CalDavBackend::class); $this->backgroundJob = new UpdateCalendarResourcesRoomsBackgroundJob( $this->time, $this->resourceManager, - $this->roomManager, + $roomManager, self::$realDatabase, - $this->calDavBackend + $calDavBackend ); } + /** + * @throws Exception + */ protected function tearDown(): void { $query = self::$realDatabase->getQueryBuilder(); - $query->delete('calendar_resources')->execute(); - $query->delete('calendar_resources_md')->execute(); - $query->delete('calendar_rooms')->execute(); - $query->delete('calendar_rooms_md')->execute(); + $query->delete('calendar_resources')->executeStatement(); + $query->delete('calendar_resources_md')->executeStatement(); + $query->delete('calendar_rooms')->executeStatement(); + $query->delete('calendar_rooms_md')->executeStatement(); } /** @@ -106,7 +103,7 @@ protected function tearDown(): void { * [backend4, res9, Beamer2, {}] - [] * * Expected after run: - * [backend1, res1, Beamer1, {}] - [] + * [backend1, res1, Beamer1, {}] - [] * [backend1, res2, TV1, {}] - [] * [backend2, res3, Beamer2, {}] - ['meta1' => 'value1', 'meta2' => 'value2'] * [backend2, res4, TV2, {}] - ['meta1' => 'value1', 'meta3' => 'value3-old'] @@ -114,6 +111,8 @@ protected function tearDown(): void { * [backend3, res7, Resource4, {biz}] - ['meta1' => 'value1'] * [backend4, res8, Beamer, {}] - ['meta2' => 'value2'] * [backend4, res9, Beamer2, {}] - [] + * + * @throws Exception */ public function testRun() { @@ -233,8 +232,8 @@ public function testRun() { $rows = []; $ids = []; - $stmt = $query->execute(); - while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + $stmt = $query->executeQuery(); + while ($row = $stmt->fetch()) { $ids[$row['backend_id'] . '::' . $row['resource_id']] = $row['id']; unset($row['id']); $rows[] = $row; @@ -303,8 +302,8 @@ public function testRun() { $query2->select('*')->from('calendar_resources_md'); $rows2 = []; - $stmt = $query2->execute(); - while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + $stmt = $query2->executeQuery(); + while ($row = $stmt->fetch()) { unset($row['id']); $rows2[] = $row; } @@ -353,6 +352,9 @@ public function testRun() { ], $rows2); } + /** + * @throws Exception + */ protected function createTestResourcesInCache() { $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendar_resources') @@ -363,7 +365,7 @@ protected function createTestResourcesInCache() { 'displayname' => $query->createNamedParameter('Beamer1'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources') ->values([ @@ -373,7 +375,7 @@ protected function createTestResourcesInCache() { 'displayname' => $query->createNamedParameter('TV1'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources') ->values([ @@ -383,7 +385,7 @@ protected function createTestResourcesInCache() { 'displayname' => $query->createNamedParameter('Beamer2'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $id3 = $query->getLastInsertId(); $query->insert('calendar_resources') @@ -394,7 +396,7 @@ protected function createTestResourcesInCache() { 'displayname' => $query->createNamedParameter('TV2'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $id4 = $query->getLastInsertId(); $query->insert('calendar_resources') @@ -405,7 +407,7 @@ protected function createTestResourcesInCache() { 'displayname' => $query->createNamedParameter('Beamer3'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources') ->values([ @@ -415,7 +417,7 @@ protected function createTestResourcesInCache() { 'displayname' => $query->createNamedParameter('Pointer'), 'group_restrictions' => $query->createNamedParameter('["foo", "bar"]'), ]) - ->execute(); + ->executeStatement(); $id6 = $query->getLastInsertId(); $query->insert('calendar_resources_md') @@ -424,34 +426,34 @@ protected function createTestResourcesInCache() { 'key' => $query->createNamedParameter('meta1'), 'value' => $query->createNamedParameter('value1') ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources_md') ->values([ 'resource_id' => $query->createNamedParameter($id3), 'key' => $query->createNamedParameter('meta2'), 'value' => $query->createNamedParameter('value2') ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources_md') ->values([ 'resource_id' => $query->createNamedParameter($id4), 'key' => $query->createNamedParameter('meta1'), 'value' => $query->createNamedParameter('value1') ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources_md') ->values([ 'resource_id' => $query->createNamedParameter($id4), 'key' => $query->createNamedParameter('meta3'), 'value' => $query->createNamedParameter('value3-old') ]) - ->execute(); + ->executeStatement(); $query->insert('calendar_resources_md') ->values([ 'resource_id' => $query->createNamedParameter($id6), 'key' => $query->createNamedParameter('meta99'), 'value' => $query->createNamedParameter('value99') ]) - ->execute(); + ->executeStatement(); } } diff --git a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php index fbd96eb169f1b..f6d0d1b8cea98 100644 --- a/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php +++ b/apps/dav/tests/unit/CalDAV/AbstractCalDavBackend.php @@ -41,8 +41,12 @@ use OCP\L10N\IFactory; use OCP\Security\ISecureRandom; use OCP\Share\IManager as ShareManager; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Sabre\CalDAV\Xml\Property\SupportedCalendarComponentSet; +use Sabre\DAV\Exception; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Xml\Property\Href; use Test\TestCase; @@ -58,20 +62,15 @@ abstract class AbstractCalDavBackend extends TestCase { /** @var CalDavBackend */ protected $backend; - /** @var Principal | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Principal | MockObject */ protected $principal; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ protected $userManager; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IGroupManager|MockObject */ protected $groupManager; - /** @var IEventDispatcher|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IEventDispatcher|MockObject */ protected $dispatcher; - /** @var ISecureRandom */ - private $random; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ - private $logger; - public const UNIT_TEST_USER = 'principals/users/caldav-unit-test'; public const UNIT_TEST_USER1 = 'principals/users/caldav-unit-test1'; public const UNIT_TEST_GROUP = 'principals/groups/caldav-unit-test-group'; @@ -95,7 +94,7 @@ protected function setUp(): void { $this->createMock(IConfig::class), $this->createMock(IFactory::class) ]) - ->setMethods(['getPrincipalByPath', 'getGroupMembership']) + ->onlyMethods(['getPrincipalByPath', 'getGroupMembership']) ->getMock(); $this->principal->expects($this->any())->method('getPrincipalByPath') ->willReturn([ @@ -107,16 +106,16 @@ protected function setUp(): void { ->willReturn([self::UNIT_TEST_GROUP, self::UNIT_TEST_GROUP2]); $db = \OC::$server->get(IDBConnection::class); - $this->random = \OC::$server->get(ISecureRandom::class); - $this->logger = $this->createMock(LoggerInterface::class); + $random = \OC::$server->get(ISecureRandom::class); + $logger = $this->createMock(LoggerInterface::class); $this->config = $this->createMock(IConfig::class); $this->backend = new CalDavBackend( $db, $this->principal, $this->userManager, $this->groupManager, - $this->random, - $this->logger, + $random, + $logger, $this->dispatcher, $this->config ); @@ -153,6 +152,9 @@ private function cleanupForPrincipal($principal): void { } } + /** + * @throws Exception + */ protected function createTestCalendar() { $this->dispatcher->expects(self::any()) ->method('dispatchTyped'); @@ -161,7 +163,7 @@ protected function createTestCalendar() { '{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF' ]); $calendars = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($calendars)); + $this->assertCount(1, $calendars); $this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']); /** @var SupportedCalendarComponentSet $components */ $components = $calendars[0]['{urn:ietf:params:xml:ns:caldav}supported-calendar-component-set']; @@ -170,26 +172,28 @@ protected function createTestCalendar() { $this->assertEquals('#1C4587FF', $color); $this->assertEquals('Example', $calendars[0]['uri']); $this->assertEquals('Example', $calendars[0]['{DAV:}displayname']); - $calendarId = $calendars[0]['id']; - - return $calendarId; + return $calendars[0]['id']; } + /** + * @throws Forbidden + */ protected function createTestSubscription() { $this->backend->createSubscription(self::UNIT_TEST_USER, 'Example', [ '{http://apple.com/ns/ical/}calendar-color' => '#1C4587FF', '{http://calendarserver.org/ns/}source' => new Href(['foo']), ]); $calendars = $this->backend->getSubscriptionsForUser(self::UNIT_TEST_USER); - $this->assertEquals(1, count($calendars)); + $this->assertCount(1, $calendars); $this->assertEquals(self::UNIT_TEST_USER, $calendars[0]['principaluri']); $this->assertEquals('Example', $calendars[0]['uri']); - $calendarId = $calendars[0]['id']; - - return $calendarId; + return $calendars[0]['id']; } - protected function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z') { + /** + * @throws BadRequest + */ + protected function createEvent($calendarId, $start = '20130912T130000Z', $end = '20130912T140000Z'): string { $randomPart = self::getUniqueID(); $calData = <<fail("ACL contains $principal / $privilege"); - return; } } $this->addToAssertionCount(1); diff --git a/apps/dav/tests/unit/CalDAV/Activity/BackendTest.php b/apps/dav/tests/unit/CalDAV/Activity/BackendTest.php index 21cbbd169ff80..84d81c73c1649 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/BackendTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/BackendTest.php @@ -79,12 +79,12 @@ protected function getBackend(array $methods = []) { $this->userSession, $this->appManager, ]) - ->setMethods($methods) + ->onlyMethods($methods) ->getMock(); } } - public function dataCallTriggerCalendarActivity() { + public function dataCallTriggerCalendarActivity(): array { return [ ['onCalendarAdd', [['data']], Calendar::SUBJECT_ADD, [['data'], [], []]], ['onCalendarUpdate', [['data'], ['shares'], ['changed-properties']], Calendar::SUBJECT_UPDATE, [['data'], ['shares'], ['changed-properties']]], @@ -95,13 +95,8 @@ public function dataCallTriggerCalendarActivity() { /** * @dataProvider dataCallTriggerCalendarActivity - * - * @param string $method - * @param array $payload - * @param string $expectedSubject - * @param array $expectedPayload */ - public function testCallTriggerCalendarActivity($method, array $payload, $expectedSubject, array $expectedPayload) { + public function testCallTriggerCalendarActivity(string $method, array $payload, string $expectedSubject, array $expectedPayload) { $backend = $this->getBackend(['triggerCalendarActivity']); $backend->expects($this->once()) ->method('triggerCalendarActivity') @@ -114,7 +109,7 @@ public function testCallTriggerCalendarActivity($method, array $payload, $expect call_user_func_array([$backend, $method], $payload); } - public function dataTriggerCalendarActivity() { + public function dataTriggerCalendarActivity(): array { return [ // Add calendar [Calendar::SUBJECT_ADD, [], [], [], '', '', null, []], @@ -197,16 +192,8 @@ public function dataTriggerCalendarActivity() { /** * @dataProvider dataTriggerCalendarActivity - * @param string $action - * @param array $data - * @param array $shares - * @param array $changedProperties - * @param string $currentUser - * @param string $author - * @param string[]|null $shareUsers - * @param string[] $users */ - public function testTriggerCalendarActivity($action, array $data, array $shares, array $changedProperties, $currentUser, $author, $shareUsers, array $users) { + public function testTriggerCalendarActivity(string $action, array $data, array $shares, array $changedProperties, string $currentUser, string $author, ?array $shareUsers, array $users) { $backend = $this->getBackend(['getUsersForShares']); if ($shareUsers === null) { @@ -269,7 +256,7 @@ public function testTriggerCalendarActivity($action, array $data, array $shares, $this->invokePrivate($backend, 'triggerCalendarActivity', [$action, $data, $shares, $changedProperties]); } - public function dataGetUsersForShares() { + public function dataGetUsersForShares(): array { return [ [ [], @@ -349,7 +336,7 @@ public function testGetUsersForShares(array $shares, array $groups, array $expec * @param string[] $users * @return IUser[]|MockObject[] */ - protected function getUsers(array $users) { + protected function getUsers(array $users): array { $list = []; foreach ($users as $user) { $list[] = $this->getUserMock($user); @@ -361,7 +348,7 @@ protected function getUsers(array $users) { * @param string $uid * @return IUser|MockObject */ - protected function getUserMock($uid) { + protected function getUserMock(string $uid) { $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') diff --git a/apps/dav/tests/unit/CalDAV/Activity/Filter/CalendarTest.php b/apps/dav/tests/unit/CalDAV/Activity/Filter/CalendarTest.php index de31c71aacb0a..8c7a40199191e 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Filter/CalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Filter/CalendarTest.php @@ -30,14 +30,15 @@ use OCP\Activity\IFilter; use OCP\IL10N; use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CalendarTest extends TestCase { - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ protected $url; - /** @var IFilter|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IFilter|MockObject */ protected $filter; protected function setUp(): void { @@ -69,7 +70,7 @@ public function testGetIcon() { $this->assertEquals('absolute-path-to-icon', $this->filter->getIcon()); } - public function dataFilterTypes() { + public function dataFilterTypes(): array { return [ [[], []], [['calendar', 'calendar_event'], ['calendar', 'calendar_event']], @@ -83,7 +84,7 @@ public function dataFilterTypes() { * @param string[] $types * @param string[] $expected */ - public function testFilterTypes($types, $expected) { + public function testFilterTypes(array $types, array $expected) { $this->assertEquals($expected, $this->filter->filterTypes($types)); } } diff --git a/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php b/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php index 4cfc7ef7144ca..8f94590806107 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Filter/GenericTest.php @@ -23,16 +23,19 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Activity\Filter; +use OC; use OCA\DAV\CalDAV\Activity\Filter\Calendar; use OCA\DAV\CalDAV\Activity\Filter\Todo; use OCP\Activity\IFilter; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Test\TestCase; /** * @group DB */ class GenericTest extends TestCase { - public function dataFilters() { + public function dataFilters(): array { return [ [Calendar::class], [Todo::class], @@ -41,40 +44,44 @@ public function dataFilters() { /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testImplementsInterface($filterClass) { - $filter = \OC::$server->get($filterClass); + public function testImplementsInterface(string $filterClass) { + $filter = OC::$server->get($filterClass); $this->assertInstanceOf(IFilter::class, $filter); } /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetIdentifier($filterClass) { + public function testGetIdentifier(string $filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->get($filterClass); + $filter = OC::$server->get($filterClass); $this->assertIsString($filter->getIdentifier()); } /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetName($filterClass) { + public function testGetName(string $filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->get($filterClass); + $filter = OC::$server->get($filterClass); $this->assertIsString($filter->getName()); } /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetPriority($filterClass) { + public function testGetPriority(string $filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->get($filterClass); + $filter = OC::$server->get($filterClass); $priority = $filter->getPriority(); $this->assertIsInt($filter->getPriority()); $this->assertGreaterThanOrEqual(0, $priority); @@ -83,32 +90,35 @@ public function testGetPriority($filterClass) { /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetIcon($filterClass) { + public function testGetIcon(string $filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->get($filterClass); + $filter = OC::$server->get($filterClass); $this->assertIsString($filter->getIcon()); $this->assertStringStartsWith('http', $filter->getIcon()); } /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testFilterTypes($filterClass) { + public function testFilterTypes(string $filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->get($filterClass); + $filter = OC::$server->get($filterClass); $this->assertIsArray($filter->filterTypes([])); } /** * @dataProvider dataFilters - * @param string $filterClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testAllowedApps($filterClass) { + public function testAllowedApps(string $filterClass) { /** @var IFilter $filter */ - $filter = \OC::$server->get($filterClass); + $filter = OC::$server->get($filterClass); $this->assertIsArray($filter->allowedApps()); } } diff --git a/apps/dav/tests/unit/CalDAV/Activity/Filter/TodoTest.php b/apps/dav/tests/unit/CalDAV/Activity/Filter/TodoTest.php index e119064046bd5..27cd85546dfdd 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Filter/TodoTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Filter/TodoTest.php @@ -29,14 +29,15 @@ use OCP\Activity\IFilter; use OCP\IL10N; use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class TodoTest extends TestCase { - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ protected $url; - /** @var IFilter|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IFilter|MockObject */ protected $filter; protected function setUp(): void { @@ -68,7 +69,7 @@ public function testGetIcon() { $this->assertEquals('absolute-path-to-icon', $this->filter->getIcon()); } - public function dataFilterTypes() { + public function dataFilterTypes(): array { return [ [[], []], [['calendar_todo'], ['calendar_todo']], @@ -82,7 +83,7 @@ public function dataFilterTypes() { * @param string[] $types * @param string[] $expected */ - public function testFilterTypes($types, $expected) { + public function testFilterTypes(array $types, array $expected) { $this->assertEquals($expected, $this->filter->filterTypes($types)); } } diff --git a/apps/dav/tests/unit/CalDAV/Activity/Provider/BaseTest.php b/apps/dav/tests/unit/CalDAV/Activity/Provider/BaseTest.php index 21cafee4f889e..6fcd8f140f88b 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Provider/BaseTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Provider/BaseTest.php @@ -62,11 +62,11 @@ protected function setUp(): void { $this->groupManager, $this->url, ]) - ->setMethods(['parse']) + ->onlyMethods(['parse']) ->getMock(); } - public function dataSetSubjects() { + public function dataSetSubjects(): array { return [ ['abc', [], 'abc'], ['{actor} created {calendar}', ['actor' => ['name' => 'abc'], 'calendar' => ['name' => 'xyz']], 'abc created xyz'], @@ -93,7 +93,7 @@ public function testSetSubjects(string $subject, array $parameters, string $pars $this->invokePrivate($this->provider, 'setSubjects', [$event, $subject, $parameters]); } - public function dataGenerateCalendarParameter() { + public function dataGenerateCalendarParameter(): array { return [ [['id' => 23, 'uri' => 'foo', 'name' => 'bar'], 'bar'], [['id' => 42, 'uri' => 'foo', 'name' => 'Personal'], 'Personal'], @@ -122,7 +122,7 @@ public function testGenerateCalendarParameter(array $data, string $name) { ], $this->invokePrivate($this->provider, 'generateCalendarParameter', [$data, $l])); } - public function dataGenerateLegacyCalendarParameter() { + public function dataGenerateLegacyCalendarParameter(): array { return [ [23, 'c1'], [42, 'c2'], @@ -142,7 +142,7 @@ public function testGenerateLegacyCalendarParameter(int $id, string $name) { ], $this->invokePrivate($this->provider, 'generateLegacyCalendarParameter', [$id, $name])); } - public function dataGenerateGroupParameter() { + public function dataGenerateGroupParameter(): array { return [ ['g1'], ['g2'], @@ -161,7 +161,7 @@ public function testGenerateGroupParameter(string $gid) { ], $this->invokePrivate($this->provider, 'generateGroupParameter', [$gid])); } - public function dataGenerateUserParameter() { + public function dataGenerateUserParameter(): array { $u1 = $this->createMock(IUser::class); $u1->expects($this->any()) ->method('getDisplayName') diff --git a/apps/dav/tests/unit/CalDAV/Activity/Provider/EventTest.php b/apps/dav/tests/unit/CalDAV/Activity/Provider/EventTest.php index cb86b80d3111e..f13d4579a5c76 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Provider/EventTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Provider/EventTest.php @@ -82,11 +82,11 @@ protected function setUp(): void { $this->eventMerger, $this->appManager ]) - ->setMethods(['parse']) + ->onlyMethods(['parse']) ->getMock(); } - public function dataGenerateObjectParameter() { + public function dataGenerateObjectParameter(): array { $link = [ 'object_uri' => 'someuuid.ics', 'calendar_uri' => 'personal', @@ -142,7 +142,7 @@ public function testGenerateObjectParameter(int $id, string $name, ?array $link, $this->assertEquals($result, $this->invokePrivate($this->provider, 'generateObjectParameter', [$objectParameter])); } - public function dataGenerateObjectParameterThrows() { + public function dataGenerateObjectParameterThrows(): array { return [ ['event', TypeError::class], [['name' => 'event']], diff --git a/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php b/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php index 582885c5ea59d..7a02f42b17397 100644 --- a/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php +++ b/apps/dav/tests/unit/CalDAV/Activity/Setting/GenericTest.php @@ -23,14 +23,17 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Activity\Setting; +use OC; use OCA\DAV\CalDAV\Activity\Setting\Calendar; use OCA\DAV\CalDAV\Activity\Setting\Event; use OCA\DAV\CalDAV\Activity\Setting\Todo; use OCP\Activity\ISetting; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Test\TestCase; class GenericTest extends TestCase { - public function dataSettings() { + public function dataSettings(): array { return [ [Calendar::class], [Event::class], @@ -40,40 +43,44 @@ public function dataSettings() { /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testImplementsInterface($settingClass) { - $setting = \OC::$server->get($settingClass); + public function testImplementsInterface(string $settingClass) { + $setting = OC::$server->get($settingClass); $this->assertInstanceOf(ISetting::class, $setting); } /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetIdentifier($settingClass) { + public function testGetIdentifier(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $this->assertIsString($setting->getIdentifier()); } /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetName($settingClass) { + public function testGetName(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $this->assertIsString($setting->getName()); } /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testGetPriority($settingClass) { + public function testGetPriority(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $priority = $setting->getPriority(); $this->assertIsInt($setting->getPriority()); $this->assertGreaterThanOrEqual(0, $priority); @@ -82,41 +89,45 @@ public function testGetPriority($settingClass) { /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testCanChangeStream($settingClass) { + public function testCanChangeStream(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $this->assertIsBool($setting->canChangeStream()); } /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testIsDefaultEnabledStream($settingClass) { + public function testIsDefaultEnabledStream(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $this->assertIsBool($setting->isDefaultEnabledStream()); } /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testCanChangeMail($settingClass) { + public function testCanChangeMail(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $this->assertIsBool($setting->canChangeMail()); } /** * @dataProvider dataSettings - * @param string $settingClass + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ - public function testIsDefaultEnabledMail($settingClass) { + public function testIsDefaultEnabledMail(string $settingClass) { /** @var ISetting $setting */ - $setting = \OC::$server->get($settingClass); + $setting = OC::$server->get($settingClass); $this->assertIsBool($setting->isDefaultEnabledMail()); } } diff --git a/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php b/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php index 99e5f2e8e542c..3e9252891b0fd 100644 --- a/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php +++ b/apps/dav/tests/unit/CalDAV/BirthdayCalendar/EnablePluginTest.php @@ -31,20 +31,27 @@ use OCA\DAV\CalDAV\Calendar; use OCA\DAV\CalDAV\CalendarHome; use OCP\IConfig; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Server; +use Sabre\DAV\Tree; +use Sabre\DAV\Xml\Service; +use Sabre\HTTP\RequestInterface; +use Sabre\HTTP\Response; +use Sabre\HTTP\ResponseInterface; use Test\TestCase; class EnablePluginTest extends TestCase { - /** @var \Sabre\DAV\Server|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Server|MockObject */ protected $server; - /** @var \OCP\IConfig|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig|MockObject */ protected $config; - /** @var BirthdayService |\PHPUnit\Framework\MockObject\MockObject */ + /** @var BirthdayService |MockObject */ protected $birthdayService; - /** @var \OCA\DAV\CalDAV\BirthdayCalendar\EnablePlugin $plugin */ + /** @var EnablePlugin $plugin */ protected $plugin; protected $request; @@ -54,10 +61,10 @@ class EnablePluginTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->server = $this->createMock(\Sabre\DAV\Server::class); - $this->server->tree = $this->createMock(\Sabre\DAV\Tree::class); - $this->server->httpResponse = $this->createMock(\Sabre\HTTP\Response::class); - $this->server->xml = $this->createMock(\Sabre\DAV\Xml\Service::class); + $this->server = $this->createMock(Server::class); + $this->server->tree = $this->createMock(Tree::class); + $this->server->httpResponse = $this->createMock(Response::class); + $this->server->xml = $this->createMock(Service::class); $this->config = $this->createMock(IConfig::class); $this->birthdayService = $this->createMock(BirthdayService::class); @@ -65,8 +72,8 @@ protected function setUp(): void { $this->plugin = new EnablePlugin($this->config, $this->birthdayService); $this->plugin->initialize($this->server); - $this->request = $this->createMock(\Sabre\HTTP\RequestInterface::class); - $this->response = $this->createMock(\Sabre\HTTP\ResponseInterface::class); + $this->request = $this->createMock(RequestInterface::class); + $this->response = $this->createMock(ResponseInterface::class); } public function testGetFeatures() { @@ -78,7 +85,7 @@ public function testGetName() { } public function testInitialize() { - $server = $this->createMock(\Sabre\DAV\Server::class); + $server = $this->createMock(Server::class); $plugin = new EnablePlugin($this->config, $this->birthdayService); diff --git a/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php b/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php index 74e3784aefa9b..752816c93f1c3 100644 --- a/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php +++ b/apps/dav/tests/unit/CalDAV/CachedSubscriptionObjectTest.php @@ -26,8 +26,10 @@ use OCA\DAV\CalDAV\CachedSubscriptionObject; use OCA\DAV\CalDAV\CalDavBackend; +use Sabre\DAV\Exception\MethodNotAllowed; +use Test\TestCase; -class CachedSubscriptionObjectTest extends \Test\TestCase { +class CachedSubscriptionObjectTest extends TestCase { public function testGet() { $backend = $this->createMock(CalDavBackend::class); $calendarInfo = [ @@ -51,9 +53,9 @@ public function testGet() { $this->assertEquals('BEGIN...', $calendarObject->get()); } - + public function testPut() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('Creating objects in a cached subscription is not allowed'); $backend = $this->createMock(CalDavBackend::class); @@ -71,9 +73,9 @@ public function testPut() { $calendarObject->put(''); } - + public function testDelete() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('Deleting objects in a cached subscription is not allowed'); $backend = $this->createMock(CalDavBackend::class); diff --git a/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php b/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php index dac5090dccca9..c0108484658a7 100644 --- a/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php +++ b/apps/dav/tests/unit/CalDAV/CachedSubscriptionTest.php @@ -27,9 +27,12 @@ use OCA\DAV\CalDAV\CachedSubscription; use OCA\DAV\CalDAV\CachedSubscriptionObject; use OCA\DAV\CalDAV\CalDavBackend; +use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\PropPatch; +use Test\TestCase; -class CachedSubscriptionTest extends \Test\TestCase { +class CachedSubscriptionTest extends TestCase { public function testGetACL() { $backend = $this->createMock(CalDavBackend::class); $calendarInfo = [ @@ -141,9 +144,9 @@ public function testPropPatch() { $calendar->propPatch($propPatch); } - + public function testGetChild() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->expectExceptionMessage('Calendar object not found'); $backend = $this->createMock(CalDavBackend::class); @@ -154,18 +157,19 @@ public function testGetChild() { 'uri' => 'cal', ]; - $backend->expects($this->at(0)) + $backend->expects($this->exactly(2)) ->method('getCalendarObject') - ->with(666, 'foo1', 1) - ->willReturn([ - 'id' => 99, - 'uri' => 'foo1' - ]); - $backend->expects($this->at(1)) - ->method('getCalendarObject') - ->with(666, 'foo2', 1) - ->willReturn(null); - + ->withConsecutive( + [666, 'foo1', 1], + [666, 'foo2', 1] + ) + ->willReturnOnConsecutiveCalls( + [ + 'id' => 99, + 'uri' => 'foo1' + ], + null + ); $calendar = new CachedSubscription($backend, $calendarInfo); $first = $calendar->getChild('foo1'); @@ -183,7 +187,7 @@ public function testGetChildren() { 'uri' => 'cal', ]; - $backend->expects($this->at(0)) + $backend->expects($this->once()) ->method('getCalendarObjects') ->with(666, 1) ->willReturn([ @@ -214,7 +218,7 @@ public function testGetMultipleChildren() { 'uri' => 'cal', ]; - $backend->expects($this->at(0)) + $backend->expects($this->once()) ->method('getMultipleCalendarObjects') ->with(666, ['foo1', 'foo2'], 1) ->willReturn([ @@ -236,9 +240,9 @@ public function testGetMultipleChildren() { $this->assertInstanceOf(CachedSubscriptionObject::class, $res[1]); } - + public function testCreateFile() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('Creating objects in cached subscription is not allowed'); $backend = $this->createMock(CalDavBackend::class); @@ -262,17 +266,16 @@ public function testChildExists() { 'uri' => 'cal', ]; - $backend->expects($this->at(0)) + $backend->expects($this->exactly(2)) ->method('getCalendarObject') - ->with(666, 'foo1', 1) - ->willReturn([ + ->withConsecutive( + [666, 'foo1', 1], + [666, 'foo2', 1] + ) + ->willReturnOnConsecutiveCalls([ 'id' => 99, 'uri' => 'foo1' - ]); - $backend->expects($this->at(1)) - ->method('getCalendarObject') - ->with(666, 'foo2', 1) - ->willReturn(null); + ], null); $calendar = new CachedSubscription($backend, $calendarInfo); diff --git a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php index 8e4bb1f79324b..56dc0c91c4356 100644 --- a/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/CalDavBackendTest.php @@ -38,6 +38,9 @@ use OCA\DAV\Events\CalendarDeletedEvent; use OCP\IConfig; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception; +use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\PropPatch; use Sabre\DAV\Xml\Property\Href; @@ -51,6 +54,9 @@ * @package OCA\DAV\Tests\unit\CalDAV */ class CalDavBackendTest extends AbstractCalDavBackend { + /** + * @throws Exception + */ public function testCalendarOperations() { $calendarId = $this->createTestCalendar(); @@ -78,7 +84,7 @@ public function testCalendarOperations() { self::assertEmpty($calendars); } - public function providesSharingData() { + public function providesSharingData(): array { return [ [true, true, true, false, [ [ @@ -122,10 +128,11 @@ public function providesSharingData() { /** * @dataProvider providesSharingData + * @throws Exception */ - public function testCalendarSharing($userCanRead, $userCanWrite, $groupCanRead, $groupCanWrite, $add) { + public function testCalendarSharing(bool $userCanRead, bool $userCanWrite, bool $groupCanRead, bool $groupCanWrite, array $add) { - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l10n */ + /** @var IL10N|MockObject $l10n */ $l10n = $this->createMock(IL10N::class); $l10n ->expects($this->any()) @@ -203,6 +210,11 @@ public function testCalendarSharing($userCanRead, $userCanWrite, $groupCanRead, self::assertEmpty($calendars); } + /** + * @throws Exception + * @throws BadRequest + * @throws Exception\Forbidden + */ public function testCalendarObjectsOperations() { $calendarId = $this->createTestCalendar(); @@ -277,8 +289,11 @@ public function testCalendarObjectsOperations() { } + /** + * @throws Exception + */ public function testMultipleCalendarObjectsWithSameUID() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('Calendar object with uid already exists in this calendar collection.'); $calendarId = $this->createTestCalendar(); @@ -306,6 +321,11 @@ public function testMultipleCalendarObjectsWithSameUID() { $this->backend->createCalendarObject($calendarId, $uri1, $calData); } + /** + * @throws Exception + * @throws BadRequest + * @throws Exception\Forbidden + */ public function testMultiCalendarObjects() { $calendarId = $this->createTestCalendar(); @@ -414,11 +434,13 @@ public function testMultiCalendarObjects() { /** * @dataProvider providesCalendarQueryParameters + * @throws BadRequest + * @throws Exception */ - public function testCalendarQuery($expectedEventsInResult, $propFilters, $compFilter) { + public function testCalendarQuery(array $expectedEventsInResult, array $propFilters, array $compFilter) { $calendarId = $this->createTestCalendar(); $events = []; - $events[0] = $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); + $events[0] = $this->createEvent($calendarId); $events[1] = $this->createEvent($calendarId, '20130912T150000Z', '20130912T170000Z'); $events[2] = $this->createEvent($calendarId, '20130912T173000Z', '20130912T220000Z'); $events[3] = $this->createEvent($calendarId, '21130912T130000Z', '22130912T130000Z'); @@ -435,6 +457,10 @@ public function testCalendarQuery($expectedEventsInResult, $propFilters, $compFi $this->assertEqualsCanonicalizing($expectedEventsInResult, $result); } + /** + * @throws Exception + * @throws BadRequest + */ public function testGetCalendarObjectByUID() { $calendarId = $this->createTestCalendar(); $uri = static::getUniqueID('calobj'); @@ -462,7 +488,10 @@ public function testGetCalendarObjectByUID() { $this->assertNotNull($co); } - public function providesCalendarQueryParameters() { + /** + * @throws \Exception + */ + public function providesCalendarQueryParameters(): array { return [ 'all' => [[0, 1, 2, 3], [], []], 'only-todos' => [[], ['name' => 'VTODO'], []], @@ -473,6 +502,10 @@ public function providesCalendarQueryParameters() { ]; } + /** + * @throws Exception + * @throws BadRequest + */ public function testSyncSupport() { $calendarId = $this->createTestCalendar(); @@ -481,13 +514,17 @@ public function testSyncSupport() { $syncToken = $changes['syncToken']; // add a change - $event = $this->createEvent($calendarId, '20130912T130000Z', '20130912T140000Z'); + $event = $this->createEvent($calendarId); // look for changes $changes = $this->backend->getChangesForCalendar($calendarId, $syncToken, 1); $this->assertEquals($event, $changes['added'][0]); } + /** + * @throws Exception + * @throws NotFound + */ public function testPublications() { $this->dispatcher->expects(self::atLeastOnce()) ->method('dispatchTyped'); @@ -496,7 +533,7 @@ public function testPublications() { $calendarInfo = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER)[0]; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject $l10n */ + /** @var IL10N|MockObject $l10n */ $l10n = $this->createMock(IL10N::class); $config = $this->createMock(IConfig::class); $logger = $this->createMock(\Psr\Log\LoggerInterface::class); @@ -520,6 +557,9 @@ public function testPublications() { $this->backend->getPublicCalendar($publicCalendarURI); } + /** + * @throws Exception\Forbidden + */ public function testSubscriptions() { $id = $this->backend->createSubscription(self::UNIT_TEST_USER, 'Subscription', [ '{http://calendarserver.org/ns/}source' => new Href('test-source'), @@ -551,7 +591,7 @@ public function testSubscriptions() { $this->assertCount(0, $subscriptions); } - public function providesSchedulingData() { + public function providesSchedulingData(): array { $data = <<backend->createSchedulingObject(self::UNIT_TEST_USER, 'Sample Schedule', $objectData); $sos = $this->backend->getSchedulingObjects(self::UNIT_TEST_USER); @@ -644,13 +684,17 @@ public function testScheduling($objectData) { /** * @dataProvider providesCalDataForGetDenormalizedData + * @throws BadRequest */ - public function testGetDenormalizedData($expected, $key, $calData) { + public function testGetDenormalizedData(?int $expected, string $key, string $calData) { $actual = $this->backend->getDenormalizedData($calData); $this->assertEquals($expected, $actual[$key]); } - public function providesCalDataForGetDenormalizedData() { + /** + * @throws \Exception + */ + public function providesCalDataForGetDenormalizedData(): array { return [ 'first occurrence before unix epoch starts' => [0, 'firstOccurence', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:413F269B-B51B-46B1-AFB6-40055C53A4DC\r\nDTSTAMP:20160309T095056Z\r\nDTSTART;VALUE=DATE:16040222\r\nDTEND;VALUE=DATE:16040223\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:SUMMARY\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], 'no first occurrence because yearly' => [null, 'firstOccurence', "BEGIN:VCALENDAR\r\nVERSION:2.0\r\nPRODID:-//Sabre//Sabre VObject 4.1.1//EN\r\nCALSCALE:GREGORIAN\r\nBEGIN:VEVENT\r\nUID:413F269B-B51B-46B1-AFB6-40055C53A4DC\r\nDTSTAMP:20160309T095056Z\r\nRRULE:FREQ=YEARLY\r\nSUMMARY:SUMMARY\r\nTRANSP:TRANSPARENT\r\nEND:VEVENT\r\nEND:VCALENDAR\r\n"], @@ -664,6 +708,11 @@ public function providesCalDataForGetDenormalizedData() { ]; } + /** + * @throws Exception + * @throws BadRequest + * @throws Exception\Forbidden + */ public function testCalendarSearch() { $calendarId = $this->createTestCalendar(); @@ -698,7 +747,7 @@ public function testCalendarSearch() { ], 'search-term' => 'Test', ]); - $this->assertEquals(count($search1), 1); + $this->assertCount(1, $search1); // update the card @@ -731,7 +780,7 @@ public function testCalendarSearch() { ], 'search-term' => 'Test', ]); - $this->assertEquals(count($search2), 0); + $this->assertCount(0, $search2); $search3 = $this->backend->calendarSearch(self::UNIT_TEST_USER, [ 'comps' => [ @@ -750,7 +799,7 @@ public function testCalendarSearch() { ], 'search-term' => 'Test', ]); - $this->assertEquals(count($search3), 1); + $this->assertCount(1, $search3); // t matches both summary and attendee's CN, but we want unique results $search4 = $this->backend->calendarSearch(self::UNIT_TEST_USER, [ @@ -770,7 +819,7 @@ public function testCalendarSearch() { ], 'search-term' => 't', ]); - $this->assertEquals(count($search4), 1); + $this->assertCount(1, $search4); $this->backend->deleteCalendarObject($calendarId, $uri); @@ -791,11 +840,12 @@ public function testCalendarSearch() { ], 'search-term' => 't', ]); - $this->assertEquals(count($search5), 0); + $this->assertCount(0, $search5); } /** * @dataProvider searchDataProvider + * @throws Exception */ public function testSearch(bool $isShared, array $searchOptions, int $count) { $calendarId = $this->createTestCalendar(); @@ -896,7 +946,7 @@ public function testSearch(bool $isShared, array $searchOptions, int $count) { $this->assertCount($count, $result); } - public function searchDataProvider() { + public function searchDataProvider(): array { return [ [false, [], 4], [true, ['timerange' => ['start' => new DateTime('2013-09-12 13:00:00'), 'end' => new DateTime('2013-09-12 14:00:00')]], 2], @@ -904,6 +954,11 @@ public function searchDataProvider() { ]; } + /** + * @throws Exception + * @throws BadRequest + * @throws Exception\Forbidden + */ public function testSameUriSameIdForDifferentCalendarTypes() { $calendarId = $this->createTestCalendar(); $subscriptionId = $this->createTestSubscription(); @@ -950,6 +1005,10 @@ public function testSameUriSameIdForDifferentCalendarTypes() { $this->assertEquals($calData2, $this->backend->getCalendarObject($subscriptionId, $uri, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION)['calendardata']); } + /** + * @throws BadRequest + * @throws Exception\Forbidden + */ public function testPurgeAllCachedEventsForSubscription() { $subscriptionId = $this->createTestSubscription(); $uri = static::getUniqueID('calobj'); @@ -976,6 +1035,9 @@ public function testPurgeAllCachedEventsForSubscription() { $this->assertEquals(null, $this->backend->getCalendarObject($subscriptionId, $uri, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION)); } + /** + * @throws Exception + */ public function testCalendarMovement() { $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', []); @@ -992,6 +1054,10 @@ public function testCalendarMovement() { $this->assertEquals($calendarInfoUser['uri'], $calendarInfoUser1['uri']); } + /** + * @throws Exception + * @throws BadRequest + */ public function testSearchPrincipal(): void { $myPublic = <<backend = $this->createMock(CalDavBackend::class); - $this->principalInfo = [ + $principalInfo = [ 'uri' => 'user-principal-123', ]; $this->pluginManager = $this->createMock(PluginManager::class); @@ -67,7 +67,7 @@ protected function setUp(): void { $this->calendarHome = new CalendarHome( $this->backend, - $this->principalInfo, + $principalInfo, $this->logger ); @@ -78,6 +78,9 @@ protected function setUp(): void { $reflectionProperty->setValue($this->calendarHome, $this->pluginManager); } + /** + * @throws InvalidResourceType + */ public function testCreateCalendarValidName() { /** @var MkCol | MockObject $mkCol */ $mkCol = $this->createMock(MkCol::class); @@ -95,8 +98,11 @@ public function testCreateCalendarValidName() { $this->calendarHome->createExtendedCollection('name123', $mkCol); } + /** + * @throws InvalidResourceType + */ public function testCreateCalendarReservedName() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('The resource you tried to create has a reserved name'); /** @var MkCol | MockObject $mkCol */ @@ -105,8 +111,11 @@ public function testCreateCalendarReservedName() { $this->calendarHome->createExtendedCollection('contact_birthdays', $mkCol); } + /** + * @throws InvalidResourceType + */ public function testCreateCalendarReservedNameAppGenerated() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('The resource you tried to create has a reserved name'); /** @var MkCol | MockObject $mkCol */ @@ -117,13 +126,13 @@ public function testCreateCalendarReservedNameAppGenerated() { public function testGetChildren():void { $this->backend - ->expects($this->at(0)) + ->expects($this->once()) ->method('getCalendarsForUser') ->with('user-principal-123') ->willReturn([]); $this->backend - ->expects($this->at(1)) + ->expects($this->once()) ->method('getSubscriptionsForUser') ->with('user-principal-123') ->willReturn([]); @@ -162,13 +171,13 @@ public function testGetChildren():void { public function testGetChildNonAppGenerated():void { $this->backend - ->expects($this->at(0)) + ->expects($this->once()) ->method('getCalendarsForUser') ->with('user-principal-123') ->willReturn([]); $this->backend - ->expects($this->at(1)) + ->expects($this->once()) ->method('getSubscriptionsForUser') ->with('user-principal-123') ->willReturn([]); @@ -177,21 +186,24 @@ public function testGetChildNonAppGenerated():void { ->expects($this->never()) ->method('getCalendarPlugins'); - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->expectExceptionMessage('Node with name \'personal\' could not be found'); $this->calendarHome->getChild('personal'); } + /** + * @throws NotFound + */ public function testGetChildAppGenerated():void { $this->backend - ->expects($this->at(0)) + ->expects($this->once()) ->method('getCalendarsForUser') ->with('user-principal-123') ->willReturn([]); $this->backend - ->expects($this->at(1)) + ->expects($this->once()) ->method('getSubscriptionsForUser') ->with('user-principal-123') ->willReturn([]); diff --git a/apps/dav/tests/unit/CalDAV/CalendarImplTest.php b/apps/dav/tests/unit/CalDAV/CalendarImplTest.php index af8c056cac78d..b484650f69f92 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarImplTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarImplTest.php @@ -28,19 +28,21 @@ use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\Calendar; use OCA\DAV\CalDAV\CalendarImpl; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; -class CalendarImplTest extends \Test\TestCase { +class CalendarImplTest extends TestCase { /** @var CalendarImpl */ private $calendarImpl; - /** @var Calendar | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Calendar | MockObject */ private $calendar; /** @var array */ private $calendarInfo; - /** @var CalDavBackend | \PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend | MockObject */ private $backend; protected function setUp(): void { @@ -60,15 +62,15 @@ protected function setUp(): void { public function testGetKey() { - $this->assertEquals($this->calendarImpl->getKey(), 'fancy_id_123'); + $this->assertEquals('fancy_id_123', $this->calendarImpl->getKey()); } public function testGetDisplayname() { - $this->assertEquals($this->calendarImpl->getDisplayName(),'user readable name 123'); + $this->assertEquals('user readable name 123', $this->calendarImpl->getDisplayName()); } public function testGetDisplayColor() { - $this->assertEquals($this->calendarImpl->getDisplayColor(), '#AABBCC'); + $this->assertEquals('#AABBCC', $this->calendarImpl->getDisplayColor()); } public function testSearch() { @@ -78,7 +80,7 @@ public function testSearch() { ->willReturn(['SEARCHRESULTS']); $result = $this->calendarImpl->search('abc', ['def'], ['ghi'], 42, 1337); - $this->assertEquals($result, ['SEARCHRESULTS']); + $this->assertEquals(['SEARCHRESULTS'], $result); } public function testGetPermissionRead() { diff --git a/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php b/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php index f16a06f953dbb..b808cec3e6f0c 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarManagerTest.php @@ -34,36 +34,24 @@ use OCP\IL10N; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; +use Test\TestCase; -class CalendarManagerTest extends \Test\TestCase { +class CalendarManagerTest extends TestCase { /** @var CalDavBackend | MockObject */ private $backend; - /** @var IL10N | MockObject */ - private $l10n; - - /** @var IConfig|MockObject */ - private $config; - /** @var CalendarManager */ private $manager; - /** @var MockObject|LoggerInterface */ - private $logger; - protected function setUp(): void { parent::setUp(); $this->backend = $this->createMock(CalDavBackend::class); - $this->l10n = $this->createMock(IL10N::class); - $this->config = $this->createMock(IConfig::class); - $this->logger = $this->createMock(LoggerInterface::class); - $this->manager = new CalendarManager( - $this->backend, - $this->l10n, - $this->config, - $this->logger - ); + $logger = $this->createMock(LoggerInterface::class); + $l10n = $this->createMock(IL10N::class); + $config = $this->createMock(IConfig::class); + $this->manager = new CalendarManager($this->backend, + $l10n, $config, $logger); } public function testSetupCalendarProvider() { @@ -77,21 +65,20 @@ public function testSetupCalendarProvider() { /** @var IManager | MockObject $calendarManager */ $calendarManager = $this->createMock(Manager::class); - $calendarManager->expects($this->at(0)) - ->method('registerCalendar') - ->willReturnCallback(function () { - $parameter = func_get_arg(0); - $this->assertInstanceOf(CalendarImpl::class, $parameter); - $this->assertEquals(123, $parameter->getKey()); - }); - - $calendarManager->expects($this->at(1)) + $calendarManager->expects($this->exactly(2)) ->method('registerCalendar') - ->willReturnCallback(function () { - $parameter = func_get_arg(0); - $this->assertInstanceOf(CalendarImpl::class, $parameter); - $this->assertEquals(456, $parameter->getKey()); - }); + ->willReturnOnConsecutiveCalls( + $this->callback(function () { + $parameter = func_get_arg(0); + $this->assertInstanceOf(CalendarImpl::class, $parameter); + $this->assertEquals(123, $parameter->getKey()); + }), + $this->callback(function () { + $parameter = func_get_arg(0); + $this->assertInstanceOf(CalendarImpl::class, $parameter); + $this->assertEquals(456, $parameter->getKey()); + }) + ); $this->manager->setupCalendarProvider($calendarManager, 'user123'); } diff --git a/apps/dav/tests/unit/CalDAV/CalendarTest.php b/apps/dav/tests/unit/CalDAV/CalendarTest.php index 95cedb6da6aa6..75ddc79aa8692 100644 --- a/apps/dav/tests/unit/CalDAV/CalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/CalendarTest.php @@ -28,6 +28,7 @@ */ namespace OCA\DAV\Tests\unit\CalDAV; +use Exception; use OCA\DAV\CalDAV\BirthdayService; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\Calendar; @@ -35,6 +36,8 @@ use OCP\IL10N; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\PropPatch; use Sabre\VObject\Reader; use Test\TestCase; @@ -52,8 +55,7 @@ class CalendarTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->l10n = $this->getMockBuilder(IL10N::class) - ->disableOriginalConstructor()->getMock(); + $this->l10n = $this->createMock(IL10N::class); $this->config = $this->createMock(IConfig::class); $this->logger = $this->createMock(LoggerInterface::class); $this->l10n @@ -64,9 +66,12 @@ protected function setUp(): void { }); } + /** + * @throws Forbidden + */ public function testDelete() { /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->once())->method('updateShares'); $backend->expects($this->any())->method('getShares')->willReturn([ ['href' => 'principal:user2'] @@ -83,10 +88,10 @@ public function testDelete() { public function testDeleteFromGroup() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->never())->method('updateShares'); $backend->expects($this->any())->method('getShares')->willReturn([ ['href' => 'principal:group2'] @@ -101,6 +106,9 @@ public function testDeleteFromGroup() { $c->delete(); } + /** + * @throws Forbidden + */ public function testDeleteOwn() { /** @var MockObject | CalDavBackend $backend */ $backend = $this->createMock(CalDavBackend::class); @@ -122,6 +130,9 @@ public function testDeleteOwn() { $c->delete(); } + /** + * @throws Forbidden + */ public function testDeleteBirthdayCalendar() { /** @var MockObject | CalDavBackend $backend */ $backend = $this->createMock(CalDavBackend::class); @@ -143,7 +154,7 @@ public function testDeleteBirthdayCalendar() { $c->delete(); } - public function dataPropPatch() { + public function dataPropPatch(): array { return [ ['user1', 'user2', [], true], ['user1', 'user2', [ @@ -173,9 +184,9 @@ public function dataPropPatch() { /** * @dataProvider dataPropPatch */ - public function testPropPatch($ownerPrincipal, $principalUri, $mutations, $shared) { + public function testPropPatch(string $ownerPrincipal, string $principalUri, array $mutations, bool $shared) { /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + $backend = $this->createMock(CalDavBackend::class); $calendarInfo = [ '{http://owncloud.org/ns}owner-principal' => $ownerPrincipal, 'principaluri' => $principalUri, @@ -197,9 +208,9 @@ public function testPropPatch($ownerPrincipal, $principalUri, $mutations, $share /** * @dataProvider providesReadOnlyInfo */ - public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet, $uri = 'default') { + public function testAcl(bool $expectsWrite, ?bool $readOnlyValue, bool $hasOwnerSet, string $uri = 'default') { /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); $calendarInfo = [ 'principaluri' => 'user2', @@ -283,7 +294,7 @@ public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet, $uri = 'def $this->assertEquals($expectedAcl, $childAcl); } - public function providesReadOnlyInfo() { + public function providesReadOnlyInfo(): array { return [ 'read-only property not set' => [true, null, true], 'read-only property is false' => [true, false, true], @@ -297,16 +308,14 @@ public function providesReadOnlyInfo() { /** * @dataProvider providesConfidentialClassificationData - * @param int $expectedChildren - * @param bool $isShared */ - public function testPrivateClassification($expectedChildren, $isShared) { + public function testPrivateClassification(int $expectedChildren, bool $isShared) { $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC]; $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL]; $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE]; /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->any())->method('getCalendarObjects')->willReturn([ $calObject0, $calObject1, $calObject2 ]); @@ -330,19 +339,18 @@ public function testPrivateClassification($expectedChildren, $isShared) { } $c = new Calendar($backend, $calendarInfo, $this->l10n, $this->config, $this->logger); $children = $c->getChildren(); - $this->assertEquals($expectedChildren, count($children)); + $this->assertCount($expectedChildren, $children); $children = $c->getMultipleChildren(['event-0', 'event-1', 'event-2']); - $this->assertEquals($expectedChildren, count($children)); + $this->assertCount($expectedChildren, $children); $this->assertEquals(!$isShared, $c->childExists('event-2')); } /** * @dataProvider providesConfidentialClassificationData - * @param int $expectedChildren - * @param bool $isShared + * @throws NotFound */ - public function testConfidentialClassification($expectedChildren, $isShared) { + public function testConfidentialClassification(int $expectedChildren, bool $isShared) { $start = '20160609'; $end = '20160610'; @@ -393,7 +401,7 @@ public function testConfidentialClassification($expectedChildren, $isShared) { $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE]; /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->any())->method('getCalendarObjects')->willReturn([ $calObject0, $calObject1, $calObject2 ]); @@ -457,13 +465,16 @@ public function testConfidentialClassification($expectedChildren, $isShared) { } } - public function providesConfidentialClassificationData() { + public function providesConfidentialClassificationData(): array { return [ [3, false], [2, true] ]; } + /** + * @throws NotFound + */ public function testRemoveVAlarms() { $publicObjectData = <<assertEquals('app-generated--example-app-id--calendar-uri-in-backend', $this->abstractExternalCalendar->getName()); - // Check that the method is final and can't be overriden by other classes - $reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'getName'); + // Check that the method is final and can't be overridden by other classes + $reflectionMethod = new ReflectionMethod(ExternalCalendar::class, 'getName'); $this->assertTrue($reflectionMethod->isFinal()); } public function testSetName():void { - // Check that the method is final and can't be overriden by other classes - $reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'setName'); + // Check that the method is final and can't be overridden by other classes + $reflectionMethod = new ReflectionMethod(ExternalCalendar::class, 'setName'); $this->assertTrue($reflectionMethod->isFinal()); - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('Renaming calendars is not yet supported'); $this->abstractExternalCalendar->setName('other-name'); } public function createDirectory():void { - // Check that the method is final and can't be overriden by other classes - $reflectionMethod = new \ReflectionMethod(ExternalCalendar::class, 'createDirectory'); + // Check that the method is final and can't be overridden by other classes + $reflectionMethod = new ReflectionMethod(ExternalCalendar::class, 'createDirectory'); $this->assertTrue($reflectionMethod->isFinal()); - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->expectExceptionMessage('Creating collections in calendar objects is not allowed'); $this->abstractExternalCalendar->createDirectory('other-name'); @@ -84,7 +87,7 @@ public function testIsAppGeneratedCalendar():void { * @dataProvider splitAppGeneratedCalendarUriDataProvider */ public function testSplitAppGeneratedCalendarUriInvalid(string $name):void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Provided calendar uri was not app-generated'); ExternalCalendar::splitAppGeneratedCalendarUri($name); diff --git a/apps/dav/tests/unit/CalDAV/PluginTest.php b/apps/dav/tests/unit/CalDAV/PluginTest.php index b5da2199e1c70..7973a16c601df 100644 --- a/apps/dav/tests/unit/CalDAV/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/PluginTest.php @@ -38,7 +38,7 @@ protected function setUp(): void { $this->plugin = new Plugin(); } - public function linkProvider() { + public function linkProvider(): array { return [ [ 'principals/users/MyUserName', @@ -57,11 +57,8 @@ public function linkProvider() { /** * @dataProvider linkProvider - * - * @param $input - * @param $expected */ - public function testGetCalendarHomeForPrincipal($input, $expected) { + public function testGetCalendarHomeForPrincipal(string $input, string $expected) { $this->assertSame($expected, $this->plugin->getCalendarHomeForPrincipal($input)); } diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php index 758e5ee1b20a4..beaec83aa40fc 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarRootTest.php @@ -30,6 +30,7 @@ */ namespace OCA\DAV\Tests\unit\CalDAV; +use OC; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\Calendar; use OCA\DAV\CalDAV\PublicCalendar; @@ -42,7 +43,12 @@ use OCP\IL10N; use OCP\IUserManager; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception; +use Sabre\DAV\Exception\NotFound; use Test\TestCase; /** @@ -60,28 +66,29 @@ class PublicCalendarRootTest extends TestCase { private $publicCalendarRoot; /** @var IL10N */ private $l10n; - /** @var Principal|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Principal|MockObject */ private $principal; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ protected $userManager; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IGroupManager|MockObject */ protected $groupManager; /** @var IConfig */ protected $config; - - /** @var ISecureRandom */ - private $random; /** @var LoggerInterface */ - private $logger; + protected $logger; + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { parent::setUp(); - $db = \OC::$server->get(IDBConnection::class); + $db = OC::$server->get(IDBConnection::class); $this->principal = $this->createMock(Principal::class); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); - $this->random = \OC::$server->get(ISecureRandom::class); + $random = OC::$server->get(ISecureRandom::class); $this->logger = $this->createMock(LoggerInterface::class); $dispatcher = $this->createMock(IEventDispatcher::class); $config = $this->createMock(IConfig::class); @@ -99,13 +106,12 @@ protected function setUp(): void { $this->principal, $this->userManager, $this->groupManager, - $this->random, + $random, $this->logger, $dispatcher, $config ); - $this->l10n = $this->getMockBuilder(IL10N::class) - ->disableOriginalConstructor()->getMock(); + $this->l10n = $this->createMock(IL10N::class); $this->config = $this->createMock(IConfig::class); $this->publicCalendarRoot = new PublicCalendarRoot($this->backend, @@ -137,11 +143,15 @@ public function testGetName() { $this->assertEquals('public-calendars', $name); } + /** + * @throws Exception + * @throws NotFound + */ public function testGetChild() { $calendar = $this->createPublicCalendar(); $publicCalendars = $this->backend->getPublicCalendars(); - $this->assertEquals(1, count($publicCalendars)); + $this->assertCount(1, $publicCalendars); $this->assertEquals(true, $publicCalendars[0]['{http://owncloud.org/ns}public']); $publicCalendarURI = $publicCalendars[0]['uri']; @@ -150,6 +160,9 @@ public function testGetChild() { $this->assertEquals($calendar, $calendarResult); } + /** + * @throws Exception + */ public function testGetChildren() { $this->createPublicCalendar(); $calendarResults = $this->publicCalendarRoot->getChildren(); @@ -158,17 +171,16 @@ public function testGetChildren() { /** * @return Calendar + * @throws Exception */ protected function createPublicCalendar() { $this->backend->createCalendar(self::UNIT_TEST_USER, 'Example', []); $calendarInfo = $this->backend->getCalendarsForUser(self::UNIT_TEST_USER)[0]; - $calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->psrLogger); + $calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->logger); $publicUri = $calendar->setPublishStatus(true); $calendarInfo = $this->backend->getPublicCalendar($publicUri); - $calendar = new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->psrLogger); - - return $calendar; + return new PublicCalendar($this->backend, $calendarInfo, $this->l10n, $this->config, $this->logger); } } diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php index d7a281e9d27cf..dbb5a33c834d3 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php @@ -36,16 +36,14 @@ class PublicCalendarTest extends CalendarTest { /** * @dataProvider providesConfidentialClassificationData - * @param int $expectedChildren - * @param bool $isShared */ - public function testPrivateClassification($expectedChildren, $isShared) { + public function testPrivateClassification(int $expectedChildren, bool $isShared) { $calObject0 = ['uri' => 'event-0', 'classification' => CalDavBackend::CLASSIFICATION_PUBLIC]; $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL]; $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE]; - /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + /** @var \PHPUnit\Framework\MockObject\MockObject | CalDavBackend $backend */ + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->any())->method('getCalendarObjects')->willReturn([ $calObject0, $calObject1, $calObject2 ]); @@ -79,10 +77,8 @@ public function testPrivateClassification($expectedChildren, $isShared) { /** * @dataProvider providesConfidentialClassificationData - * @param int $expectedChildren - * @param bool $isShared */ - public function testConfidentialClassification($expectedChildren, $isShared) { + public function testConfidentialClassification(int $expectedChildren, bool $isShared) { $start = '20160609'; $end = '20160610'; @@ -132,8 +128,8 @@ public function testConfidentialClassification($expectedChildren, $isShared) { $calObject1 = ['uri' => 'event-1', 'classification' => CalDavBackend::CLASSIFICATION_CONFIDENTIAL, 'calendardata' => $calData]; $calObject2 = ['uri' => 'event-2', 'classification' => CalDavBackend::CLASSIFICATION_PRIVATE]; - /** @var MockObject | CalDavBackend $backend */ - $backend = $this->getMockBuilder(CalDavBackend::class)->disableOriginalConstructor()->getMock(); + /** @var \PHPUnit\Framework\MockObject\MockObject | CalDavBackend $backend */ + $backend = $this->createMock(CalDavBackend::class); $backend->expects($this->any())->method('getCalendarObjects')->willReturn([ $calObject0, $calObject1, $calObject2 ]); diff --git a/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php b/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php index d6b97648436a9..f57be83ed3c03 100644 --- a/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php +++ b/apps/dav/tests/unit/CalDAV/Publishing/PublisherTest.php @@ -67,7 +67,7 @@ public function testSerializeNotPublished() { protected $namespaceMap = ['DAV:' => 'd']; protected $contextUri = '/'; - private function write($input) { + private function write($input): string { $writer = new Writer(); $writer->contextUri = $this->contextUri; $writer->namespaceMap = $this->namespaceMap; diff --git a/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php b/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php index 2490bdc363975..916c7329f489a 100644 --- a/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php +++ b/apps/dav/tests/unit/CalDAV/Publishing/PublishingTest.php @@ -30,6 +30,8 @@ use OCP\IConfig; use OCP\IRequest; use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception; use Sabre\DAV\Server; use Sabre\DAV\SimpleCollection; use Sabre\HTTP\Request; @@ -40,41 +42,32 @@ class PluginTest extends TestCase { /** @var PublishPlugin */ private $plugin; - /** @var Server */ - private $server; - /** @var Calendar | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Calendar | MockObject */ private $book; - /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ - private $config; - /** @var IURLGenerator | \PHPUnit\Framework\MockObject\MockObject */ - private $urlGenerator; + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder(IConfig::class)-> - disableOriginalConstructor()-> - getMock(); - $this->config->expects($this->any())->method('getSystemValue') + $config = $this->createMock(IConfig::class); + $config->expects($this->any())->method('getSystemValue') ->with($this->equalTo('secret')) ->willReturn('mysecret'); - $this->urlGenerator = $this->getMockBuilder(IURLGenerator::class)-> - disableOriginalConstructor()-> - getMock(); + $urlGenerator = $this->createMock(IURLGenerator::class); /** @var IRequest $request */ - $this->plugin = new PublishPlugin($this->config, $this->urlGenerator); + $this->plugin = new PublishPlugin($config, $urlGenerator); $root = new SimpleCollection('calendars'); - $this->server = new Server($root); + $server = new Server($root); /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder(Calendar::class)-> - disableOriginalConstructor()-> - getMock(); + $this->book = $this->createMock(Calendar::class); $this->book->method('getName')->willReturn('cal1'); $root->addChild($this->book); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } public function testPublishing() { diff --git a/apps/dav/tests/unit/CalDAV/Reminder/BackendTest.php b/apps/dav/tests/unit/CalDAV/Reminder/BackendTest.php index 15f949d9adb2e..01fd744e81a55 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/BackendTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/BackendTest.php @@ -30,6 +30,8 @@ use OCA\DAV\CalDAV\Reminder\Backend as ReminderBackend; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\DB\Exception; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class BackendTest extends TestCase { @@ -37,20 +39,23 @@ class BackendTest extends TestCase { /** * Reminder Backend * - * @var ReminderBackend|\PHPUnit\Framework\MockObject\MockObject + * @var ReminderBackend|MockObject */ private $reminderBackend; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); $query = self::$realDatabase->getQueryBuilder(); - $query->delete('calendar_reminders')->execute(); - $query->delete('calendarobjects')->execute(); - $query->delete('calendars')->execute(); + $query->delete('calendar_reminders')->executeStatement(); + $query->delete('calendarobjects')->executeStatement(); + $query->delete('calendars')->executeStatement(); $this->timeFactory = $this->createMock(ITimeFactory::class); $this->reminderBackend = new ReminderBackend(self::$realDatabase, $this->timeFactory); @@ -58,19 +63,25 @@ protected function setUp(): void { $this->createRemindersTestSet(); } + /** + * @throws Exception + */ protected function tearDown(): void { $query = self::$realDatabase->getQueryBuilder(); - $query->delete('calendar_reminders')->execute(); - $query->delete('calendarobjects')->execute(); - $query->delete('calendars')->execute(); + $query->delete('calendar_reminders')->executeStatement(); + $query->delete('calendarobjects')->executeStatement(); + $query->delete('calendars')->executeStatement(); } + /** + * @throws Exception + */ public function testCleanRemindersForEvent(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(4, $rows); @@ -80,17 +91,20 @@ public function testCleanRemindersForEvent(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(2, $rows); } + /** + * @throws Exception + */ public function testCleanRemindersForCalendar(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(4, $rows); @@ -100,17 +114,20 @@ public function testCleanRemindersForCalendar(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(1, $rows); } + /** + * @throws Exception + */ public function testRemoveReminder(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(4, $rows); @@ -120,12 +137,15 @@ public function testRemoveReminder(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(3, $rows); } + /** + * @throws \Exception + */ public function testGetRemindersToProcess(): void { $this->timeFactory->expects($this->exactly(1)) ->method('getTime') @@ -138,7 +158,7 @@ public function testGetRemindersToProcess(): void { unset($rows[0]['id']); unset($rows[1]['id']); - $this->assertEquals($rows[0], [ + $this->assertEquals([ 'calendar_id' => 1, 'object_id' => 1, 'uid' => 'asd', @@ -154,8 +174,8 @@ public function testGetRemindersToProcess(): void { 'calendardata' => 'Calendar data 123', 'displayname' => 'Displayname 123', 'principaluri' => 'principals/users/user001', - ]); - $this->assertEquals($rows[1], [ + ], $rows[0]); + $this->assertEquals([ 'calendar_id' => 1, 'object_id' => 1, 'uid' => 'asd', @@ -171,7 +191,7 @@ public function testGetRemindersToProcess(): void { 'calendardata' => 'Calendar data 123', 'displayname' => 'Displayname 123', 'principaluri' => 'principals/users/user001', - ]); + ], $rows[1]); } public function testGetAllScheduledRemindersForEvent(): void { @@ -181,7 +201,7 @@ public function testGetAllScheduledRemindersForEvent(): void { unset($rows[0]['id']); unset($rows[1]['id']); - $this->assertEquals($rows[0], [ + $this->assertEquals([ 'calendar_id' => 1, 'object_id' => 1, 'uid' => 'asd', @@ -194,8 +214,8 @@ public function testGetAllScheduledRemindersForEvent(): void { 'is_relative' => true, 'notification_date' => 123456, 'is_repeat_based' => false, - ]); - $this->assertEquals($rows[1], [ + ], $rows[0]); + $this->assertEquals([ 'calendar_id' => 1, 'object_id' => 1, 'uid' => 'asd', @@ -208,14 +228,17 @@ public function testGetAllScheduledRemindersForEvent(): void { 'is_relative' => true, 'notification_date' => 123456, 'is_repeat_based' => false, - ]); + ], $rows[1]); } + /** + * @throws Exception + */ public function testInsertReminder(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(4, $rows); @@ -226,14 +249,14 @@ public function testInsertReminder(): void { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(5, $rows); unset($rows[4]['id']); - $this->assertEquals($rows[4], [ + $this->assertEquals([ 'calendar_id' => '42', 'object_id' => '1337', 'is_recurring' => '1', @@ -246,19 +269,22 @@ public function testInsertReminder(): void { 'is_relative' => '0', 'notification_date' => '12345670', 'is_repeat_based' => '0', - ]); + ], $rows[4]); } + /** + * @throws Exception + */ public function testUpdateReminder() { $query = self::$realDatabase->getQueryBuilder(); $rows = $query->select('*') ->from('calendar_reminders') - ->execute() + ->executeQuery() ->fetchAll(); $this->assertCount(4, $rows); - $this->assertEquals($rows[3]['notification_date'], 123600); + $this->assertEquals(123600, $rows[3]['notification_date']); $reminderId = (int) $rows[3]['id']; $newNotificationDate = 123700; @@ -272,10 +298,13 @@ public function testUpdateReminder() { ->execute() ->fetch(); - $this->assertEquals((int) $row['notification_date'], 123700); + $this->assertEquals(123700, (int) $row['notification_date']); } + /** + * @throws Exception + */ private function createRemindersTestSet(): void { $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendars') @@ -284,7 +313,7 @@ private function createRemindersTestSet(): void { 'principaluri' => $query->createNamedParameter('principals/users/user001'), 'displayname' => $query->createNamedParameter('Displayname 123'), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendars') @@ -293,7 +322,7 @@ private function createRemindersTestSet(): void { 'principaluri' => $query->createNamedParameter('principals/users/user002'), 'displayname' => $query->createNamedParameter('Displayname 99'), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendarobjects') @@ -303,7 +332,7 @@ private function createRemindersTestSet(): void { 'calendarid' => $query->createNamedParameter(1), 'size' => $query->createNamedParameter(42), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendarobjects') @@ -313,7 +342,7 @@ private function createRemindersTestSet(): void { 'calendarid' => $query->createNamedParameter(1), 'size' => $query->createNamedParameter(42), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendarobjects') @@ -323,7 +352,7 @@ private function createRemindersTestSet(): void { 'calendarid' => $query->createNamedParameter(99), 'size' => $query->createNamedParameter(42), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendar_reminders') @@ -341,7 +370,7 @@ private function createRemindersTestSet(): void { 'notification_date' => $query->createNamedParameter(123456), 'is_repeat_based' => $query->createNamedParameter(0), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendar_reminders') @@ -359,7 +388,7 @@ private function createRemindersTestSet(): void { 'notification_date' => $query->createNamedParameter(123456), 'is_repeat_based' => $query->createNamedParameter(0), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendar_reminders') @@ -377,7 +406,7 @@ private function createRemindersTestSet(): void { 'notification_date' => $query->createNamedParameter(123499), 'is_repeat_based' => $query->createNamedParameter(0), ]) - ->execute(); + ->executeStatement(); $query = self::$realDatabase->getQueryBuilder(); $query->insert('calendar_reminders') @@ -395,6 +424,6 @@ private function createRemindersTestSet(): void { 'notification_date' => $query->createNamedParameter(123600), 'is_repeat_based' => $query->createNamedParameter(0), ]) - ->execute(); + ->executeStatement(); } } diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php index ae272e6b1a9e9..3d0b9bc7f68f4 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/AbstractNotificationProviderTest.php @@ -33,28 +33,29 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VCalendar; use Test\TestCase; abstract class AbstractNotificationProviderTest extends TestCase { - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var L10NFactory|MockObject */ protected $l10nFactory; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N|MockObject */ protected $l10n; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ protected $urlGenerator; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig|MockObject */ protected $config; - /** @var AbstractProvider|\PHPUnit\Framework\MockObject\MockObject */ + /** @var AbstractProvider|MockObject */ protected $provider; /** @@ -68,7 +69,7 @@ abstract class AbstractNotificationProviderTest extends TestCase { protected $calendarDisplayName; /** - * @var IUser|\PHPUnit\Framework\MockObject\MockObject + * @var IUser|MockObject */ protected $user; diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php index ededcf819bb0c..72faf92d967ae 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/EmailProviderTest.php @@ -31,6 +31,7 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider; +use DateTime; use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; use OCP\IConfig; use OCP\IL10N; @@ -40,6 +41,7 @@ use OCP\Mail\IEMailTemplate; use OCP\Mail\IMailer; use OCP\Mail\IMessage; +use OCP\Util; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VCalendar; @@ -127,62 +129,34 @@ public function testSendWithoutAttendees():void { $message21 = $this->getMessageMock('uid2@example.com', $template2); $message22 = $this->getMessageMock('uid3@example.com', $template2); - $this->mailer->expects($this->at(0)) + $this->mailer->expects($this->exactly(2)) ->method('createEMailTemplate') ->with('dav.calendarReminder') - ->willReturn($template1); + ->willReturnOnConsecutiveCalls($template1, $template2); - $this->mailer->expects($this->at(1)) + $this->mailer->expects($this->exactly(4)) ->method('validateMailAddress') - ->with('uid1@example.com') - ->willReturn(true); - - $this->mailer->expects($this->at(2)) - ->method('createMessage') - ->with() - ->willReturn($message11); - $this->mailer->expects($this->at(3)) - ->method('send') - ->with($message11) - ->willReturn([]); - - $this->mailer->expects($this->at(4)) - ->method('createEMailTemplate') - ->with('dav.calendarReminder') - ->willReturn($template2); - - $this->mailer->expects($this->at(5)) - ->method('validateMailAddress') - ->with('uid2@example.com') - ->willReturn(true); - - $this->mailer->expects($this->at(6)) - ->method('createMessage') - ->with() - ->willReturn($message21); - $this->mailer->expects($this->at(7)) - ->method('send') - ->with($message21) - ->willReturn([]); - $this->mailer->expects($this->at(8)) - ->method('validateMailAddress') - ->with('uid3@example.com') - ->willReturn(true); - - $this->mailer->expects($this->at(9)) + ->withConsecutive( + ['uid1@example.com'], + ['uid2@example.com'], + ['uid3@example.com'], + ['invalid'] + ) + ->willReturnOnConsecutiveCalls(true, true, true, false); + + $this->mailer->expects($this->exactly(3)) ->method('createMessage') ->with() - ->willReturn($message22); - $this->mailer->expects($this->at(10)) + ->willReturnOnConsecutiveCalls($message11, $message21, $message22); + $this->mailer->expects($this->exactly(3)) ->method('send') - ->with($message22) + ->withConsecutive( + [$message11], + [$message21], + [$message22] + ) ->willReturn([]); - $this->mailer->expects($this->at(11)) - ->method('validateMailAddress') - ->with('invalid') - ->willReturn(false); - $this->setupURLGeneratorMock(2); $vcalendar = $this->getNoAttendeeVCalendar(); @@ -240,97 +214,47 @@ public function testSendWithAttendees(): void { $message22 = $this->getMessageMock('foo4@example.org', $template2); $message23 = $this->getMessageMock('uid1@example.com', $template2); - $this->mailer->expects($this->at(0)) + $this->mailer->expects($this->exactly(2)) ->method('createEMailTemplate') ->with('dav.calendarReminder') - ->willReturn($template1); - - $this->mailer->expects($this->at(1)) - ->method('validateMailAddress') - ->with('foo1@example.org') - ->willReturn(true); - - $this->mailer->expects($this->at(2)) - ->method('createMessage') - ->with() - ->willReturn($message11); - $this->mailer->expects($this->at(3)) - ->method('send') - ->with($message11) - ->willReturn([]); - $this->mailer->expects($this->at(4)) - ->method('validateMailAddress') - ->with('uid2@example.com') - ->willReturn(true); - $this->mailer->expects($this->at(5)) - ->method('createMessage') - ->with() - ->willReturn($message12); - $this->mailer->expects($this->at(6)) - ->method('send') - ->with($message12) - ->willReturn([]); + ->willReturnOnConsecutiveCalls($template1, $template2); - $this->mailer->expects($this->at(7)) + $this->mailer->expects($this->exactly(7)) ->method('validateMailAddress') - ->with('uid3@example.com') - ->willReturn(true); - - $this->mailer->expects($this->at(8)) + ->withConsecutive( + ['foo1@example.org'], + ['uid2@example.com'], + ['uid3@example.com'], + ['invalid'], + ['foo3@example.org'], + ['foo4@example.org'], + ['uid1@example.com'] + ) + ->willReturnOnConsecutiveCalls(true, true, true, false, true, true, true); + + $this->mailer->expects($this->exactly(6)) ->method('createMessage') ->with() - ->willReturn($message13); - $this->mailer->expects($this->at(9)) - ->method('send') - ->with($message13) - ->willReturn([]); - - $this->mailer->expects($this->at(10)) - ->method('validateMailAddress') - ->with('invalid') - ->willReturn(false); + ->willReturnOnConsecutiveCalls( + $message11, + $message12, + $message13, + $message21, + $message22, + $message23 + ); - $this->mailer->expects($this->at(11)) - ->method('createEMailTemplate') - ->with('dav.calendarReminder') - ->willReturn($template2); - - $this->mailer->expects($this->at(12)) - ->method('validateMailAddress') - ->with('foo3@example.org') - ->willReturn(true); - $this->mailer->expects($this->at(13)) - ->method('createMessage') - ->with() - ->willReturn($message21); - $this->mailer->expects($this->at(14)) - ->method('send') - ->with($message21) - ->willReturn([]); - $this->mailer->expects($this->at(15)) - ->method('validateMailAddress') - ->with('foo4@example.org') - ->willReturn(true); - $this->mailer->expects($this->at(16)) - ->method('createMessage') - ->with() - ->willReturn($message22); - $this->mailer->expects($this->at(17)) - ->method('send') - ->with($message22) - ->willReturn([]); - $this->mailer->expects($this->at(18)) - ->method('validateMailAddress') - ->with('uid1@example.com') - ->willReturn(true); - $this->mailer->expects($this->at(19)) - ->method('createMessage') - ->with() - ->willReturn($message23); - $this->mailer->expects($this->at(20)) + $this->mailer->expects($this->exactly(6)) ->method('send') - ->with($message23) + ->withConsecutive( + [$message11], + [$message12], + [$message13], + [$message21], + [$message22], + [$message23] + ) ->willReturn([]); $this->setupURLGeneratorMock(2); @@ -345,42 +269,27 @@ public function testSendWithAttendees(): void { private function getTemplateMock():IEMailTemplate { $template = $this->createMock(IEMailTemplate::class); - $template->expects($this->at(0)) + $template->expects($this->once()) ->method('addHeader') ->with() ->willReturn($template); - $template->expects($this->at(1)) + $template->expects($this->once()) ->method('setSubject') ->with() ->willReturn($template); - $template->expects($this->at(2)) + $template->expects($this->once()) ->method('addHeading') ->with() ->willReturn($template); - $template->expects($this->at(3)) - ->method('addBodyListItem') - ->with() - ->willReturn($template); - - $template->expects($this->at(4)) - ->method('addBodyListItem') - ->with() - ->willReturn($template); - - $template->expects($this->at(5)) + $template->expects($this->exactly(4)) ->method('addBodyListItem') ->with() ->willReturn($template); - $template->expects($this->at(6)) - ->method('addBodyListItem') - ->with() - ->willReturn($template); - - $template->expects($this->at(7)) + $template->expects($this->once()) ->method('addFooter') ->with() ->willReturn($template); @@ -391,31 +300,29 @@ private function getTemplateMock():IEMailTemplate { /** * @param string $toMail * @param IEMailTemplate $templateMock - * @param array|null $replyTo * @return IMessage */ - private function getMessageMock(string $toMail, IEMailTemplate $templateMock, array $replyTo = null):IMessage { + private function getMessageMock(string $toMail, IEMailTemplate $templateMock):IMessage { $message = $this->createMock(IMessage::class); - $i = 0; - $message->expects($this->at($i++)) + $message->expects($this->once()) ->method('setFrom') - ->with([\OCP\Util::getDefaultEmailAddress('reminders-noreply')]) + ->with([Util::getDefaultEmailAddress('reminders-noreply')]) ->willReturn($message); - if ($replyTo) { - $message->expects($this->at($i++)) + if (null) { + $message->expects($this->once()) ->method('setReplyTo') - ->with($replyTo) + ->with(null) ->willReturn($message); } - $message->expects($this->at($i++)) + $message->expects($this->once()) ->method('setTo') ->with([$toMail]) ->willReturn($message); - $message->expects($this->at($i++)) + $message->expects($this->once()) ->method('useTemplate') ->with($templateMock) ->willReturn($message); @@ -427,7 +334,7 @@ private function getNoAttendeeVCalendar():VCalendar { $vcalendar = new VCalendar(); $vcalendar->add('VEVENT', [ 'SUMMARY' => 'Fellowship meeting', - 'DTSTART' => new \DateTime('2017-01-01 00:00:00+00:00'), // 1483228800, + 'DTSTART' => new DateTime('2017-01-01 00:00:00+00:00'), // 1483228800, 'UID' => 'uid1234', 'LOCATION' => 'Location 123', 'DESCRIPTION' => 'DESCRIPTION 456', @@ -440,7 +347,7 @@ private function getAttendeeVCalendar():VCalendar { $vcalendar = new VCalendar(); $vcalendar->add('VEVENT', [ 'SUMMARY' => 'Fellowship meeting', - 'DTSTART' => new \DateTime('2017-01-01 00:00:00+00:00'), // 1483228800, + 'DTSTART' => new DateTime('2017-01-01 00:00:00+00:00'), // 1483228800, 'UID' => 'uid1234', 'LOCATION' => 'Location 123', 'DESCRIPTION' => 'DESCRIPTION 456', @@ -487,55 +394,42 @@ private function getAttendeeVCalendar():VCalendar { } private function setupURLGeneratorMock(int $times = 1):void { - for ($i = 0; $i < $times; $i++) { - $this->urlGenerator - ->expects($this->at(8 * $i)) - ->method('imagePath') - ->with('core', 'actions/info.png') - ->willReturn('imagePath1'); - - $this->urlGenerator - ->expects($this->at(8 * $i + 1)) - ->method('getAbsoluteURL') - ->with('imagePath1') - ->willReturn('AbsURL1'); - - $this->urlGenerator - ->expects($this->at(8 * $i + 2)) - ->method('imagePath') - ->with('core', 'places/calendar.png') - ->willReturn('imagePath2'); + $imagePathArgs = []; + $imagePathReturns = []; - $this->urlGenerator - ->expects($this->at(8 * $i + 3)) - ->method('getAbsoluteURL') - ->with('imagePath2') - ->willReturn('AbsURL2'); - - $this->urlGenerator - ->expects($this->at(8 * $i + 4)) - ->method('imagePath') - ->with('core', 'actions/address.png') - ->willReturn('imagePath3'); + $absoluteURLArgs = []; + $absoluteURLReturns = []; - $this->urlGenerator - ->expects($this->at(8 * $i + 5)) - ->method('getAbsoluteURL') - ->with('imagePath3') - ->willReturn('AbsURL3'); + for ($i = 0; $i < $times; $i++) { + $imagePathArgs = array_merge($imagePathArgs, [ + ['core', 'actions/info.png'], + ['core', 'places/calendar.png'], + ['core', 'actions/address.png'], + ['core', 'actions/more.png'] + ]); + $imagePathReturns = array_merge($imagePathReturns, ['imagePath1', 'imagePath2', 'imagePath3', 'imagePath4']); - $this->urlGenerator - ->expects($this->at(8 * $i + 6)) - ->method('imagePath') - ->with('core', 'actions/more.png') - ->willReturn('imagePath4'); + $absoluteURLArgs = array_merge($absoluteURLArgs, [ + ['imagePath1'], + ['imagePath2'], + ['imagePath3'], + ['imagePath4'] + ]); - $this->urlGenerator - ->expects($this->at(8 * $i + 7)) - ->method('getAbsoluteURL') - ->with('imagePath4') - ->willReturn('AbsURL4'); + $absoluteURLReturns = array_merge($absoluteURLReturns, ['AbsURL1', 'AbsURL2', 'AbsURL3', 'AbsURL4']); } + + $this->urlGenerator + ->expects($this->exactly(4 * $times)) + ->method('imagePath') + ->withConsecutive(...$imagePathArgs) + ->willReturnOnConsecutiveCalls(...$imagePathReturns); + + $this->urlGenerator + ->expects($this->exactly(4 * $times)) + ->method('getAbsoluteURL') + ->withConsecutive(...$absoluteURLArgs) + ->willReturnOnConsecutiveCalls(...$absoluteURLReturns); } private function getUsers(): array { diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php index b1f76fe9448bc..8537f784f1d72 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProvider/PushProviderTest.php @@ -29,6 +29,7 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Reminder\NotificationProvider; +use DateTime; use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; @@ -38,29 +39,30 @@ use OCP\L10N\IFactory as L10NFactory; use OCP\Notification\IManager; use OCP\Notification\INotification; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; class PushProviderTest extends AbstractNotificationProviderTest { - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var L10NFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var L10NFactory|MockObject */ protected $l10nFactory; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N|MockObject */ protected $l10n; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ protected $urlGenerator; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig|MockObject */ protected $config; - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IManager|MockObject */ private $manager; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; protected function setUp(): void { @@ -128,7 +130,7 @@ public function testSend(): void { $users = [$user1, $user2, $user3]; - $dateTime = new \DateTime('@946684800'); + $dateTime = new DateTime('@946684800'); $this->timeFactory->method('getDateTime') ->with() ->willReturn($dateTime); @@ -137,37 +139,26 @@ public function testSend(): void { $notification2 = $this->createNotificationMock('uid2', $dateTime); $notification3 = $this->createNotificationMock('uid3', $dateTime); - $this->manager->expects($this->at(0)) + $this->manager->expects($this->exactly(3)) ->method('createNotification') ->with() - ->willReturn($notification1); - $this->manager->expects($this->at(2)) - ->method('createNotification') - ->with() - ->willReturn($notification2); - $this->manager->expects($this->at(4)) - ->method('createNotification') - ->with() - ->willReturn($notification3); - - $this->manager->expects($this->at(1)) - ->method('notify') - ->with($notification1); - $this->manager->expects($this->at(3)) - ->method('notify') - ->with($notification2); - $this->manager->expects($this->at(5)) + ->willReturnOnConsecutiveCalls( + $notification1, + $notification2, + $notification3 + ); + $this->manager->expects($this->exactly(3)) ->method('notify') - ->with($notification3); + ->withConsecutive( + [$notification1], + [$notification2], + [$notification3] + ); $this->provider->send($this->vcalendar->VEVENT, $this->calendarDisplayName, $users); } - /** - * @param string $uid - * @param \DateTime $dt - */ - private function createNotificationMock(string $uid, \DateTime $dt):INotification { + private function createNotificationMock(string $uid, DateTime $dt):INotification { $notification = $this->createMock(INotification::class); $notification ->expects($this->once()) diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProviderManagerTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProviderManagerTest.php index be19f5de8a096..2c1d199615416 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotificationProviderManagerTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotificationProviderManagerTest.php @@ -29,21 +29,26 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Reminder; +use InvalidArgumentException; use OCA\DAV\CalDAV\Reminder\NotificationProvider\EmailProvider; use OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException; use OCA\DAV\CalDAV\Reminder\NotificationProvider\PushProvider; use OCA\DAV\CalDAV\Reminder\NotificationProviderManager; use OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException; use OCA\DAV\Capabilities; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Test\TestCase; class NotificationProviderManagerTest extends TestCase { - /** @var NotificationProviderManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var NotificationProviderManager|MockObject */ private $providerManager; /** - * @throws \OCP\AppFramework\QueryException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ protected function setUp(): void { parent::setUp(); @@ -57,7 +62,7 @@ protected function setUp(): void { * @throws NotificationTypeDoesNotExistException */ public function testGetProviderForUnknownType(): void { - $this->expectException(\OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException::class); + $this->expectException(NotificationTypeDoesNotExistException::class); $this->expectExceptionMessage('Type NOT EXISTENT is not an accepted type of notification'); $this->providerManager->getProvider('NOT EXISTENT'); @@ -68,17 +73,27 @@ public function testGetProviderForUnknownType(): void { * @throws ProviderNotAvailableException */ public function testGetProviderForUnRegisteredType(): void { - $this->expectException(\OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException::class); + $this->expectException(ProviderNotAvailableException::class); $this->expectExceptionMessage('No notification provider for type AUDIO available'); $this->providerManager->getProvider('AUDIO'); } + /** + * @throws ProviderNotAvailableException + * @throws NotificationTypeDoesNotExistException + */ public function testGetProvider(): void { $provider = $this->providerManager->getProvider('EMAIL'); $this->assertInstanceOf(EmailProvider::class, $provider); } + /** + * @throws NotFoundExceptionInterface + * @throws ContainerExceptionInterface + * @throws ProviderNotAvailableException + * @throws NotificationTypeDoesNotExistException + */ public function testRegisterProvider(): void { $this->providerManager->registerProvider(PushProvider::class); $provider = $this->providerManager->getProvider('DISPLAY'); @@ -86,10 +101,11 @@ public function testRegisterProvider(): void { } /** - * @throws \OCP\AppFramework\QueryException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function testRegisterBadProvider(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Invalid notification provider registered'); $this->providerManager->registerProvider(Capabilities::class); diff --git a/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php b/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php index 1c823ac68303d..5aeb943035690 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/NotifierTest.php @@ -29,6 +29,10 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Reminder; +use DateTime; +use DateTimeInterface; +use Exception; +use InvalidArgumentException; use OCA\DAV\AppInfo\Application; use OCA\DAV\CalDAV\Reminder\Notifier; use OCP\AppFramework\Utility\ITimeFactory; @@ -73,7 +77,7 @@ protected function setUp(): void { ->method('l') ->willReturnCallback(function ($string, $args) { /** \DateTime $args */ - return $args->format(\DateTime::ATOM); + return $args->format(DateTimeInterface::ATOM); }); $this->l10n->expects($this->any()) ->method('n') @@ -90,7 +94,7 @@ protected function setUp(): void { $this->timeFactory = $this->createMock(ITimeFactory::class); $this->timeFactory ->method('getDateTime') - ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2005-08-15T14:00:00+02:00')); + ->willReturn(DateTime::createFromFormat(DateTimeInterface::ATOM, '2005-08-15T14:00:00+02:00')); $this->notifier = new Notifier( $this->factory, @@ -100,16 +104,19 @@ protected function setUp(): void { } public function testGetId():void { - $this->assertEquals($this->notifier->getID(), 'dav'); + $this->assertEquals('dav', $this->notifier->getID()); } public function testGetName():void { - $this->assertEquals($this->notifier->getName(), 'Calendar'); + $this->assertEquals('Calendar', $this->notifier->getName()); } + /** + * @throws Exception + */ public function testPrepareWrongApp(): void { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Notification not from this app'); /** @var INotification|MockObject $notification */ @@ -125,8 +132,11 @@ public function testPrepareWrongApp(): void { } + /** + * @throws Exception + */ public function testPrepareWrongSubject() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('Unknown subject'); /** @var INotification|MockObject $notification */ @@ -199,7 +209,7 @@ public function dataPrepare(): array { * @param string $subject * @param array $messageParams * @param string $message - * @throws \Exception + * @throws Exception */ public function testPrepare(string $subjectType, array $subjectParams, string $subject, array $messageParams, string $message): void { /** @var INotification|MockObject $notification */ @@ -246,6 +256,9 @@ public function testPrepare(string $subjectType, array $subjectParams, string $s $this->assertEquals($notification, $return); } + /** + * @throws Exception + */ public function testPassedEvent(): void { /** @var INotification|MockObject $notification */ $notification = $this->createMock(INotification::class); diff --git a/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php b/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php index 39fbf1c79ffc2..449d367de8402 100644 --- a/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php +++ b/apps/dav/tests/unit/CalDAV/Reminder/ReminderServiceTest.php @@ -28,40 +28,42 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Reminder; +use DateTime; +use DateTimeInterface; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\CalDAV\Reminder\Backend; use OCA\DAV\CalDAV\Reminder\INotificationProvider; +use OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException; use OCA\DAV\CalDAV\Reminder\NotificationProviderManager; +use OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException; use OCA\DAV\CalDAV\Reminder\ReminderService; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserManager; -use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\VObject\InvalidDataException; use Test\TestCase; class ReminderServiceTest extends TestCase { - /** @var Backend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Backend|MockObject */ private $backend; - /** @var NotificationProviderManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var NotificationProviderManager|MockObject */ private $notificationProviderManager; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ private $userManager; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject*/ + /** @var IGroupManager|MockObject*/ private $groupManager; - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - private $userSession; - - /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend|MockObject */ private $caldavBackend; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ @@ -211,6 +213,9 @@ protected function setUp(): void { $this->config); } + /** + * @throws InvalidDataException + */ public function testOnCalendarObjectDelete():void { $this->backend->expects($this->once()) ->method('cleanRemindersForEvent') @@ -224,6 +229,9 @@ public function testOnCalendarObjectDelete():void { $this->reminderService->onCalendarObjectDelete($objectData); } + /** + * @throws InvalidDataException + */ public function testOnCalendarObjectCreateSingleEntry():void { $objectData = [ 'calendardata' => self::CALENDAR_DATA, @@ -243,11 +251,14 @@ public function testOnCalendarObjectCreateSingleEntry():void { $this->timeFactory->expects($this->once()) ->method('getDateTime') ->with() - ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-08T00:00:00+00:00')); + ->willReturn(DateTime::createFromFormat(DateTimeInterface::ATOM, '2016-06-08T00:00:00+00:00')); $this->reminderService->onCalendarObjectCreate($objectData); } + /** + * @throws InvalidDataException + */ public function testOnCalendarObjectCreateSingleEntryWithRepeat(): void { $objectData = [ 'calendardata' => self::CALENDAR_DATA_REPEAT, @@ -270,11 +281,14 @@ public function testOnCalendarObjectCreateSingleEntryWithRepeat(): void { $this->timeFactory->expects($this->once()) ->method('getDateTime') ->with() - ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-08T00:00:00+00:00')); + ->willReturn(DateTime::createFromFormat(DateTimeInterface::ATOM, '2016-06-08T00:00:00+00:00')); $this->reminderService->onCalendarObjectCreate($objectData); } + /** + * @throws InvalidDataException + */ public function testOnCalendarObjectCreateRecurringEntry(): void { $objectData = [ 'calendardata' => self::CALENDAR_DATA_RECURRING, @@ -294,11 +308,14 @@ public function testOnCalendarObjectCreateRecurringEntry(): void { $this->timeFactory->expects($this->once()) ->method('getDateTime') ->with() - ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-29T00:00:00+00:00')); + ->willReturn(DateTime::createFromFormat(DateTimeInterface::ATOM, '2016-06-29T00:00:00+00:00')); $this->reminderService->onCalendarObjectCreate($objectData); } + /** + * @throws InvalidDataException + */ public function testOnCalendarObjectCreateEmpty():void { $objectData = [ 'calendardata' => self::CALENDAR_DATA_NO_ALARM, @@ -313,6 +330,9 @@ public function testOnCalendarObjectCreateEmpty():void { $this->reminderService->onCalendarObjectCreate($objectData); } + /** + * @throws InvalidDataException + */ public function testOnCalendarObjectCreateRecurringEntryWithRepeat():void { $objectData = [ 'calendardata' => self::CALENDAR_DATA_RECURRING_REPEAT, @@ -336,13 +356,17 @@ public function testOnCalendarObjectCreateRecurringEntryWithRepeat():void { $this->timeFactory->expects($this->once()) ->method('getDateTime') ->with() - ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-29T00:00:00+00:00')); + ->willReturn(DateTime::createFromFormat(DateTimeInterface::ATOM, '2016-06-29T00:00:00+00:00')); $this->reminderService->onCalendarObjectCreate($objectData); } + /** + * @throws ProviderNotAvailableException + * @throws NotificationTypeDoesNotExistException + */ public function testProcessReminders():void { - $this->backend->expects($this->at(0)) + $this->backend->expects($this->once()) ->method('getRemindersToProcess') ->with() ->willReturn([ @@ -438,60 +462,34 @@ public function testProcessReminders():void { ] ]); - $this->notificationProviderManager->expects($this->at(0)) + $this->notificationProviderManager->expects($this->exactly(5)) ->method('hasProvider') - ->with('EMAIL') + ->withConsecutive( + ['EMAIL'], + ['EMAIL'], + ['DISPLAY'], + ['EMAIL'], + ['EMAIL'], + ) ->willReturn(true); $provider1 = $this->createMock(INotificationProvider::class); - $this->notificationProviderManager->expects($this->at(1)) - ->method('getProvider') - ->with('EMAIL') - ->willReturn($provider1); - - $this->notificationProviderManager->expects($this->at(2)) - ->method('hasProvider') - ->with('EMAIL') - ->willReturn(true); - $provider2 = $this->createMock(INotificationProvider::class); - $this->notificationProviderManager->expects($this->at(3)) - ->method('getProvider') - ->with('EMAIL') - ->willReturn($provider2); - - $this->notificationProviderManager->expects($this->at(4)) - ->method('hasProvider') - ->with('DISPLAY') - ->willReturn(true); - $provider3 = $this->createMock(INotificationProvider::class); - $this->notificationProviderManager->expects($this->at(5)) - ->method('getProvider') - ->with('DISPLAY') - ->willReturn($provider3); - - $this->notificationProviderManager->expects($this->at(6)) - ->method('hasProvider') - ->with('EMAIL') - ->willReturn(true); - $provider4 = $this->createMock(INotificationProvider::class); - $this->notificationProviderManager->expects($this->at(7)) - ->method('getProvider') - ->with('EMAIL') - ->willReturn($provider4); - - $this->notificationProviderManager->expects($this->at(8)) - ->method('hasProvider') - ->with('EMAIL') - ->willReturn(true); - $provider5 = $this->createMock(INotificationProvider::class); - $this->notificationProviderManager->expects($this->at(9)) + + $this->notificationProviderManager->expects($this->exactly(5)) ->method('getProvider') - ->with('EMAIL') - ->willReturn($provider5); + ->withConsecutive( + ['EMAIL'], + ['EMAIL'], + ['DISPLAY'], + ['EMAIL'], + ['EMAIL'], + ) + ->willReturnOnConsecutiveCalls($provider1, $provider2, $provider3, $provider4, $provider5); + $user = $this->createMock(IUser::class); $this->userManager->expects($this->exactly(5)) @@ -502,87 +500,62 @@ public function testProcessReminders():void { $provider1->expects($this->once()) ->method('send') ->with($this->callback(function ($vevent) { - if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-09T00:00:00+00:00') { + if ($vevent->DTSTART->getDateTime()->format(DateTimeInterface::ATOM) !== '2016-06-09T00:00:00+00:00') { return false; } return true; - }, 'Displayname 123', $user)); + }), 'Displayname 123', [$user]); $provider2->expects($this->once()) ->method('send') ->with($this->callback(function ($vevent) { - if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-09T00:00:00+00:00') { + if ($vevent->DTSTART->getDateTime()->format(DateTimeInterface::ATOM) !== '2016-06-09T00:00:00+00:00') { return false; } return true; - }, 'Displayname 123', $user)); + }), 'Displayname 123', [$user]); $provider3->expects($this->once()) ->method('send') ->with($this->callback(function ($vevent) { - if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-09T00:00:00+00:00') { + if ($vevent->DTSTART->getDateTime()->format(DateTimeInterface::ATOM) !== '2016-06-09T00:00:00+00:00') { return false; } return true; - }, 'Displayname 123', $user)); + }), 'Displayname 123', [$user]); $provider4->expects($this->once()) ->method('send') ->with($this->callback(function ($vevent) { - if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-06-30T00:00:00+00:00') { + if ($vevent->DTSTART->getDateTime()->format(DateTimeInterface::ATOM) !== '2016-06-30T00:00:00+00:00') { return false; } return true; - }, 'Displayname 123', $user)); + }), 'Displayname 123', [$user]); $provider5->expects($this->once()) ->method('send') ->with($this->callback(function ($vevent) { - if ($vevent->DTSTART->getDateTime()->format(\DateTime::ATOM) !== '2016-07-07T00:00:00+00:00') { + if ($vevent->DTSTART->getDateTime()->format(DateTimeInterface::ATOM) !== '2016-07-07T00:00:00+00:00') { return false; } return true; - }, 'Displayname 123', $user)); + }), 'Displayname 123', [$user]); - $this->backend->expects($this->at(1)) - ->method('removeReminder') - ->with(1); - $this->backend->expects($this->at(2)) - ->method('removeReminder') - ->with(2); - $this->backend->expects($this->at(3)) - ->method('removeReminder') - ->with(3); - $this->backend->expects($this->at(4)) + $this->backend->expects($this->exactly(5)) ->method('removeReminder') - ->with(4); - $this->backend->expects($this->at(5)) - ->method('insertReminder') - ->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848700, false) - ->willReturn(99); + ->withConsecutive([1], [2], [3], [4], [5]); - $this->backend->expects($this->at(6)) - ->method('insertReminder') - ->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848820, true) - ->willReturn(99); - $this->backend->expects($this->at(7)) - ->method('insertReminder') - ->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848940, true) - ->willReturn(99); - $this->backend->expects($this->at(8)) - ->method('insertReminder') - ->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467849060, true) - ->willReturn(99); - $this->backend->expects($this->at(9)) - ->method('insertReminder') - ->with(1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467849180, true) - ->willReturn(99); - $this->backend->expects($this->at(10)) - ->method('removeReminder') - ->with(5); - $this->backend->expects($this->at(11)) + $this->backend->expects($this->exactly(6)) ->method('insertReminder') - ->with(1337, 42, 'wej2z68l9h', true, 1468454400, false, 'fbdb2726bc0f7dfacac1d881c1453e20', '8996992118817f9f311ac5cc56d1cc97', 'EMAIL', true, 1467763200, false) + ->withConsecutive( + [1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848700, false], + [1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848820, true], + [1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467848940, true], + [1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467849060, true], + [1337, 42, 'wej2z68l9h', true, 1467849600, false, 'fbdb2726bc0f7dfacac1d881c1453e20', 'ecacbf07d413c3c78d1ac7ad8c469602', 'EMAIL', true, 1467849180, true], + [1337, 42, 'wej2z68l9h', true, 1468454400, false, 'fbdb2726bc0f7dfacac1d881c1453e20', '8996992118817f9f311ac5cc56d1cc97', 'EMAIL', true, 1467763200, false] + ) ->willReturn(99); $this->timeFactory->method('getDateTime') - ->willReturn(\DateTime::createFromFormat(\DateTime::ATOM, '2016-06-08T00:00:00+00:00')); + ->willReturn(DateTime::createFromFormat(DateTimeInterface::ATOM, '2016-06-08T00:00:00+00:00')); $this->reminderService->processReminders(); } diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php index 0fffbc2cd1070..bb311fb3b042c 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php @@ -27,28 +27,32 @@ use OCA\DAV\CalDAV\Proxy\Proxy; use OCA\DAV\CalDAV\Proxy\ProxyMapper; +use OCA\DAV\CalDAV\ResourceBooking\ResourcePrincipalBackend; +use OCA\DAV\CalDAV\ResourceBooking\RoomPrincipalBackend; +use OCP\DB\Exception; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Sabre\DAV\PropPatch; use Test\TestCase; abstract class AbstractPrincipalBackendTest extends TestCase { - /** @var \OCA\DAV\CalDAV\ResourceBooking\ResourcePrincipalBackend|\OCA\DAV\CalDAV\ResourceBooking\RoomPrincipalBackend */ + /** @var ResourcePrincipalBackend|RoomPrincipalBackend */ protected $principalBackend; - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserSession|MockObject */ protected $userSession; - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IGroupManager|MockObject */ protected $groupManager; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var ProxyMapper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ProxyMapper|MockObject */ protected $proxyMapper; /** @var string */ @@ -75,13 +79,16 @@ protected function setUp(): void { $this->proxyMapper = $this->createMock(ProxyMapper::class); } + /** + * @throws Exception + */ protected function tearDown(): void { $query = self::$realDatabase->getQueryBuilder(); - $query->delete('calendar_resources')->execute(); - $query->delete('calendar_resources_md')->execute(); - $query->delete('calendar_rooms')->execute(); - $query->delete('calendar_rooms_md')->execute(); + $query->delete('calendar_resources')->executeStatement(); + $query->delete('calendar_resources_md')->executeStatement(); + $query->delete('calendar_rooms')->executeStatement(); + $query->delete('calendar_rooms_md')->executeStatement(); } public function testGetPrincipalsByPrefix() { @@ -159,11 +166,17 @@ public function testGetPrincipalByPathWrongPrefix() { $this->assertEquals(null, $actual); } + /** + * @throws \Sabre\DAV\Exception + */ public function testGetGroupMemberSet() { $actual = $this->principalBackend->getGroupMemberSet($this->principalPrefix . '/backend1-res1'); $this->assertEquals([], $actual); } + /** + * @throws \Sabre\DAV\Exception + */ public function testGetGroupMemberSetProxyRead() { $proxy1 = new Proxy(); $proxy1->setProxyId('proxyId1'); @@ -186,6 +199,9 @@ public function testGetGroupMemberSetProxyRead() { $this->assertEquals(['proxyId1'], $actual); } + /** + * @throws \Sabre\DAV\Exception + */ public function testGetGroupMemberSetProxyWrite() { $proxy1 = new Proxy(); $proxy1->setProxyId('proxyId1'); @@ -208,6 +224,9 @@ public function testGetGroupMemberSetProxyWrite() { $this->assertEquals(['proxyId2', 'proxyId3'], $actual); } + /** + * @throws \Sabre\DAV\Exception + */ public function testGetGroupMembership() { $proxy1 = new Proxy(); $proxy1->setOwnerId('proxyId1'); @@ -227,48 +246,40 @@ public function testGetGroupMembership() { $this->assertEquals(['proxyId1/calendar-proxy-read', 'proxyId2/calendar-proxy-write'], $actual); } + /** + * @throws \Sabre\DAV\Exception + * @throws Exception + */ public function testSetGroupMemberSet() { - $this->proxyMapper->expects($this->at(0)) + $this->proxyMapper->expects($this->once()) ->method('getProxiesOf') ->with($this->principalPrefix . '/backend1-res1') ->willReturn([]); - $this->proxyMapper->expects($this->at(1)) - ->method('insert') - ->with($this->callback(function ($proxy) { - /** @var Proxy $proxy */ - if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') { - return false; - } - if ($proxy->getProxyId() !== $this->principalPrefix . '/backend1-res2') { - return false; - } - if ($proxy->getPermissions() !== 3) { - return false; - } - - return true; - })); - $this->proxyMapper->expects($this->at(2)) + $this->proxyMapper->expects($this->exactly(2)) ->method('insert') - ->with($this->callback(function ($proxy) { - /** @var Proxy $proxy */ - if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') { - return false; - } - if ($proxy->getProxyId() !== $this->principalPrefix . '/backend2-res3') { - return false; - } - if ($proxy->getPermissions() !== 3) { - return false; - } - - return true; - })); + ->withConsecutive( + [$this->callback(function ($proxy) { return $this->callbackForTestSetGroupMemberSet($proxy, '/backend1-res2'); })], + [$this->callback(function ($proxy) { return $this->callbackForTestSetGroupMemberSet($proxy, '/backend2-res3'); })] + ); $this->principalBackend->setGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-write', [$this->principalPrefix . '/backend1-res2', $this->principalPrefix . '/backend2-res3']); } + private function callbackForTestSetGroupMemberSet (Proxy $proxy, string $proxyId): bool { + if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') { + return false; + } + if ($proxy->getProxyId() !== $this->principalPrefix . $proxyId) { + return false; + } + if ($proxy->getPermissions() !== 3) { + return false; + } + + return true; + } + public function testUpdatePrincipal() { $propPatch = $this->createMock(PropPatch::class); $actual = $this->principalBackend->updatePrincipal($this->principalPrefix . '/foo-bar', $propPatch); @@ -279,7 +290,7 @@ public function testUpdatePrincipal() { /** * @dataProvider dataSearchPrincipals */ - public function testSearchPrincipals($expected, $test) { + public function testSearchPrincipals(array $expected, string $test) { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) ->method('getUser') @@ -300,7 +311,7 @@ public function testSearchPrincipals($expected, $test) { $actual); } - public function dataSearchPrincipals() { + public function dataSearchPrincipals(): array { // data providers are called before we subclass // this class, $this->principalPrefix is null // at that point, so we need this hack @@ -379,6 +390,9 @@ public function testSearchPrincipalsWrongPrincipalPrefix() { ]); } + /** + * @throws Exception + */ public function testFindByUriByEmail() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -394,6 +408,9 @@ public function testFindByUriByEmail() { $this->assertEquals($this->principalPrefix . '/backend1-res1', $actual); } + /** + * @throws Exception + */ public function testFindByUriByEmailForbiddenResource() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -409,6 +426,9 @@ public function testFindByUriByEmailForbiddenResource() { $this->assertEquals(null, $actual); } + /** + * @throws Exception + */ public function testFindByUriByEmailNotFound() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -424,6 +444,9 @@ public function testFindByUriByEmailNotFound() { $this->assertEquals(null, $actual); } + /** + * @throws Exception + */ public function testFindByUriByPrincipal() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -439,6 +462,9 @@ public function testFindByUriByPrincipal() { $this->assertEquals($this->principalPrefix . '/backend3-res6', $actual); } + /** + * @throws Exception + */ public function testFindByUriByPrincipalForbiddenResource() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -454,6 +480,9 @@ public function testFindByUriByPrincipalForbiddenResource() { $this->assertEquals(null, $actual); } + /** + * @throws Exception + */ public function testFindByUriByPrincipalNotFound() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -469,6 +498,9 @@ public function testFindByUriByPrincipalNotFound() { $this->assertEquals(null, $actual); } + /** + * @throws Exception + */ public function testFindByUriByUnknownUri() { $user = $this->createMock(IUser::class); $this->userSession->expects($this->once()) @@ -484,6 +516,9 @@ public function testFindByUriByUnknownUri() { $this->assertEquals(null, $actual); } + /** + * @throws Exception + */ protected function createTestDatasetInDb() { $query = self::$realDatabase->getQueryBuilder(); $query->insert($this->mainDbTable) @@ -494,7 +529,7 @@ protected function createTestDatasetInDb() { 'displayname' => $query->createNamedParameter('Beamer1'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $query->insert($this->mainDbTable) ->values([ @@ -504,7 +539,7 @@ protected function createTestDatasetInDb() { 'displayname' => $query->createNamedParameter('TV1'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $query->insert($this->mainDbTable) ->values([ @@ -514,7 +549,7 @@ protected function createTestDatasetInDb() { 'displayname' => $query->createNamedParameter('Beamer2'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $id3 = $query->getLastInsertId(); $query->insert($this->mainDbTable) @@ -525,7 +560,7 @@ protected function createTestDatasetInDb() { 'displayname' => $query->createNamedParameter('TV2'), 'group_restrictions' => $query->createNamedParameter('[]'), ]) - ->execute(); + ->executeStatement(); $id4 = $query->getLastInsertId(); $query->insert($this->mainDbTable) @@ -536,7 +571,7 @@ protected function createTestDatasetInDb() { 'displayname' => $query->createNamedParameter('Beamer3'), 'group_restrictions' => $query->createNamedParameter('["foo", "bar"]'), ]) - ->execute(); + ->executeStatement(); $query->insert($this->mainDbTable) ->values([ @@ -546,7 +581,7 @@ protected function createTestDatasetInDb() { 'displayname' => $query->createNamedParameter('Pointer'), 'group_restrictions' => $query->createNamedParameter('["group1", "bar"]'), ]) - ->execute(); + ->executeStatement(); $id6 = $query->getLastInsertId(); $query->insert($this->metadataDbTable) @@ -555,34 +590,34 @@ protected function createTestDatasetInDb() { 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}foo'), 'value' => $query->createNamedParameter('value1') ]) - ->execute(); + ->executeStatement(); $query->insert($this->metadataDbTable) ->values([ $this->foreignKey => $query->createNamedParameter($id3), 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta2'), 'value' => $query->createNamedParameter('value2') ]) - ->execute(); + ->executeStatement(); $query->insert($this->metadataDbTable) ->values([ $this->foreignKey => $query->createNamedParameter($id4), 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta1'), 'value' => $query->createNamedParameter('value1') ]) - ->execute(); + ->executeStatement(); $query->insert($this->metadataDbTable) ->values([ $this->foreignKey => $query->createNamedParameter($id4), 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta3'), 'value' => $query->createNamedParameter('value3-old') ]) - ->execute(); + ->executeStatement(); $query->insert($this->metadataDbTable) ->values([ $this->foreignKey => $query->createNamedParameter($id6), 'key' => $query->createNamedParameter('{http://nextcloud.com/ns}meta99'), 'value' => $query->createNamedParameter('value99') ]) - ->execute(); + ->executeStatement(); } } diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php index 8b40088b0dccd..c498f903d3712 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/ResourcePrincipalBackendTest.php @@ -25,8 +25,12 @@ namespace OCA\DAV\Tests\unit\CalDAV\ResourceBooking; use OCA\DAV\CalDAV\ResourceBooking\ResourcePrincipalBackend; +use OCP\DB\Exception; class ResourcePrincipalBackendTest extends AbstractPrincipalBackendTest { + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php index 3d4e118b2e846..e1a5b7d0d51ad 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/RoomPrincipalBackendTest.php @@ -25,8 +25,12 @@ namespace OCA\DAV\Tests\unit\CalDAV\ResourceBooking; use OCA\DAV\CalDAV\ResourceBooking\RoomPrincipalBackend; +use OCP\DB\Exception; class RoomPrincipalBackendTest extends AbstractPrincipalBackendTest { + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php index 0d8076f7aa455..d5730d05c2c36 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php @@ -29,6 +29,8 @@ */ namespace OCA\DAV\Tests\unit\CalDAV\Schedule; +use DateTime; +use Exception; use OCA\DAV\CalDAV\Schedule\IMipPlugin; use OCP\AppFramework\Utility\ITimeFactory; use OCP\DB\QueryBuilder\IQueryBuilder; @@ -62,12 +64,6 @@ class IMipPluginTest extends TestCase { /** @var IEMailTemplate|MockObject */ private $emailTemplate; - /** @var IAttachment|MockObject */ - private $emailAttachment; - - /** @var ITimeFactory|MockObject */ - private $timeFactory; - /** @var IConfig|MockObject */ private $config; @@ -86,20 +82,20 @@ protected function setUp(): void { $this->mailMessage->method('setReplyTo')->willReturn($this->mailMessage); $this->mailMessage->method('setTo')->willReturn($this->mailMessage); - $this->mailer = $this->getMockBuilder(IMailer::class)->disableOriginalConstructor()->getMock(); + $this->mailer = $this->createMock(IMailer::class); $this->mailer->method('createMessage')->willReturn($this->mailMessage); $this->emailTemplate = $this->createMock(IEMailTemplate::class); $this->mailer->method('createEMailTemplate')->willReturn($this->emailTemplate); - $this->emailAttachment = $this->createMock(IAttachment::class); - $this->mailer->method('createAttachment')->willReturn($this->emailAttachment); + $emailAttachment = $this->createMock(IAttachment::class); + $this->mailer->method('createAttachment')->willReturn($emailAttachment); /** @var LoggerInterface|MockObject $logger */ - $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); + $logger = $this->createMock(LoggerInterface::class); - $this->timeFactory = $this->getMockBuilder(ITimeFactory::class)->disableOriginalConstructor()->getMock(); - $this->timeFactory->method('getTime')->willReturn(1496912528); // 2017-01-01 + $timeFactory = $this->createMock(ITimeFactory::class); + $timeFactory->method('getTime')->willReturn(1496912528); // 2017-01-01 $this->config = $this->createMock(IConfig::class); @@ -130,15 +126,20 @@ protected function setUp(): void { $defaults->method('getName') ->willReturn('Instance Name 123'); - $this->plugin = new IMipPlugin($this->config, $this->mailer, $logger, $this->timeFactory, $l10nFactory, $urlGenerator, $defaults, $random, $db, $this->userManager, 'user123'); + $this->plugin = new IMipPlugin($this->config, $this->mailer, $logger, $timeFactory, $l10nFactory, $urlGenerator, $defaults, $random, $db, $this->userManager, 'user123'); } + /** + * @throws Exception + */ public function testDelivery() { - $this->config - ->expects($this->at(1)) + $this->config->expects($this->exactly(2)) ->method('getAppValue') - ->with('dav', 'invitation_link_recipients', 'yes') - ->willReturn('yes'); + ->withConsecutive( + ['dav', 'invitation_list_attendees', 'no'], + ['dav', 'invitation_link_recipients', 'yes'] + ) + ->willReturnOnConsecutiveCalls('no', 'yes'); $this->mailer->method('validateMailAddress')->willReturn(true); $message = $this->_testMessage(); @@ -147,23 +148,31 @@ public function testDelivery() { $this->assertEquals('1.1', $message->getScheduleStatus()); } + /** + * @throws Exception + */ public function testFailedDelivery() { - $this->config - ->expects($this->at(1)) + $this->config->expects($this->exactly(2)) ->method('getAppValue') - ->with('dav', 'invitation_link_recipients', 'yes') - ->willReturn('yes'); + ->withConsecutive( + ['dav', 'invitation_list_attendees', 'no'], + ['dav', 'invitation_link_recipients', 'yes'] + ) + ->willReturnOnConsecutiveCalls('no', 'yes'); $this->mailer->method('validateMailAddress')->willReturn(true); $message = $this->_testMessage(); $this->mailer ->method('send') - ->willThrowException(new \Exception()); + ->willThrowException(new Exception()); $this->_expectSend(); $this->plugin->schedule($message); $this->assertEquals('5.0', $message->getScheduleStatus()); } + /** + * @throws Exception + */ public function testInvalidEmailDelivery() { $this->mailer->method('validateMailAddress')->willReturn(false); @@ -172,12 +181,17 @@ public function testInvalidEmailDelivery() { $this->assertEquals('5.0', $message->getScheduleStatus()); } + /** + * @throws Exception + */ public function testDeliveryWithNoCommonName() { - $this->config - ->expects($this->at(1)) + $this->config->expects($this->exactly(2)) ->method('getAppValue') - ->with('dav', 'invitation_link_recipients', 'yes') - ->willReturn('yes'); + ->withConsecutive( + ['dav', 'invitation_list_attendees', 'no'], + ['dav', 'invitation_link_recipients', 'yes'] + ) + ->willReturnOnConsecutiveCalls('no', 'yes'); $this->mailer->method('validateMailAddress')->willReturn(true); $message = $this->_testMessage(); @@ -218,18 +232,18 @@ public function testNoMessageSendForPastEvents(array $veventParams, bool $expect } } - public function dataNoMessageSendForPastEvents() { + public function dataNoMessageSendForPastEvents(): array { return [ - [['DTSTART' => new \DateTime('2017-01-01 00:00:00')], false], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-01-01 00:00:00')], false], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-12-31 00:00:00')], true], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DURATION' => 'P1D'], false], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DURATION' => 'P52W'], true], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY'], true], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;COUNT=3'], false], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;UNTIL=20170301T000000Z'], false], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;COUNT=33'], true], - [['DTSTART' => new \DateTime('2017-01-01 00:00:00'), 'DTEND' => new \DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;UNTIL=20171001T000000Z'], true], + [['DTSTART' => new DateTime('2017-01-01 00:00:00')], false], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-01-01 00:00:00')], false], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-12-31 00:00:00')], true], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DURATION' => 'P1D'], false], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DURATION' => 'P52W'], true], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY'], true], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;COUNT=3'], false], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;UNTIL=20170301T000000Z'], false], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;COUNT=33'], true], + [['DTSTART' => new DateTime('2017-01-01 00:00:00'), 'DTEND' => new DateTime('2017-01-01 00:00:00'), 'RRULE' => 'FREQ=WEEKLY;UNTIL=20171001T000000Z'], true], ]; } @@ -241,17 +255,20 @@ public function testIncludeResponseButtons(string $config_setting, string $recip $this->mailer->method('validateMailAddress')->willReturn(true); $this->_expectSend($recipient, true, $has_buttons); - $this->config - ->expects($this->at(1)) + + $this->config->expects($this->exactly(2)) ->method('getAppValue') - ->with('dav', 'invitation_link_recipients', 'yes') - ->willReturn($config_setting); + ->withConsecutive( + ['dav', 'invitation_list_attendees', 'no'], + ['dav', 'invitation_link_recipients', 'yes'] + ) + ->willReturnOnConsecutiveCalls('no', $config_setting); $this->plugin->schedule($message); $this->assertEquals('1.1', $message->getScheduleStatus()); } - public function dataIncludeResponseButtons() { + public function dataIncludeResponseButtons(): array { return [ // dav.invitation_link_recipients, recipient, $has_buttons [ 'yes', 'joe@internal.com', true], @@ -279,7 +296,7 @@ public function testMessageSendWhenEventWithoutName() { $this->assertEquals('1.1', $message->getScheduleStatus()); } - private function _testMessage(array $attrs = [], string $recipient = 'frodo@hobb.it') { + private function _testMessage(array $attrs = [], string $recipient = 'frodo@hobb.it'): Message { $message = new Message(); $message->method = 'REQUEST'; $message->message = new VCalendar(); @@ -287,7 +304,7 @@ private function _testMessage(array $attrs = [], string $recipient = 'frodo@hobb 'UID' => 'uid-1234', 'SEQUENCE' => 0, 'SUMMARY' => 'Fellowship meeting', - 'DTSTART' => new \DateTime('2018-01-01 00:00:00') + 'DTSTART' => new DateTime('2018-01-01 00:00:00') ], $attrs)); $message->message->VEVENT->add('ORGANIZER', 'mailto:gandalf@wiz.ard'); $message->message->VEVENT->add('ATTENDEE', 'mailto:'.$recipient, [ 'RSVP' => 'TRUE' ]); @@ -325,15 +342,15 @@ private function _expectSend(string $recipient = 'frodo@hobb.it', bool $expectSe ->method('send'); if ($expectButtons) { - $this->queryBuilder->expects($this->at(0)) + $this->queryBuilder->expects($this->once()) ->method('insert') ->with('calendar_invitations') ->willReturn($this->queryBuilder); - $this->queryBuilder->expects($this->at(8)) + $this->queryBuilder->expects($this->once()) ->method('values') ->willReturn($this->queryBuilder); - $this->queryBuilder->expects($this->at(9)) - ->method('execute'); + $this->queryBuilder->expects($this->once()) + ->method('executeStatement'); } else { $this->queryBuilder->expects($this->never()) ->method('insert') diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php index 972a77873b8ab..d9822263005cb 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php @@ -33,6 +33,7 @@ use OCP\IConfig; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\MockObject\Stub\ReturnCallback; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\PropFind; use Sabre\DAV\Server; use Sabre\DAV\Tree; @@ -60,9 +61,7 @@ protected function setUp(): void { $this->server = $this->createMock(Server::class); $this->config = $this->createMock(IConfig::class); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $response = $this->createMock(ResponseInterface::class); $this->server->httpResponse = $response; $this->server->xml = new Service(); @@ -74,18 +73,22 @@ protected function setUp(): void { public function testInitialize() { $plugin = new Plugin($this->config); - $this->server->expects($this->at(7)) + $this->server->expects($this->exactly(10)) ->method('on') - ->with('propFind', [$plugin, 'propFindDefaultCalendarUrl'], 90); - - $this->server->expects($this->at(8)) - ->method('on') - ->with('afterWriteContent', [$plugin, 'dispatchSchedulingResponses']); - - $this->server->expects($this->at(9)) - ->method('on') - ->with('afterCreateFile', [$plugin, 'dispatchSchedulingResponses']); - + ->withConsecutive( + // Sabre\CalDAV\Schedule\Plugin + ['method:POST', [$plugin, 'httpPost']], + ['propFind', [$plugin, 'propFind']], + ['propPatch', [$plugin, 'propPatch']], + ['calendarObjectChange', [$plugin, 'calendarObjectChange']], + ['beforeUnbind', [$plugin, 'beforeUnbind']], + ['schedule', [$plugin, 'scheduleLocalDelivery']], + ['getSupportedPrivilegeSet', [$plugin, 'getSupportedPrivilegeSet']], + // OCA\DAV\CalDAV\Schedule\Plugin + ['propFind', [$plugin, 'propFindDefaultCalendarUrl'], 90], + ['afterWriteContent', [$plugin, 'dispatchSchedulingResponses']], + ['afterCreateFile', [$plugin, 'dispatchSchedulingResponses']] + ); $plugin->initialize($this->server); } @@ -247,6 +250,7 @@ public function propFindDefaultCalendarUrlProvider(): array { * @param string $displayName * @param bool $exists * @param bool $propertiesForPath + * @throws NotFound */ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $calendarHome, bool $isResource, string $calendarUri, string $displayName, bool $exists, bool $propertiesForPath = true) { $propFind = new PropFind( @@ -257,19 +261,13 @@ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $ca 0 ); /** @var IPrincipal|MockObject $node */ - $node = $this->getMockBuilder(IPrincipal::class) - ->disableOriginalConstructor() - ->getMock(); - + $node = $this->createMock(IPrincipal::class); $node->expects($this->once()) ->method('getPrincipalUrl') ->with() ->willReturn($principalUri); - $calDAVPlugin = $this->getMockBuilder(CalDAVPlugin::class) - ->disableOriginalConstructor() - ->getMock(); - + $calDAVPlugin = $this->createMock(CalDAVPlugin::class); $calDAVPlugin->expects($this->once()) ->method('getCalendarHomeForPrincipal') ->willReturn($calendarHome); diff --git a/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php b/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php index 1d4c34ae84cf5..9b0596fd7e347 100644 --- a/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php +++ b/apps/dav/tests/unit/CalDAV/Search/Request/CalendarSearchReportTest.php @@ -25,6 +25,8 @@ namespace OCA\DAV\Tests\unit\CalDAV\Search\Xml\Request; use OCA\DAV\CalDAV\Search\Xml\Request\CalendarSearchReport; +use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; use Sabre\Xml\Reader; use Test\TestCase; @@ -34,6 +36,9 @@ class CalendarSearchReportTest extends TestCase { 'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport', ]; + /** + * @throws LibXMLException + */ public function testFoo() { $xml = << @@ -90,6 +95,9 @@ public function testFoo() { ); } + /** + * @throws LibXMLException + */ public function testNoLimitOffset() { $xml = << @@ -131,9 +139,12 @@ public function testNoLimitOffset() { ); } - + + /** + * @throws LibXMLException + */ public function testRequiresCompFilter() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('{http://nextcloud.com/ns}prop-filter or {http://nextcloud.com/ns}param-filter given without any {http://nextcloud.com/ns}comp-filter'); $xml = <<parse($xml); } - + + /** + * @throws LibXMLException + */ public function testRequiresFilter() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('The {http://nextcloud.com/ns}filter element is required for this request'); $xml = <<parse($xml); } - + + /** + * @throws LibXMLException + */ public function testNoSearchTerm() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('{http://nextcloud.com/ns}search-term is required for this request'); $xml = <<parse($xml); } - + + /** + * @throws LibXMLException + */ public function testCompOnly() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('At least one{http://nextcloud.com/ns}prop-filter or {http://nextcloud.com/ns}param-filter is required for this request'); $xml = << @@ -288,6 +311,9 @@ public function testPropOnly() { ); } + /** + * @throws LibXMLException + */ public function testParamOnly() { $xml = << @@ -332,7 +358,11 @@ public function testParamOnly() { ); } - private function parse($xml, array $elementMap = []) { + /** + * @throws LibXMLException + */ + private function parse($xml): array { + $elementMap = []; $reader = new Reader(); $reader->elementMap = array_merge($this->elementMap, $elementMap); $reader->xml($xml); diff --git a/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php b/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php index 811550390156b..99a40c2b0b71f 100644 --- a/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Search/SearchPluginTest.php @@ -27,21 +27,24 @@ use OCA\DAV\CalDAV\CalendarHome; use OCA\DAV\CalDAV\Search\SearchPlugin; use OCA\DAV\CalDAV\Search\Xml\Request\CalendarSearchReport; +use Sabre\DAV\Server; +use Sabre\DAV\Tree; +use Sabre\HTTP\Response; use Sabre\Xml\Service; use Test\TestCase; class SearchPluginTest extends TestCase { protected $server; - /** @var \OCA\DAV\CalDAV\Search\SearchPlugin $plugin */ + /** @var SearchPlugin $plugin */ protected $plugin; protected function setUp(): void { parent::setUp(); - $this->server = $this->createMock(\Sabre\DAV\Server::class); - $this->server->tree = $this->createMock(\Sabre\DAV\Tree::class); - $this->server->httpResponse = $this->createMock(\Sabre\HTTP\Response::class); + $this->server = $this->createMock(Server::class); + $this->server->tree = $this->createMock(Tree::class); + $this->server->httpResponse = $this->createMock(Response::class); $this->server->xml = new Service(); $this->plugin = new SearchPlugin(); @@ -57,11 +60,11 @@ public function testGetName() { } public function testInitialize() { - $server = $this->createMock(\Sabre\DAV\Server::class); + $server = $this->createMock(Server::class); $plugin = new SearchPlugin(); - $server->expects($this->at(0)) + $server->expects($this->once()) ->method('on') ->with('report', [$plugin, 'report']); $server->xml = new Service(); @@ -69,30 +72,30 @@ public function testInitialize() { $plugin->initialize($server); $this->assertEquals( - $server->xml->elementMap['{http://nextcloud.com/ns}calendar-search'], - 'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport' + 'OCA\\DAV\\CalDAV\\Search\\Xml\\Request\\CalendarSearchReport', + $server->xml->elementMap['{http://nextcloud.com/ns}calendar-search'] ); } public function testReportUnknown() { $result = $this->plugin->report('{urn:ietf:params:xml:ns:caldav}calendar-query', 'REPORT', null); - $this->assertEquals($result, null); - $this->assertNotEquals($this->server->transactionType, 'report-nc-calendar-search'); + $this->assertEquals(null, $result); + $this->assertNotEquals('report-nc-calendar-search', $this->server->transactionType); } public function testReport() { $report = $this->createMock(CalendarSearchReport::class); $report->filters = []; $calendarHome = $this->createMock(CalendarHome::class); - $this->server->expects($this->at(0)) + $this->server->expects($this->once()) ->method('getRequestUri') ->with() ->willReturn('/re/quest/u/r/i'); - $this->server->tree->expects($this->at(0)) + $this->server->tree->expects($this->once()) ->method('getNodeForPath') ->with('/re/quest/u/r/i') ->willReturn($calendarHome); - $this->server->expects($this->at(1)) + $this->server->expects($this->once()) ->method('getHTTPDepth') ->with(2) ->willReturn(2); @@ -101,7 +104,7 @@ public function testReport() { ->willReturn([ 'return' => null ]); - $calendarHome->expects($this->at(0)) + $calendarHome->expects($this->once()) ->method('calendarSearch') ->willReturn([]); diff --git a/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php b/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php index 310d266cd575f..05ef18910368d 100644 --- a/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/WebcalCaching/PluginTest.php @@ -4,6 +4,7 @@ * * @author Christoph Wurst * @author Georg Ehrke + * @author Thomas Citharel * * @license GNU AGPL version 3 or any later version * @@ -25,16 +26,17 @@ use OCA\DAV\CalDAV\WebcalCaching\Plugin; use OCP\IRequest; +use Test\TestCase; -class PluginTest extends \Test\TestCase { +class PluginTest extends TestCase { public function testDisabled() { $request = $this->createMock(IRequest::class); - $request->expects($this->at(0)) + $request->expects($this->once()) ->method('isUserAgent') ->with(Plugin::ENABLE_FOR_CLIENTS) ->willReturn(false); - $request->expects($this->at(1)) + $request->expects($this->once()) ->method('getHeader') ->with('X-NC-CalDAV-Webcal-Caching') ->willReturn(''); @@ -46,12 +48,12 @@ public function testDisabled() { public function testEnabled() { $request = $this->createMock(IRequest::class); - $request->expects($this->at(0)) + $request->expects($this->once()) ->method('isUserAgent') ->with(Plugin::ENABLE_FOR_CLIENTS) ->willReturn(false); - $request->expects($this->at(1)) + $request->expects($this->once()) ->method('getHeader') ->with('X-NC-CalDAV-Webcal-Caching') ->willReturn('On'); diff --git a/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php b/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php index 00a9dbcf8f4af..4d0625eeae20d 100644 --- a/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php +++ b/apps/dav/tests/unit/CalDAV/WebcalCaching/RefreshWebcalServiceTest.php @@ -74,7 +74,7 @@ protected function setUp(): void { */ public function testRun(string $body, string $contentType, string $result) { $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class) - ->setMethods(['getRandomCalendarObjectUri']) + ->onlyMethods(['getRandomCalendarObjectUri']) ->setConstructorArgs([$this->caldavBackend, $this->clientService, $this->config, $this->logger]) ->getMock(); @@ -156,7 +156,7 @@ public function testRunCreateCalendarNoException(string $body, string $contentTy $client = $this->createMock(IClient::class); $response = $this->createMock(IResponse::class); $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class) - ->setMethods(['getRandomCalendarObjectUri', 'getSubscription', 'queryWebcalFeed']) + ->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription', 'queryWebcalFeed']) ->setConstructorArgs([$this->caldavBackend, $this->clientService, $this->config, $this->logger]) ->getMock(); @@ -233,7 +233,7 @@ public function testRunCreateCalendarBadRequest(string $body, string $contentTyp $client = $this->createMock(IClient::class); $response = $this->createMock(IResponse::class); $refreshWebcalService = $this->getMockBuilder(RefreshWebcalService::class) - ->setMethods(['getRandomCalendarObjectUri', 'getSubscription', 'queryWebcalFeed']) + ->onlyMethods(['getRandomCalendarObjectUri', 'getSubscription', 'queryWebcalFeed']) ->setConstructorArgs([$this->caldavBackend, $this->clientService, $this->config, $this->logger]) ->getMock(); @@ -294,7 +294,7 @@ public function testRunCreateCalendarBadRequest(string $body, string $contentTyp $this->logger->expects($this->once()) ->method('error') - ->with($badRequestException); + ->with($this->anything(), ['exception' => $badRequestException]); $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123'); } @@ -327,7 +327,7 @@ public function runDataProvider():array { * * @param string $source */ - public function testRunLocalURL($source) { + public function testRunLocalURL(string $source): void { $refreshWebcalService = new RefreshWebcalService( $this->caldavBackend, $this->clientService, @@ -367,7 +367,7 @@ public function testRunLocalURL($source) { $this->logger->expects($this->once()) ->method('warning') - ->with($this->anything(), $this->isInstanceOf(LocalServerException::class)); + ->with($this->anything(), ['exception' => new LocalServerException()]); $refreshWebcalService->refreshSubscription('principals/users/testuser', 'sub123'); } diff --git a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php index 3cbaf91659851..a649d7ab9446e 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php @@ -69,10 +69,8 @@ protected function setUp(): void { 'principaluri' => 'principals/system/system', '{DAV:}displayname' => 'display name', ]; - $this->addressBook = $this->getMockBuilder(AddressBook::class) - ->disableOriginalConstructor()->getMock(); - $this->backend = $this->getMockBuilder(CardDavBackend::class) - ->disableOriginalConstructor()->getMock(); + $this->addressBook = $this->createMock(AddressBook::class); + $this->backend = $this->createMock(CardDavBackend::class); $this->vCard = $this->createMock(VCard::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); diff --git a/apps/dav/tests/unit/CardDAV/AddressBookTest.php b/apps/dav/tests/unit/CardDAV/AddressBookTest.php index 23e3e4f3b2ae9..052afb8efd622 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookTest.php @@ -28,13 +28,18 @@ use OCA\DAV\CardDAV\AddressBook; use OCA\DAV\CardDAV\CardDavBackend; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\PropPatch; use Test\TestCase; class AddressBookTest extends TestCase { + /** + * @throws Forbidden + */ public function testDelete() { - /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); + /** @var MockObject | CardDavBackend $backend */ + $backend = $this->createMock(CardDavBackend::class); $backend->expects($this->once())->method('updateShares'); $backend->expects($this->any())->method('getShares')->willReturn([ ['href' => 'principal:user2'] @@ -53,10 +58,10 @@ public function testDelete() { public function testDeleteFromGroup() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); - /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); + /** @var MockObject | CardDavBackend $backend */ + $backend = $this->createMock(CardDavBackend::class); $backend->expects($this->never())->method('updateShares'); $backend->expects($this->any())->method('getShares')->willReturn([ ['href' => 'principal:group2'] @@ -75,10 +80,10 @@ public function testDeleteFromGroup() { public function testPropPatch() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); - /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); + /** @var MockObject | CardDavBackend $backend */ + $backend = $this->createMock(CardDavBackend::class); $calendarInfo = [ '{http://owncloud.org/ns}owner-principal' => 'user1', '{DAV:}displayname' => 'Test address book', @@ -94,9 +99,9 @@ public function testPropPatch() { /** * @dataProvider providesReadOnlyInfo */ - public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet) { - /** @var \PHPUnit\Framework\MockObject\MockObject | CardDavBackend $backend */ - $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); + public function testAcl(bool $expectsWrite, ?bool $readOnlyValue, bool $hasOwnerSet) { + /** @var MockObject | CardDavBackend $backend */ + $backend = $this->createMock(CardDavBackend::class); $backend->expects($this->any())->method('applyShareAcl')->willReturnArgument(1); $calendarInfo = [ '{DAV:}displayname' => 'Test address book', @@ -142,7 +147,7 @@ public function testAcl($expectsWrite, $readOnlyValue, $hasOwnerSet) { $this->assertEquals($expectedAcl, $childAcl); } - public function providesReadOnlyInfo() { + public function providesReadOnlyInfo(): array { return [ 'read-only property not set' => [true, null, true], 'read-only property is false' => [true, false, true], diff --git a/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php b/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php index bb45c88b10d55..3778d66f097ce 100644 --- a/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php +++ b/apps/dav/tests/unit/CardDAV/BirthdayServiceTest.php @@ -33,7 +33,10 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\BadRequest; use Sabre\VObject\Component\VCalendar; +use Sabre\VObject\InvalidDataException; use Sabre\VObject\Reader; use Test\TestCase; @@ -41,17 +44,17 @@ class BirthdayServiceTest extends TestCase { /** @var BirthdayService */ private $service; - /** @var CalDavBackend | \PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend | MockObject */ private $calDav; - /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject */ + /** @var CardDavBackend | MockObject */ private $cardDav; - /** @var GroupPrincipalBackend | \PHPUnit\Framework\MockObject\MockObject */ + /** @var GroupPrincipalBackend | MockObject */ private $groupPrincipalBackend; - /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig | MockObject */ private $config; - /** @var IDBConnection | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IDBConnection | MockObject */ private $dbConnection; - /** @var IL10N | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N | MockObject */ private $l10n; protected function setUp(): void { @@ -77,21 +80,26 @@ protected function setUp(): void { /** * @dataProvider providesVCards - * @param string $expectedSummary - * @param string $expectedDTStart - * @param string $expectedFieldType - * @param string $expectedUnknownYear - * @param string $expectedOriginalYear - * @param string | null $data + * @throws InvalidDataException */ - public function testBuildBirthdayFromContact($expectedSummary, $expectedDTStart, $expectedFieldType, $expectedUnknownYear, $expectedOriginalYear, $data, $fieldType, $prefix, $supports4Bytes) { + public function testBuildBirthdayFromContact( + ?string $expectedSummary, + ?string $expectedDTStart, + ?string $expectedFieldType, + ?string $expectedUnknownYear, + ?string $expectedOriginalYear, + ?string $data, + string $fieldType, + string $prefix, + bool $supports4Bytes + ) { $this->dbConnection->method('supports4ByteText')->willReturn($supports4Bytes); $cal = $this->service->buildDateFromContact($data, $fieldType, $prefix); if ($expectedSummary === null) { $this->assertNull($cal); } else { - $this->assertInstanceOf('Sabre\VObject\Component\VCalendar', $cal); + $this->assertInstanceOf(VCalendar::class, $cal); $this->assertEquals('-//IDN nextcloud.com//Birthday calendar//EN', $cal->PRODID->getValue()); $this->assertTrue(isset($cal->VEVENT)); $this->assertEquals('FREQ=YEARLY', $cal->VEVENT->RRULE->getValue()); @@ -165,9 +173,11 @@ public function testOnCardDeleted() { ->willReturn([ 'id' => 1234 ]); - $this->calDav->expects($this->at(1))->method('deleteCalendarObject')->with(1234, 'default-gump.vcf.ics'); - $this->calDav->expects($this->at(2))->method('deleteCalendarObject')->with(1234, 'default-gump.vcf-death.ics'); - $this->calDav->expects($this->at(3))->method('deleteCalendarObject')->with(1234, 'default-gump.vcf-anniversary.ics'); + $this->calDav->expects($this->exactly(3))->method('deleteCalendarObject')->withConsecutive( + [1234, 'default-gump.vcf.ics'], + [1234, 'default-gump.vcf-death.ics'], + [1234, 'default-gump.vcf-anniversary.ics'] + ); $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); $this->service->onCardDeleted(666, 'gump.vcf'); @@ -182,7 +192,7 @@ public function testOnCardChangedGloballyDisabled() { $this->cardDav->expects($this->never())->method('getAddressBookById'); $service = $this->getMockBuilder(BirthdayService::class) - ->setMethods(['buildDateFromContact', 'birthdayEvenChanged']) + ->onlyMethods(['buildDateFromContact', 'birthdayEvenChanged']) ->setConstructorArgs([$this->calDav, $this->cardDav, $this->groupPrincipalBackend, $this->config, $this->dbConnection, $this->l10n]) ->getMock(); @@ -209,9 +219,9 @@ public function testOnCardChangedUserDisabled() { $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); $this->calDav->expects($this->never())->method('getCalendarByUri'); - /** @var BirthdayService | \PHPUnit\Framework\MockObject\MockObject $service */ + /** @var BirthdayService | MockObject $service */ $service = $this->getMockBuilder(BirthdayService::class) - ->setMethods(['buildDateFromContact', 'birthdayEvenChanged']) + ->onlyMethods(['buildDateFromContact', 'birthdayEvenChanged']) ->setConstructorArgs([$this->calDav, $this->cardDav, $this->groupPrincipalBackend, $this->config, $this->dbConnection, $this->l10n]) ->getMock(); @@ -221,7 +231,7 @@ public function testOnCardChangedUserDisabled() { /** * @dataProvider providesCardChanges */ - public function testOnCardChanged($expectedOp) { + public function testOnCardChanged(string $expectedOp) { $this->config->expects($this->once()) ->method('getAppValue') ->with('dav', 'generateBirthdayCalendar', 'yes') @@ -245,9 +255,9 @@ public function testOnCardChanged($expectedOp) { ]); $this->cardDav->expects($this->once())->method('getShares')->willReturn([]); - /** @var BirthdayService | \PHPUnit\Framework\MockObject\MockObject $service */ + /** @var BirthdayService | MockObject $service */ $service = $this->getMockBuilder(BirthdayService::class) - ->setMethods(['buildDateFromContact', 'birthdayEvenChanged']) + ->onlyMethods(['buildDateFromContact', 'birthdayEvenChanged']) ->setConstructorArgs([$this->calDav, $this->cardDav, $this->groupPrincipalBackend, $this->config, $this->dbConnection, $this->l10n]) ->getMock(); @@ -290,11 +300,8 @@ public function testOnCardChanged($expectedOp) { /** * @dataProvider providesBirthday - * @param $expected - * @param $old - * @param $new */ - public function testBirthdayEvenChanged($expected, $old, $new) { + public function testBirthdayEvenChanged(bool $expected, string $old, string $new) { $new = Reader::read($new); $this->assertEquals($expected, $this->service->birthdayEvenChanged($old, $new)); } @@ -338,6 +345,9 @@ public function testGetAllAffectedPrincipals() { ], $users); } + /** + * @throws BadRequest + */ public function testBirthdayCalendarHasComponentEvent() { $this->calDav->expects($this->once()) ->method('createCalendar') @@ -350,32 +360,28 @@ public function testBirthdayCalendarHasComponentEvent() { } public function testResetForUser() { - $this->calDav->expects($this->at(0)) + $this->calDav->expects($this->once()) ->method('getCalendarByUri') ->with('principals/users/user123', 'contact_birthdays') ->willReturn(['id' => 42]); - $this->calDav->expects($this->at(1)) + $this->calDav->expects($this->once()) ->method('getCalendarObjects') ->with(42, 0) ->willReturn([['uri' => '1.ics'], ['uri' => '2.ics'], ['uri' => '3.ics']]); - $this->calDav->expects($this->at(2)) + $this->calDav->expects($this->exactly(3)) ->method('deleteCalendarObject') - ->with(42, '1.ics', 0); - - $this->calDav->expects($this->at(3)) - ->method('deleteCalendarObject') - ->with(42, '2.ics', 0); - - $this->calDav->expects($this->at(4)) - ->method('deleteCalendarObject') - ->with(42, '3.ics', 0); + ->withConsecutive( + [42, '1.ics', 0], + [42, '2.ics', 0], + [42, '3.ics', 0] + ); $this->service->resetForUser('user123'); } - public function providesBirthday() { + public function providesBirthday(): array { return [ [true, '', @@ -392,7 +398,7 @@ public function providesBirthday() { ]; } - public function providesCardChanges() { + public function providesCardChanges(): array { return[ ['delete'], ['create'], @@ -400,7 +406,7 @@ public function providesCardChanges() { ]; } - public function providesVCards() { + public function providesVCards(): array { return [ // $expectedSummary, $expectedDTStart, $expectedFieldType, $expectedUnknownYear, $expectedOriginalYear, $data, $fieldType, $prefix, $supports4Byte [null, null, null, null, null, 'yasfewf', '', '', true], diff --git a/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php b/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php index e9153c4d19747..93d5a8dbe721e 100644 --- a/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php +++ b/apps/dav/tests/unit/CardDAV/ContactsManagerTest.php @@ -30,16 +30,17 @@ use OCP\Contacts\IManager; use OCP\IL10N; use OCP\IURLGenerator; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class ContactsManagerTest extends TestCase { public function test() { - /** @var IManager | \PHPUnit\Framework\MockObject\MockObject $cm */ - $cm = $this->getMockBuilder(IManager::class)->disableOriginalConstructor()->getMock(); + /** @var IManager | MockObject $cm */ + $cm = $this->createMock(IManager::class); $cm->expects($this->exactly(2))->method('registerAddressBook'); - $urlGenerator = $this->getMockBuilder(IURLGenerator::class)->disableOriginalConstructor()->getMock(); - /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backEnd */ - $backEnd = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); + $urlGenerator = $this->createMock(IURLGenerator::class); + /** @var CardDavBackend | MockObject $backEnd */ + $backEnd = $this->createMock(CardDavBackend::class); $backEnd->method('getAddressBooksForUser')->willReturn([ ['{DAV:}displayname' => 'Test address book', 'uri' => 'default'], ]); diff --git a/apps/dav/tests/unit/CardDAV/ConverterTest.php b/apps/dav/tests/unit/CardDAV/ConverterTest.php index cc5f707bb3617..d0c35b8a587a9 100644 --- a/apps/dav/tests/unit/CardDAV/ConverterTest.php +++ b/apps/dav/tests/unit/CardDAV/ConverterTest.php @@ -34,11 +34,12 @@ use OCP\IImage; use OCP\IUser; use PHPUnit\Framework\MockObject\MockObject; +use Sabre\VObject\Component\VCard; use Test\TestCase; class ConverterTest extends TestCase { - /** @var IAccountManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IAccountManager|MockObject */ private $accountManager; protected function setUp(): void { @@ -83,9 +84,7 @@ public function getAccountManager(IUser $user) { ]; }); - $accountManager = $this->getMockBuilder(IAccountManager::class) - ->disableOriginalConstructor()->getMock(); - + $accountManager = $this->createMock(IAccountManager::class); $accountManager->expects($this->any())->method('getAccount')->willReturn($account); return $accountManager; @@ -94,14 +93,14 @@ public function getAccountManager(IUser $user) { /** * @dataProvider providesNewUsers */ - public function testCreation($expectedVCard, $displayName = null, $eMailAddress = null, $cloudId = null) { + public function testCreation(?array $expectedVCard, ?string $displayName = null, ?string $eMailAddress = null, string $cloudId = null) { $user = $this->getUserMock((string)$displayName, $eMailAddress, $cloudId); $accountManager = $this->getAccountManager($user); $converter = new Converter($accountManager); $vCard = $converter->createCardFromUser($user); if ($expectedVCard !== null) { - $this->assertInstanceOf('Sabre\VObject\Component\VCard', $vCard); + $this->assertInstanceOf(VCard::class, $vCard); $cardData = $vCard->jsonSerialize(); $this->compareData($expectedVCard, $cardData); } else { @@ -119,12 +118,12 @@ protected function compareData($expected, $data) { } } if (!$found) { - $this->assertTrue(false, 'Expected data: ' . $key . ' not found.'); + $this->fail('Expected data: ' . $key . ' not found.'); } } } - public function providesNewUsers() { + public function providesNewUsers(): array { return [ [ null @@ -180,17 +179,15 @@ public function providesNewUsers() { /** * @dataProvider providesNames - * @param $expected - * @param $fullName */ - public function testNameSplitter($expected, $fullName) { + public function testNameSplitter(string $expected, string $fullName) { $converter = new Converter($this->accountManager); $r = $converter->splitFullName($fullName); $r = implode(';', $r); $this->assertEquals($expected, $r); } - public function providesNames() { + public function providesNames(): array { return [ ['Sauron;;;;', 'Sauron'], ['Baggins;Bilbo;;;', 'Bilbo Baggins'], @@ -199,16 +196,13 @@ public function providesNames() { } /** - * @param $displayName - * @param $eMailAddress - * @param $cloudId - * @return IUser | \PHPUnit\Framework\MockObject\MockObject + * @return IUser | MockObject */ protected function getUserMock(string $displayName, ?string $eMailAddress, ?string $cloudId) { - $image0 = $this->getMockBuilder(IImage::class)->disableOriginalConstructor()->getMock(); + $image0 = $this->createMock(IImage::class); $image0->method('mimeType')->willReturn('image/jpeg'); $image0->method('data')->willReturn('123456789'); - $user = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock(); + $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('12345'); $user->method('getDisplayName')->willReturn($displayName); $user->method('getEMailAddress')->willReturn($eMailAddress); diff --git a/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php b/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php index ed5ec544fb686..8339e5ff6a470 100644 --- a/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php +++ b/apps/dav/tests/unit/CardDAV/ImageExportPluginTest.php @@ -30,6 +30,7 @@ use OCA\DAV\CardDAV\PhotoCache; use OCP\Files\NotFoundException; use OCP\Files\SimpleFS\ISimpleFile; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\CardDAV\Card; use Sabre\DAV\Node; use Sabre\DAV\Server; @@ -40,17 +41,15 @@ class ImageExportPluginTest extends TestCase { - /** @var ResponseInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResponseInterface|MockObject */ private $response; - /** @var RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var ImageExportPlugin|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ImageExportPlugin|MockObject */ private $plugin; - /** @var Server */ - private $server; - /** @var Tree|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Tree|MockObject */ private $tree; - /** @var PhotoCache|\PHPUnit\Framework\MockObject\MockObject */ + /** @var PhotoCache|MockObject */ private $cache; protected function setUp(): void { @@ -58,29 +57,28 @@ protected function setUp(): void { $this->request = $this->createMock(RequestInterface::class); $this->response = $this->createMock(ResponseInterface::class); - $this->server = $this->createMock(Server::class); + $server = $this->createMock(Server::class); $this->tree = $this->createMock(Tree::class); - $this->server->tree = $this->tree; + $server->tree = $this->tree; $this->cache = $this->createMock(PhotoCache::class); $this->plugin = $this->getMockBuilder(ImageExportPlugin::class) - ->setMethods(['getPhoto']) + ->addMethods(['getPhoto']) ->setConstructorArgs([$this->cache]) ->getMock(); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } /** * @dataProvider providesQueryParams - * @param $param */ - public function testQueryParams($param) { + public function testQueryParams(array $param) { $this->request->expects($this->once())->method('getQueryParameters')->willReturn($param); $result = $this->plugin->httpGet($this->request, $this->response); $this->assertTrue($result); } - public function providesQueryParams() { + public function providesQueryParams(): array { return [ [[]], [['1']], @@ -105,7 +103,7 @@ public function testNoCard() { $this->assertTrue($result); } - public function dataTestCard() { + public function dataTestCard(): array { return [ [null, false], [null, true], @@ -116,11 +114,8 @@ public function dataTestCard() { /** * @dataProvider dataTestCard - * - * @param $size - * @param bool $photo */ - public function testCard($size, $photo) { + public function testCard(?int $size, bool $photo) { $query = ['photo' => null]; if ($size !== null) { $query['size'] = $size; @@ -150,18 +145,14 @@ public function testCard($size, $photo) { $this->fail(); }); - $this->response->expects($this->at(0)) - ->method('setHeader') - ->with('Cache-Control', 'private, max-age=3600, must-revalidate'); - $this->response->expects($this->at(1)) - ->method('setHeader') - ->with('Etag', '"myEtag"'); - $this->response->expects($this->at(2)) - ->method('setHeader') - ->with('Pragma', 'public'); - $size = $size === null ? -1 : $size; + $setHeadersParams = [ + ['Cache-Control', 'private, max-age=3600, must-revalidate'], + ['Etag', '"myEtag"'], + ['Pragma', 'public'] + ]; + if ($photo) { $file = $this->createMock(ISimpleFile::class); $file->method('getMimeType') @@ -173,12 +164,10 @@ public function testCard($size, $photo) { ->with(1, 'card', $size, $card) ->willReturn($file); - $this->response->expects($this->at(3)) - ->method('setHeader') - ->with('Content-Type', 'image/jpeg'); - $this->response->expects($this->at(4)) - ->method('setHeader') - ->with('Content-Disposition', 'attachment; filename=card.jpg'); + $setHeadersParams = array_merge($setHeadersParams, [ + ['Content-Type', 'image/jpeg'], + ['Content-Disposition', 'attachment; filename=card.jpg'] + ]); $this->response->expects($this->once()) ->method('setStatus') @@ -195,6 +184,10 @@ public function testCard($size, $photo) { ->with(404); } + $this->response->expects($this->exactly(count($setHeadersParams))) + ->method('setHeader') + ->withConsecutive(...$setHeadersParams); + $result = $this->plugin->httpGet($this->request, $this->response); $this->assertFalse($result); } diff --git a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php index e9429e4e18f88..bd43af8025ff0 100644 --- a/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php +++ b/apps/dav/tests/unit/CardDAV/Sharing/PluginTest.php @@ -31,6 +31,8 @@ use OCA\DAV\DAV\Sharing\Plugin; use OCP\IConfig; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception; use Sabre\DAV\Server; use Sabre\DAV\SimpleCollection; use Sabre\HTTP\Request; @@ -41,30 +43,31 @@ class PluginTest extends TestCase { /** @var Plugin */ private $plugin; - /** @var Server */ - private $server; - /** @var IShareable | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IShareable | MockObject */ private $book; + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); - /** @var Auth | \PHPUnit\Framework\MockObject\MockObject $authBackend */ - $authBackend = $this->getMockBuilder(Auth::class)->disableOriginalConstructor()->getMock(); + /** @var Auth | MockObject $authBackend */ + $authBackend = $this->createMock(Auth::class); $authBackend->method('isDavAuthenticated')->willReturn(true); /** @var IRequest $request */ - $request = $this->getMockBuilder(IRequest::class)->disableOriginalConstructor()->getMock(); + $request = $this->createMock(IRequest::class); $config = $this->createMock(IConfig::class); $this->plugin = new Plugin($authBackend, $request, $config); $root = new SimpleCollection('root'); - $this->server = new \Sabre\DAV\Server($root); + $server = new Server($root); /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder(IShareable::class)->disableOriginalConstructor()->getMock(); + $this->book = $this->createMock(IShareable::class); $this->book->method('getName')->willReturn('addressbook1.vcf'); $root->addChild($this->book); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } public function testSharing() { diff --git a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php index 58af8a64d0b4e..cb914c0fe1733 100644 --- a/apps/dav/tests/unit/CardDAV/SyncServiceTest.php +++ b/apps/dav/tests/unit/CardDAV/SyncServiceTest.php @@ -27,16 +27,22 @@ */ namespace OCA\DAV\Tests\unit\CardDAV; +use Exception; use OCA\DAV\CardDAV\CardDavBackend; use OCA\DAV\CardDAV\Converter; use OCA\DAV\CardDAV\SyncService; use OCP\IUser; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\BadRequest; use Sabre\VObject\Component\VCard; use Test\TestCase; class SyncServiceTest extends TestCase { + /** + * @throws Exception + */ public function testEmptySync() { $backend = $this->getBackendMock(0, 0, 0); @@ -45,6 +51,9 @@ public function testEmptySync() { $this->assertEquals('sync-token-1', $return); } + /** + * @throws Exception + */ public function testSyncWithNewElement() { $backend = $this->getBackendMock(1, 0, 0); $backend->method('getCard')->willReturn(false); @@ -54,6 +63,9 @@ public function testSyncWithNewElement() { $this->assertEquals('sync-token-1', $return); } + /** + * @throws Exception + */ public function testSyncWithUpdatedElement() { $backend = $this->getBackendMock(0, 1, 0); $backend->method('getCard')->willReturn(true); @@ -63,6 +75,9 @@ public function testSyncWithUpdatedElement() { $this->assertEquals('sync-token-1', $return); } + /** + * @throws Exception + */ public function testSyncWithDeletedElement() { $backend = $this->getBackendMock(0, 0, 1); @@ -71,12 +86,14 @@ public function testSyncWithDeletedElement() { $this->assertEquals('sync-token-1', $return); } + /** + * @throws BadRequest + */ public function testEnsureSystemAddressBookExists() { - /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backend */ + /** @var CardDavBackend | MockObject $backend */ $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); $backend->expects($this->exactly(1))->method('createAddressBook'); - $backend->expects($this->at(0))->method('getAddressBooksByUri')->willReturn(null); - $backend->expects($this->at(1))->method('getAddressBooksByUri')->willReturn([]); + $backend->expects($this->exactly(2))->method('getAddressBooksByUri')->willReturnOnConsecutiveCalls(null, []); /** @var IUserManager $userManager */ $userManager = $this->getMockBuilder(IUserManager::class)->disableOriginalConstructor()->getMock(); @@ -87,7 +104,7 @@ public function testEnsureSystemAddressBookExists() { $ss->ensureSystemAddressBookExists('principals/users/adam', 'contacts', []); } - public function dataActivatedUsers() { + public function dataActivatedUsers(): array { return [ [true, 1, 1, 1], [false, 0, 0, 3], @@ -96,15 +113,9 @@ public function dataActivatedUsers() { /** * @dataProvider dataActivatedUsers - * - * @param boolean $activated - * @param integer $createCalls - * @param integer $updateCalls - * @param integer $deleteCalls - * @return void */ - public function testUpdateAndDeleteUser($activated, $createCalls, $updateCalls, $deleteCalls) { - /** @var CardDavBackend | \PHPUnit\Framework\MockObject\MockObject $backend */ + public function testUpdateAndDeleteUser(bool $activated, int $createCalls, int $updateCalls, int $deleteCalls): void { + /** @var CardDavBackend | MockObject $backend */ $backend = $this->getMockBuilder(CardDavBackend::class)->disableOriginalConstructor()->getMock(); $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); @@ -120,10 +131,10 @@ public function testUpdateAndDeleteUser($activated, $createCalls, $updateCalls, ->with('principals/system/system', 'system') ->willReturn(['id' => -1]); - /** @var IUserManager | \PHPUnit\Framework\MockObject\MockObject $userManager */ + /** @var IUserManager | MockObject $userManager */ $userManager = $this->getMockBuilder(IUserManager::class)->disableOriginalConstructor()->getMock(); - /** @var IUser | \PHPUnit\Framework\MockObject\MockObject $user */ + /** @var IUser | MockObject $user */ $user = $this->getMockBuilder(IUser::class)->disableOriginalConstructor()->getMock(); $user->method('getBackendClassName')->willReturn('unittest'); $user->method('getUID')->willReturn('test-user'); @@ -143,13 +154,7 @@ public function testUpdateAndDeleteUser($activated, $createCalls, $updateCalls, $ss->deleteUser($user); } - /** - * @param int $createCount - * @param int $updateCount - * @param int $deleteCount - * @return \PHPUnit\Framework\MockObject\MockObject - */ - private function getBackendMock($createCount, $updateCount, $deleteCount) { + private function getBackendMock(int $createCount, int $updateCount, int $deleteCount): MockObject { $backend = $this->getMockBuilder(CardDavBackend::class) ->disableOriginalConstructor() ->getMock(); @@ -162,15 +167,15 @@ private function getBackendMock($createCount, $updateCount, $deleteCount) { /** * @param $backend * @param $response - * @return SyncService|\PHPUnit\Framework\MockObject\MockObject + * @return SyncService|MockObject */ private function getSyncServiceMock($backend, $response) { $userManager = $this->getMockBuilder(IUserManager::class)->disableOriginalConstructor()->getMock(); $logger = $this->getMockBuilder(LoggerInterface::class)->disableOriginalConstructor()->getMock(); $converter = $this->createMock(Converter::class); - /** @var SyncService | \PHPUnit\Framework\MockObject\MockObject $ss */ + /** @var SyncService | MockObject $ss */ $ss = $this->getMockBuilder(SyncService::class) - ->setMethods(['ensureSystemAddressBookExists', 'requestSyncReport', 'download', 'getCertPath']) + ->onlyMethods(['ensureSystemAddressBookExists', 'requestSyncReport', 'download', 'getCertPath']) ->setConstructorArgs([$backend, $userManager, $logger, $converter]) ->getMock(); $ss->method('requestSyncReport')->withAnyParameters()->willReturn(['response' => $response, 'token' => 'sync-token-1']); diff --git a/apps/dav/tests/unit/Command/DeleteCalendarTest.php b/apps/dav/tests/unit/Command/DeleteCalendarTest.php index db0ee31f6be4e..a23303a7eaa41 100644 --- a/apps/dav/tests/unit/Command/DeleteCalendarTest.php +++ b/apps/dav/tests/unit/Command/DeleteCalendarTest.php @@ -24,6 +24,7 @@ namespace OCA\DAV\Tests\Command; +use InvalidArgumentException; use OCA\DAV\CalDAV\BirthdayService; use OCA\DAV\CalDav\CalDavBackend; use OCA\DAV\Command\DeleteCalendar; @@ -47,12 +48,6 @@ class DeleteCalendarTest extends TestCase { /** @var CalDavBackend|MockObject */ private $calDav; - /** @var IConfig|MockObject */ - private $config; - - /** @var IL10N|MockObject */ - private $l10n; - /** @var IUserManager|MockObject */ private $userManager; @@ -66,22 +61,22 @@ protected function setUp(): void { parent::setUp(); $this->calDav = $this->createMock(CalDavBackend::class); - $this->config = $this->createMock(IConfig::class); - $this->l10n = $this->createMock(IL10N::class); + $config = $this->createMock(IConfig::class); + $l10n = $this->createMock(IL10N::class); $this->userManager = $this->createMock(IUserManager::class); $this->logger = $this->createMock(LoggerInterface::class); $this->command = new DeleteCalendar( $this->calDav, - $this->config, - $this->l10n, + $config, + $l10n, $this->userManager, $this->logger ); } public function testInvalidUser() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'User <' . self::USER . '> is unknown.'); @@ -98,7 +93,7 @@ public function testInvalidUser() { } public function testNoCalendarName() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'Please specify a calendar name or --birthday'); @@ -114,7 +109,7 @@ public function testNoCalendarName() { } public function testInvalidCalendar() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage( 'User <' . self::USER . '> has no calendar named <' . self::NAME . '>.'); diff --git a/apps/dav/tests/unit/Command/ListCalendarsTest.php b/apps/dav/tests/unit/Command/ListCalendarsTest.php index 6f200da01bf14..43b4f183e4efc 100644 --- a/apps/dav/tests/unit/Command/ListCalendarsTest.php +++ b/apps/dav/tests/unit/Command/ListCalendarsTest.php @@ -26,10 +26,13 @@ */ namespace OCA\DAV\Tests\Command; +use InvalidArgumentException; use OCA\DAV\CalDAV\BirthdayService; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\Command\ListCalendars; +use OCA\DAV\DAV\Sharing\Plugin; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; use Symfony\Component\Console\Tester\CommandTester; use Test\TestCase; @@ -40,10 +43,10 @@ */ class ListCalendarsTest extends TestCase { - /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject $userManager */ + /** @var IUserManager|MockObject $userManager */ private $userManager; - /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject $l10n */ + /** @var CalDavBackend|MockObject $l10n */ private $calDav; /** @var ListCalendars */ @@ -64,7 +67,7 @@ protected function setUp(): void { } public function testWithBadUser() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->userManager->expects($this->once()) ->method('userExists') @@ -96,7 +99,7 @@ public function testWithCorrectUserWithNoCalendars() { $this->assertStringContainsString("User <" . self::USERNAME . "> has no calendars\n", $commandTester->getDisplay()); } - public function dataExecute() { + public function dataExecute(): array { return [ [false, '✓'], [true, 'x'] @@ -120,11 +123,11 @@ public function testWithCorrectUser(bool $readOnly, string $output) { 'uri' => BirthdayService::BIRTHDAY_CALENDAR_URI, ], [ - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}read-only' => $readOnly, + '{' . Plugin::NS_OWNCLOUD . '}read-only' => $readOnly, 'uri' => 'test', '{DAV:}displayname' => 'dp', - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_OWNCLOUD . '}owner-principal' => 'owner-principal', - '{' . \OCA\DAV\DAV\Sharing\Plugin::NS_NEXTCLOUD . '}owner-displayname' => 'owner-dp', + '{' . Plugin::NS_OWNCLOUD . '}owner-principal' => 'owner-principal', + '{' . Plugin::NS_NEXTCLOUD . '}owner-displayname' => 'owner-dp', ] ]); diff --git a/apps/dav/tests/unit/Command/MoveCalendarTest.php b/apps/dav/tests/unit/Command/MoveCalendarTest.php index 5a858e140ac7e..364fa8687fd79 100644 --- a/apps/dav/tests/unit/Command/MoveCalendarTest.php +++ b/apps/dav/tests/unit/Command/MoveCalendarTest.php @@ -46,53 +46,44 @@ */ class MoveCalendarTest extends TestCase { - /** @var \OCP\IUserManager|MockObject $userManager */ + /** @var IUserManager|MockObject $userManager */ private $userManager; - /** @var \OCP\IGroupManager|MockObject $groupManager */ + /** @var IGroupManager|MockObject $groupManager */ private $groupManager; - /** @var \OCP\Share\IManager|MockObject $shareManager */ + /** @var IManager|MockObject $shareManager */ private $shareManager; - /** @var IConfig|MockObject $l10n */ - private $config; - - /** @var IL10N|MockObject $l10n */ - private $l10n; - /** @var CalDavBackend|MockObject $l10n */ private $calDav; /** @var MoveCalendar */ private $command; - /** @var LoggerInterface|MockObject */ - private $logger; - protected function setUp(): void { parent::setUp(); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->shareManager = $this->createMock(IManager::class); - $this->config = $this->createMock(IConfig::class); - $this->l10n = $this->createMock(IL10N::class); + $config = $this->createMock(IConfig::class); + $l10n = $this->createMock(IL10N::class); $this->calDav = $this->createMock(CalDavBackend::class); - $this->logger = $this->createMock(LoggerInterface::class); + $logger = $this->createMock(LoggerInterface::class); $this->command = new MoveCalendar( $this->userManager, $this->groupManager, $this->shareManager, - $this->config, - $this->l10n, + $config, + $l10n, $this->calDav, - $this->logger + $logger ); } - public function dataExecute() { + public function dataExecute(): array { return [ [false, true], [true, false] @@ -105,19 +96,24 @@ public function dataExecute() { * @param $userOriginExists * @param $userDestinationExists */ - public function testWithBadUserOrigin($userOriginExists, $userDestinationExists) { - $this->expectException(\InvalidArgumentException::class); - - $this->userManager->expects($this->at(0)) - ->method('userExists') - ->with('user') - ->willReturn($userOriginExists); + public function testWithBadUserOrigin(bool $userOriginExists, bool $userDestinationExists) { + $this->expectException(InvalidArgumentException::class); - if (!$userDestinationExists) { - $this->userManager->expects($this->at(1)) + if ($userDestinationExists) { + $this->userManager->expects($this->once()) + ->method('userExists') + ->with('user') + ->willReturn($userOriginExists); + } else { + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user2') - ->willReturn($userDestinationExists); + ->withConsecutive( + ['user'], + ['user2'] + ) + ->willReturnOnConsecutiveCalls( + $userOriginExists, $userDestinationExists + ); } $commandTester = new CommandTester($this->command); @@ -130,17 +126,12 @@ public function testWithBadUserOrigin($userOriginExists, $userDestinationExists) public function testMoveWithInexistantCalendar() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('User has no calendar named . You can run occ dav:list-calendars to list calendars URIs for this user.'); - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user') - ->willReturn(true); - - $this->userManager->expects($this->at(1)) - ->method('userExists') - ->with('user2') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); $this->calDav->expects($this->once())->method('getCalendarByUri') @@ -157,27 +148,19 @@ public function testMoveWithInexistantCalendar() { public function testMoveWithExistingDestinationCalendar() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->expectExceptionMessage('User already has a calendar named .'); - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); - $this->userManager->expects($this->at(1)) - ->method('userExists') - ->with('user2') - ->willReturn(true); - - $this->calDav->expects($this->at(0))->method('getCalendarByUri') - ->with('principals/users/user', 'personal') - ->willReturn([ - 'id' => 1234, - ]); - - $this->calDav->expects($this->at(1))->method('getCalendarByUri') - ->with('principals/users/user2', 'personal') + $this->calDav->expects($this->exactly(2))->method('getCalendarByUri') + ->withConsecutive( + ['principals/users/user', 'personal'], + ['principals/users/user2', 'personal'] + ) ->willReturn([ 'id' => 1234, ]); @@ -191,25 +174,19 @@ public function testMoveWithExistingDestinationCalendar() { } public function testMove() { - $this->userManager->expects($this->at(0)) - ->method('userExists') - ->with('user') - ->willReturn(true); - - $this->userManager->expects($this->at(1)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user2') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); - $this->calDav->expects($this->at(0))->method('getCalendarByUri') - ->with('principals/users/user', 'personal') - ->willReturn([ + $this->calDav->expects($this->exactly(2))->method('getCalendarByUri') + ->withConsecutive( + ['principals/users/user', 'personal'], + ['principals/users/user2', 'personal'] + ) + ->willReturnOnConsecutiveCalls([ 'id' => 1234, - ]); - - $this->calDav->expects($this->at(1))->method('getCalendarByUri') - ->with('principals/users/user2', 'personal') - ->willReturn(null); + ], null); $this->calDav->expects($this->once())->method('getShares') ->with(1234) @@ -236,26 +213,20 @@ public function dataTestMoveWithDestinationNotPartOfGroup(): array { * @dataProvider dataTestMoveWithDestinationNotPartOfGroup */ public function testMoveWithDestinationNotPartOfGroup(bool $shareWithGroupMembersOnly) { - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); - $this->userManager->expects($this->at(1)) - ->method('userExists') - ->with('user2') - ->willReturn(true); - - $this->calDav->expects($this->at(0))->method('getCalendarByUri') - ->with('principals/users/user', 'personal') - ->willReturn([ + $this->calDav->expects($this->exactly(2))->method('getCalendarByUri') + ->withConsecutive( + ['principals/users/user', 'personal'], + ['principals/users/user2', 'personal'] + ) + ->willReturnOnConsecutiveCalls([ 'id' => 1234, 'uri' => 'personal' - ]); - - $this->calDav->expects($this->at(1))->method('getCalendarByUri') - ->with('principals/users/user2', 'personal') - ->willReturn(null); + ], null); $this->shareManager->expects($this->once())->method('shareWithGroupMembersOnly') ->willReturn($shareWithGroupMembersOnly); @@ -279,26 +250,20 @@ public function testMoveWithDestinationNotPartOfGroup(bool $shareWithGroupMember } public function testMoveWithDestinationPartOfGroup() { - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); - $this->userManager->expects($this->at(1)) - ->method('userExists') - ->with('user2') - ->willReturn(true); - - $this->calDav->expects($this->at(0))->method('getCalendarByUri') - ->with('principals/users/user', 'personal') - ->willReturn([ + $this->calDav->expects($this->exactly(2))->method('getCalendarByUri') + ->withConsecutive( + ['principals/users/user', 'personal'], + ['principals/users/user2', 'personal'] + ) + ->willReturnOnConsecutiveCalls([ 'id' => 1234, 'uri' => 'personal' - ]); - - $this->calDav->expects($this->at(1))->method('getCalendarByUri') - ->with('principals/users/user2', 'personal') - ->willReturn(null); + ], null); $this->shareManager->expects($this->once())->method('shareWithGroupMembersOnly') ->willReturn(true); @@ -324,27 +289,21 @@ public function testMoveWithDestinationPartOfGroup() { } public function testMoveWithDestinationNotPartOfGroupAndForce() { - $this->userManager->expects($this->at(0)) - ->method('userExists') - ->with('user') - ->willReturn(true); - - $this->userManager->expects($this->at(1)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user2') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); - $this->calDav->expects($this->at(0))->method('getCalendarByUri') - ->with('principals/users/user', 'personal') - ->willReturn([ + $this->calDav->expects($this->exactly(2))->method('getCalendarByUri') + ->withConsecutive( + ['principals/users/user', 'personal'], + ['principals/users/user2', 'personal'] + ) + ->willReturnOnConsecutiveCalls([ 'id' => 1234, 'uri' => 'personal', '{DAV:}displayname' => 'Personal' - ]); - - $this->calDav->expects($this->at(1))->method('getCalendarByUri') - ->with('principals/users/user2', 'personal') - ->willReturn(null); + ], null); $this->shareManager->expects($this->once())->method('shareWithGroupMembersOnly') ->willReturn(true); @@ -381,27 +340,21 @@ public function dataTestMoveWithCalendarAlreadySharedToDestination(): array { * @dataProvider dataTestMoveWithCalendarAlreadySharedToDestination */ public function testMoveWithCalendarAlreadySharedToDestination(bool $force) { - $this->userManager->expects($this->at(0)) - ->method('userExists') - ->with('user') - ->willReturn(true); - - $this->userManager->expects($this->at(1)) + $this->userManager->expects($this->exactly(2)) ->method('userExists') - ->with('user2') + ->withConsecutive(['user'], ['user2']) ->willReturn(true); - $this->calDav->expects($this->at(0))->method('getCalendarByUri') - ->with('principals/users/user', 'personal') - ->willReturn([ + $this->calDav->expects($this->exactly(2))->method('getCalendarByUri') + ->withConsecutive( + ['principals/users/user', 'personal'], + ['principals/users/user2', 'personal'] + ) + ->willReturnOnConsecutiveCalls([ 'id' => 1234, 'uri' => 'personal', - '{DAV:}displayname' => 'Personal', - ]); - - $this->calDav->expects($this->at(1))->method('getCalendarByUri') - ->with('principals/users/user2', 'personal') - ->willReturn(null); + '{DAV:}displayname' => 'Personal' + ], null); $this->calDav->expects($this->once())->method('getShares') ->with(1234) diff --git a/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php b/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php index 61c79a32c12f7..02f3400d7e0f1 100644 --- a/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php +++ b/apps/dav/tests/unit/Command/RemoveInvalidSharesTest.php @@ -22,10 +22,14 @@ */ namespace OCA\DAV\Tests\Unit\Command; +use OC; use OCA\DAV\Command\RemoveInvalidShares; use OCA\DAV\Connector\Sabre\Principal; use OCP\IDBConnection; use OCP\Migration\IOutput; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Test\TestCase; @@ -37,9 +41,13 @@ * @group DB */ class RemoveInvalidSharesTest extends TestCase { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { parent::setUp(); - $db = \OC::$server->get(IDBConnection::class); + $db = OC::$server->get(IDBConnection::class); $db->insertIfNotExist('*PREFIX*dav_shares', [ 'principaluri' => 'principal:unknown', @@ -49,13 +57,17 @@ protected function setUp(): void { ]); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ public function test() { - $db = \OC::$server->get(IDBConnection::class); - /** @var Principal | \PHPUnit\Framework\MockObject\MockObject $principal */ + $db = OC::$server->get(IDBConnection::class); + /** @var Principal | MockObject $principal */ $principal = $this->createMock(Principal::class); - /** @var IOutput | \PHPUnit\Framework\MockObject\MockObject $output */ - $output = $this->createMock(IOutput::class); + /** @var IOutput | MockObject $output */ + $this->createMock(IOutput::class); $repair = new RemoveInvalidShares($db, $principal); $this->invokePrivate($repair, 'run', [$this->createMock(InputInterface::class), $this->createMock(OutputInterface::class)]); @@ -65,6 +77,6 @@ public function test() { ->where($query->expr()->eq('principaluri', $query->createNamedParameter('principal:unknown')))->execute(); $data = $result->fetchAll(); $result->closeCursor(); - $this->assertEquals(0, count($data)); + $this->assertCount(0, $data); } } diff --git a/apps/dav/tests/unit/Comments/CommentsNodeTest.php b/apps/dav/tests/unit/Comments/CommentsNodeTest.php index ea3a1952e45e9..75fdd2be04137 100644 --- a/apps/dav/tests/unit/Comments/CommentsNodeTest.php +++ b/apps/dav/tests/unit/Comments/CommentsNodeTest.php @@ -26,6 +26,9 @@ */ namespace OCA\DAV\Tests\unit\Comments; +use DateInterval; +use DateTime; +use Exception; use OCA\DAV\Comments\CommentNode; use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; @@ -33,38 +36,42 @@ use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\PropPatch; +use Test\TestCase; -class CommentsNodeTest extends \Test\TestCase { +class CommentsNodeTest extends TestCase { - /** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ICommentsManager|MockObject */ protected $commentsManager; + /** @var IComment|MockObject */ protected $comment; + + /** @var CommentNode */ protected $node; + + /** @var IUserManager|MockObject */ protected $userManager; + + /** @var LoggerInterface|MockObject */ protected $logger; + + /** @var IUserSession|MockObject */ protected $userSession; protected function setUp(): void { parent::setUp(); - $this->commentsManager = $this->getMockBuilder(ICommentsManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->comment = $this->getMockBuilder(IComment::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->commentsManager = $this->createMock(ICommentsManager::class); + $this->comment = $this->createMock(IComment::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->logger = $this->createMock(LoggerInterface::class); $this->node = new CommentNode( $this->commentsManager, @@ -76,10 +83,7 @@ protected function setUp(): void { } public function testDelete() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); @@ -109,12 +113,9 @@ public function testDelete() { public function testDeleteForbidden() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); - - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $this->expectException(Forbidden::class); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('mallory'); @@ -151,22 +152,22 @@ public function testGetName() { public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->node->setName('666'); } public function testGetLastModified() { - $this->assertSame($this->node->getLastModified(), null); + $this->assertNull($this->node->getLastModified()); } + /** + * @throws BadRequest + */ public function testUpdateComment() { $msg = 'Hello Earth'; - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); @@ -195,16 +196,16 @@ public function testUpdateComment() { } + /** + * @throws BadRequest + */ public function testUpdateCommentLogException() { - $this->expectException(\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('buh!'); $msg = null; - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); @@ -216,7 +217,7 @@ public function testUpdateCommentLogException() { $this->comment->expects($this->once()) ->method('setMessage') ->with($msg) - ->will($this->throwException(new \Exception('buh!'))); + ->will($this->throwException(new Exception('buh!'))); $this->comment->expects($this->any()) ->method('getActorType') @@ -237,13 +238,10 @@ public function testUpdateCommentLogException() { public function testUpdateCommentMessageTooLongException() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('Message exceeds allowed character limit of'); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); @@ -275,15 +273,15 @@ public function testUpdateCommentMessageTooLongException() { } + /** + * @throws BadRequest + */ public function testUpdateForbiddenByUser() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $msg = 'HaXX0r'; - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('mallory'); @@ -310,15 +308,15 @@ public function testUpdateForbiddenByUser() { } + /** + * @throws BadRequest + */ public function testUpdateForbiddenByType() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $msg = 'HaXX0r'; - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - + $user = $this->createMock(IUser::class); $user->expects($this->never()) ->method('getUID'); @@ -340,8 +338,11 @@ public function testUpdateForbiddenByType() { } + /** + * @throws BadRequest + */ public function testUpdateForbiddenByNotLoggedIn() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $msg = 'HaXX0r'; @@ -363,10 +364,7 @@ public function testUpdateForbiddenByNotLoggedIn() { } public function testPropPatch() { - $propPatch = $this->getMockBuilder(PropPatch::class) - ->disableOriginalConstructor() - ->getMock(); - + $propPatch = $this->createMock(PropPatch::class); $propPatch->expects($this->once()) ->method('handle') ->with('{http://owncloud.org/ns}message'); @@ -398,8 +396,8 @@ public function testGetProperties() { $ns . 'actorType' => 'users', $ns . 'actorId' => 'alice', $ns . 'actorDisplayName' => 'Alice of Wonderland', - $ns . 'creationDateTime' => new \DateTime('2016-01-10 18:48:00'), - $ns . 'latestChildDateTime' => new \DateTime('2016-01-12 18:48:00'), + $ns . 'creationDateTime' => new DateTime('2016-01-10 18:48:00'), + $ns . 'latestChildDateTime' => new DateTime('2016-01-12 18:48:00'), $ns . 'objectType' => 'files', $ns . 'objectId' => '1848', $ns . 'referenceId' => 'ref', @@ -474,9 +472,7 @@ public function testGetProperties() { ->method('getReferenceId') ->willReturn($expected[$ns . 'referenceId']); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getDisplayName') ->willReturn($expected[$ns . 'actorDisplayName']); @@ -493,28 +489,27 @@ public function testGetProperties() { $this->assertSame($expected[$name], $value); unset($expected[$name]); } - $this->assertTrue(empty($expected)); + $this->assertEmpty($expected); } - public function readCommentProvider() { - $creationDT = new \DateTime('2016-01-19 18:48:00'); - $diff = new \DateInterval('PT2H'); + public function readCommentProvider(): array { + $creationDT = new DateTime('2016-01-19 18:48:00'); + $diff = new DateInterval('PT2H'); $readDT1 = clone $creationDT; $readDT1->sub($diff); $readDT2 = clone $creationDT; $readDT2->add($diff); return [ - [$creationDT, $readDT1, 'true'], - [$creationDT, $readDT2, 'false'], - [$creationDT, null, 'true'], + [$creationDT, $readDT1, true], + [$creationDT, $readDT2, false], + [$creationDT, null, true], ]; } /** * @dataProvider readCommentProvider - * @param $expected */ - public function testGetPropertiesUnreadProperty($creationDT, $readDT, $expected) { + public function testGetPropertiesUnreadProperty(DateTime $creationDT, ?DateTime $readDT, bool $expected) { $this->comment->expects($this->any()) ->method('getCreationDateTime') ->willReturn($creationDT); @@ -530,14 +525,12 @@ public function testGetPropertiesUnreadProperty($creationDT, $readDT, $expected) $this->userSession->expects($this->once()) ->method('getUser') ->willReturn( - $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(IUser::class) ); $properties = $this->node->getProperties(null); - $this->assertTrue(array_key_exists(CommentNode::PROPERTY_NAME_UNREAD, $properties)); - $this->assertSame($properties[CommentNode::PROPERTY_NAME_UNREAD], $expected); + $this->assertArrayHasKey(CommentNode::PROPERTY_NAME_UNREAD, $properties); + $this->assertSame($properties[CommentNode::PROPERTY_NAME_UNREAD], $expected ? 'true' : 'false'); } } diff --git a/apps/dav/tests/unit/Comments/CommentsPluginTest.php b/apps/dav/tests/unit/Comments/CommentsPluginTest.php index 5d05b278e1895..5bde6a0bdee60 100644 --- a/apps/dav/tests/unit/Comments/CommentsPluginTest.php +++ b/apps/dav/tests/unit/Comments/CommentsPluginTest.php @@ -26,29 +26,39 @@ */ namespace OCA\DAV\Tests\unit\Comments; +use DateTime; +use Exception; use OC\Comments\Comment; use OCA\DAV\Comments\CommentsPlugin as CommentsPluginImplementation; use OCA\DAV\Comments\EntityCollection; use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; +use OCP\Comments\IllegalIDChangeException; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\ReportNotSupported; +use Sabre\DAV\Exception\UnsupportedMediaType; use Sabre\DAV\INode; +use Sabre\DAV\Server; use Sabre\DAV\Tree; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; +use Test\TestCase; -class CommentsPluginTest extends \Test\TestCase { - /** @var \Sabre\DAV\Server */ +class CommentsPluginTest extends TestCase { + /** @var Server|MockObject */ private $server; - /** @var Tree */ + /** @var Tree|MockObject */ private $tree; - /** @var ICommentsManager */ + /** @var ICommentsManager|MockObject */ private $commentsManager; - /** @var IUserSession */ + /** @var IUserSession|MockObject */ private $userSession; /** @var CommentsPluginImplementation */ @@ -56,25 +66,21 @@ class CommentsPluginTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->tree = $this->getMockBuilder(Tree::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + $this->tree = $this->createMock(Tree::class); + $this->server = $this->getMockBuilder(Server::class) ->setConstructorArgs([$this->tree]) - ->setMethods(['getRequestUri']) + ->onlyMethods(['getRequestUri']) ->getMock(); - $this->commentsManager = $this->getMockBuilder(ICommentsManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); + $this->commentsManager = $this->createMock(ICommentsManager::class); + $this->userSession = $this->createMock(IUserSession::class); $this->plugin = new CommentsPluginImplementation($this->commentsManager, $this->userSession); } + /** + * @throws IllegalIDChangeException + */ public function testCreateComment() { $commentData = [ 'actorType' => 'users', @@ -94,16 +100,12 @@ public function testCreateComment() { $requestData = json_encode($commentData); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('getName') ->willReturn('files'); @@ -133,14 +135,8 @@ public function testCreateComment() { ->with('/' . $path) ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/' . $path); @@ -170,9 +166,12 @@ public function testCreateComment() { $this->plugin->httpPost($request, $response); } - + + /** + * @throws IllegalIDChangeException + */ public function testCreateCommentInvalidObject() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $commentData = [ 'actorType' => 'users', @@ -190,15 +189,11 @@ public function testCreateCommentInvalidObject() { $path = 'comments/files/666'; - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->never()) ->method('getUID'); - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->never()) ->method('getName'); $node->expects($this->never()) @@ -217,16 +212,10 @@ public function testCreateCommentInvalidObject() { $this->tree->expects($this->any()) ->method('getNodeForPath') ->with('/' . $path) - ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); - - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->will($this->throwException(new NotFound())); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/' . $path); @@ -252,9 +241,12 @@ public function testCreateCommentInvalidObject() { $this->plugin->httpPost($request, $response); } - + + /** + * @throws IllegalIDChangeException + */ public function testCreateCommentInvalidActor() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $commentData = [ 'actorType' => 'robots', @@ -274,15 +266,11 @@ public function testCreateCommentInvalidActor() { $requestData = json_encode($commentData); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->never()) ->method('getUID'); - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('getName') ->willReturn('files'); @@ -305,14 +293,8 @@ public function testCreateCommentInvalidActor() { ->with('/' . $path) ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/' . $path); @@ -340,9 +322,12 @@ public function testCreateCommentInvalidActor() { $this->plugin->httpPost($request, $response); } - + + /** + * @throws IllegalIDChangeException + */ public function testCreateCommentUnsupportedMediaType() { - $this->expectException(\Sabre\DAV\Exception\UnsupportedMediaType::class); + $this->expectException(UnsupportedMediaType::class); $commentData = [ 'actorType' => 'users', @@ -362,15 +347,11 @@ public function testCreateCommentUnsupportedMediaType() { $requestData = json_encode($commentData); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->never()) ->method('getUID'); - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('getName') ->willReturn('files'); @@ -393,14 +374,8 @@ public function testCreateCommentUnsupportedMediaType() { ->with('/' . $path) ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/' . $path); @@ -428,9 +403,12 @@ public function testCreateCommentUnsupportedMediaType() { $this->plugin->httpPost($request, $response); } - + + /** + * @throws IllegalIDChangeException + */ public function testCreateCommentInvalidPayload() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $commentData = [ 'actorType' => 'users', @@ -452,16 +430,12 @@ public function testCreateCommentInvalidPayload() { $requestData = json_encode($commentData); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('getName') ->willReturn('files'); @@ -487,14 +461,8 @@ public function testCreateCommentInvalidPayload() { ->with('/' . $path) ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/' . $path); @@ -522,9 +490,12 @@ public function testCreateCommentInvalidPayload() { $this->plugin->httpPost($request, $response); } - + + /** + * @throws IllegalIDChangeException + */ public function testCreateCommentMessageTooLong() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('Message exceeds allowed character limit of'); $commentData = [ @@ -546,16 +517,12 @@ public function testCreateCommentMessageTooLong() { $requestData = json_encode($commentData); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('alice'); - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('getName') ->willReturn('files'); @@ -584,14 +551,8 @@ public function testCreateCommentMessageTooLong() { ->with('/' . $path) ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/' . $path); @@ -616,9 +577,12 @@ public function testCreateCommentMessageTooLong() { $this->plugin->httpPost($request, $response); } - + + /** + * @throws NotFound + */ public function testOnReportInvalidNode() { - $this->expectException(\Sabre\DAV\Exception\ReportNotSupported::class); + $this->expectException(ReportNotSupported::class); $path = 'totally/unrelated/13'; @@ -626,9 +590,7 @@ public function testOnReportInvalidNode() { ->method('getNodeForPath') ->with('/' . $path) ->willReturn( - $this->getMockBuilder(INode::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(INode::class) ); $this->server->expects($this->any()) @@ -639,9 +601,12 @@ public function testOnReportInvalidNode() { $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, [], '/' . $path); } - + + /** + * @throws NotFound + */ public function testOnReportInvalidReportName() { - $this->expectException(\Sabre\DAV\Exception\ReportNotSupported::class); + $this->expectException(ReportNotSupported::class); $path = 'comments/files/42'; @@ -649,9 +614,7 @@ public function testOnReportInvalidReportName() { ->method('getNodeForPath') ->with('/' . $path) ->willReturn( - $this->getMockBuilder(INode::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(INode::class) ); $this->server->expects($this->any()) @@ -662,6 +625,10 @@ public function testOnReportInvalidReportName() { $this->plugin->onReport('{whoever}whatever', [], '/' . $path); } + /** + * @throws ReportNotSupported + * @throws NotFound + */ public function testOnReportDateTimeEmpty() { $path = 'comments/files/42'; @@ -680,18 +647,13 @@ public function testOnReportDateTimeEmpty() { ] ]; - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('findChildren') ->with(5, 10, null) ->willReturn([]); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('setHeader') ->with('Content-Type', 'application/xml; charset=utf-8'); @@ -717,6 +679,11 @@ public function testOnReportDateTimeEmpty() { $this->plugin->onReport(CommentsPluginImplementation::REPORT_NAME, $parameters, '/' . $path); } + /** + * @throws ReportNotSupported + * @throws NotFound + * @throws Exception + */ public function testOnReport() { $path = 'comments/files/42'; @@ -735,18 +702,13 @@ public function testOnReport() { ] ]; - $node = $this->getMockBuilder(EntityCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(EntityCollection::class); $node->expects($this->once()) ->method('findChildren') - ->with(5, 10, new \DateTime($parameters[2]['value'])) + ->with(5, 10, new DateTime($parameters[2]['value'])) ->willReturn([]); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('setHeader') ->with('Content-Type', 'application/xml; charset=utf-8'); diff --git a/apps/dav/tests/unit/Comments/EntityCollectionTest.php b/apps/dav/tests/unit/Comments/EntityCollectionTest.php index f95dbf839ee8f..53599be94cf5d 100644 --- a/apps/dav/tests/unit/Comments/EntityCollectionTest.php +++ b/apps/dav/tests/unit/Comments/EntityCollectionTest.php @@ -25,43 +25,41 @@ */ namespace OCA\DAV\Tests\unit\Comments; +use DateTime; +use OCA\DAV\Comments\CommentNode; use OCA\DAV\Comments\EntityCollection; use OCP\Comments\IComment; use OCP\Comments\ICommentsManager; +use OCP\Comments\NotFoundException; use OCP\IUserManager; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class EntityCollectionTest extends \Test\TestCase { +class EntityCollectionTest extends TestCase { - /** @var \OCP\Comments\ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ICommentsManager|MockObject */ protected $commentsManager; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ protected $userManager; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; /** @var EntityCollection */ protected $collection; - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserSession|MockObject */ protected $userSession; protected function setUp(): void { parent::setUp(); - $this->commentsManager = $this->getMockBuilder(ICommentsManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->collection = new \OCA\DAV\Comments\EntityCollection( + $this->commentsManager = $this->createMock(ICommentsManager::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->logger = $this->createMock(LoggerInterface::class); + + $this->collection = new EntityCollection( '19', 'files', $this->commentsManager, @@ -72,31 +70,32 @@ protected function setUp(): void { } public function testGetId() { - $this->assertSame($this->collection->getId(), '19'); + $this->assertSame('19', $this->collection->getId()); } + /** + * @throws NotFound + */ public function testGetChild() { $this->commentsManager->expects($this->once()) ->method('get') ->with('55') ->willReturn( - $this->getMockBuilder(IComment::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(IComment::class) ); $node = $this->collection->getChild('55'); - $this->assertTrue($node instanceof \OCA\DAV\Comments\CommentNode); + $this->assertTrue($node instanceof CommentNode); } public function testGetChildException() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->commentsManager->expects($this->once()) ->method('get') ->with('55') - ->will($this->throwException(new \OCP\Comments\NotFoundException())); + ->will($this->throwException(new NotFoundException())); $this->collection->getChild('55'); } @@ -106,32 +105,28 @@ public function testGetChildren() { ->method('getForObject') ->with('files', '19') ->willReturn([ - $this->getMockBuilder(IComment::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(IComment::class) ]); $result = $this->collection->getChildren(); - $this->assertSame(count($result), 1); - $this->assertTrue($result[0] instanceof \OCA\DAV\Comments\CommentNode); + $this->assertCount(1, $result); + $this->assertTrue($result[0] instanceof CommentNode); } public function testFindChildren() { - $dt = new \DateTime('2016-01-10 18:48:00'); + $dt = new DateTime('2016-01-10 18:48:00'); $this->commentsManager->expects($this->once()) ->method('getForObject') ->with('files', '19', 5, 15, $dt) ->willReturn([ - $this->getMockBuilder(IComment::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(IComment::class) ]); $result = $this->collection->findChildren(5, 15, $dt); - $this->assertSame(count($result), 1); - $this->assertTrue($result[0] instanceof \OCA\DAV\Comments\CommentNode); + $this->assertCount(1, $result); + $this->assertTrue($result[0] instanceof CommentNode); } public function testChildExistsTrue() { @@ -142,7 +137,7 @@ public function testChildExistsFalse() { $this->commentsManager->expects($this->once()) ->method('get') ->with('44') - ->will($this->throwException(new \OCP\Comments\NotFoundException())); + ->will($this->throwException(new NotFoundException())); $this->assertFalse($this->collection->childExists('44')); } diff --git a/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php b/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php index 89f84fb6ad422..70035f9c0a418 100644 --- a/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php +++ b/apps/dav/tests/unit/Comments/EntityTypeCollectionTest.php @@ -25,22 +25,27 @@ namespace OCA\DAV\Tests\unit\Comments; use OCA\DAV\Comments\EntityCollection as EntityCollectionImplemantation; +use OCA\DAV\Comments\EntityTypeCollection; use OCP\Comments\ICommentsManager; use OCP\IUserManager; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class EntityTypeCollectionTest extends \Test\TestCase { +class EntityTypeCollectionTest extends TestCase { - /** @var ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ICommentsManager|MockObject */ protected $commentsManager; - /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ protected $userManager; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var \OCA\DAV\Comments\EntityTypeCollection */ + /** @var EntityTypeCollection */ protected $collection; - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserSession|MockObject */ protected $userSession; protected $childMap = []; @@ -48,22 +53,14 @@ class EntityTypeCollectionTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->commentsManager = $this->getMockBuilder(ICommentsManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $this->commentsManager = $this->createMock(ICommentsManager::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->logger = $this->createMock(LoggerInterface::class); $instance = $this; - $this->collection = new \OCA\DAV\Comments\EntityTypeCollection( + $this->collection = new EntityTypeCollection( 'files', $this->commentsManager, $this->userManager, @@ -84,6 +81,9 @@ public function testChildExistsNo() { $this->assertFalse($this->collection->childExists('17')); } + /** + * @throws NotFound + */ public function testGetChild() { $this->childMap[17] = true; @@ -93,14 +93,14 @@ public function testGetChild() { public function testGetChildException() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->collection->getChild('17'); } public function testGetChildren() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->collection->getChildren(); } diff --git a/apps/dav/tests/unit/Comments/RootCollectionTest.php b/apps/dav/tests/unit/Comments/RootCollectionTest.php index 51777c96db7c1..e28d6fd056cdc 100644 --- a/apps/dav/tests/unit/Comments/RootCollectionTest.php +++ b/apps/dav/tests/unit/Comments/RootCollectionTest.php @@ -25,57 +25,56 @@ */ namespace OCA\DAV\Tests\unit\Comments; +use OC; use OCA\DAV\Comments\EntityTypeCollection as EntityTypeCollectionImplementation; +use OCA\DAV\Comments\RootCollection; use OCP\Comments\CommentsEntityEvent; use OCP\Comments\ICommentsManager; use OCP\EventDispatcher\IEventDispatcher; use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; -use Symfony\Component\EventDispatcher\EventDispatcherInterface; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotAuthenticated; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class RootCollectionTest extends \Test\TestCase { +class RootCollectionTest extends TestCase { - /** @var \OCP\Comments\ICommentsManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ICommentsManager|MockObject */ protected $commentsManager; - /** @var \OCP\IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ protected $userManager; - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ protected $logger; - /** @var \OCA\DAV\Comments\RootCollection */ + /** @var RootCollection */ protected $collection; - /** @var \OCP\IUserSession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserSession|MockObject */ protected $userSession; - /** @var EventDispatcherInterface */ + /** @var IEventDispatcher|IEventDispatcher */ protected $dispatcher; - /** @var \OCP\IUser|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUser|MockObject */ protected $user; + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { parent::setUp(); - $this->user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->commentsManager = $this->getMockBuilder(ICommentsManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userManager = $this->getMockBuilder(IUserManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); - $this->logger = $this->getMockBuilder(LoggerInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $this->dispatcher = $this->getMockBuilder(IEventDispatcher::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->collection = new \OCA\DAV\Comments\RootCollection( + $this->user = $this->createMock(IUser::class); + $this->commentsManager = $this->createMock(ICommentsManager::class); + $this->userManager = $this->createMock(IUserManager::class); + $this->userSession = $this->createMock(IUserSession::class); + $this->logger = $this->createMock(LoggerInterface::class); + $this->dispatcher = OC::$server->get(IEventDispatcher::class); + + $this->collection = new RootCollection( $this->commentsManager, $this->userManager, $this->userSession, @@ -93,69 +92,89 @@ protected function prepareForInitCollections() { ->method('getUser') ->willReturn($this->user); + foreach ($this->dispatcher->getSymfonyDispatcher()->getListeners(CommentsEntityEvent::class) as $listener) { + $this->dispatcher->removeListener(CommentsEntityEvent::class, $listener); + } $this->dispatcher->addListener(CommentsEntityEvent::class, function (CommentsEntityEvent $event) { $event->addEntityCollection('files', function () { return true; }); - }); + }, 100); } - public function testCreateFile() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->collection->createFile('foo'); } public function testCreateDirectory() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->collection->createDirectory('foo'); } + /** + * @throws NotFound|NotAuthenticated + */ public function testGetChild() { $this->prepareForInitCollections(); $etc = $this->collection->getChild('files'); - $this->assertTrue($etc instanceof EntityTypeCollectionImplementation); + $this->assertInstanceOf(EntityTypeCollectionImplementation::class, $etc); } + /** + * @throws NotAuthenticated + */ public function testGetChildInvalid() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->prepareForInitCollections(); $this->collection->getChild('robots'); } + /** + * @throws NotFound + */ public function testGetChildNoAuth() { - $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class); + $this->expectException(NotAuthenticated::class); $this->collection->getChild('files'); } + /** + * @throws NotAuthenticated + */ public function testGetChildren() { $this->prepareForInitCollections(); $children = $this->collection->getChildren(); - $this->assertFalse(empty($children)); + $this->assertNotEmpty($children); foreach ($children as $child) { - $this->assertTrue($child instanceof EntityTypeCollectionImplementation); + $this->assertInstanceOf(EntityTypeCollectionImplementation::class, $child); } } public function testGetChildrenNoAuth() { - $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class); + $this->expectException(NotAuthenticated::class); $this->collection->getChildren(); } + /** + * @throws NotAuthenticated + */ public function testChildExistsYes() { $this->prepareForInitCollections(); $this->assertTrue($this->collection->childExists('files')); } + /** + * @throws NotAuthenticated + */ public function testChildExistsNo() { $this->prepareForInitCollections(); $this->assertFalse($this->collection->childExists('robots')); @@ -163,14 +182,14 @@ public function testChildExistsNo() { public function testChildExistsNoAuth() { - $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class); + $this->expectException(NotAuthenticated::class); $this->collection->childExists('files'); } public function testDelete() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->collection->delete(); } @@ -181,7 +200,7 @@ public function testGetName() { public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->collection->setName('foobar'); } diff --git a/apps/dav/tests/unit/Connector/PublicAuthTest.php b/apps/dav/tests/unit/Connector/PublicAuthTest.php index 89068c0e6effd..2fd4b10a92a9d 100644 --- a/apps/dav/tests/unit/Connector/PublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/PublicAuthTest.php @@ -27,11 +27,16 @@ namespace OCA\DAV\Tests\unit\Connector; use OC\Security\Bruteforce\Throttler; +use OC_User; +use OC_Util; +use OCA\DAV\Connector\PublicAuth; use OCP\IRequest; use OCP\ISession; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IShare; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; /** * Class PublicAuthTest @@ -40,18 +45,14 @@ * * @package OCA\DAV\Tests\unit\Connector */ -class PublicAuthTest extends \Test\TestCase { +class PublicAuthTest extends TestCase { - /** @var ISession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISession|MockObject */ private $session; - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IManager|MockObject */ private $shareManager; - /** @var \OCA\DAV\Connector\PublicAuth */ + /** @var PublicAuth */ private $auth; - /** @var Throttler|\PHPUnit\Framework\MockObject\MockObject */ - private $throttler; /** @var string */ private $oldUser; @@ -59,36 +60,28 @@ class PublicAuthTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->session = $this->getMockBuilder(ISession::class) - ->disableOriginalConstructor() - ->getMock(); - $this->request = $this->getMockBuilder(IRequest::class) - ->disableOriginalConstructor() - ->getMock(); - $this->shareManager = $this->getMockBuilder(IManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->throttler = $this->getMockBuilder(Throttler::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->auth = new \OCA\DAV\Connector\PublicAuth( - $this->request, + $this->session = $this->createMock(ISession::class); + $request = $this->createMock(IRequest::class); + $this->shareManager = $this->createMock(IManager::class); + $throttler = $this->createMock(Throttler::class); + + $this->auth = new PublicAuth( + $request, $this->shareManager, $this->session, - $this->throttler + $throttler ); // Store current user - $this->oldUser = \OC_User::getUser(); + $this->oldUser = OC_User::getUser(); } protected function tearDown(): void { - \OC_User::setIncognitoMode(false); + OC_User::setIncognitoMode(false); // Set old user - \OC_User::setUserId($this->oldUser); - \OC_Util::setupFS($this->oldUser); + OC_User::setUserId($this->oldUser); + OC_Util::setupFS($this->oldUser); parent::tearDown(); } @@ -104,9 +97,7 @@ public function testNoShare() { } public function testShareNoPassword() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn(null); $this->shareManager->expects($this->once()) @@ -119,9 +110,7 @@ public function testShareNoPassword() { } public function testSharePasswordFancyShareType() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(42); @@ -136,9 +125,7 @@ public function testSharePasswordFancyShareType() { public function testSharePasswordRemote() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(IShare::TYPE_REMOTE); @@ -152,9 +139,7 @@ public function testSharePasswordRemote() { } public function testSharePasswordLinkValidPassword() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(IShare::TYPE_LINK); @@ -174,9 +159,7 @@ public function testSharePasswordLinkValidPassword() { } public function testSharePasswordMailValidPassword() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(IShare::TYPE_EMAIL); @@ -196,9 +179,7 @@ public function testSharePasswordMailValidPassword() { } public function testSharePasswordLinkValidSession() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(IShare::TYPE_LINK); $share->method('getId')->willReturn('42'); @@ -222,9 +203,7 @@ public function testSharePasswordLinkValidSession() { } public function testSharePasswordLinkInvalidSession() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(IShare::TYPE_LINK); $share->method('getId')->willReturn('42'); @@ -249,9 +228,7 @@ public function testSharePasswordLinkInvalidSession() { public function testSharePasswordMailInvalidSession() { - $share = $this->getMockBuilder(IShare::class) - ->disableOriginalConstructor() - ->getMock(); + $share = $this->createMock(IShare::class); $share->method('getPassword')->willReturn('password'); $share->method('getShareType')->willReturn(IShare::TYPE_EMAIL); $share->method('getId')->willReturn('42'); diff --git a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php index 9355b34d66a37..40d9603cfbf9e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/AuthTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/AuthTest.php @@ -29,12 +29,18 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre; +use OC\Authentication\Exceptions\PasswordLoginForbiddenException; use OC\Authentication\TwoFactorAuth\Manager; use OC\Security\Bruteforce\Throttler; use OC\User\Session; +use OCA\DAV\Connector\Sabre\Auth; +use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden; use OCP\IRequest; use OCP\ISession; use OCP\IUser; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\NotAuthenticated; +use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\Server; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -49,7 +55,7 @@ class AuthTest extends TestCase { /** @var ISession */ private $session; - /** @var \OCA\DAV\Connector\Sabre\Auth */ + /** @var Auth */ private $auth; /** @var Session */ private $userSession; @@ -57,29 +63,20 @@ class AuthTest extends TestCase { private $request; /** @var Manager */ private $twoFactorManager; - /** @var Throttler */ - private $throttler; protected function setUp(): void { parent::setUp(); - $this->session = $this->getMockBuilder(ISession::class) - ->disableOriginalConstructor()->getMock(); - $this->userSession = $this->getMockBuilder(Session::class) - ->disableOriginalConstructor()->getMock(); - $this->request = $this->getMockBuilder(IRequest::class) - ->disableOriginalConstructor()->getMock(); - $this->twoFactorManager = $this->getMockBuilder(Manager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->throttler = $this->getMockBuilder(Throttler::class) - ->disableOriginalConstructor() - ->getMock(); - $this->auth = new \OCA\DAV\Connector\Sabre\Auth( + $this->session = $this->createMock(ISession::class); + $this->userSession = $this->createMock(Session::class); + $this->request = $this->createMock(IRequest::class); + $this->twoFactorManager = $this->createMock(Manager::class); + $throttler = $this->createMock(Throttler::class); + $this->auth = new Auth( $this->session, $this->userSession, $this->request, $this->twoFactorManager, - $this->throttler + $throttler ); } @@ -114,9 +111,7 @@ public function testIsDavAuthenticatedWithCorrectDavSession() { } public function testValidateUserPassOfAlreadyDAVAuthenticatedUser() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->exactly(2)) ->method('getUID') ->willReturn('MyTestUser'); @@ -141,9 +136,7 @@ public function testValidateUserPassOfAlreadyDAVAuthenticatedUser() { } public function testValidateUserPassOfInvalidDAVAuthenticatedUser() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->once()) ->method('getUID') ->willReturn('MyTestUser'); @@ -168,9 +161,7 @@ public function testValidateUserPassOfInvalidDAVAuthenticatedUser() { } public function testValidateUserPassOfInvalidDAVAuthenticatedUserWithValidPassword() { - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->exactly(3)) ->method('getUID') ->willReturn('MyTestUser'); @@ -220,9 +211,9 @@ public function testValidateUserPassWithInvalidPassword() { $this->assertFalse($this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword'])); } - + public function testValidateUserPassWithPasswordLoginForbidden() { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden::class); + $this->expectException(PasswordLoginForbidden::class); $this->userSession ->expects($this->once()) @@ -232,7 +223,7 @@ public function testValidateUserPassWithPasswordLoginForbidden() { ->expects($this->once()) ->method('logClientIn') ->with('MyTestUser', 'MyTestPassword') - ->will($this->throwException(new \OC\Authentication\Exceptions\PasswordLoginForbiddenException())); + ->will($this->throwException(new PasswordLoginForbiddenException())); $this->session ->expects($this->once()) ->method('close'); @@ -240,13 +231,13 @@ public function testValidateUserPassWithPasswordLoginForbidden() { $this->invokePrivate($this->auth, 'validateUserPass', ['MyTestUser', 'MyTestPassword']); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGet() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -260,9 +251,7 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGet() { ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn(null); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('MyWrongDavUser'); @@ -283,13 +272,13 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGet() { $this->assertSame($expectedResponse, $response); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndCorrectlyDavAuthenticated() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -312,9 +301,7 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndCorrectlyDavAu ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn('LoggedInUser'); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('LoggedInUser'); @@ -329,17 +316,16 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndCorrectlyDavAu $this->auth->check($request, $response); } - + + /** + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithoutTwoFactorChallengePassed() { - $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class); + $this->expectException(NotAuthenticated::class); $this->expectExceptionMessage('2FA challenge not passed.'); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -362,9 +348,7 @@ public function testAuthenticateAlreadyLoggedInWithoutTwoFactorChallengePassed() ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn('LoggedInUser'); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('LoggedInUser'); @@ -383,17 +367,16 @@ public function testAuthenticateAlreadyLoggedInWithoutTwoFactorChallengePassed() $this->auth->check($request, $response); } - + + /** + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndIncorrectlyDavAuthenticated() { - $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class); + $this->expectException(NotAuthenticated::class); $this->expectExceptionMessage('CSRF check not passed.'); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -416,9 +399,7 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndIncorrectlyDav ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn('AnotherUser'); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('LoggedInUser'); @@ -433,13 +414,13 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenAndIncorrectlyDav $this->auth->check($request, $response); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGetAndDesktopClient() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -462,9 +443,7 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGetAndDeskt ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn(null); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('MyWrongDavUser'); @@ -480,13 +459,13 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForNonGetAndDeskt $this->auth->check($request, $response); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForGet() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -496,9 +475,7 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForGet() { ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn(null); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('MyWrongDavUser'); @@ -515,13 +492,13 @@ public function testAuthenticateAlreadyLoggedInWithoutCsrfTokenForGet() { $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateAlreadyLoggedInWithCsrfTokenForGet() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -531,9 +508,7 @@ public function testAuthenticateAlreadyLoggedInWithCsrfTokenForGet() { ->method('get') ->with('AUTHENTICATED_TO_DAV_BACKEND') ->willReturn(null); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('MyWrongDavUser'); @@ -550,33 +525,30 @@ public function testAuthenticateAlreadyLoggedInWithCsrfTokenForGet() { $this->assertEquals([true, 'principals/users/MyWrongDavUser'], $response); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateNoBasicAuthenticateHeadersProvided() { - $server = $this->getMockBuilder(Server::class) - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $server->httpResponse = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $server = $this->createMock(Server::class); + $server->httpRequest = $this->createMock(RequestInterface::class); + $server->httpResponse = $this->createMock(ResponseInterface::class); $response = $this->auth->check($server->httpRequest, $server->httpResponse); $this->assertEquals([false, 'No \'Authorization: Basic\' header found. Either the client didn\'t send one, or the server is misconfigured'], $response); } - + + /** + * @throws ServiceUnavailable + */ public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjax() { - $this->expectException(\Sabre\DAV\Exception\NotAuthenticated::class); + $this->expectException(NotAuthenticated::class); $this->expectExceptionMessage('Cannot authenticate over ajax calls'); - /** @var \Sabre\HTTP\RequestInterface $httpRequest */ - $httpRequest = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ - $httpResponse = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var RequestInterface|MockObject $httpRequest */ + $httpRequest = $this->createMock(RequestInterface::class); + /** @var ResponseInterface|MockObject $httpResponse */ + $httpResponse = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->any()) ->method('isLoggedIn') @@ -589,19 +561,17 @@ public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjax() { $this->auth->check($httpRequest, $httpResponse); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjaxButUserIsStillLoggedIn() { - /** @var \Sabre\HTTP\RequestInterface $httpRequest */ - $httpRequest = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var \Sabre\HTTP\ResponseInterface $httpResponse */ - $httpResponse = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var RequestInterface|MockObject $httpRequest */ + $httpRequest = $this->createMock(RequestInterface::class); + /** @var ResponseInterface|MockObject $httpResponse */ + $httpResponse = $this->createMock(ResponseInterface::class); /** @var IUser */ - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->method('getUID')->willReturn('MyTestUser'); $this->userSession ->expects($this->any()) @@ -631,34 +601,30 @@ public function testAuthenticateNoBasicAuthenticateHeadersProvidedWithAjaxButUse ); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateValidCredentials() { - $server = $this->getMockBuilder(Server::class) - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest - ->expects($this->at(0)) - ->method('getHeader') - ->with('X-Requested-With') - ->willReturn(null); + $server = $this->createMock(Server::class); + $server->httpRequest = $this->createMock(RequestInterface::class); $server->httpRequest - ->expects($this->at(1)) + ->expects($this->exactly(2)) ->method('getHeader') - ->with('Authorization') - ->willReturn('basic dXNlcm5hbWU6cGFzc3dvcmQ='); - $server->httpResponse = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->withConsecutive( + ['X-Requested-With'], + ['Authorization'] + ) + ->willReturnOnConsecutiveCalls( + null, 'basic dXNlcm5hbWU6cGFzc3dvcmQ=' + ); + $server->httpResponse = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->once()) ->method('logClientIn') ->with('username', 'password') ->willReturn(true); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->exactly(3)) ->method('getUID') ->willReturn('MyTestUser'); @@ -670,26 +636,27 @@ public function testAuthenticateValidCredentials() { $this->assertEquals([true, 'principals/users/MyTestUser'], $response); } + /** + * @throws NotAuthenticated + * @throws ServiceUnavailable + */ public function testAuthenticateInvalidCredentials() { - $server = $this->getMockBuilder(Server::class) - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $server->httpRequest - ->expects($this->at(0)) - ->method('getHeader') - ->with('X-Requested-With') - ->willReturn(null); + /** @var Server|MockObject $server */ + $server = $this->createMock(Server::class); + /** @var RequestInterface|MockObject $httpRequest */ + $httpRequest = $this->createMock(RequestInterface::class); + $server->httpRequest = $httpRequest; $server->httpRequest - ->expects($this->at(1)) + ->expects($this->exactly(2)) ->method('getHeader') - ->with('Authorization') - ->willReturn('basic dXNlcm5hbWU6cGFzc3dvcmQ='); - $server->httpResponse = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + ->withConsecutive( + ['X-Requested-With'], + ['Authorization'] + ) + ->willReturnOnConsecutiveCalls( + null, 'basic dXNlcm5hbWU6cGFzc3dvcmQ=' + ); + $server->httpResponse = $this->createMock(ResponseInterface::class); $this->userSession ->expects($this->once()) ->method('logClientIn') diff --git a/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php b/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php index 007b5c90295db..a6e659c3e6934 100644 --- a/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/BearerAuthTest.php @@ -24,11 +24,13 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre; +use OC\User\Session; use OCA\DAV\Connector\Sabre\BearerAuth; use OCP\IRequest; use OCP\ISession; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; use Test\TestCase; @@ -37,26 +39,22 @@ * @group DB */ class BearerAuthTest extends TestCase { - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserSession|MockObject */ private $userSession; - /** @var ISession|\PHPUnit\Framework\MockObject\MockObject */ - private $session; - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; /** @var BearerAuth */ private $bearerAuth; protected function setUp(): void { parent::setUp(); - $this->userSession = $this->createMock(\OC\User\Session::class); - $this->session = $this->createMock(ISession::class); - $this->request = $this->createMock(IRequest::class); + $this->userSession = $this->createMock(Session::class); + $session = $this->createMock(ISession::class); + $request = $this->createMock(IRequest::class); $this->bearerAuth = new BearerAuth( $this->userSession, - $this->session, - $this->request + $session, + $request ); } @@ -66,13 +64,9 @@ public function testValidateBearerTokenNotLoggedIn() { public function testValidateBearerToken() { $this->userSession - ->expects($this->at(0)) + ->expects($this->exactly(2)) ->method('isLoggedIn') - ->willReturn(false); - $this->userSession - ->expects($this->at(2)) - ->method('isLoggedIn') - ->willReturn(true); + ->willReturnOnConsecutiveCalls(false, true); $user = $this->createMock(IUser::class); $user ->expects($this->once()) @@ -87,9 +81,9 @@ public function testValidateBearerToken() { } public function testChallenge() { - /** @var \PHPUnit\Framework\MockObject\MockObject|RequestInterface $request */ + /** @var MockObject|RequestInterface $request */ $request = $this->createMock(RequestInterface::class); - /** @var \PHPUnit\Framework\MockObject\MockObject|ResponseInterface $response */ + /** @var MockObject|ResponseInterface $response */ $response = $this->createMock(ResponseInterface::class); $result = $this->bearerAuth->challenge($request, $response); $this->assertEmpty($result); diff --git a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php index 4d2771132ccb5..48936130d8a62 100644 --- a/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/BlockLegacyClientPluginTest.php @@ -28,6 +28,9 @@ use OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin; use OCP\IConfig; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\Forbidden; +use Sabre\HTTP\RequestInterface; use Test\TestCase; /** @@ -36,7 +39,7 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre */ class BlockLegacyClientPluginTest extends TestCase { - /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig | MockObject */ private $config; /** @var BlockLegacyClientPlugin */ private $blockLegacyClientVersionPlugin; @@ -44,16 +47,14 @@ class BlockLegacyClientPluginTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder(IConfig::class) - ->disableOriginalConstructor() - ->getMock(); + $this->config = $this->createMock(IConfig::class); $this->blockLegacyClientVersionPlugin = new BlockLegacyClientPlugin($this->config); } /** * @return array */ - public function oldDesktopClientProvider() { + public function oldDesktopClientProvider(): array { return [ ['Mozilla/5.0 (1.5.0) mirall/1.5.0'], ['mirall/1.5.0'], @@ -67,12 +68,12 @@ public function oldDesktopClientProvider() { * @dataProvider oldDesktopClientProvider * @param string $userAgent */ - public function testBeforeHandlerException($userAgent) { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + public function testBeforeHandlerException(string $userAgent) { + $this->expectException(Forbidden::class); $this->expectExceptionMessage('Unsupported client version.'); - /** @var \Sabre\HTTP\RequestInterface | \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + /** @var RequestInterface | MockObject $request */ + $request = $this->createMock(RequestInterface::class); $request ->expects($this->once()) ->method('getHeader') @@ -91,7 +92,7 @@ public function testBeforeHandlerException($userAgent) { /** * @return array */ - public function newAndAlternateDesktopClientProvider() { + public function newAndAlternateDesktopClientProvider(): array { return [ ['Mozilla/5.0 (1.7.0) mirall/1.7.0'], ['mirall/1.8.3'], @@ -103,11 +104,11 @@ public function newAndAlternateDesktopClientProvider() { /** * @dataProvider newAndAlternateDesktopClientProvider - * @param string $userAgent + * @throws Forbidden */ - public function testBeforeHandlerSuccess($userAgent) { - /** @var \Sabre\HTTP\RequestInterface | \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + public function testBeforeHandlerSuccess(string $userAgent) { + /** @var RequestInterface | MockObject $request */ + $request = $this->createMock(RequestInterface::class); $request ->expects($this->once()) ->method('getHeader') @@ -123,9 +124,12 @@ public function testBeforeHandlerSuccess($userAgent) { $this->blockLegacyClientVersionPlugin->beforeHandler($request); } + /** + * @throws Forbidden + */ public function testBeforeHandlerNoUserAgent() { - /** @var \Sabre\HTTP\RequestInterface | \PHPUnit\Framework\MockObject\MockObject $request */ - $request = $this->createMock('\Sabre\HTTP\RequestInterface'); + /** @var RequestInterface | MockObject $request */ + $request = $this->createMock(RequestInterface::class); $request ->expects($this->once()) ->method('getHeader') diff --git a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php index ea49cef5d0f42..340f4b94b110e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CommentsPropertiesPluginTest.php @@ -26,13 +26,18 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; use OCA\DAV\Connector\Sabre\CommentPropertiesPlugin as CommentPropertiesPluginImplementation; +use OCA\DAV\Connector\Sabre\Directory; use OCA\DAV\Connector\Sabre\File; use OCP\Comments\ICommentsManager; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\INode; use Sabre\DAV\PropFind; +use Sabre\DAV\Server; +use Test\TestCase; -class CommentsPropertiesPluginTest extends \Test\TestCase { +class CommentsPropertiesPluginTest extends TestCase { /** @var CommentPropertiesPluginImplementation */ protected $plugin; @@ -43,27 +48,19 @@ class CommentsPropertiesPluginTest extends \Test\TestCase { protected function setUp(): void { parent::setUp(); - $this->commentsManager = $this->getMockBuilder(ICommentsManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->disableOriginalConstructor() - ->getMock(); + $this->commentsManager = $this->createMock(ICommentsManager::class); + $this->userSession = $this->createMock(IUserSession::class); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); + $this->server = $this->createMock(Server::class); $this->plugin = new CommentPropertiesPluginImplementation($this->commentsManager, $this->userSession); $this->plugin->initialize($this->server); } - public function nodeProvider() { + public function nodeProvider(): array { $mocks = []; - foreach (['\OCA\DAV\Connector\Sabre\File', '\OCA\DAV\Connector\Sabre\Directory', '\Sabre\DAV\INode'] as $class) { - $mocks[] = $this->getMockBuilder($class) - ->disableOriginalConstructor() - ->getMock(); + foreach ([File::class, Directory::class, INode::class] as $class) { + $mocks[] = $this->createMock($class); } return [ @@ -75,13 +72,9 @@ public function nodeProvider() { /** * @dataProvider nodeProvider - * @param $node - * @param $expectedSuccessful */ - public function testHandleGetProperties($node, $expectedSuccessful) { - $propFind = $this->getMockBuilder(PropFind::class) - ->disableOriginalConstructor() - ->getMock(); + public function testHandleGetProperties($node, bool $expectedSuccessful) { + $propFind = $this->createMock(PropFind::class); if ($expectedSuccessful) { $propFind->expects($this->exactly(3)) @@ -94,24 +87,19 @@ public function testHandleGetProperties($node, $expectedSuccessful) { $this->plugin->handleGetProperties($propFind, $node); } - public function baseUriProvider() { + public function baseUriProvider(): array { return [ - ['owncloud/remote.php/webdav/', '4567', 'owncloud/remote.php/dav/comments/files/4567'], - ['owncloud/remote.php/files/', '4567', 'owncloud/remote.php/dav/comments/files/4567'], - ['owncloud/wicked.php/files/', '4567', null] + ['owncloud/remote.php/webdav/', 4567, 'owncloud/remote.php/dav/comments/files/4567'], + ['owncloud/remote.php/files/', 4567, 'owncloud/remote.php/dav/comments/files/4567'], + ['owncloud/wicked.php/files/', 4567, null] ]; } /** * @dataProvider baseUriProvider - * @param $baseUri - * @param $fid - * @param $expectedHref */ - public function testGetCommentsLink($baseUri, $fid, $expectedHref) { - $node = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + public function testGetCommentsLink(string $baseUri, int $fid, ?string $expectedHref) { + $node = $this->createMock(File::class); $node->expects($this->any()) ->method('getId') ->willReturn($fid); @@ -124,12 +112,10 @@ public function testGetCommentsLink($baseUri, $fid, $expectedHref) { $this->assertSame($expectedHref, $href); } - public function userProvider() { + public function userProvider(): array { return [ [ - $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(IUser::class) ], [null] ]; @@ -137,15 +123,13 @@ public function userProvider() { /** * @dataProvider userProvider - * @param $user + * @param IUser|MockObject|null $user */ public function testGetUnreadCount($user) { - $node = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(File::class); $node->expects($this->any()) ->method('getId') - ->willReturn('4567'); + ->willReturn(4567); $this->userSession->expects($this->once()) ->method('getUser') @@ -159,7 +143,7 @@ public function testGetUnreadCount($user) { if (is_null($user)) { $this->assertNull($unread); } else { - $this->assertSame($unread, 42); + $this->assertSame(42, $unread); } } } diff --git a/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php index 858e5c8199bb3..8e2e41703849f 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CopyEtagHeaderPluginTest.php @@ -34,6 +34,8 @@ use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Server; use Sabre\DAV\Tree; +use Sabre\Http\Request; +use Sabre\Http\Response; use Test\TestCase; /** @@ -52,14 +54,14 @@ class CopyEtagHeaderPluginTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->server = new \Sabre\DAV\Server(); + $this->server = new Server(); $this->plugin = new CopyEtagHeaderPlugin(); $this->plugin->initialize($this->server); } public function testCopyEtag() { - $request = new \Sabre\Http\Request('GET', 'dummy.file'); - $response = new \Sabre\Http\Response(); + $request = new Request('GET', 'dummy.file'); + $response = new Response(); $response->setHeader('Etag', 'abcd'); $this->plugin->afterMethod($request, $response); @@ -68,8 +70,8 @@ public function testCopyEtag() { } public function testNoopWhenEmpty() { - $request = new \Sabre\Http\Request('GET', 'dummy.file'); - $response = new \Sabre\Http\Response(); + $request = new Request('GET', 'dummy.file'); + $response = new Response(); $this->plugin->afterMethod($request, $response); @@ -90,15 +92,11 @@ public function testAfterMoveNodeNotFound(): void { } public function testAfterMove() { - $node = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(File::class); $node->expects($this->once()) ->method('getETag') ->willReturn('123456'); - $tree = $this->getMockBuilder(Tree::class) - ->disableOriginalConstructor() - ->getMock(); + $tree = $this->createMock(Tree::class); $tree->expects($this->once()) ->method('getNodeForPath') ->with('test.txt') diff --git a/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php b/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php index a7b1225bdc052..86a1875b30b9e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/CustomPropertiesBackendTest.php @@ -36,11 +36,17 @@ * See the COPYING-README file. */ -use OCA\DAV\Connector\Sabre\Directory; -use OCA\DAV\Connector\Sabre\File; +use OC; +use OCA\DAV\DAV\CustomPropertiesBackend; use OCP\IDBConnection; use OCP\IUser; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use Sabre\DAV\PropFind; +use Sabre\DAV\PropPatch; +use Sabre\DAV\Server; use Sabre\DAV\Tree; +use Test\TestCase; /** * Class CustomPropertiesBackend @@ -49,53 +55,51 @@ * * @package OCA\DAV\Tests\unit\Connector\Sabre */ -class CustomPropertiesBackendTest extends \Test\TestCase { +class CustomPropertiesBackendTest extends TestCase { /** - * @var \Sabre\DAV\Server + * @var Server */ private $server; /** - * @var \Sabre\DAV\Tree - */ - private $tree; - - /** - * @var \OCA\DAV\DAV\CustomPropertiesBackend + * @var CustomPropertiesBackend */ private $plugin; /** - * @var \OCP\IUser + * @var IUser */ private $user; + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder(Tree::class) - ->disableOriginalConstructor() - ->getMock(); - + $this->server = new Server(); + $tree = $this->createMock(Tree::class); $userId = $this->getUniqueID('testcustompropertiesuser'); - $this->user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $this->user = $this->createMock(IUser::class); $this->user->expects($this->any()) ->method('getUID') ->willReturn($userId); - $this->plugin = new \OCA\DAV\DAV\CustomPropertiesBackend( - $this->tree, - \OC::$server->get(IDBConnection::class), + $this->plugin = new CustomPropertiesBackend( + $tree, + OC::$server->get(IDBConnection::class), $this->user ); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function tearDown(): void { - $connection = \OC::$server->get(IDBConnection::class); + $connection = OC::$server->get(IDBConnection::class); $deleteStatement = $connection->prepare( 'DELETE FROM `*PREFIX*properties`' . ' WHERE `userid` = ?' @@ -108,24 +112,9 @@ protected function tearDown(): void { $deleteStatement->closeCursor(); } - private function createTestNode($class) { - $node = $this->getMockBuilder($class) - ->disableOriginalConstructor() - ->getMock(); - $node->expects($this->any()) - ->method('getId') - ->willReturn(123); - - $node->expects($this->any()) - ->method('getPath') - ->willReturn('/dummypath'); - - return $node; - } - private function applyDefaultProps($path = '/dummypath') { // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ + $propPatch = new PropPatch([ 'customprop' => 'value1', 'customprop2' => 'value2', ]); @@ -148,7 +137,7 @@ private function applyDefaultProps($path = '/dummypath') { * Test that propFind on a missing file soft fails */ public function testPropFindMissingFileSoftFail() { - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/dummypath', [ 'customprop', @@ -178,7 +167,7 @@ public function testPropFindMissingFileSoftFail() { public function testSetGetPropertiesForFile() { $this->applyDefaultProps(); - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/dummypath', [ 'customprop', @@ -202,7 +191,7 @@ public function testSetGetPropertiesForFile() { * Test getting properties from directory */ public function testGetPropertiesForDirectory() { - $this->applyDefaultProps('/dummypath'); + $this->applyDefaultProps(); $this->applyDefaultProps('/dummypath/test.txt'); $propNames = [ @@ -211,13 +200,13 @@ public function testGetPropertiesForDirectory() { 'unsetprop', ]; - $propFindRoot = new \Sabre\DAV\PropFind( + $propFindRoot = new PropFind( '/dummypath', $propNames, 1 ); - $propFindSub = new \Sabre\DAV\PropFind( + $propFindSub = new PropFind( '/dummypath/test.txt', $propNames, 0 @@ -251,7 +240,7 @@ public function testGetPropertiesForDirectory() { public function testDeleteProperty() { $this->applyDefaultProps(); - $propPatch = new \Sabre\DAV\PropPatch([ + $propPatch = new PropPatch([ 'customprop' => null, ]); diff --git a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php index 024a6432d0132..fa309eee996f5 100644 --- a/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/DirectoryTest.php @@ -28,13 +28,29 @@ */ namespace OCA\DAV\Tests\Unit\Connector\Sabre; +use Exception; use OC\Files\FileInfo; use OC\Files\Storage\Wrapper\Quota; +use OC\Files\View; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\Exception\FileLocked; +use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCA\Files_Sharing\SharedStorage; use OCP\Files\ForbiddenException; +use OCP\Files\InvalidPathException; use OCP\Files\Mount\IMountPoint; - -class TestViewDirectory extends \OC\Files\View { +use OCP\Files\StorageNotAvailableException; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\Locked; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\ServiceUnavailable; +use Test\TestCase; + +class TestViewDirectory extends View { private $updatables; private $deletables; private $canRename; @@ -61,7 +77,7 @@ public function rename($path1, $path2) { return $this->canRename; } - public function getRelativePath($path) { + public function getRelativePath($path): ?string { return $path; } } @@ -70,24 +86,28 @@ public function getRelativePath($path) { /** * @group DB */ -class DirectoryTest extends \Test\TestCase { +class DirectoryTest extends TestCase { - /** @var \OC\Files\View | \PHPUnit\Framework\MockObject\MockObject */ + /** @var View | MockObject */ private $view; - /** @var \OC\Files\FileInfo | \PHPUnit\Framework\MockObject\MockObject */ + /** @var FileInfo | MockObject */ private $info; protected function setUp(): void { parent::setUp(); - $this->view = $this->createMock('OC\Files\View'); - $this->info = $this->createMock('OC\Files\FileInfo'); + $this->view = $this->createMock(View::class); + $this->info = $this->createMock(FileInfo::class); $this->info->expects($this->any()) ->method('isReadable') ->willReturn(true); } - private function getDir($path = '/') { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ + private function getDir(string $path = '/'): Directory { $this->view->expects($this->once()) ->method('getRelativePath') ->willReturn($path); @@ -100,8 +120,14 @@ private function getDir($path = '/') { } + /** + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + */ public function testDeleteRootFolderFails() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->info->expects($this->any()) ->method('isDeletable') @@ -113,6 +139,12 @@ public function testDeleteRootFolderFails() { } + /** + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + */ public function testDeleteForbidden() { $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class); @@ -132,6 +164,12 @@ public function testDeleteForbidden() { } + /** + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + */ public function testDeleteFolderWhenAllowed() { // deletion allowed $this->info->expects($this->once()) @@ -149,8 +187,14 @@ public function testDeleteFolderWhenAllowed() { } + /** + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + */ public function testDeleteFolderFailsWhenNotAllowed() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->info->expects($this->once()) ->method('isDeletable') @@ -161,8 +205,14 @@ public function testDeleteFolderFailsWhenNotAllowed() { } + /** + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + */ public function testDeleteFolderThrowsWhenDeletionFailed() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); // deletion allowed $this->info->expects($this->once()) @@ -179,13 +229,19 @@ public function testDeleteFolderThrowsWhenDeletionFailed() { $dir->delete(); } + /** + * @throws ContainerExceptionInterface + * @throws Forbidden + * @throws InvalidPath + * @throws Locked + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden + */ public function testGetChildren() { - $info1 = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); - $info2 = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $info1 = $this->createMock(FileInfo::class); + $info2 = $this->createMock(FileInfo::class); $info1->expects($this->any()) ->method('getName') ->willReturn('first'); @@ -211,7 +267,7 @@ public function testGetChildren() { $dir = new Directory($this->view, $this->info); $nodes = $dir->getChildren(); - $this->assertEquals(2, count($nodes)); + $this->assertCount(2, $nodes); // calling a second time just returns the cached values, // does not call getDirectoryContents again @@ -219,8 +275,18 @@ public function testGetChildren() { } + /** + * @throws ContainerExceptionInterface + * @throws Forbidden + * @throws InvalidPath + * @throws Locked + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden + */ public function testGetChildrenNoPermission() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $info = $this->createMock(FileInfo::class); $info->expects($this->any()) @@ -232,8 +298,16 @@ public function testGetChildrenNoPermission() { } + /** + * @throws ContainerExceptionInterface + * @throws InvalidPath + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws Forbidden + */ public function testGetChildNoPermission() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->info->expects($this->any()) ->method('isReadable') @@ -244,24 +318,38 @@ public function testGetChildNoPermission() { } + /** + * @throws ContainerExceptionInterface + * @throws InvalidPath + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable|Forbidden + */ public function testGetChildThrowStorageNotAvailableException() { - $this->expectException(\Sabre\DAV\Exception\ServiceUnavailable::class); + $this->expectException(ServiceUnavailable::class); $this->view->expects($this->once()) ->method('getFileInfo') - ->willThrowException(new \OCP\Files\StorageNotAvailableException()); + ->willThrowException(new StorageNotAvailableException()); $dir = new Directory($this->view, $this->info); $dir->getChild('.'); } + /** + * @throws ContainerExceptionInterface + * @throws InvalidPath + * @throws NotFound + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable|Forbidden + */ public function testGetChildThrowInvalidPath() { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\InvalidPath::class); + $this->expectException(InvalidPath::class); $this->view->expects($this->once()) ->method('verifyPath') - ->willThrowException(new \OCP\Files\InvalidPathException()); + ->willThrowException(new InvalidPathException()); $this->view->expects($this->never()) ->method('getFileInfo'); @@ -269,19 +357,21 @@ public function testGetChildThrowInvalidPath() { $dir->getChild('.'); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ public function testGetQuotaInfoUnlimited() { $mountPoint = $this->createMock(IMountPoint::class); - $storage = $this->getMockBuilder(Quota::class) - ->disableOriginalConstructor() - ->getMock(); + $storage = $this->createMock(Quota::class); $mountPoint->method('getStorage') ->willReturn($storage); $storage->expects($this->any()) ->method('instanceOfStorage') ->willReturnMap([ - '\OCA\Files_Sharing\SharedStorage' => false, - '\OC\Files\Storage\Wrapper\Quota' => false, + SharedStorage::class => false, + Quota::class => false, ]); $storage->expects($this->never()) @@ -310,19 +400,24 @@ public function testGetQuotaInfoUnlimited() { $this->assertEquals([200, -3], $dir->getQuotaInfo()); //200 used, unlimited } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ public function testGetQuotaInfoSpecific() { $mountPoint = $this->createMock(IMountPoint::class); + //$storage = $this->createMock(Quota::class); $storage = $this->getMockBuilder(Quota::class) ->disableOriginalConstructor() ->getMock(); $mountPoint->method('getStorage') ->willReturn($storage); - $storage->expects($this->any()) + $storage->expects($this->exactly(2)) ->method('instanceOfStorage') ->willReturnMap([ - ['\OCA\Files_Sharing\SharedStorage', false], - ['\OC\Files\Storage\Wrapper\Quota', true], + [SharedStorage::class, false], + [Quota::class, true], ]); $storage->expects($this->once()) @@ -337,6 +432,10 @@ public function testGetQuotaInfoSpecific() { ->method('getSize') ->willReturn(200); + $this->info->expects($this->any()) + ->method('getPath') + ->willReturn('/sub'); + $this->info->expects($this->once()) ->method('getMountPoint') ->willReturn($mountPoint); @@ -354,37 +453,58 @@ public function testGetQuotaInfoSpecific() { /** * @dataProvider moveFailedProvider + * @throws BadRequest + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden */ - public function testMoveFailed($source, $destination, $updatables, $deletables) { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + public function testMoveFailed(string $source, string $destination, array $updatables, array $deletables) { + $this->expectException(Forbidden::class); $this->moveTest($source, $destination, $updatables, $deletables); } /** * @dataProvider moveSuccessProvider + * @throws BadRequest + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden */ - public function testMoveSuccess($source, $destination, $updatables, $deletables) { + public function testMoveSuccess(string $source, string $destination, array $updatables, array $deletables) { $this->moveTest($source, $destination, $updatables, $deletables); $this->addToAssertionCount(1); } /** * @dataProvider moveFailedInvalidCharsProvider + * @throws BadRequest + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden */ - public function testMoveFailedInvalidChars($source, $destination, $updatables, $deletables) { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\InvalidPath::class); + public function testMoveFailedInvalidChars(string $source, string $destination, array $updatables, array $deletables) { + $this->expectException(InvalidPath::class); $this->moveTest($source, $destination, $updatables, $deletables); } - public function moveFailedInvalidCharsProvider() { + public function moveFailedInvalidCharsProvider(): array { return [ ['a/b', 'a/*', ['a' => true, 'a/b' => true, 'a/c*' => false], []], ]; } - public function moveFailedProvider() { + public function moveFailedProvider(): array { return [ ['a/b', 'a/c', ['a' => false, 'a/b' => false, 'a/c' => false], []], ['a/b', 'b/b', ['a' => false, 'a/b' => false, 'b' => false, 'b/b' => false], []], @@ -395,7 +515,7 @@ public function moveFailedProvider() { ]; } - public function moveSuccessProvider() { + public function moveSuccessProvider(): array { return [ ['a/b', 'b/b', ['a' => true, 'a/b' => true, 'b' => true, 'b/b' => false], ['a/b' => true]], // older files with special chars can still be renamed to valid names @@ -404,11 +524,16 @@ public function moveSuccessProvider() { } /** - * @param $source - * @param $destination - * @param $updatables + * @throws BadRequest + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden + * @throws Exception */ - private function moveTest($source, $destination, $updatables, $deletables) { + private function moveTest(string $source, string $destination, array $updatables, array $deletables) { $view = new TestViewDirectory($updatables, $deletables); $sourceInfo = new FileInfo($source, null, null, [], null); @@ -416,7 +541,7 @@ private function moveTest($source, $destination, $updatables, $deletables) { $sourceNode = new Directory($view, $sourceInfo); $targetNode = $this->getMockBuilder(Directory::class) - ->setMethods(['childExists']) + ->onlyMethods(['childExists']) ->setConstructorArgs([$view, $targetInfo]) ->getMock(); $targetNode->expects($this->any())->method('childExists') @@ -426,8 +551,18 @@ private function moveTest($source, $destination, $updatables, $deletables) { } + /** + * @throws BadRequest + * @throws ContainerExceptionInterface + * @throws FileLocked + * @throws Forbidden + * @throws NotFoundExceptionInterface + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden + * @throws Exception + */ public function testFailingMove() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->expectExceptionMessage('Could not copy directory b, target exists'); $source = 'a/b'; @@ -442,7 +577,7 @@ public function testFailingMove() { $sourceNode = new Directory($view, $sourceInfo); $targetNode = $this->getMockBuilder(Directory::class) - ->setMethods(['childExists']) + ->onlyMethods(['childExists']) ->setConstructorArgs([$view, $targetInfo]) ->getMock(); $targetNode->expects($this->once())->method('childExists') diff --git a/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php index c4b7ed15f2b4e..da901a928b7d4 100644 --- a/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/DummyGetResponsePluginTest.php @@ -26,6 +26,7 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; use OCA\DAV\Connector\Sabre\DummyGetResponsePlugin; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\DAV\Server; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -47,10 +48,8 @@ protected function setUp(): void { } public function testInitialize() { - /** @var Server $server */ - $server = $this->getMockBuilder(Server::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var Server|MockObject $server */ + $server = $this->createMock(Server::class); $server ->expects($this->once()) ->method('on') @@ -61,14 +60,10 @@ public function testInitialize() { public function testHttpGet() { - /** @var \Sabre\HTTP\RequestInterface $request */ - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - /** @var \Sabre\HTTP\ResponseInterface $response */ - $response = $server = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var RequestInterface|MockObject $request */ + $request = $this->createMock(RequestInterface::class); + /** @var ResponseInterface|MockObject $response */ + $response = $this->createMock(ResponseInterface::class); $response ->expects($this->once()) ->method('setBody'); diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php index 4d316bf870aa4..8e50c2e1cd51c 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php @@ -22,21 +22,27 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\Exception; +use DOMDocument; +use DOMException; use OCA\DAV\Connector\Sabre\Exception\Forbidden; +use Sabre\DAV\Server; +use Test\TestCase; -class ForbiddenTest extends \Test\TestCase { +class ForbiddenTest extends TestCase { + /** + * @throws DOMException + */ public function testSerialization() { // create xml doc - $DOM = new \DOMDocument('1.0','utf-8'); + $DOM = new DOMDocument('1.0','utf-8'); $DOM->formatOutput = true; $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s', \Sabre\DAV\Server::NS_SABREDAV); + $error->setAttribute('xmlns:s', Server::NS_SABREDAV); $DOM->appendChild($error); // serialize the exception $message = "1234567890"; - $retry = false; $expectedXml = << @@ -46,10 +52,8 @@ public function testSerialization() { EOD; - $ex = new Forbidden($message, $retry); - $server = $this->getMockBuilder('Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); + $ex = new Forbidden($message, false); + $server = $this->createMock(Server::class); $ex->serialize($server, $error); // assert diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php index 3c68d780ff3db..1bf3526ef619d 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php @@ -23,21 +23,27 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\Exception; +use DOMDocument; +use DOMException; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use Sabre\DAV\Server; +use Test\TestCase; -class InvalidPathTest extends \Test\TestCase { +class InvalidPathTest extends TestCase { + /** + * @throws DOMException + */ public function testSerialization() { // create xml doc - $DOM = new \DOMDocument('1.0','utf-8'); + $DOM = new DOMDocument('1.0','utf-8'); $DOM->formatOutput = true; $error = $DOM->createElementNS('DAV:','d:error'); - $error->setAttribute('xmlns:s', \Sabre\DAV\Server::NS_SABREDAV); + $error->setAttribute('xmlns:s', Server::NS_SABREDAV); $DOM->appendChild($error); // serialize the exception $message = "1234567890"; - $retry = false; $expectedXml = << @@ -47,10 +53,8 @@ public function testSerialization() { EOD; - $ex = new InvalidPath($message, $retry); - $server = $this->getMockBuilder('Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); + $ex = new InvalidPath($message, false); + $server = $this->createMock(Server::class); $ex->serialize($server, $error); // assert diff --git a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php index 83f8c4165778c..227e76154b3ad 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ExceptionLoggerPluginTest.php @@ -27,34 +27,39 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre; -use OC\Log; +use Exception; use OC\SystemConfig; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin as PluginToTest; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Log\AbstractLogger; +use Psr\Log\LogLevel; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\Server; use Test\TestCase; -class TestLogger extends Log { +class TestLogger extends AbstractLogger { + /** @var string $message */ public $message; + /** @var int $level */ public $level; + /** @var array $context */ + public $context; - public function writeLog(string $app, $entry, int $level) { + public function log($level, $message, array $context = array()) { $this->level = $level; - $this->message = $entry; + $this->message = $message; + $this->context = $context; } } class ExceptionLoggerPluginTest extends TestCase { - /** @var Server */ - private $server; - /** @var PluginToTest */ private $plugin; - /** @var TestLogger | \PHPUnit\Framework\MockObject\MockObject */ + /** @var TestLogger | MockObject */ private $logger; private function init() { @@ -70,30 +75,30 @@ private function init() { } }); - $this->server = new Server(); - $this->logger = new TestLogger(new Log\File(\OC::$SERVERROOT.'/data/nextcloud.log', '', $config), $config); + $server = new Server(); + $this->logger = new TestLogger(); $this->plugin = new PluginToTest('unit-test', $this->logger); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } /** * @dataProvider providesExceptions */ - public function testLogging($expectedLogLevel, $expectedMessage, $exception) { + public function testLogging(string $expectedLogLevel, string $expectedMessage, Exception $exception) { $this->init(); $this->plugin->logException($exception); $this->assertEquals($expectedLogLevel, $this->logger->level); - $this->assertEquals(get_class($exception), $this->logger->message['Exception']); - $this->assertEquals($expectedMessage, $this->logger->message['Message']); + $this->assertInstanceOf(get_class($exception), $this->logger->context['exception']); + $this->assertEquals($expectedMessage, $this->logger->message); } - public function providesExceptions() { + public function providesExceptions(): array { return [ - [0, '', new NotFound()], - [0, 'System in maintenance mode.', new ServiceUnavailable('System in maintenance mode.')], - [4, 'Upgrade needed', new ServiceUnavailable('Upgrade needed')], - [4, 'This path leads to nowhere', new InvalidPath('This path leads to nowhere')] + [LogLevel::DEBUG, '', new NotFound()], + [LogLevel::DEBUG, 'System in maintenance mode.', new ServiceUnavailable('System in maintenance mode.')], + [LogLevel::CRITICAL, 'Upgrade needed', new ServiceUnavailable('Upgrade needed')], + [LogLevel::CRITICAL, 'This path leads to nowhere', new InvalidPath('This path leads to nowhere')] ]; } } diff --git a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php index 578576e3f0709..8a69317fb97ee 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php @@ -28,9 +28,11 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; use OCA\DAV\Connector\Sabre\FakeLockerPlugin; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\Server; +use Sabre\DAV\Xml\Service; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\Response; use Sabre\HTTP\ResponseInterface; @@ -51,26 +53,17 @@ protected function setUp(): void { } public function testInitialize() { - /** @var Server $server */ - $server = $this->getMockBuilder(Server::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var Server|MockObject $server */ + $server = $this->createMock(Server::class); $server - ->expects($this->at(0)) + ->expects($this->exactly(4)) ->method('on') - ->with('method:LOCK', [$this->fakeLockerPlugin, 'fakeLockProvider'], 1); - $server - ->expects($this->at(1)) - ->method('on') - ->with('method:UNLOCK', [$this->fakeLockerPlugin, 'fakeUnlockProvider'], 1); - $server - ->expects($this->at(2)) - ->method('on') - ->with('propFind', [$this->fakeLockerPlugin, 'propFind']); - $server - ->expects($this->at(3)) - ->method('on') - ->with('validateTokens', [$this->fakeLockerPlugin, 'validateTokens']); + ->withConsecutive( + ['method:LOCK', [$this->fakeLockerPlugin, 'fakeLockProvider'], 1], + ['method:UNLOCK', [$this->fakeLockerPlugin, 'fakeUnlockProvider'], 1], + ['propFind', [$this->fakeLockerPlugin, 'propFind']], + ['validateTokens', [$this->fakeLockerPlugin, 'validateTokens']] + ); $this->fakeLockerPlugin->initialize($server); } @@ -91,24 +84,20 @@ public function testGetFeatures() { } public function testPropFind() { - $propFind = $this->getMockBuilder(PropFind::class) - ->disableOriginalConstructor() - ->getMock(); - $node = $this->getMockBuilder(INode::class) - ->disableOriginalConstructor() - ->getMock(); - - $propFind->expects($this->at(0)) - ->method('handle') - ->with('{DAV:}supportedlock'); - $propFind->expects($this->at(1)) + $propFind = $this->createMock(PropFind::class); + $node = $this->createMock(INode::class); + + $propFind->expects($this->exactly(2)) ->method('handle') - ->with('{DAV:}lockdiscovery'); + ->withConsecutive( + ['{DAV:}supportedlock'], + ['{DAV:}lockdiscovery'] + ); $this->fakeLockerPlugin->propFind($propFind, $node); } - public function tokenDataProvider() { + public function tokenDataProvider(): array { return [ [ [ @@ -151,20 +140,15 @@ public function tokenDataProvider() { * @param array $expected */ public function testValidateTokens(array $input, array $expected) { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); $this->fakeLockerPlugin->validateTokens($request, $input); $this->assertSame($expected, $input); } public function testFakeLockProvider() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); $response = new Response(); - $server = $this->getMockBuilder(Server::class) - ->getMock(); + $server = $this->getMockBuilder(Server::class)->getMock(); $this->fakeLockerPlugin->initialize($server); $request->expects($this->exactly(2)) @@ -179,12 +163,8 @@ public function testFakeLockProvider() { } public function testFakeUnlockProvider() { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('setStatus') diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index 050fa029784d3..15bf74e639aa2 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -29,22 +29,48 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre; +use InvalidArgumentException; +use OC; use OC\AppFramework\Http\Request; +use OC\Files\FileInfo; use OC\Files\Filesystem; use OC\Files\Storage\Local; +use OC\Files\Storage\Storage; use OC\Files\Storage\Temporary; use OC\Files\Storage\Wrapper\PermissionsMask; use OC\Files\View; +use OC\Security\SecureRandom; +use OCA\DAV\Connector\Sabre\Exception\EntityTooLarge; +use OCA\DAV\Connector\Sabre\Exception\FileLocked; +use OCA\DAV\Connector\Sabre\Exception\Forbidden; +use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType; use OCA\DAV\Connector\Sabre\File; use OCP\Constants; +use OCP\Encryption\Exceptions\GenericEncryptionException; +use OCP\Files\EntityTooLargeException; use OCP\Files\ForbiddenException; +use OCP\Files\InvalidContentException; +use OCP\Files\InvalidPathException; +use OCP\Files\LockNotAcquiredException; +use OCP\Files\NotPermittedException; use OCP\Files\Storage\IStorage; +use OCP\Files\StorageNotAvailableException; use OCP\IConfig; use OCP\IRequestId; use OCP\ITempManager; use OCP\IUserManager; use OCP\Lock\ILockingProvider; use PHPUnit\Framework\MockObject\MockObject; +use OCP\Lock\LockedException; +use OCP\Util; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use Sabre\DAV\Exception; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\ServiceUnavailable; +use stdclass; use Test\HookHelper; use Test\TestCase; use Test\Traits\MountProviderTrait; @@ -61,12 +87,17 @@ class FileTest extends TestCase { use MountProviderTrait; use UserTrait; + /** + * @var array + */ + private static $hookCalls = []; + /** * @var string */ private $user; - /** @var IConfig|MockObject */ + /** @var IConfig | MockObject */ protected $config; /** @var IRequestId|MockObject */ @@ -87,10 +118,15 @@ protected function setUp(): void { $this->config = $this->createMock(IConfig::class); $this->requestId = $this->createMock(IRequestId::class); + $this->secureRandom = new SecureRandom(); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function tearDown(): void { - $userManager = \OC::$server->get(IUserManager::class); + $userManager = OC::$server->get(IUserManager::class); $userManager->get($this->user)->delete(); unset($_SERVER['HTTP_OC_CHUNKED']); @@ -98,12 +134,14 @@ protected function tearDown(): void { } /** +<<<<<<< HEAD * @return MockObject|IStorage +======= + * @return Storage|IStorage|MockObject +>>>>>>> 23922574b5 (Improve tests) */ private function getMockStorage() { - $storage = $this->getMockBuilder(IStorage::class) - ->disableOriginalConstructor() - ->getMock(); + $storage = $this->createMock(IStorage::class); $storage->method('getId') ->willReturn('home::someuser'); return $storage; @@ -111,8 +149,9 @@ private function getMockStorage() { /** * @param string $string + * @return resource|false */ - private function getStream($string) { + private function getStream(string $string) { $stream = fopen('php://temp', 'r+'); fwrite($stream, $string); fseek($stream, 0); @@ -120,75 +159,81 @@ private function getStream($string) { } - public function fopenFailuresProvider() { + public function fopenFailuresProvider(): array { return [ [ // return false null, - '\Sabre\Dav\Exception', + Exception::class, false ], [ - new \OCP\Files\NotPermittedException(), - 'Sabre\DAV\Exception\Forbidden' + new NotPermittedException(), + Exception\Forbidden::class ], [ - new \OCP\Files\EntityTooLargeException(), - 'OCA\DAV\Connector\Sabre\Exception\EntityTooLarge' + new EntityTooLargeException(), + EntityTooLarge::class ], [ - new \OCP\Files\InvalidContentException(), - 'OCA\DAV\Connector\Sabre\Exception\UnsupportedMediaType' + new InvalidContentException(), + UnsupportedMediaType::class ], [ - new \OCP\Files\InvalidPathException(), - 'Sabre\DAV\Exception\Forbidden' + new InvalidPathException(), + Exception\Forbidden::class ], [ - new \OCP\Files\ForbiddenException('', true), - 'OCA\DAV\Connector\Sabre\Exception\Forbidden' + new ForbiddenException('', true), + Forbidden::class ], [ - new \OCP\Files\LockNotAcquiredException('/test.txt', 1), - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' + new LockNotAcquiredException('/test.txt', 1), + FileLocked::class ], [ - new \OCP\Lock\LockedException('/test.txt'), - 'OCA\DAV\Connector\Sabre\Exception\FileLocked' + new LockedException('/test.txt'), + FileLocked::class ], [ - new \OCP\Encryption\Exceptions\GenericEncryptionException(), - 'Sabre\DAV\Exception\ServiceUnavailable' + new GenericEncryptionException(), + ServiceUnavailable::class ], [ - new \OCP\Files\StorageNotAvailableException(), - 'Sabre\DAV\Exception\ServiceUnavailable' + new StorageNotAvailableException(), + ServiceUnavailable::class ], [ - new \Sabre\DAV\Exception('Generic sabre exception'), - 'Sabre\DAV\Exception', + new Exception('Generic sabre exception'), + Exception::class, false ], [ new \Exception('Generic exception'), - 'Sabre\DAV\Exception' + Exception::class ], ]; } /** * @dataProvider fopenFailuresProvider + * @param \Exception|null $thrownException + * @param string $expectedException + * @param bool $checkPreviousClass + * @throws ContainerExceptionInterface + * @throws ForbiddenException + * @throws NotFoundExceptionInterface */ - public function testSimplePutFails($thrownException, $expectedException, $checkPreviousClass = true) { + public function testSimplePutFails(?\Exception $thrownException, string $expectedException, bool $checkPreviousClass = true) { // setup $storage = $this->getMockBuilder(Local::class) - ->setMethods(['writeStream']) - ->setConstructorArgs([['datadir' => \OC::$server->get(ITempManager::class)->getTemporaryFolder()]]) + ->onlyMethods(['writeStream']) + ->setConstructorArgs([['datadir' => OC::$server->get(ITempManager::class)->getTemporaryFolder()]]) ->getMock(); - \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); + Filesystem::mount($storage, [], $this->user . '/'); /** @var View | MockObject $view */ $view = $this->getMockBuilder(View::class) - ->setMethods(['getRelativePath', 'resolvePath']) + ->onlyMethods(['getRelativePath', 'resolvePath']) ->getMock(); $view->expects($this->atLeastOnce()) ->method('resolvePath') @@ -212,11 +257,11 @@ function ($path) use ($storage) { ->method('getRelativePath') ->willReturnArgument(0); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $caughtException = null; @@ -231,23 +276,32 @@ function ($path) use ($storage) { $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious()); } - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } /** * Test putting a file using chunking * * @dataProvider fopenFailuresProvider + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws LockedException + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface|ForbiddenException */ - public function testChunkedPutFails($thrownException, $expectedException, $checkPreviousClass = false) { + public function testChunkedPutFails(?\Exception $thrownException, string $expectedException, bool $checkPreviousClass = false) { // setup $storage = $this->getMockBuilder(Local::class) - ->setMethods(['fopen']) - ->setConstructorArgs([['datadir' => \OC::$server->get(ITempManager::class)->getTemporaryFolder()]]) + ->onlyMethods(['fopen']) + ->setConstructorArgs([['datadir' => OC::$server->get(ITempManager::class)->getTemporaryFolder()]]) ->getMock(); - \OC\Files\Filesystem::mount($storage, [], $this->user . '/'); + Filesystem::mount($storage, [], $this->user . '/'); $view = $this->getMockBuilder(View::class) - ->setMethods(['getRelativePath', 'resolvePath']) + ->onlyMethods(['getRelativePath', 'resolvePath']) ->getMock(); $view->expects($this->atLeastOnce()) ->method('resolvePath') @@ -273,20 +327,20 @@ function ($path) use ($storage) { $_SERVER['HTTP_OC_CHUNKED'] = true; - $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // put first chunk $file->acquireLock(ILockingProvider::LOCK_SHARED); $this->assertNull($file->put('test data one')); $file->releaseLock(ILockingProvider::LOCK_SHARED); - $info = new \OC\Files\FileInfo('/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $caughtException = null; @@ -304,38 +358,46 @@ function ($path) use ($storage) { $this->assertInstanceOf(get_class($thrownException), $caughtException->getPrevious()); } - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } /** * Simulate putting a file to the given path. * * @param string $path path to put the file into - * @param string $viewRoot root to use for the view + * @param string|null $viewRoot root to use for the view * @param null|Request $request the HTTP request * - * @return null|string of the PUT operaiton which is usually the etag + * @return null|string of the PUT operation which is usually the etag + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException + * @throws \Exception */ - private function doPut($path, $viewRoot = null, Request $request = null) { - $view = \OC\Files\Filesystem::getView(); + private function doPut(string $path, string $viewRoot = null, Request $request = null): ?string { + $view = Filesystem::getView(); if (!is_null($viewRoot)) { - $view = new \OC\Files\View($viewRoot); + $view = new View($viewRoot); } else { $viewRoot = '/' . $this->user . '/files'; } - $info = new \OC\Files\FileInfo( + $info = new FileInfo( $viewRoot . '/' . ltrim($path, '/'), $this->getMockStorage(), null, - ['permissions' => \OCP\Constants::PERMISSION_ALL], + ['permissions' => Constants::PERMISSION_ALL], null ); - /** @var \OCA\DAV\Connector\Sabre\File | MockObject $file */ - $file = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\File::class) + /** @var File | MockObject $file */ + $file = $this->getMockBuilder(File::class) ->setConstructorArgs([$view, $info, null, $request]) - ->setMethods(['header']) + ->onlyMethods(['header']) ->getMock(); // beforeMethod locks @@ -351,12 +413,20 @@ private function doPut($path, $viewRoot = null, Request $request = null) { /** * Test putting a single file + * + * @throws Exception + * @throws Exception\Forbidden + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException + * @throws ServiceUnavailable */ public function testPutSingleFile() { $this->assertNotEmpty($this->doPut('/foo.txt')); } - public function legalMtimeProvider() { + public function legalMtimeProvider(): array { return [ "string" => [ 'HTTP_X_OC_MTIME' => "string", @@ -411,9 +481,18 @@ public function legalMtimeProvider() { /** * Test putting a file with string Mtime + * * @dataProvider legalMtimeProvider + * @throws Exception + * @throws Exception\Forbidden + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws InvalidPathException + * @throws LockedException + * @throws ServiceUnavailable */ - public function testPutSingleFileLegalMtime($requestMtime, $resultMtime) { + public function testPutSingleFileLegalMtime($requestMtime, ?int $resultMtime) { $request = new Request([ 'server' => [ 'HTTP_X_OC_MTIME' => $requestMtime, @@ -422,7 +501,7 @@ public function testPutSingleFileLegalMtime($requestMtime, $resultMtime) { $file = 'foo.txt'; if ($resultMtime === null) { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); } $this->doPut($file, null, $request); @@ -434,9 +513,17 @@ public function testPutSingleFileLegalMtime($requestMtime, $resultMtime) { /** * Test putting a file with string Mtime using chunking + * * @dataProvider legalMtimeProvider + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException|InvalidPathException */ - public function testChunkedPutLegalMtime($requestMtime, $resultMtime) { + public function testChunkedPutLegalMtime($requestMtime, ?int $resultMtime) { $request = new Request([ 'server' => [ 'HTTP_X_OC_MTIME' => $requestMtime, @@ -447,7 +534,7 @@ public function testChunkedPutLegalMtime($requestMtime, $resultMtime) { $file = 'foo.txt'; if ($resultMtime === null) { - $this->expectException(\Sabre\DAV\Exception::class); + $this->expectException(Exception::class); } $this->doPut($file.'-chunking-12345-2-0', null, $request); @@ -460,6 +547,14 @@ public function testChunkedPutLegalMtime($requestMtime, $resultMtime) { /** * Test putting a file using chunking + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException */ public function testChunkedPut() { $_SERVER['HTTP_OC_CHUNKED'] = true; @@ -469,6 +564,14 @@ public function testChunkedPut() { /** * Test that putting a file triggers create hooks + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException */ public function testPutSingleFileTriggersHooks() { HookHelper::setUpHooks(); @@ -500,9 +603,17 @@ public function testPutSingleFileTriggersHooks() { /** * Test that putting a file triggers update hooks + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException */ public function testPutOverwriteFileTriggersHooks() { - $view = \OC\Files\Filesystem::getView(); + $view = Filesystem::getView(); $view->file_put_contents('/foo.txt', 'some content that will be replaced'); HookHelper::setUpHooks(); @@ -536,9 +647,17 @@ public function testPutOverwriteFileTriggersHooks() { * Test that putting a file triggers hooks with the correct path * if the passed view was chrooted (can happen with public webdav * where the root is the share root) + * + * @throws Exception + * @throws Exception\Forbidden + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException + * @throws ServiceUnavailable */ public function testPutSingleFileTriggersHooksDifferentRoot() { - $view = \OC\Files\Filesystem::getView(); + $view = Filesystem::getView(); $view->mkdir('noderoot'); HookHelper::setUpHooks(); @@ -571,6 +690,14 @@ public function testPutSingleFileTriggersHooksDifferentRoot() { /** * Test that putting a file with chunks triggers create hooks + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException */ public function testPutChunkedFileTriggersHooks() { HookHelper::setUpHooks(); @@ -604,9 +731,17 @@ public function testPutChunkedFileTriggersHooks() { /** * Test that putting a chunked file triggers update hooks + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException */ public function testPutOverwriteChunkedFileTriggersHooks() { - $view = \OC\Files\Filesystem::getView(); + $view = Filesystem::getView(); $view->file_put_contents('/foo.txt', 'some content that will be replaced'); HookHelper::setUpHooks(); @@ -647,9 +782,11 @@ public static function cancellingHook($params) { /** * Test put file with cancelled hook + * + * @throws LockedException|ForbiddenException */ public function testPutSingleFileCancelPreHook() { - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_create, '\Test\HookHelper', @@ -660,7 +797,7 @@ public function testPutSingleFileCancelPreHook() { $thrown = false; try { $this->doPut('/foo.txt'); - } catch (\Sabre\DAV\Exception $e) { + } catch (Exception $e) { $thrown = true; } @@ -670,11 +807,19 @@ public function testPutSingleFileCancelPreHook() { /** * Test exception when the uploaded size did not match + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException|ForbiddenException */ public function testSimplePutFailsSizeCheck() { // setup $view = $this->getMockBuilder(View::class) - ->setMethods(['rename', 'getRelativePath', 'filesize']) + ->onlyMethods(['rename', 'getRelativePath', 'filesize']) ->getMock(); $view->expects($this->any()) ->method('rename') @@ -691,11 +836,11 @@ public function testSimplePutFailsSizeCheck() { $_SERVER['CONTENT_LENGTH'] = 123456; $_SERVER['REQUEST_METHOD'] = 'PUT'; - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $thrown = false; @@ -707,28 +852,36 @@ public function testSimplePutFailsSizeCheck() { // afterMethod unlocks $file->releaseLock(ILockingProvider::LOCK_SHARED); - } catch (\Sabre\DAV\Exception\BadRequest $e) { + } catch (BadRequest $e) { $thrown = true; } $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } /** * Test exception during final rename in simple upload mode + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException|ForbiddenException + * @throws \Exception */ public function testSimplePutFailsMoveFromStorage() { - $view = new \OC\Files\View('/' . $this->user . '/files'); + $view = new View('/' . $this->user . '/files'); // simulate situation where the target file is locked $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE); - $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/' . $this->user . '/files/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $thrown = false; @@ -740,37 +893,47 @@ public function testSimplePutFailsMoveFromStorage() { // afterMethod unlocks $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + } catch (FileLocked $e) { $thrown = true; } $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } /** * Test exception during final rename in chunk upload mode + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException + * @throws ForbiddenException + * @throws \Exception */ public function testChunkedPutFailsFinalRename() { - $view = new \OC\Files\View('/' . $this->user . '/files'); + $view = new View('/' . $this->user . '/files'); // simulate situation where the target file is locked $view->lockFile('/test.txt', ILockingProvider::LOCK_EXCLUSIVE); $_SERVER['HTTP_OC_CHUNKED'] = true; - $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-0', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); $file->acquireLock(ILockingProvider::LOCK_SHARED); $this->assertNull($file->put('test data one')); $file->releaseLock(ILockingProvider::LOCK_SHARED); - $info = new \OC\Files\FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/' . $this->user . '/files/test.txt-chunking-12345-2-1', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $thrown = false; @@ -778,30 +941,37 @@ public function testChunkedPutFailsFinalRename() { $file->acquireLock(ILockingProvider::LOCK_SHARED); $file->put($this->getStream('test data')); $file->releaseLock(ILockingProvider::LOCK_SHARED); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + } catch (FileLocked $e) { $thrown = true; } $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } /** * Test put file with invalid chars + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws LockedException|ForbiddenException */ public function testSimplePutInvalidChars() { // setup $view = $this->getMockBuilder(View::class) - ->setMethods(['getRelativePath']) + ->onlyMethods(['getRelativePath']) ->getMock(); $view->expects($this->any()) ->method('getRelativePath') ->willReturnArgument(0); - $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/*', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $thrown = false; @@ -813,42 +983,56 @@ public function testSimplePutInvalidChars() { // afterMethod unlocks $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - } catch (\OCA\DAV\Connector\Sabre\Exception\InvalidPath $e) { + } catch (InvalidPath $e) { $thrown = true; } $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } /** * Test setting name with setName() with invalid chars * + * @throws Exception + * @throws Exception\Forbidden + * @throws InvalidPath + * @throws LockedException */ public function testSetNameInvalidChars() { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\InvalidPath::class); + $this->expectException(InvalidPath::class); // setup $view = $this->getMockBuilder(View::class) - ->setMethods(['getRelativePath']) + ->onlyMethods(['getRelativePath']) ->getMock(); $view->expects($this->any()) ->method('getRelativePath') ->willReturnArgument(0); - $info = new \OC\Files\FileInfo('/*', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/*', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); $file->setName('/super*star.txt'); } + /** + * @throws FileLocked + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws InvalidPath + * @throws Forbidden + * @throws LockedException + * @throws ForbiddenException + */ public function testUploadAbort() { // setup $view = $this->getMockBuilder(View::class) - ->setMethods(['rename', 'getRelativePath', 'filesize']) + ->onlyMethods(['rename', 'getRelativePath', 'filesize']) ->getMock(); $view->expects($this->any()) ->method('rename') @@ -864,11 +1048,11 @@ public function testUploadAbort() { $_SERVER['CONTENT_LENGTH'] = 12345; $_SERVER['REQUEST_METHOD'] = 'PUT'; - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $thrown = false; @@ -880,93 +1064,107 @@ public function testUploadAbort() { // afterMethod unlocks $view->unlockFile($info->getPath(), ILockingProvider::LOCK_SHARED); - } catch (\Sabre\DAV\Exception\BadRequest $e) { + } catch (BadRequest $e) { $thrown = true; } $this->assertTrue($thrown); - $this->assertEmpty($this->listPartFiles($view, ''), 'No stray part files'); + $this->assertEmpty($this->listPartFiles($view), 'No stray part files'); } + /** + * @throws FileLocked + * @throws ServiceUnavailable + * @throws Exception\Forbidden + */ public function testDeleteWhenAllowed() { // setup - $view = $this->getMockBuilder(View::class) - ->getMock(); + $view = $this->createMock(View::class); $view->expects($this->once()) ->method('unlink') ->willReturn(true); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $file->delete(); } + /** + * @throws FileLocked + * @throws ServiceUnavailable + */ public function testDeleteThrowsWhenDeletionNotAllowed() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Exception\Forbidden::class); // setup - $view = $this->getMockBuilder(View::class) - ->getMock(); + $view = $this->createMock(View::class); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ 'permissions' => 0 ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $file->delete(); } + /** + * @throws FileLocked + * @throws ServiceUnavailable + */ public function testDeleteThrowsWhenDeletionFailed() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Exception\Forbidden::class); // setup - $view = $this->getMockBuilder(View::class) - ->getMock(); + $view = $this->createMock(View::class); // but fails $view->expects($this->once()) ->method('unlink') ->willReturn(false); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $file->delete(); } + /** + * @throws FileLocked + * @throws ServiceUnavailable + * @throws Exception\Forbidden + */ public function testDeleteThrowsWhenDeletionThrows() { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class); + $this->expectException(Forbidden::class); // setup - $view = $this->getMockBuilder(View::class) - ->getMock(); + $view = $this->createMock(View::class); // but fails $view->expects($this->once()) ->method('unlink') ->willThrowException(new ForbiddenException('', true)); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // action $file->delete(); @@ -979,7 +1177,7 @@ public function testDeleteThrowsWhenDeletionThrows() { * @param string $signal signal name * @param string $hookPath hook path */ - protected function assertHookCall($callData, $signal, $hookPath) { + protected function assertHookCall(array $callData, string $signal, string $hookPath) { $this->assertEquals($signal, $callData['signal']); $params = $callData['params']; $this->assertEquals( @@ -990,34 +1188,43 @@ protected function assertHookCall($callData, $signal, $hookPath) { /** * Test whether locks are set before and after the operation + * + * @throws Exception + * @throws Exception\Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws LockedException + * @throws \Exception */ public function testPutLocking() { - $view = new \OC\Files\View('/' . $this->user . '/files/'); + $view = new View('/' . $this->user . '/files/'); $path = 'test-locking.txt'; - $info = new \OC\Files\FileInfo( + $info = new FileInfo( '/' . $this->user . '/files/' . $path, $this->getMockStorage(), null, - ['permissions' => \OCP\Constants::PERMISSION_ALL], + ['permissions' => Constants::PERMISSION_ALL], null ); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED), + $this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED), 'File unlocked before put' ); $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE), + $this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE), 'File unlocked before put' ); $wasLockedPre = false; $wasLockedPost = false; - $eventHandler = $this->getMockBuilder(\stdclass::class) - ->setMethods(['writeCallback', 'postWriteCallback']) + $eventHandler = $this->getMockBuilder(stdclass::class) + ->addMethods(['writeCallback', 'postWriteCallback']) ->getMock(); // both pre and post hooks might need access to the file, @@ -1026,26 +1233,26 @@ public function testPutLocking() { ->method('writeCallback') ->willReturnCallback( function () use ($view, $path, &$wasLockedPre) { - $wasLockedPre = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED); - $wasLockedPre = $wasLockedPre && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE); + $wasLockedPre = $this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED); + $wasLockedPre = $wasLockedPre && !$this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE); } ); $eventHandler->expects($this->once()) ->method('postWriteCallback') ->willReturnCallback( function () use ($view, $path, &$wasLockedPost) { - $wasLockedPost = $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED); - $wasLockedPost = $wasLockedPost && !$this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE); + $wasLockedPost = $this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED); + $wasLockedPost = $wasLockedPost && !$this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE); } ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_write, $eventHandler, 'writeCallback' ); - \OCP\Util::connectHook( + Util::connectHook( Filesystem::CLASSNAME, Filesystem::signal_post_write, $eventHandler, @@ -1064,11 +1271,11 @@ function () use ($view, $path, &$wasLockedPost) { $this->assertTrue($wasLockedPost, 'File was locked during post-hooks'); $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_SHARED), + $this->isFileLocked($view, $path, ILockingProvider::LOCK_SHARED), 'File unlocked after put' ); $this->assertFalse( - $this->isFileLocked($view, $path, \OCP\Lock\ILockingProvider::LOCK_EXCLUSIVE), + $this->isFileLocked($view, $path, ILockingProvider::LOCK_EXCLUSIVE), 'File unlocked after put' ); } @@ -1076,14 +1283,15 @@ function () use ($view, $path, &$wasLockedPost) { /** * Returns part files in the given path * - * @param \OC\Files\View view which root is the current user's "files" folder + * @param View|null $userView view which root is the current user's "files" folder * @param string $path path for which to list part files * * @return array list of part files + * @throws ForbiddenException */ - private function listPartFiles(\OC\Files\View $userView = null, $path = '') { + private function listPartFiles(View $userView = null, string $path = ''): array { if ($userView === null) { - $userView = \OC\Files\Filesystem::getView(); + $userView = Filesystem::getView(); } $files = []; [$storage, $internalPath] = $userView->resolvePath($path); @@ -1104,10 +1312,11 @@ private function listPartFiles(\OC\Files\View $userView = null, $path = '') { * returns an array of file information filesize, mtime, filetype, mimetype * * @param string $path - * @param View $userView + * @param View|null $userView * @return array + * @throws InvalidPathException */ - private function getFileInfos($path = '', View $userView = null) { + private function getFileInfos(string $path = '', View $userView = null): array { if ($userView === null) { $userView = Filesystem::getView(); } @@ -1120,64 +1329,92 @@ private function getFileInfos($path = '', View $userView = null) { } + /** + * @throws FileLocked + * @throws Forbidden + * @throws NotFound + * @throws Exception + */ public function testGetFopenFails() { - $this->expectException(\Sabre\DAV\Exception\ServiceUnavailable::class); + $this->expectException(ServiceUnavailable::class); $view = $this->getMockBuilder(View::class) - ->setMethods(['fopen']) + ->onlyMethods(['fopen']) ->getMock(); $view->expects($this->atLeastOnce()) ->method('fopen') ->willReturn(false); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); $file->get(); } + /** + * @throws FileLocked + * @throws NotFound + * @throws Exception + * @throws ServiceUnavailable + */ public function testGetFopenThrows() { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $view = $this->getMockBuilder(View::class) - ->setMethods(['fopen']) + ->onlyMethods(['fopen']) ->getMock(); $view->expects($this->atLeastOnce()) ->method('fopen') ->willThrowException(new ForbiddenException('', true)); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_ALL + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_ALL ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); $file->get(); } + /** + * @throws FileLocked + * @throws Forbidden + * @throws Exception + * @throws ServiceUnavailable + */ public function testGetThrowsIfNoPermission() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $view = $this->getMockBuilder(View::class) - ->setMethods(['fopen']) + ->onlyMethods(['fopen']) ->getMock(); $view->expects($this->never()) ->method('fopen'); - $info = new \OC\Files\FileInfo('/test.txt', $this->getMockStorage(), null, [ - 'permissions' => \OCP\Constants::PERMISSION_CREATE // no read perm + $info = new FileInfo('/test.txt', $this->getMockStorage(), null, [ + 'permissions' => Constants::PERMISSION_CREATE // no read perm ], null); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); $file->get(); } + /** + * @throws FileLocked + * @throws Exception + * @throws ServiceUnavailable + * @throws Exception\Forbidden + * @throws InvalidPath + * @throws Forbidden + * @throws LockedException + * @throws \Exception + */ public function testSimplePutNoCreatePermissions() { $this->logout(); @@ -1209,19 +1446,29 @@ public function testSimplePutNoCreatePermissions() { $this->assertEquals('new content', $view->file_get_contents('root/file.txt')); } + /** + * @throws FileLocked + * @throws Exception + * @throws ServiceUnavailable + * @throws Exception\Forbidden + * @throws InvalidPath + * @throws Forbidden + * @throws LockedException + * @throws \Exception + */ public function testPutLockExpired() { - $view = new \OC\Files\View('/' . $this->user . '/files/'); + $view = new View('/' . $this->user . '/files/'); $path = 'test-locking.txt'; - $info = new \OC\Files\FileInfo( + $info = new FileInfo( '/' . $this->user . '/files/' . $path, $this->getMockStorage(), null, - ['permissions' => \OCP\Constants::PERMISSION_ALL], + ['permissions' => Constants::PERMISSION_ALL], null ); - $file = new \OCA\DAV\Connector\Sabre\File($view, $info); + $file = new File($view, $info); // don't lock before the PUT to simulate an expired shared lock $this->assertNotEmpty($file->put($this->getStream('test data'))); diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php index 201b2b863ab17..ce86f12572b4b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesPluginTest.php @@ -43,6 +43,8 @@ use OCP\IRequest; use OCP\IUserSession; use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; use Sabre\DAV\Server; @@ -73,12 +75,12 @@ class FilesPluginTest extends TestCase { public const HAS_PREVIEW_PROPERTYNAME = FilesPlugin::HAS_PREVIEW_PROPERTYNAME; /** - * @var \Sabre\DAV\Server | \PHPUnit\Framework\MockObject\MockObject + * @var Server | MockObject */ private $server; /** - * @var \Sabre\DAV\Tree | \PHPUnit\Framework\MockObject\MockObject + * @var Tree | MockObject */ private $tree; @@ -88,17 +90,17 @@ class FilesPluginTest extends TestCase { private $plugin; /** - * @var \OCP\IConfig | \PHPUnit\Framework\MockObject\MockObject + * @var IConfig | MockObject */ private $config; /** - * @var \OCP\IRequest | \PHPUnit\Framework\MockObject\MockObject + * @var IRequest | MockObject */ private $request; /** - * @var \OCP\IPreview | \PHPUnit\Framework\MockObject\MockObject + * @var IPreview | MockObject */ private $previewManager; @@ -125,23 +127,15 @@ protected function setUp(): void { $this->userSession ); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $response = $this->createMock(ResponseInterface::class); $this->server->httpResponse = $response; $this->server->xml = new Service(); $this->plugin->initialize($this->server); } - /** - * @param string $class - * @return \PHPUnit\Framework\MockObject\MockObject - */ - private function createTestNode($class, $path = '/dummypath') { - $node = $this->getMockBuilder($class) - ->disableOriginalConstructor() - ->getMock(); + private function createTestNode(string $class): MockObject { + $node = $this->createMock($class); $node->expects($this->any()) ->method('getId') @@ -149,7 +143,7 @@ private function createTestNode($class, $path = '/dummypath') { $this->tree->expects($this->any()) ->method('getNodeForPath') - ->with($path) + ->with('/dummypath') ->willReturn($node); $node->expects($this->any()) @@ -157,7 +151,7 @@ private function createTestNode($class, $path = '/dummypath') { ->willReturn('00000123instanceid'); $node->expects($this->any()) ->method('getInternalFileId') - ->willReturn('123'); + ->willReturn(123); $node->expects($this->any()) ->method('getEtag') ->willReturn('"abc"'); @@ -181,8 +175,8 @@ private function createTestNode($class, $path = '/dummypath') { } public function testGetPropertiesForFile() { - /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + /** @var File | MockObject $node */ + $node = $this->createTestNode(File::class); $propFind = new PropFind( '/dummyPath', @@ -201,8 +195,7 @@ public function testGetPropertiesForFile() { 0 ); - $user = $this->getMockBuilder(User::class) - ->disableOriginalConstructor()->getMock(); + $user = $this->createMock(User::class); $user ->expects($this->once()) ->method('getUID') @@ -238,8 +231,8 @@ public function testGetPropertiesForFile() { } public function testGetPropertiesStorageNotAvailable() { - /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + /** @var File | MockObject $node */ + $node = $this->createTestNode(File::class); $propFind = new PropFind( '/dummyPath', @@ -265,9 +258,7 @@ public function testGetPublicPermissions() { $this->plugin = new FilesPlugin( $this->tree, $this->config, - $this->getMockBuilder(IRequest::class) - ->disableOriginalConstructor() - ->getMock(), + $this->createMock(IRequest::class), $this->previewManager, $this->userSession, true); @@ -281,8 +272,8 @@ public function testGetPublicPermissions() { 0 ); - /** @var \OCA\DAV\Connector\Sabre\File | \PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + /** @var File | MockObject $node */ + $node = $this->createTestNode(File::class); $node->expects($this->any()) ->method('getDavPermissions') ->willReturn('DWCKMSR'); @@ -296,8 +287,8 @@ public function testGetPublicPermissions() { } public function testGetPropertiesForDirectory() { - /** @var \OCA\DAV\Connector\Sabre\Directory | \PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); + /** @var Directory | MockObject $node */ + $node = $this->createTestNode(Directory::class); $propFind = new PropFind( '/dummyPath', @@ -331,10 +322,8 @@ public function testGetPropertiesForDirectory() { } public function testGetPropertiesForRootDirectory() { - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var Directory|MockObject $node */ + $node = $this->createMock(Directory::class); $node->expects($this->any())->method('getPath')->willReturn('/'); $fileInfo = $this->createMock(FileInfo::class); @@ -367,10 +356,8 @@ public function testGetPropertiesWhenNoPermission() { // But we still want to load the directory list, so this is okay for us. // $this->expectException(\Sabre\DAV\Exception\NotFound::class); - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var Directory|MockObject $node */ + $node = $this->createMock(Directory::class); $node->expects($this->any())->method('getPath')->willReturn('/'); $fileInfo = $this->createMock(FileInfo::class); @@ -398,8 +385,11 @@ public function testGetPropertiesWhenNoPermission() { $this->addToAssertionCount(1); } + /** + * @throws NotFound + */ public function testUpdateProps() { - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\File'); + $node = $this->createTestNode(File::class); $testDate = 'Fri, 13 Feb 2015 00:01:02 GMT'; $testCreationDate = '2007-08-31T16:47+00:00'; @@ -411,7 +401,7 @@ public function testUpdateProps() { $node->expects($this->once()) ->method('setEtag') ->with('newetag') - ->willReturn(true); + ->willReturn(1); $node->expects($this->once()) ->method('setCreationTime') @@ -439,6 +429,9 @@ public function testUpdateProps() { $this->assertEquals(200, $result[self::CREATIONDATE_PROPERTYNAME]); } + /** + * @throws NotFound + */ public function testUpdatePropsForbidden() { $propPatch = new PropPatch([ self::OWNER_ID_PROPERTYNAME => 'user2', @@ -477,21 +470,18 @@ public function testUpdatePropsForbidden() { * FolderA is an incoming shared folder and there are no delete permissions. * Thus moving /FolderA/test.txt to /test.txt should fail already on that check * + * @throws NotFound */ public function testMoveSrcNotDeletable() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->expectExceptionMessage('FolderA/test.txt cannot be deleted'); - $fileInfoFolderATestTXT = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $fileInfoFolderATestTXT = $this->createMock(FileInfo::class); $fileInfoFolderATestTXT->expects($this->once()) ->method('isDeletable') ->willReturn(false); - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Node::class); $node->expects($this->once()) ->method('getFileInfo') ->willReturn($fileInfoFolderATestTXT); @@ -502,17 +492,17 @@ public function testMoveSrcNotDeletable() { $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); } + /** + * @throws Forbidden + * @throws NotFound + */ public function testMoveSrcDeletable() { - $fileInfoFolderATestTXT = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $fileInfoFolderATestTXT = $this->createMock(FileInfo::class); $fileInfoFolderATestTXT->expects($this->once()) ->method('isDeletable') ->willReturn(true); - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Node::class); $node->expects($this->once()) ->method('getFileInfo') ->willReturn($fileInfoFolderATestTXT); @@ -524,13 +514,14 @@ public function testMoveSrcDeletable() { } + /** + * @throws Forbidden + */ public function testMoveSrcNotExist() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->expectExceptionMessage('FolderA/test.txt does not exist'); - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Node::class); $node->expects($this->once()) ->method('getFileInfo') ->willReturn(null); @@ -541,7 +532,7 @@ public function testMoveSrcNotExist() { $this->plugin->checkMove('FolderA/test.txt', 'test.txt'); } - public function downloadHeadersProvider() { + public function downloadHeadersProvider(): array { return [ [ false, @@ -556,23 +547,18 @@ public function downloadHeadersProvider() { /** * @dataProvider downloadHeadersProvider + * @throws NotFound */ public function testDownloadHeaders($isClumsyAgent, $contentDispositionHeader) { - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request ->expects($this->once()) ->method('getPath') ->willReturn('test/somefile.xml'); - $node = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(File::class); $node ->expects($this->once()) ->method('getName') @@ -598,8 +584,8 @@ public function testDownloadHeaders($isClumsyAgent, $contentDispositionHeader) { } public function testHasPreview() { - /** @var \OCA\DAV\Connector\Sabre\Directory | \PHPUnit\Framework\MockObject\MockObject $node */ - $node = $this->createTestNode('\OCA\DAV\Connector\Sabre\Directory'); + /** @var Directory | MockObject $node */ + $node = $this->createTestNode(Directory::class); $propFind = new PropFind( '/dummyPath', diff --git a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php index 29852c245ed26..a6b07a42ead2a 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FilesReportPluginTest.php @@ -28,11 +28,14 @@ use OC\Files\View; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\File as SabreFile; +use OCA\DAV\Connector\Sabre\FilesPlugin; use OCA\DAV\Connector\Sabre\FilesReportPlugin as FilesReportPluginImplementation; use OCP\App\IAppManager; use OCP\Files\File; use OCP\Files\FileInfo; use OCP\Files\Folder; +use OCP\Files\NotFoundException; use OCP\IConfig; use OCP\IGroupManager; use OCP\IPreview; @@ -44,85 +47,67 @@ use OCP\SystemTag\ISystemTag; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; +use OCP\SystemTag\TagNotFoundException; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\PreconditionFailed; use Sabre\DAV\INode; +use Sabre\DAV\Server; use Sabre\DAV\Tree; +use Sabre\DAV\Xml\Property\ResourceType; use Sabre\HTTP\ResponseInterface; +use Test\TestCase; -class FilesReportPluginTest extends \Test\TestCase { - /** @var \Sabre\DAV\Server|\PHPUnit\Framework\MockObject\MockObject */ +class FilesReportPluginTest extends TestCase { + /** @var Server|MockObject */ private $server; - /** @var \Sabre\DAV\Tree|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Tree|MockObject */ private $tree; - /** @var ISystemTagObjectMapper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISystemTagObjectMapper|MockObject */ private $tagMapper; - /** @var ISystemTagManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISystemTagManager|MockObject */ private $tagManager; - /** @var ITags|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITags|MockObject */ private $privateTags; - /** @var \OCP\IUserSession */ - private $userSession; - /** @var FilesReportPluginImplementation */ private $plugin; - /** @var View|\PHPUnit\Framework\MockObject\MockObject **/ - private $view; - - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject **/ + /** @var IGroupManager|MockObject **/ private $groupManager; - /** @var Folder|\PHPUnit\Framework\MockObject\MockObject **/ + /** @var Folder|MockObject **/ private $userFolder; - /** @var IPreview|\PHPUnit\Framework\MockObject\MockObject * */ + /** @var IPreview|MockObject * */ private $previewManager; - /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject * */ - private $appManager; - protected function setUp(): void { parent::setUp(); - $this->tree = $this->getMockBuilder(Tree::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') + $this->tree = $this->createMock(Tree::class); + $view = $this->createMock(View::class); + $this->server = $this->getMockBuilder(Server::class) ->setConstructorArgs([$this->tree]) - ->setMethods(['getRequestUri', 'getBaseUri']) + ->onlyMethods(['getRequestUri', 'getBaseUri']) ->getMock(); $this->server->expects($this->any()) ->method('getBaseUri') ->willReturn('http://example.com/owncloud/remote.php/dav'); - $this->groupManager = $this->getMockBuilder(IGroupManager::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->userFolder = $this->getMockBuilder(Folder::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->previewManager = $this->getMockBuilder(IPreview::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->appManager = $this->getMockBuilder(IAppManager::class) - ->disableOriginalConstructor() - ->getMock(); - + $this->groupManager = $this->createMock(IGroupManager::class); + $this->userFolder = $this->createMock(Folder::class); + $this->previewManager = $this->createMock(IPreview::class); + /** @var IAppManager|MockObject $appManager */ + $appManager = $this->createMock(IAppManager::class); $this->tagManager = $this->createMock(ISystemTagManager::class); $this->tagMapper = $this->createMock(ISystemTagObjectMapper::class); - $this->userSession = $this->createMock(IUserSession::class); + $userSession = $this->createMock(IUserSession::class); $this->privateTags = $this->createMock(ITags::class); $privateTagManager = $this->createMock(ITagManager::class); $privateTagManager->expects($this->any()) @@ -130,26 +115,24 @@ protected function setUp(): void { ->with('files') ->willReturn($this->privateTags); - $user = $this->getMockBuilder(IUser::class) - ->disableOriginalConstructor() - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('testuser'); - $this->userSession->expects($this->any()) + $userSession->expects($this->any()) ->method('getUser') ->willReturn($user); $this->plugin = new FilesReportPluginImplementation( $this->tree, - $this->view, + $view, $this->tagManager, $this->tagMapper, $privateTagManager, - $this->userSession, + $userSession, $this->groupManager, $this->userFolder, - $this->appManager + $appManager ); } @@ -166,9 +149,7 @@ public function testOnReportInvalidNode() { ->method('getNodeForPath') ->with('/' . $path) ->willReturn( - $this->getMockBuilder(INode::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(INode::class) ); $this->server->expects($this->any()) @@ -179,6 +160,12 @@ public function testOnReportInvalidNode() { $this->assertNull($this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, [], '/' . $path)); } + /** + * @throws PreconditionFailed + * @throws BadRequest + * @throws NotFound + * @throws NotFoundException + */ public function testOnReportInvalidReportName() { $path = 'test'; @@ -186,9 +173,7 @@ public function testOnReportInvalidReportName() { ->method('getNodeForPath') ->with('/' . $path) ->willReturn( - $this->getMockBuilder(INode::class) - ->disableOriginalConstructor() - ->getMock() + $this->createMock(INode::class) ); $this->server->expects($this->any()) @@ -199,6 +184,12 @@ public function testOnReportInvalidReportName() { $this->assertNull($this->plugin->onReport('{whoever}whatever', [], '/' . $path)); } + /** + * @throws PreconditionFailed + * @throws BadRequest + * @throws NotFound + * @throws NotFoundException + */ public function testOnReport() { $path = 'test'; @@ -223,25 +214,23 @@ public function testOnReport() { ->method('isAdmin') ->willReturn(true); - $this->tagMapper->expects($this->at(0)) - ->method('getObjectIdsForTags') - ->with('123', 'files') - ->willReturn(['111', '222']); - $this->tagMapper->expects($this->at(1)) + $this->tagMapper->expects($this->exactly(2)) ->method('getObjectIdsForTags') - ->with('456', 'files') - ->willReturn(['111', '222', '333']); + ->withConsecutive( + ['123', 'files'], + ['456', 'files'] + ) + ->willReturnOnConsecutiveCalls( + ['111', '222'], + ['111', '222', '333'] + ); - $reportTargetNode = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + $reportTargetNode = $this->createMock(Directory::class); $reportTargetNode->expects($this->any()) ->method('getPath') ->willReturn(''); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $response = $this->createMock(ResponseInterface::class); $response->expects($this->once()) ->method('setHeader') @@ -259,21 +248,16 @@ public function testOnReport() { ->with('/' . $path) ->willReturn($reportTargetNode); - $filesNode1 = $this->getMockBuilder(Folder::class) - ->disableOriginalConstructor() - ->getMock(); - $filesNode2 = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $filesNode1 = $this->createMock(Folder::class); + $filesNode2 = $this->createMock(File::class); - $this->userFolder->expects($this->at(0)) - ->method('getById') - ->with('111') - ->willReturn([$filesNode1]); - $this->userFolder->expects($this->at(1)) + $this->userFolder->expects($this->exactly(2)) ->method('getById') - ->with('222') - ->willReturn([$filesNode2]); + ->withConsecutive( + ['111'], ['222'] + )->willReturnOnConsecutiveCalls( + [$filesNode1], [$filesNode2] + ); $this->server->expects($this->any()) ->method('getRequestUri') @@ -284,95 +268,85 @@ public function testOnReport() { $this->assertFalse($this->plugin->onReport(FilesReportPluginImplementation::REPORT_NAME, $parameters, '/' . $path)); } + /** + * @throws NotFoundException + */ public function testFindNodesByFileIdsRoot() { - $filesNode1 = $this->getMockBuilder(Folder::class) - ->disableOriginalConstructor() - ->getMock(); + $filesNode1 = $this->createMock(Folder::class); $filesNode1->expects($this->once()) ->method('getName') ->willReturn('first node'); - $filesNode2 = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $filesNode2 = $this->createMock(File::class); $filesNode2->expects($this->once()) ->method('getName') ->willReturn('second node'); - $reportTargetNode = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + $reportTargetNode = $this->createMock(Directory::class); $reportTargetNode->expects($this->any()) ->method('getPath') ->willReturn('/'); - $this->userFolder->expects($this->at(0)) + $this->userFolder->expects($this->exactly(2)) ->method('getById') - ->with('111') - ->willReturn([$filesNode1]); - $this->userFolder->expects($this->at(1)) - ->method('getById') - ->with('222') - ->willReturn([$filesNode2]); + ->withConsecutive( + ['111'], ['222'] + )->willReturnOnConsecutiveCalls( + [$filesNode1], [$filesNode2] + ); - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit\Framework\MockObject\MockObject $reportTargetNode */ + /** @var Directory|MockObject $reportTargetNode */ $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); + $this->assertInstanceOf(Directory::class, $result[0]); $this->assertEquals('first node', $result[0]->getName()); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); + $this->assertInstanceOf(SabreFile::class, $result[1]); $this->assertEquals('second node', $result[1]->getName()); } + /** + * @throws NotFoundException + */ public function testFindNodesByFileIdsSubDir() { - $filesNode1 = $this->getMockBuilder(Folder::class) - ->disableOriginalConstructor() - ->getMock(); + $filesNode1 = $this->createMock(Folder::class); $filesNode1->expects($this->once()) ->method('getName') ->willReturn('first node'); - $filesNode2 = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $filesNode2 = $this->createMock(File::class); $filesNode2->expects($this->once()) ->method('getName') ->willReturn('second node'); - $reportTargetNode = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); - $reportTargetNode->expects($this->any()) + $reportTargetNode = $this->createMock(Directory::class); + $reportTargetNode->expects($this->exactly(2)) ->method('getPath') ->willReturn('/sub1/sub2'); - $subNode = $this->getMockBuilder(Folder::class) - ->disableOriginalConstructor() - ->getMock(); + $subNode = $this->createMock(Folder::class); - $this->userFolder->expects($this->at(0)) + $this->userFolder->expects($this->once()) ->method('get') ->with('/sub1/sub2') ->willReturn($subNode); - $subNode->expects($this->at(0)) - ->method('getById') - ->with('111') - ->willReturn([$filesNode1]); - $subNode->expects($this->at(1)) + $subNode->expects($this->exactly(2)) ->method('getById') - ->with('222') - ->willReturn([$filesNode2]); + ->withConsecutive( + ['111'], ['222'] + )->willReturnOnConsecutiveCalls( + [$filesNode1], [$filesNode2] + ); - /** @var \OCA\DAV\Connector\Sabre\Directory|\PHPUnit\Framework\MockObject\MockObject $reportTargetNode */ + /** @var Directory|MockObject $reportTargetNode */ $result = $this->plugin->findNodesByFileIds($reportTargetNode, ['111', '222']); $this->assertCount(2, $result); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\Directory', $result[0]); + $this->assertInstanceOf(Directory::class, $result[0]); $this->assertEquals('first node', $result[0]->getName()); - $this->assertInstanceOf('\OCA\DAV\Connector\Sabre\File', $result[1]); + $this->assertInstanceOf(SabreFile::class, $result[1]); $this->assertEquals('second node', $result[1]->getName()); } @@ -382,23 +356,19 @@ public function testPrepareResponses() { $fileInfo = $this->createMock(FileInfo::class); $fileInfo->method('isReadable')->willReturn(true); - $node1 = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); - $node2 = $this->getMockBuilder(\OCA\DAV\Connector\Sabre\File::class) - ->disableOriginalConstructor() - ->getMock(); + $node1 = $this->createMock(Directory::class); + $node2 = $this->createMock(SabreFile::class); $node1->expects($this->once()) ->method('getInternalFileId') - ->willReturn('111'); + ->willReturn(111); $node1->expects($this->any()) ->method('getPath') ->willReturn('/node1'); $node1->method('getFileInfo')->willReturn($fileInfo); $node2->expects($this->once()) ->method('getInternalFileId') - ->willReturn('222'); + ->willReturn(222); $node2->expects($this->once()) ->method('getSize') ->willReturn(1024); @@ -407,12 +377,10 @@ public function testPrepareResponses() { ->willReturn('/sub/node2'); $node2->method('getFileInfo')->willReturn($fileInfo); - $config = $this->getMockBuilder(IConfig::class) - ->disableOriginalConstructor() - ->getMock(); + $config = $this->createMock(IConfig::class); $this->server->addPlugin( - new \OCA\DAV\Connector\Sabre\FilesPlugin( + new FilesPlugin( $this->tree, $config, $this->createMock(IRequest::class), @@ -434,14 +402,14 @@ public function testPrepareResponses() { $props1 = $responses[0]->getResponseProperties(); $this->assertEquals('111', $props1[200]['{http://owncloud.org/ns}fileid']); $this->assertNull($props1[404]['{DAV:}getcontentlength']); - $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props1[200]['{DAV:}resourcetype']); + $this->assertInstanceOf(ResourceType::class, $props1[200]['{DAV:}resourcetype']); $resourceType1 = $props1[200]['{DAV:}resourcetype']->getValue(); $this->assertEquals('{DAV:}collection', $resourceType1[0]); $props2 = $responses[1]->getResponseProperties(); $this->assertEquals('1024', $props2[200]['{DAV:}getcontentlength']); $this->assertEquals('222', $props2[200]['{http://owncloud.org/ns}fileid']); - $this->assertInstanceOf('\Sabre\DAV\Xml\Property\ResourceType', $props2[200]['{DAV:}resourcetype']); + $this->assertInstanceOf(ResourceType::class, $props2[200]['{DAV:}resourcetype']); $this->assertCount(0, $props2[200]['{DAV:}resourcetype']->getValue()); } @@ -570,9 +538,7 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { ->method('isAdmin') ->willReturn(true); - $tag1 = $this->getMockBuilder(ISystemTag::class) - ->disableOriginalConstructor() - ->getMock(); + $tag1 = $this->createMock(ISystemTag::class); $tag1->expects($this->any()) ->method('getId') ->willReturn('123'); @@ -580,9 +546,7 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { ->method('isUserVisible') ->willReturn(true); - $tag2 = $this->getMockBuilder(ISystemTag::class) - ->disableOriginalConstructor() - ->getMock(); + $tag2 = $this->createMock(ISystemTag::class); $tag2->expects($this->any()) ->method('getId') ->willReturn('123'); @@ -594,14 +558,10 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { $this->tagManager->expects($this->never()) ->method('getTagsByIds'); - $this->tagMapper->expects($this->at(0)) - ->method('getObjectIdsForTags') - ->with('123') - ->willReturn(['111', '222']); - $this->tagMapper->expects($this->at(1)) + $this->tagMapper->expects($this->exactly(2)) ->method('getObjectIdsForTags') - ->with('456') - ->willReturn(['222', '333']); + ->withConsecutive(['123'], ['456']) + ->willReturnOnConsecutiveCalls(['111', '222'], ['222', '333']); $rules = [ ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], @@ -613,15 +573,13 @@ public function testProcessFilterRulesInvisibleTagAsAdmin() { public function testProcessFilterRulesInvisibleTagAsUser() { - $this->expectException(\OCP\SystemTag\TagNotFoundException::class); + $this->expectException(TagNotFoundException::class); $this->groupManager->expects($this->any()) ->method('isAdmin') ->willReturn(false); - $tag1 = $this->getMockBuilder(ISystemTag::class) - ->disableOriginalConstructor() - ->getMock(); + $tag1 = $this->createMock(ISystemTag::class); $tag1->expects($this->any()) ->method('getId') ->willReturn('123'); @@ -629,9 +587,7 @@ public function testProcessFilterRulesInvisibleTagAsUser() { ->method('isUserVisible') ->willReturn(true); - $tag2 = $this->getMockBuilder(ISystemTag::class) - ->disableOriginalConstructor() - ->getMock(); + $tag2 = $this->createMock(ISystemTag::class); $tag2->expects($this->any()) ->method('getId') ->willReturn('123'); @@ -657,9 +613,7 @@ public function testProcessFilterRulesVisibleTagAsUser() { ->method('isAdmin') ->willReturn(false); - $tag1 = $this->getMockBuilder(ISystemTag::class) - ->disableOriginalConstructor() - ->getMock(); + $tag1 = $this->createMock(ISystemTag::class); $tag1->expects($this->any()) ->method('getId') ->willReturn('123'); @@ -667,9 +621,7 @@ public function testProcessFilterRulesVisibleTagAsUser() { ->method('isUserVisible') ->willReturn(true); - $tag2 = $this->getMockBuilder(ISystemTag::class) - ->disableOriginalConstructor() - ->getMock(); + $tag2 = $this->createMock(ISystemTag::class); $tag2->expects($this->any()) ->method('getId') ->willReturn('123'); @@ -682,14 +634,10 @@ public function testProcessFilterRulesVisibleTagAsUser() { ->with(['123', '456']) ->willReturn([$tag1, $tag2]); - $this->tagMapper->expects($this->at(0)) - ->method('getObjectIdsForTags') - ->with('123') - ->willReturn(['111', '222']); - $this->tagMapper->expects($this->at(1)) + $this->tagMapper->expects($this->exactly(2)) ->method('getObjectIdsForTags') - ->with('456') - ->willReturn(['222', '333']); + ->withConsecutive(['123'], ['456']) + ->willReturnOnConsecutiveCalls(['111', '222'], ['222', '333']); $rules = [ ['name' => '{http://owncloud.org/ns}systemtag', 'value' => '123'], @@ -711,7 +659,7 @@ public function testProcessFavoriteFilter() { $this->assertEquals(['456', '789'], array_values($this->invokePrivate($this->plugin, 'processFilterRules', [$rules]))); } - public function filesBaseUriProvider() { + public function filesBaseUriProvider(): array { return [ ['', '', ''], ['files/username', '', '/files/username'], @@ -724,7 +672,7 @@ public function filesBaseUriProvider() { /** * @dataProvider filesBaseUriProvider */ - public function testFilesBaseUri($uri, $reportPath, $expectedUri) { + public function testFilesBaseUri(string $uri, string $reportPath, string $expectedUri) { $this->assertEquals($expectedUri, $this->invokePrivate($this->plugin, 'getFilesBaseUri', [$uri, $reportPath])); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php index 3f38008559ca5..12c02c5b5fc74 100644 --- a/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/MaintenancePluginTest.php @@ -29,6 +29,8 @@ use OCA\DAV\Connector\Sabre\MaintenancePlugin; use OCP\IConfig; use OCP\IL10N; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\ServiceUnavailable; use Test\TestCase; /** @@ -37,9 +39,9 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre */ class MaintenancePluginTest extends TestCase { - /** @var IConfig */ + /** @var IConfig|MockObject */ private $config; - /** @var \PHPUnit\Framework\MockObject\Builder\InvocationMocker|\PHPUnit_Framework_MockObject_Builder_InvocationMocker|IL10N */ + /** @var IL10N|MockObject */ private $l10n; /** @var MaintenancePlugin */ private $maintenancePlugin; @@ -47,14 +49,14 @@ class MaintenancePluginTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->config = $this->getMockBuilder(IConfig::class)->getMock(); - $this->l10n = $this->getMockBuilder(IL10N::class)->getMock(); + $this->config = $this->createMock(IConfig::class); + $this->l10n = $this->createMock(IL10N::class); $this->maintenancePlugin = new MaintenancePlugin($this->config, $this->l10n); } public function testMaintenanceMode() { - $this->expectException(\Sabre\DAV\Exception\ServiceUnavailable::class); + $this->expectException(ServiceUnavailable::class); $this->expectExceptionMessage('System is in maintenance mode.'); $this->config diff --git a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php index 9889dcbe3bd9c..b036dd4539353 100644 --- a/apps/dav/tests/unit/Connector/Sabre/NodeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/NodeTest.php @@ -27,12 +27,16 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre; +use InvalidArgumentException; use OC\Files\FileInfo; use OC\Files\View; +use OCA\DAV\Connector\Sabre\File; +use OCP\Constants; use OCP\Files\Mount\IMountPoint; use OCP\Files\Storage\IStorage; use OCP\Share\IManager; use OCP\Share\IShare; +use Test\TestCase; /** * Class NodeTest @@ -40,30 +44,30 @@ * @group DB * @package OCA\DAV\Tests\unit\Connector\Sabre */ -class NodeTest extends \Test\TestCase { - public function davPermissionsProvider() { +class NodeTest extends TestCase { + public function davPermissionsProvider(): array { return [ - [\OCP\Constants::PERMISSION_ALL, 'file', false, false, 'RGDNVW'], - [\OCP\Constants::PERMISSION_ALL, 'dir', false, false, 'RGDNVCK'], - [\OCP\Constants::PERMISSION_ALL, 'file', true, false, 'SRGDNVW'], - [\OCP\Constants::PERMISSION_ALL, 'file', true, true, 'SRMGDNVW'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_SHARE, 'file', true, false, 'SGDNVW'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_UPDATE, 'file', false, false, 'RGD'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_DELETE, 'file', false, false, 'RGNVW'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, 'file', false, false, 'RGDNVW'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_READ, 'file', false, false, 'RDNVW'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE, 'dir', false, false, 'RGDNV'], - [\OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_READ, 'dir', false, false, 'RDNVCK'], + [Constants::PERMISSION_ALL, 'file', false, false, 'RGDNVW'], + [Constants::PERMISSION_ALL, 'dir', false, false, 'RGDNVCK'], + [Constants::PERMISSION_ALL, 'file', true, false, 'SRGDNVW'], + [Constants::PERMISSION_ALL, 'file', true, true, 'SRMGDNVW'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_SHARE, 'file', true, false, 'SGDNVW'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_UPDATE, 'file', false, false, 'RGD'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_DELETE, 'file', false, false, 'RGNVW'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE, 'file', false, false, 'RGDNVW'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_READ, 'file', false, false, 'RDNVW'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_CREATE, 'dir', false, false, 'RGDNV'], + [Constants::PERMISSION_ALL - Constants::PERMISSION_READ, 'dir', false, false, 'RDNVCK'], ]; } /** * @dataProvider davPermissionsProvider */ - public function testDavPermissions($permissions, $type, $shared, $mounted, $expected) { + public function testDavPermissions(int $permissions, string $type, bool $shared, bool $mounted, string $expected) { $info = $this->getMockBuilder(FileInfo::class) ->disableOriginalConstructor() - ->setMethods(['getPermissions', 'isShared', 'isMounted', 'getType']) + ->onlyMethods(['getPermissions', 'isShared', 'isMounted', 'getType']) ->getMock(); $info->expects($this->any()) ->method('getPermissions') @@ -77,15 +81,13 @@ public function testDavPermissions($permissions, $type, $shared, $mounted, $expe $info->expects($this->any()) ->method('getType') ->willReturn($type); - $view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); + $view = $this->createMock(View::class); - $node = new \OCA\DAV\Connector\Sabre\File($view, $info); + $node = new File($view, $info); $this->assertEquals($expected, $node->getDavPermissions()); } - public function sharePermissionsProvider() { + public function sharePermissionsProvider(): array { return [ [\OCP\Files\FileInfo::TYPE_FILE, null, 1, 1], [\OCP\Files\FileInfo::TYPE_FILE, null, 3, 3], @@ -128,18 +130,14 @@ public function sharePermissionsProvider() { /** * @dataProvider sharePermissionsProvider */ - public function testSharePermissions($type, $user, $permissions, $expected) { - $storage = $this->getMockBuilder(IStorage::class) - ->disableOriginalConstructor() - ->getMock(); + public function testSharePermissions(string $type, ?string $user, int $permissions, int $expected) { + $storage = $this->createMock(IStorage::class); $storage->method('getPermissions')->willReturn($permissions); - $mountpoint = $this->getMockBuilder(IMountPoint::class) - ->disableOriginalConstructor() - ->getMock(); + $mountpoint = $this->createMock(IMountPoint::class); $mountpoint->method('getMountPoint')->willReturn('myPath'); - $shareManager = $this->getMockBuilder(IManager::class)->disableOriginalConstructor()->getMock(); - $share = $this->getMockBuilder(IShare::class)->disableOriginalConstructor()->getMock(); + $shareManager = $this->createMock(IManager::class); + $share = $this->createMock(IShare::class); if ($user === null) { $shareManager->expects($this->never())->method('getShareByToken'); @@ -152,7 +150,7 @@ public function testSharePermissions($type, $user, $permissions, $expected) { $info = $this->getMockBuilder(FileInfo::class) ->disableOriginalConstructor() - ->setMethods(['getStorage', 'getType', 'getMountPoint', 'getPermissions']) + ->onlyMethods(['getStorage', 'getType', 'getMountPoint', 'getPermissions']) ->getMock(); $info->method('getStorage')->willReturn($storage); @@ -160,16 +158,14 @@ public function testSharePermissions($type, $user, $permissions, $expected) { $info->method('getMountPoint')->willReturn($mountpoint); $info->method('getPermissions')->willReturn($permissions); - $view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); + $view = $this->createMock(View::class); - $node = new \OCA\DAV\Connector\Sabre\File($view, $info); + $node = new File($view, $info); $this->invokePrivate($node, 'shareManager', [$shareManager]); $this->assertEquals($expected, $node->getSharePermissions($user)); } - public function sanitizeMtimeProvider() { + public function sanitizeMtimeProvider(): array { return [ [123456789, 123456789], ['987654321', 987654321], @@ -179,20 +175,16 @@ public function sanitizeMtimeProvider() { /** * @dataProvider sanitizeMtimeProvider */ - public function testSanitizeMtime($mtime, $expected) { - $view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); - $info = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + public function testSanitizeMtime($mtime, int $expected) { + $view = $this->createMock(View::class); + $info = $this->createMock(FileInfo::class); - $node = new \OCA\DAV\Connector\Sabre\File($view, $info); + $node = new File($view, $info); $result = $this->invokePrivate($node, 'sanitizeMtime', [$mtime]); $this->assertEquals($expected, $result); } - public function invalidSanitizeMtimeProvider() { + public function invalidSanitizeMtimeProvider(): array { return [ [-1337], [0], ['abcdef'], ['-1337'], ['0'], [12321], [24 * 60 * 60 - 1] ]; @@ -202,16 +194,12 @@ public function invalidSanitizeMtimeProvider() { * @dataProvider invalidSanitizeMtimeProvider */ public function testInvalidSanitizeMtime($mtime) { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); - $view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); - $info = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $view = $this->createMock(View::class); + $info = $this->createMock(FileInfo::class); - $node = new \OCA\DAV\Connector\Sabre\File($view, $info); - $result = $this->invokePrivate($node, 'sanitizeMtime', [$mtime]); + $node = new File($view, $info); + $this->invokePrivate($node, 'sanitizeMtime', [$mtime]); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php index 7416cf7a3f7ae..cd95f40051175 100644 --- a/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/ObjectTreeTest.php @@ -30,11 +30,21 @@ use OC\Files\FileInfo; use OC\Files\Filesystem; use OC\Files\Mount\Manager; +use OC\Files\Storage\Common; use OC\Files\Storage\Temporary; use OC\Files\View; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\Exception\FileLocked; +use OCA\DAV\Connector\Sabre\Exception\InvalidPath; +use OCA\DAV\Connector\Sabre\File; use OCA\DAV\Connector\Sabre\ObjectTree; use OCP\Files\Mount\IMountManager; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\Locked; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\ServiceUnavailable; +use Sabre\DAV\INode; +use Test\TestCase; /** * Class ObjectTreeTest @@ -43,8 +53,8 @@ * * @package OCA\DAV\Tests\Unit\Connector\Sabre */ -class ObjectTreeTest extends \Test\TestCase { - public function copyDataProvider() { +class ObjectTreeTest extends TestCase { + public function copyDataProvider(): array { return [ // copy into same dir ['a', 'b', ''], @@ -57,8 +67,15 @@ public function copyDataProvider() { /** * @dataProvider copyDataProvider + * @throws FileLocked + * @throws Forbidden + * @throws InvalidPath + * @throws Locked + * @throws NotFound + * @throws ServiceUnavailable + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden */ - public function testCopy($sourcePath, $targetPath, $targetParent) { + public function testCopy(string $sourcePath, string $targetPath, string $targetParent) { $view = $this->createMock(View::class); $view->expects($this->once()) ->method('verifyPath') @@ -85,7 +102,7 @@ public function testCopy($sourcePath, $targetPath, $targetParent) { $rootDir = new Directory($view, $info); $objectTree = $this->getMockBuilder(ObjectTree::class) - ->setMethods(['nodeExists', 'getNodeForPath']) + ->onlyMethods(['nodeExists', 'getNodeForPath']) ->setConstructorArgs([$rootDir, $view]) ->getMock(); @@ -94,7 +111,7 @@ public function testCopy($sourcePath, $targetPath, $targetParent) { ->with($this->identicalTo($sourcePath)) ->willReturn(false); - /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ + /** @var $objectTree ObjectTree */ $mountManager = Filesystem::getMountManager(); $objectTree->init($rootDir, $view, $mountManager); $objectTree->copy($sourcePath, $targetPath); @@ -102,9 +119,16 @@ public function testCopy($sourcePath, $targetPath, $targetParent) { /** * @dataProvider copyDataProvider + * @throws Forbidden + * @throws ServiceUnavailable + * @throws FileLocked + * @throws \OCA\DAV\Connector\Sabre\Exception\Forbidden + * @throws InvalidPath + * @throws Locked + * @throws NotFound */ - public function testCopyFailNotCreatable($sourcePath, $targetPath, $targetParent) { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + public function testCopyFailNotCreatable(string $sourcePath, string $targetPath, string $targetParent) { + $this->expectException(Forbidden::class); $view = $this->createMock(View::class); $view->expects($this->never()) @@ -128,14 +152,14 @@ public function testCopyFailNotCreatable($sourcePath, $targetPath, $targetParent $rootDir = new Directory($view, $info); $objectTree = $this->getMockBuilder(ObjectTree::class) - ->setMethods(['nodeExists', 'getNodeForPath']) + ->onlyMethods(['nodeExists', 'getNodeForPath']) ->setConstructorArgs([$rootDir, $view]) ->getMock(); $objectTree->expects($this->never()) ->method('getNodeForPath'); - /** @var $objectTree \OCA\DAV\Connector\Sabre\ObjectTree */ + /** @var $objectTree ObjectTree */ $mountManager = Filesystem::getMountManager(); $objectTree->init($rootDir, $view, $mountManager); $objectTree->copy($sourcePath, $targetPath); @@ -143,30 +167,27 @@ public function testCopyFailNotCreatable($sourcePath, $targetPath, $targetParent /** * @dataProvider nodeForPathProvider + * @throws Forbidden + * @throws InvalidPath + * @throws Locked + * @throws NotFound + * @throws ServiceUnavailable */ public function testGetNodeForPath( - $inputFileName, - $fileInfoQueryPath, - $outputFileName, - $type, - $enableChunkingHeader + string $inputFileName, + string $fileInfoQueryPath, + string $outputFileName, + string $type, + bool $enableChunkingHeader ) { if ($enableChunkingHeader) { $_SERVER['HTTP_OC_CHUNKED'] = true; } - $rootNode = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); - $mountManager = $this->getMockBuilder(Manager::class) - ->disableOriginalConstructor() - ->getMock(); - $view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); - $fileInfo = $this->getMockBuilder(FileInfo::class) - ->disableOriginalConstructor() - ->getMock(); + $rootNode = $this->createMock(Directory::class); + $mountManager = $this->createMock(Manager::class); + $view = $this->createMock(View::class); + $fileInfo = $this->createMock(FileInfo::class); $fileInfo->expects($this->once()) ->method('getType') ->willReturn($type); @@ -174,14 +195,14 @@ public function testGetNodeForPath( ->method('getName') ->willReturn($outputFileName); $fileInfo->method('getStorage') - ->willReturn($this->createMock(\OC\Files\Storage\Common::class)); + ->willReturn($this->createMock(Common::class)); $view->expects($this->once()) ->method('getFileInfo') ->with($fileInfoQueryPath) ->willReturn($fileInfo); - $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); + $tree = new ObjectTree($rootNode); $tree->init($rootNode, $view, $mountManager); $node = $tree->getNodeForPath($inputFileName); @@ -190,15 +211,15 @@ public function testGetNodeForPath( $this->assertEquals($outputFileName, $node->getName()); if ($type === 'file') { - $this->assertTrue($node instanceof \OCA\DAV\Connector\Sabre\File); + $this->assertInstanceOf(File::class, $node); } else { - $this->assertTrue($node instanceof \OCA\DAV\Connector\Sabre\Directory); + $this->assertInstanceOf(Directory::class, $node); } unset($_SERVER['HTTP_OC_CHUNKED']); } - public function nodeForPathProvider() { + public function nodeForPathProvider(): array { return [ // regular file [ @@ -268,16 +289,19 @@ public function nodeForPathProvider() { } + /** + * @throws Locked + * @throws NotFound + * @throws ServiceUnavailable + * @throws Forbidden + */ public function testGetNodeForPathInvalidPath() { - $this->expectException(\OCA\DAV\Connector\Sabre\Exception\InvalidPath::class); - + $this->expectException(InvalidPath::class); $path = '/foo\bar'; - - $storage = new Temporary([]); $view = $this->getMockBuilder(View::class) - ->setMethods(['resolvePath']) + ->onlyMethods(['resolvePath']) ->getMock(); $view->expects($this->once()) ->method('resolvePath') @@ -285,25 +309,28 @@ public function testGetNodeForPathInvalidPath() { return [$storage, ltrim($path, '/')]; }); - $rootNode = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + $rootNode = $this->createMock(Directory::class); $mountManager = $this->createMock(IMountManager::class); - $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); + $tree = new ObjectTree($rootNode); $tree->init($rootNode, $view, $mountManager); $tree->getNodeForPath($path); } + /** + * @throws Locked + * @throws InvalidPath + * @throws NotFound + * @throws ServiceUnavailable + * @throws Forbidden + */ public function testGetNodeForPathRoot() { $path = '/'; - - $storage = new Temporary([]); $view = $this->getMockBuilder(View::class) - ->setMethods(['resolvePath']) + ->onlyMethods(['resolvePath']) ->getMock(); $view->expects($this->any()) ->method('resolvePath') @@ -311,14 +338,12 @@ public function testGetNodeForPathRoot() { return [$storage, ltrim($path, '/')]; }); - $rootNode = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + $rootNode = $this->createMock(Directory::class); $mountManager = $this->createMock(IMountManager::class); - $tree = new \OCA\DAV\Connector\Sabre\ObjectTree(); + $tree = new ObjectTree($rootNode); $tree->init($rootNode, $view, $mountManager); - $this->assertInstanceOf('\Sabre\DAV\INode', $tree->getNodeForPath($path)); + $this->assertInstanceOf(INode::class, $tree->getNodeForPath($path)); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index d7c074c9e3b45..7559c12d1479e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -245,6 +245,9 @@ public function testGetPrincipalsByPathEmpty(): void { $this->assertNull($response); } + /** + * @throws Exception + */ public function testGetGroupMemberSet(): void { $response = $this->connector->getGroupMemberSet('principals/users/foo'); $this->assertSame([], $response); @@ -264,6 +267,9 @@ public function testGetGroupMemberSetEmpty(): void { $this->connector->getGroupMemberSet('principals/users/foo/calendar-proxy-read'); } + /** + * @throws Exception + */ public function testGetGroupMemberSetProxyRead(): void { $fooUser = $this->createMock(User::class); $fooUser @@ -296,6 +302,9 @@ public function testGetGroupMemberSetProxyRead(): void { $this->assertEquals(['proxyId1'], $this->connector->getGroupMemberSet('principals/users/foo/calendar-proxy-read')); } + /** + * @throws Exception + */ public function testGetGroupMemberSetProxyWrite(): void { $fooUser = $this->createMock(User::class); $fooUser @@ -328,6 +337,9 @@ public function testGetGroupMemberSetProxyWrite(): void { $this->assertEquals(['proxyId2', 'proxyId3'], $this->connector->getGroupMemberSet('principals/users/foo/calendar-proxy-write')); } + /** + * @throws Exception + */ public function testGetGroupMembership(): void { $fooUser = $this->createMock(User::class); $group1 = $this->createMock(IGroup::class); @@ -390,6 +402,9 @@ public function testGetGroupMembershipEmpty(): void { } + /** + * @throws \OCP\DB\Exception + */ public function testSetGroupMembership(): void { $this->expectException(Exception::class); $this->expectExceptionMessage('Setting members of the group is not supported yet'); @@ -397,6 +412,10 @@ public function testSetGroupMembership(): void { $this->connector->setGroupMemberSet('principals/users/foo', ['foo']); } + /** + * @throws Exception + * @throws \OCP\DB\Exception + */ public function testSetGroupMembershipProxy(): void { $fooUser = $this->createMock(User::class); $fooUser @@ -409,22 +428,17 @@ public function testSetGroupMembershipProxy(): void { ->method('getUID') ->willReturn('bar'); $this->userManager - ->expects($this->at(0)) - ->method('get') - ->with('foo') - ->willReturn($fooUser); - $this->userManager - ->expects($this->at(1)) + ->expects($this->exactly(2)) ->method('get') - ->with('bar') - ->willReturn($barUser); + ->withConsecutive(['foo'], ['bar']) + ->willReturnOnConsecutiveCalls($fooUser, $barUser); - $this->proxyMapper->expects($this->at(0)) + $this->proxyMapper->expects($this->once()) ->method('getProxiesOf') ->with('principals/users/foo') ->willReturn([]); - $this->proxyMapper->expects($this->at(1)) + $this->proxyMapper->expects($this->once()) ->method('insert') ->with($this->callback(function ($proxy) { /** @var Proxy $proxy */ @@ -460,7 +474,7 @@ public function testSearchPrincipalsWithWrongPrefixPath(): void { /** * @dataProvider searchPrincipalsDataProvider */ - public function testSearchPrincipals($sharingEnabled, $groupsOnly, $test, $result): void { + public function testSearchPrincipals(bool $sharingEnabled, bool $groupsOnly, string $test, array $result): void { $this->shareManager->expects($this->once()) ->method('shareAPIEnabled') ->willReturn($sharingEnabled); @@ -479,11 +493,6 @@ public function testSearchPrincipals($sharingEnabled, $groupsOnly, $test, $resul $this->userSession->expects($this->atLeastOnce()) ->method('getUser') ->willReturn($user); - - $this->groupManager->expects($this->at(0)) - ->method('getUserGroupIds') - ->with($user) - ->willReturn(['group1', 'group2', 'group5']); } } else { $this->config->expects($this->never()) @@ -502,12 +511,12 @@ public function testSearchPrincipals($sharingEnabled, $groupsOnly, $test, $resul $user4->method('getUID')->willReturn('user4'); if ($sharingEnabled) { - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->once()) ->method('getByEmail') ->with('user@example.com') ->willReturn([$user2, $user3]); - $this->userManager->expects($this->at(1)) + $this->userManager->expects($this->once()) ->method('searchDisplayName') ->with('User 12') ->willReturn([$user3, $user4]); @@ -520,22 +529,18 @@ public function testSearchPrincipals($sharingEnabled, $groupsOnly, $test, $resul } if ($sharingEnabled && $groupsOnly) { - $this->groupManager->expects($this->at(1)) - ->method('getUserGroupIds') - ->with($user2) - ->willReturn(['group1', 'group3']); - $this->groupManager->expects($this->at(2)) - ->method('getUserGroupIds') - ->with($user3) - ->willReturn(['group3', 'group4']); - $this->groupManager->expects($this->at(3)) + $this->groupManager->expects($this->exactly(5)) ->method('getUserGroupIds') - ->with($user3) - ->willReturn(['group3', 'group4']); - $this->groupManager->expects($this->at(4)) - ->method('getUserGroupIds') - ->with($user4) - ->willReturn(['group4', 'group5']); + ->withConsecutive( + [$user], [$user2], [$user3], [$user3], [$user4] + ) + ->willReturnOnConsecutiveCalls( + ['group1', 'group2', 'group5'], + ['group1', 'group3'], + ['group3', 'group4'], + ['group3', 'group4'], + ['group4', 'group5'] + ); } @@ -573,7 +578,7 @@ public function testSearchPrincipalByCalendarUserAddressSet(): void { $user3 = $this->createMock(IUser::class); $user3->method('getUID')->willReturn('user3'); - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->once()) ->method('getByEmail') ->with('user@example.com') ->willReturn([$user2, $user3]); @@ -615,7 +620,7 @@ public function testSearchPrincipalWithEnumerationDisabledDisplayname(): void { $user2->method('getDisplayName')->willReturn('User 222'); $user2->method('getSystemEMailAddress')->willReturn('user2@foo.bar456'); - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->once()) ->method('searchDisplayName') ->with('User 2') ->willReturn([$user2, $user3, $user4]); @@ -707,15 +712,15 @@ public function testSearchPrincipalWithEnumerationDisabledEmailOnFullMatch(): vo } public function testSearchPrincipalWithEnumerationLimitedDisplayname(): void { - $this->shareManager->expects($this->at(0)) + $this->shareManager->expects($this->once()) ->method('shareAPIEnabled') ->willReturn(true); - $this->shareManager->expects($this->at(1)) + $this->shareManager->expects($this->once()) ->method('allowEnumeration') ->willReturn(true); - $this->shareManager->expects($this->at(2)) + $this->shareManager->expects($this->once()) ->method('limitEnumerationToGroups') ->willReturn(true); @@ -737,24 +742,17 @@ public function testSearchPrincipalWithEnumerationLimitedDisplayname(): void { $user4->method('getSystemEMailAddress')->willReturn('user2@foo.bar456'); - $this->userSession->expects($this->at(0)) + $this->userSession->expects($this->once()) ->method('getUser') ->willReturn($user2); - $this->groupManager->expects($this->at(0)) - ->method('getUserGroupIds') - ->willReturn(['group1']); - $this->groupManager->expects($this->at(1)) - ->method('getUserGroupIds') - ->willReturn(['group1']); - $this->groupManager->expects($this->at(2)) + $this->groupManager->expects($this->exactly(4)) ->method('getUserGroupIds') - ->willReturn(['group1']); - $this->groupManager->expects($this->at(3)) - ->method('getUserGroupIds') - ->willReturn(['group2']); + ->willReturnOnConsecutiveCalls( + ['group1'], ['group1'], ['group1'], ['group2'] + ); - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->once()) ->method('searchDisplayName') ->with('User') ->willReturn([$user2, $user3, $user4]); @@ -768,15 +766,15 @@ public function testSearchPrincipalWithEnumerationLimitedDisplayname(): void { } public function testSearchPrincipalWithEnumerationLimitedMail(): void { - $this->shareManager->expects($this->at(0)) + $this->shareManager->expects($this->once()) ->method('shareAPIEnabled') ->willReturn(true); - $this->shareManager->expects($this->at(1)) + $this->shareManager->expects($this->once()) ->method('allowEnumeration') ->willReturn(true); - $this->shareManager->expects($this->at(2)) + $this->shareManager->expects($this->once()) ->method('limitEnumerationToGroups') ->willReturn(true); @@ -798,24 +796,17 @@ public function testSearchPrincipalWithEnumerationLimitedMail(): void { $user4->method('getSystemEMailAddress')->willReturn('user2@foo.bar456'); - $this->userSession->expects($this->at(0)) + $this->userSession->expects($this->once()) ->method('getUser') ->willReturn($user2); - $this->groupManager->expects($this->at(0)) - ->method('getUserGroupIds') - ->willReturn(['group1']); - $this->groupManager->expects($this->at(1)) - ->method('getUserGroupIds') - ->willReturn(['group1']); - $this->groupManager->expects($this->at(2)) - ->method('getUserGroupIds') - ->willReturn(['group1']); - $this->groupManager->expects($this->at(3)) + $this->groupManager->expects($this->exactly(4)) ->method('getUserGroupIds') - ->willReturn(['group2']); + ->willReturnOnConsecutiveCalls( + ['group1'], ['group1'], ['group1'], ['group2'] + ); - $this->userManager->expects($this->at(0)) + $this->userManager->expects($this->once()) ->method('getByEmail') ->with('user') ->willReturn([$user2, $user3, $user4]); @@ -839,7 +830,7 @@ public function testFindByUriSharingApiDisabled(): void { /** * @dataProvider findByUriWithGroupRestrictionDataProvider */ - public function testFindByUriWithGroupRestriction($uri, $email, $expects): void { + public function testFindByUriWithGroupRestriction(string $uri, string $email, ?string $expects): void { $this->shareManager->expects($this->once()) ->method('shareApiEnabled') ->willReturn(true); @@ -853,11 +844,6 @@ public function testFindByUriWithGroupRestriction($uri, $email, $expects): void ->method('getUser') ->willReturn($user); - $this->groupManager->expects($this->at(0)) - ->method('getUserGroupIds') - ->with($user) - ->willReturn(['group1', 'group2']); - $user2 = $this->createMock(IUser::class); $user2->method('getUID')->willReturn('user2'); $user3 = $this->createMock(IUser::class); @@ -869,15 +855,15 @@ public function testFindByUriWithGroupRestriction($uri, $email, $expects): void ->willReturn([$email === 'user2@foo.bar' ? $user2 : $user3]); if ($email === 'user2@foo.bar') { - $this->groupManager->expects($this->at(1)) + $this->groupManager->expects($this->exactly(2)) ->method('getUserGroupIds') - ->with($user2) - ->willReturn(['group1', 'group3']); + ->withConsecutive([$user], [$user2]) + ->willReturnOnConsecutiveCalls(['group1', 'group2'], ['group1', 'group3']); } else { - $this->groupManager->expects($this->at(1)) - ->method('getUserGroupIds') - ->with($user3) - ->willReturn(['group3', 'group3']); + $this->groupManager->expects($this->exactly(2)) + ->method('getUserGroupIds') + ->withConsecutive([$user], [$user3]) + ->willReturnOnConsecutiveCalls(['group1', 'group2'], ['group3', 'group3']); } $this->assertEquals($expects, $this->connector->findByUri($uri, 'principals/users')); @@ -893,7 +879,7 @@ public function findByUriWithGroupRestrictionDataProvider(): array { /** * @dataProvider findByUriWithoutGroupRestrictionDataProvider */ - public function testFindByUriWithoutGroupRestriction($uri, $email, $expects): void { + public function testFindByUriWithoutGroupRestriction(string $uri, string $email, string $expects): void { $this->shareManager->expects($this->once()) ->method('shareApiEnabled') ->willReturn(true); diff --git a/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php index 69b2140e64081..d037e87170f2b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/QuotaPluginTest.php @@ -31,8 +31,14 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; use OC\Files\View; +use OC_FileChunking; use OCA\DAV\Connector\Sabre\QuotaPlugin; use OCP\Files\FileInfo; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\InsufficientStorage; +use Sabre\DAV\Exception\ServiceUnavailable; +use Sabre\DAV\Server; +use Sabre\HTTP\Request; use Test\TestCase; /** @@ -43,18 +49,18 @@ */ class QuotaPluginTest extends TestCase { - /** @var \Sabre\DAV\Server | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Server | MockObject */ private $server; - /** @var \OCA\DAV\Connector\Sabre\QuotaPlugin | \PHPUnit\Framework\MockObject\MockObject */ + /** @var QuotaPlugin | MockObject */ private $plugin; private function init($quota, $checkedPath = '') { $view = $this->buildFileViewMock($quota, $checkedPath); - $this->server = new \Sabre\DAV\Server(); + $this->server = new Server(); $this->plugin = $this->getMockBuilder(QuotaPlugin::class) ->setConstructorArgs([$view]) - ->setMethods(['getFileChunking']) + ->onlyMethods(['getFileChunking']) ->getMock(); $this->plugin->initialize($this->server); } @@ -62,56 +68,59 @@ private function init($quota, $checkedPath = '') { /** * @dataProvider lengthProvider */ - public function testLength($expected, $headers) { + public function testLength(?int $expected, array $headers) { $this->init(0); $this->plugin->expects($this->never()) ->method('getFileChunking'); - $this->server->httpRequest = new \Sabre\HTTP\Request('POST', 'dummy.file', $headers); + $this->server->httpRequest = new Request('POST', 'dummy.file', $headers); $length = $this->plugin->getLength(); $this->assertEquals($expected, $length); } /** * @dataProvider quotaOkayProvider + * @throws InsufficientStorage|ServiceUnavailable */ - public function testCheckQuota($quota, $headers) { + public function testCheckQuota(int $quota, array $headers) { $this->init($quota); $this->plugin->expects($this->never()) ->method('getFileChunking'); - $this->server->httpRequest = new \Sabre\HTTP\Request('POST', 'dummy.file', $headers); + $this->server->httpRequest = new Request('POST', 'dummy.file', $headers); $result = $this->plugin->checkQuota(''); $this->assertTrue($result); } /** * @dataProvider quotaExceededProvider + * @throws InsufficientStorage|ServiceUnavailable */ - public function testCheckExceededQuota($quota, $headers) { - $this->expectException(\Sabre\DAV\Exception\InsufficientStorage::class); + public function testCheckExceededQuota(int $quota, array $headers) { + $this->expectException(InsufficientStorage::class); $this->init($quota); $this->plugin->expects($this->never()) ->method('getFileChunking'); - $this->server->httpRequest = new \Sabre\HTTP\Request('POST', 'dummy.file', $headers); + $this->server->httpRequest = new Request('POST', 'dummy.file', $headers); $this->plugin->checkQuota(''); } /** * @dataProvider quotaOkayProvider + * @throws InsufficientStorage|ServiceUnavailable */ - public function testCheckQuotaOnPath($quota, $headers) { + public function testCheckQuotaOnPath(int $quota, array $headers) { $this->init($quota, 'sub/test.txt'); $this->plugin->expects($this->never()) ->method('getFileChunking'); - $this->server->httpRequest = new \Sabre\HTTP\Request('POST', 'dummy.file', $headers); + $this->server->httpRequest = new Request('POST', 'dummy.file', $headers); $result = $this->plugin->checkQuota('/sub/test.txt'); $this->assertTrue($result); } - public function quotaOkayProvider() { + public function quotaOkayProvider(): array { return [ [1024, []], [1024, ['X-EXPECTED-ENTITY-LENGTH' => '1024']], @@ -130,7 +139,7 @@ public function quotaOkayProvider() { ]; } - public function quotaExceededProvider() { + public function quotaExceededProvider(): array { return [ [1023, ['X-EXPECTED-ENTITY-LENGTH' => '1024']], [511, ['CONTENT-LENGTH' => '512']], @@ -138,7 +147,7 @@ public function quotaExceededProvider() { ]; } - public function lengthProvider() { + public function lengthProvider(): array { return [ [null, []], [1024, ['X-EXPECTED-ENTITY-LENGTH' => '1024']], @@ -154,7 +163,7 @@ public function lengthProvider() { ]; } - public function quotaChunkedOkProvider() { + public function quotaChunkedOkProvider(): array { return [ [1024, 0, ['X-EXPECTED-ENTITY-LENGTH' => '1024']], [1024, 0, ['CONTENT-LENGTH' => '512']], @@ -175,13 +184,12 @@ public function quotaChunkedOkProvider() { /** * @dataProvider quotaChunkedOkProvider + * @throws InsufficientStorage|ServiceUnavailable */ - public function testCheckQuotaChunkedOk($quota, $chunkTotalSize, $headers) { + public function testCheckQuotaChunkedOk(int $quota, int $chunkTotalSize, array $headers) { $this->init($quota, 'sub/test.txt'); - $mockChunking = $this->getMockBuilder(\OC_FileChunking::class) - ->disableOriginalConstructor() - ->getMock(); + $mockChunking = $this->createMock(OC_FileChunking::class); $mockChunking->expects($this->once()) ->method('getCurrentSize') ->willReturn($chunkTotalSize); @@ -191,12 +199,12 @@ public function testCheckQuotaChunkedOk($quota, $chunkTotalSize, $headers) { ->willReturn($mockChunking); $headers['OC-CHUNKED'] = 1; - $this->server->httpRequest = new \Sabre\HTTP\Request('POST', 'dummy.file', $headers); + $this->server->httpRequest = new Request('POST', 'dummy.file', $headers); $result = $this->plugin->checkQuota('/sub/test.txt-chunking-12345-3-1'); $this->assertTrue($result); } - public function quotaChunkedFailProvider() { + public function quotaChunkedFailProvider(): array { return [ [400, 0, ['X-EXPECTED-ENTITY-LENGTH' => '1024']], [400, 0, ['CONTENT-LENGTH' => '512']], @@ -210,15 +218,14 @@ public function quotaChunkedFailProvider() { /** * @dataProvider quotaChunkedFailProvider + * @throws ServiceUnavailable */ - public function testCheckQuotaChunkedFail($quota, $chunkTotalSize, $headers) { - $this->expectException(\Sabre\DAV\Exception\InsufficientStorage::class); + public function testCheckQuotaChunkedFail(int $quota, int $chunkTotalSize, array $headers) { + $this->expectException(InsufficientStorage::class); $this->init($quota, 'sub/test.txt'); - $mockChunking = $this->getMockBuilder(\OC_FileChunking::class) - ->disableOriginalConstructor() - ->getMock(); + $mockChunking = $this->createMock(OC_FileChunking::class); $mockChunking->expects($this->once()) ->method('getCurrentSize') ->willReturn($chunkTotalSize); @@ -228,14 +235,14 @@ public function testCheckQuotaChunkedFail($quota, $chunkTotalSize, $headers) { ->willReturn($mockChunking); $headers['OC-CHUNKED'] = 1; - $this->server->httpRequest = new \Sabre\HTTP\Request('POST', 'dummy.file', $headers); + $this->server->httpRequest = new Request('POST', 'dummy.file', $headers); $this->plugin->checkQuota('/sub/test.txt-chunking-12345-3-1'); } private function buildFileViewMock($quota, $checkedPath) { // mock filesysten $view = $this->getMockBuilder(View::class) - ->setMethods(['free_space']) + ->onlyMethods(['free_space']) ->disableOriginalConstructor() ->getMock(); $view->expects($this->any()) diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php index eb159b15d2b09..be970c1dfe40e 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Auth.php @@ -26,6 +26,8 @@ use OCP\Files\IRootFolder; use OCP\IUserSession; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Sabre\DAV\Auth\Backend\BackendInterface; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -76,9 +78,9 @@ public function __construct($user, $password) { * * principals/users/[username] * - * @param RequestInterface $request - * @param ResponseInterface $response * @return array + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface */ public function check(RequestInterface $request, ResponseInterface $response) { /** @var IUserSession $userSession */ diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php index b76564e59d4d5..1e21f3a2d3f72 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php @@ -22,7 +22,12 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use Exception; use OCP\AppFramework\Http; +use OCP\Files\FileInfo; +use OCP\Lock\LockedException; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; /** * Class DeleteTest @@ -32,6 +37,12 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest */ class DeleteTest extends RequestTestCase { + /** + * @throws LockedException + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws \Throwable + */ public function testBasicUpload() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -44,7 +55,7 @@ public function testBasicUpload() { $mount->getStorage()->unlink($mount->getInternalPath($internalPath)); // cache entry still exists - $this->assertInstanceOf('\OCP\Files\FileInfo', $view->getFileInfo('foo.txt')); + $this->assertInstanceOf(FileInfo::class, $view->getFileInfo('foo.txt')); $response = $this->request($view, $user, 'pass', 'DELETE', '/foo.txt'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php index ceae6fadf28b5..0338bcdd5ad94 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DownloadTest.php @@ -24,8 +24,10 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use Exception; use OCP\AppFramework\Http; use OCP\Lock\ILockingProvider; +use OCP\Lock\LockedException; /** * Class DownloadTest @@ -35,6 +37,10 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest */ class DownloadTest extends RequestTestCase { + /** + * @throws LockedException + * @throws Exception + */ public function testDownload() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -43,9 +49,13 @@ public function testDownload() { $response = $this->request($view, $user, 'pass', 'GET', '/foo.txt'); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); - $this->assertEquals(stream_get_contents($response->getBody()), 'bar'); + $this->assertEquals('bar', stream_get_contents($response->getBody())); } + /** + * @throws LockedException + * @throws Exception + */ public function testDownloadWriteLocked() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -58,6 +68,10 @@ public function testDownloadWriteLocked() { $this->assertEquals(Http::STATUS_LOCKED, $result->getStatus()); } + /** + * @throws LockedException + * @throws Exception + */ public function testDownloadReadLocked() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -68,6 +82,6 @@ public function testDownloadReadLocked() { $response = $this->request($view, $user, 'pass', 'GET', '/foo.txt', 'asd'); $this->assertEquals(Http::STATUS_OK, $response->getStatus()); - $this->assertEquals(stream_get_contents($response->getBody()), 'bar'); + $this->assertEquals('bar', stream_get_contents($response->getBody())); } } diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php index abf8165f0ac09..a0f2072810caa 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionMasterKeyUploadTest.php @@ -21,9 +21,14 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use Exception; +use OC; +use OC\Files\Storage\Local; use OC\Files\View; use OCP\IConfig; use OCP\ITempManager; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Test\Traits\EncryptionTrait; /** @@ -36,12 +41,17 @@ class EncryptionMasterKeyUploadTest extends UploadTest { use EncryptionTrait; - protected function setupUser($name, $password) { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ + protected function setupUser($name, $password): View { $this->createUser($name, $password); - $tmpFolder = \OC::$server->get(ITempManager::class)->getTemporaryFolder(); - $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); + $tmpFolder = OC::$server->get(ITempManager::class)->getTemporaryFolder(); + $this->registerMount($name, Local::class, '/' . $name, ['datadir' => $tmpFolder]); // we use the master key - \OC::$server->get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '1'); + OC::$server->get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '1'); $this->setupForUser($name, $password); $this->loginWithEncryption($name); return new View('/' . $name . '/files'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php index f29f5debe8f78..09513957c47da 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/EncryptionUploadTest.php @@ -24,9 +24,14 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use Exception; +use OC; +use OC\Files\Storage\Local; use OC\Files\View; use OCP\IConfig; use OCP\ITempManager; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Test\Traits\EncryptionTrait; /** @@ -39,12 +44,17 @@ class EncryptionUploadTest extends UploadTest { use EncryptionTrait; - protected function setupUser($name, $password) { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ + protected function setupUser($name, $password): View { $this->createUser($name, $password); - $tmpFolder = \OC::$server->get(ITempManager::class)->getTemporaryFolder(); - $this->registerMount($name, '\OC\Files\Storage\Local', '/' . $name, ['datadir' => $tmpFolder]); + $tmpFolder = OC::$server->get(ITempManager::class)->getTemporaryFolder(); + $this->registerMount($name, Local::class, '/' . $name, ['datadir' => $tmpFolder]); // we use per-user keys - \OC::$server->get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '0'); + OC::$server->get(IConfig::class)->setAppValue('encryption', 'useMasterKey', '0'); $this->setupForUser($name, $password); $this->loginWithEncryption($name); return new View('/' . $name . '/files'); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php index eb459912bf4cf..7ce6a3320e1f7 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/ExceptionPlugin.php @@ -23,13 +23,16 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; -class ExceptionPlugin extends \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin { +use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin; +use Throwable; + +class ExceptionPlugin extends ExceptionLoggerPlugin { /** - * @var \Throwable[] + * @var Throwable[] */ protected $exceptions = []; - public function logException(\Throwable $ex) { + public function logException(Throwable $ex): void { $exceptionClass = get_class($ex); if (!isset($this->nonFatalExceptions[$exceptionClass])) { $this->exceptions[] = $ex; @@ -37,9 +40,9 @@ public function logException(\Throwable $ex) { } /** - * @return \Throwable[] + * @return Throwable[] */ - public function getExceptions() { + public function getExceptions(): array { return $this->exceptions; } } diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php index 7ec9e0d4054aa..d10c6befb462d 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/PartFileInRootUploadTest.php @@ -25,7 +25,10 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use OC; use OCP\IConfig; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; /** * Class PartFileInRootUploadTest @@ -35,14 +38,17 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest */ class PartFileInRootUploadTest extends UploadTest { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { - $config = \OC::$server->get(IConfig::class); - $mockConfig = $this->getMockBuilder(IConfig::class) - ->disableOriginalConstructor() - ->getMock(); + /** @var IConfig $config */ + $config = OC::$server->get(IConfig::class); + $mockConfig = $this->createMock(IConfig::class); $mockConfig->expects($this->any()) ->method('getSystemValue') - ->willReturnCallback(function ($key, $default) use ($config) { + ->willReturnCallback(function (string $key, string $default) use ($config) { if ($key === 'part_file_in_storage') { return false; } else { diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php index 45da9cf17c5b7..38c140bf8c4f3 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/RequestTestCase.php @@ -28,10 +28,13 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use Exception; +use OC; use OC\Files\Storage\Local; use OC\Files\View; use OCA\DAV\Connector\Sabre\Server; use OCA\DAV\Connector\Sabre\ServerFactory; +use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\Mount\IMountManager; use OCP\IConfig; use OCP\IDBConnection; @@ -41,18 +44,23 @@ use OCP\ITempManager; use OCP\IUserSession; use OCP\L10N\IFactory; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; +use Sabre\DAV\Auth\Plugin; use Sabre\HTTP\Request; +use Sabre\HTTP\Response; use Test\TestCase; use Test\Traits\MountProviderTrait; use Test\Traits\UserTrait; +use Throwable; abstract class RequestTestCase extends TestCase { use UserTrait; use MountProviderTrait; /** - * @var \OCA\DAV\Connector\Sabre\ServerFactory + * @var ServerFactory */ protected $serverFactory; @@ -63,47 +71,54 @@ protected function getStream($string) { return $stream; } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { parent::setUp(); unset($_SERVER['HTTP_OC_CHUNKED']); $this->serverFactory = new ServerFactory( - \OC::$server->get(IConfig::class), - \OC::$server->get(LoggerInterface::class), - \OC::$server->get(IDBConnection::class), - \OC::$server->get(IUserSession::class), - \OC::$server->get(IMountManager::class), - \OC::$server->get(ITagManager::class), - $this->getMockBuilder(IRequest::class) - ->disableOriginalConstructor() - ->getMock(), - \OC::$server->get(IPreview::class), - \OC::$server->get(\OC\EventDispatcher\SymfonyAdapter::class), - \OC::$server->get(IFactory::class)->get('dav') + OC::$server->get(IConfig::class), + OC::$server->get(LoggerInterface::class), + OC::$server->get(IDBConnection::class), + OC::$server->get(IUserSession::class), + OC::$server->get(IMountManager::class), + OC::$server->get(ITagManager::class), + $this->createMock(IRequest::class), + OC::$server->get(IPreview::class), + OC::$server->get(IEventDispatcher::class), + OC::$server->get(IFactory::class)->get('dav') ); } - protected function setupUser($name, $password) { + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ + protected function setupUser($name, $password): View { $this->createUser($name, $password); - $tmpFolder = \OC::$server->get(ITempManager::class)->getTemporaryFolder(); + $tmpFolder = OC::$server->get(ITempManager::class)->getTemporaryFolder(); $this->registerMount($name, Local::class, '/' . $name, ['datadir' => $tmpFolder]); $this->loginAsUser($name); return new View('/' . $name . '/files'); } /** - * @param \OC\Files\View $view the view to run the webdav server against + * @param View $view the view to run the webdav server against * @param string $user * @param string $password * @param string $method * @param string $url * @param resource|string|null $body * @param array|null $headers - * @return \Sabre\HTTP\Response - * @throws \Exception + * @return Response + * @throws Exception|Throwable */ - protected function request($view, $user, $password, $method, $url, $body = null, $headers = []) { + protected function request(View $view, string $user, string $password, string $method, string $url, string $body = null, ?array $headers = []): Response { if (is_string($body)) { $body = $this->getStream($body); } @@ -131,12 +146,7 @@ protected function request($view, $user, $password, $method, $url, $body = null, return $result; } - /** - * @param Server $server - * @param Request $request - * @return \Sabre\HTTP\Response - */ - protected function makeRequest(Server $server, Request $request) { + protected function makeRequest(Server $server, Request $request): Response { $sapi = new Sapi($request); $server->sapi = $sapi; $server->httpRequest = $request; @@ -145,15 +155,11 @@ protected function makeRequest(Server $server, Request $request) { } /** - * @param View $view - * @param string $user - * @param string $password - * @param ExceptionPlugin $exceptionPlugin - * @return Server + * @throws \Sabre\DAV\Exception */ - protected function getSabreServer(View $view, $user, $password, ExceptionPlugin $exceptionPlugin) { + protected function getSabreServer(View $view, string $user, string $password, ExceptionPlugin $exceptionPlugin): Server { $authBackend = new Auth($user, $password); - $authPlugin = new \Sabre\DAV\Auth\Plugin($authBackend); + $authPlugin = new Plugin($authBackend); $server = $this->serverFactory->createServer('/', 'dummy', $authPlugin, function () use ($view) { return $view; diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php index 4a2e025f0186a..006a5335ee0ed 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/Sapi.php @@ -28,12 +28,12 @@ class Sapi { /** - * @var \Sabre\HTTP\Request + * @var Request */ private $request; /** - * @var \Sabre\HTTP\Response + * @var Response */ private $response; @@ -41,9 +41,9 @@ class Sapi { * This static method will create a new Request object, based on the * current PHP request. * - * @return \Sabre\HTTP\Request + * @return Request */ - public function getRequest() { + public function getRequest(): Request { return $this->request; } @@ -52,7 +52,7 @@ public function __construct(Request $request) { } /** - * @param \Sabre\HTTP\Response $response + * @param Response $response * @return void */ public function sendResponse(Response $response) { @@ -68,9 +68,9 @@ public function sendResponse(Response $response) { } /** - * @return \Sabre\HTTP\Response + * @return Response */ - public function getResponse() { + public function getResponse(): Response { return $this->response; } } diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php index 9f7d381ad1499..9afaf844ce1ac 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/UploadTest.php @@ -24,8 +24,14 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; +use OC\Files\FileInfo; +use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCP\AppFramework\Http; use OCP\Lock\ILockingProvider; +use OCP\Lock\LockedException; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; +use Throwable; /** * Class UploadTest @@ -35,6 +41,12 @@ * @package OCA\DAV\Tests\unit\Connector\Sabre\RequestTest */ class UploadTest extends RequestTestCase { + /** + * @throws Throwable + * @throws NotFoundExceptionInterface + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testBasicUpload() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -47,10 +59,16 @@ public function testBasicUpload() { $this->assertEquals('asd', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf(FileInfo::class, $info); $this->assertEquals(3, $info->getSize()); } + /** + * @throws NotFoundExceptionInterface + * @throws Throwable + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testUploadOverWrite() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -63,10 +81,16 @@ public function testUploadOverWrite() { $this->assertEquals('asd', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf(FileInfo::class, $info); $this->assertEquals(3, $info->getSize()); } + /** + * @throws Throwable + * @throws NotFoundExceptionInterface + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testUploadOverWriteReadLocked() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -79,6 +103,12 @@ public function testUploadOverWriteReadLocked() { $this->assertEquals(Http::STATUS_LOCKED, $result->getStatus()); } + /** + * @throws NotFoundExceptionInterface + * @throws Throwable + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testUploadOverWriteWriteLocked() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -92,6 +122,12 @@ public function testUploadOverWriteWriteLocked() { $this->assertEquals(Http::STATUS_LOCKED, $result->getStatus()); } + /** + * @throws Throwable + * @throws NotFoundExceptionInterface + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testChunkedUpload() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -110,10 +146,16 @@ public function testChunkedUpload() { $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf(FileInfo::class, $info); $this->assertEquals(6, $info->getSize()); } + /** + * @throws Throwable + * @throws NotFoundExceptionInterface + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testChunkedUploadOverWrite() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -131,10 +173,16 @@ public function testChunkedUploadOverWrite() { $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf(FileInfo::class, $info); $this->assertEquals(6, $info->getSize()); } + /** + * @throws Throwable + * @throws NotFoundExceptionInterface + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testChunkedUploadOutOfOrder() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -153,10 +201,16 @@ public function testChunkedUploadOutOfOrder() { $this->assertEquals('asdbar', $view->file_get_contents('foo.txt')); $info = $view->getFileInfo('foo.txt'); - $this->assertInstanceOf('\OC\Files\FileInfo', $info); + $this->assertInstanceOf(FileInfo::class, $info); $this->assertEquals(6, $info->getSize()); } + /** + * @throws NotFoundExceptionInterface + * @throws Throwable + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testChunkedUploadOutOfOrderReadLocked() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -167,9 +221,8 @@ public function testChunkedUploadOutOfOrderReadLocked() { try { $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + } catch (FileLocked $e) { $this->fail('Didn\'t expect locked error for the first chunk on read lock'); - return; } $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); @@ -180,6 +233,12 @@ public function testChunkedUploadOutOfOrderReadLocked() { $this->assertEquals(Http::STATUS_LOCKED, $result->getStatus()); } + /** + * @throws NotFoundExceptionInterface + * @throws Throwable + * @throws ContainerExceptionInterface + * @throws LockedException + */ public function testChunkedUploadOutOfOrderWriteLocked() { $user = $this->getUniqueID(); $view = $this->setupUser($user, 'pass'); @@ -190,9 +249,8 @@ public function testChunkedUploadOutOfOrderWriteLocked() { try { $response = $this->request($view, $user, 'pass', 'PUT', '/foo.txt-chunking-123-2-1', 'bar', ['OC-Chunked' => '1']); - } catch (\OCA\DAV\Connector\Sabre\Exception\FileLocked $e) { + } catch (FileLocked $e) { $this->fail('Didn\'t expect locked error for the first chunk on write lock'); // maybe forbid this in the future for write locks only? - return; } $this->assertEquals(Http::STATUS_CREATED, $response->getStatus()); diff --git a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php index f528310e54c30..8c0a06e87fef3 100644 --- a/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/SharesPluginTest.php @@ -32,46 +32,40 @@ use OCA\DAV\Connector\Sabre\Directory; use OCA\DAV\Connector\Sabre\File; use OCA\DAV\Connector\Sabre\Node; +use OCA\DAV\Connector\Sabre\SharesPlugin; use OCA\DAV\Upload\UploadFile; use OCP\Files\Folder; use OCP\IUser; use OCP\IUserSession; use OCP\Share\IManager; use OCP\Share\IShare; +use Sabre\DAV\PropFind; +use Sabre\DAV\Server; use Sabre\DAV\Tree; +use Test\TestCase; -class SharesPluginTest extends \Test\TestCase { - public const SHARETYPES_PROPERTYNAME = \OCA\DAV\Connector\Sabre\SharesPlugin::SHARETYPES_PROPERTYNAME; +class SharesPluginTest extends TestCase { + public const SHARETYPES_PROPERTYNAME = SharesPlugin::SHARETYPES_PROPERTYNAME; /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \Sabre\DAV\Tree - */ - private $tree; - - /** - * @var \OCP\Share\IManager + * @var IManager */ private $shareManager; /** - * @var \OCP\Files\Folder + * @var Folder */ private $userFolder; /** - * @var \OCA\DAV\Connector\Sabre\SharesPlugin + * @var SharesPlugin */ private $plugin; protected function setUp(): void { parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->createMock(Tree::class); + $server = new Server(); + $tree = $this->createMock(Tree::class); $this->shareManager = $this->createMock(IManager::class); $user = $this->createMock(IUser::class); $user->expects($this->once()) @@ -83,22 +77,20 @@ protected function setUp(): void { ->willReturn($user); $this->userFolder = $this->createMock(Folder::class); - $this->plugin = new \OCA\DAV\Connector\Sabre\SharesPlugin( - $this->tree, + $this->plugin = new SharesPlugin( + $tree, $userSession, $this->userFolder, $this->shareManager ); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } /** * @dataProvider sharesGetPropertiesDataProvider */ - public function testGetProperties($shareTypes) { - $sabreNode = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + public function testGetProperties(array $shareTypes) { + $sabreNode = $this->createMock(Node::class); $sabreNode->expects($this->any()) ->method('getId') ->willReturn(123); @@ -107,9 +99,7 @@ public function testGetProperties($shareTypes) { ->willReturn('/subdir'); // node API nodes - $node = $this->getMockBuilder(Folder::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Folder::class); $this->userFolder->expects($this->once()) ->method('get') @@ -125,7 +115,7 @@ public function testGetProperties($shareTypes) { $this->equalTo(false), $this->equalTo(-1) ) - ->willReturnCallback(function ($userId, $requestedShareType, $node, $flag, $limit) use ($shareTypes) { + ->willReturnCallback(function ($userId, $requestedShareType) use ($shareTypes) { if (in_array($requestedShareType, $shareTypes)) { $share = $this->createMock(IShare::class); $share->method('getShareType') @@ -135,7 +125,7 @@ public function testGetProperties($shareTypes) { return []; }); - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/dummyPath', [self::SHARETYPES_PROPERTYNAME], 0 @@ -156,7 +146,7 @@ public function testGetProperties($shareTypes) { /** * @dataProvider sharesGetPropertiesDataProvider */ - public function testPreloadThenGetProperties($shareTypes) { + public function testPreloadThenGetProperties(array $shareTypes) { $sabreNode1 = $this->createMock(File::class); $sabreNode1->method('getId') ->willReturn(111); @@ -192,7 +182,7 @@ public function testPreloadThenGetProperties($shareTypes) { ->willReturn($node); $dummyShares = array_map(function ($type) { - $share = $this->getMockBuilder(IShare::class)->getMock(); + $share = $this->createMock(IShare::class); $share->expects($this->any()) ->method('getShareType') ->willReturn($type); @@ -208,7 +198,7 @@ public function testPreloadThenGetProperties($shareTypes) { $this->equalTo(false), $this->equalTo(-1) ) - ->willReturnCallback(function ($userId, $requestedShareType, $node, $flag, $limit) use ($shareTypes, $dummyShares) { + ->willReturnCallback(function ($userId, $requestedShareType, $node) use ($shareTypes, $dummyShares) { if ($node->getId() === 111 && in_array($requestedShareType, $shareTypes)) { foreach ($dummyShares as $dummyShare) { if ($dummyShare->getShareType() === $requestedShareType) { @@ -227,22 +217,22 @@ public function testPreloadThenGetProperties($shareTypes) { $this->anything(), $this->equalTo(true) ) - ->willReturnCallback(function ($userId, $node, $flag) use ($shareTypes, $dummyShares) { + ->willReturnCallback(function () use ($shareTypes, $dummyShares) { return [111 => $dummyShares]; }); // simulate sabre recursive PROPFIND traversal - $propFindRoot = new \Sabre\DAV\PropFind( + $propFindRoot = new PropFind( '/subdir', [self::SHARETYPES_PROPERTYNAME], 1 ); - $propFind1 = new \Sabre\DAV\PropFind( + $propFind1 = new PropFind( '/subdir/test.txt', [self::SHARETYPES_PROPERTYNAME], 0 ); - $propFind2 = new \Sabre\DAV\PropFind( + $propFind2 = new PropFind( '/subdir/test2.txt', [self::SHARETYPES_PROPERTYNAME], 0 @@ -268,7 +258,7 @@ public function testPreloadThenGetProperties($shareTypes) { $this->assertEquals($shareTypes, $result[200][self::SHARETYPES_PROPERTYNAME]->getShareTypes()); } - public function sharesGetPropertiesDataProvider() { + public function sharesGetPropertiesDataProvider(): array { return [ [[]], [[IShare::TYPE_USER]], @@ -286,11 +276,8 @@ public function sharesGetPropertiesDataProvider() { } public function testGetPropertiesSkipChunks(): void { - $sabreNode = $this->getMockBuilder(UploadFile::class) - ->disableOriginalConstructor() - ->getMock(); - - $propFind = new \Sabre\DAV\PropFind( + $sabreNode = $this->createMock(UploadFile::class); + $propFind = new PropFind( '/dummyPath', [self::SHARETYPES_PROPERTYNAME], 0 diff --git a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php index 995342db00307..9986bb3cebb73 100644 --- a/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/TagsPluginTest.php @@ -30,12 +30,21 @@ namespace OCA\DAV\Tests\unit\Connector\Sabre; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\Exception\Forbidden; use OCA\DAV\Connector\Sabre\File; use OCA\DAV\Connector\Sabre\Node; +use OCA\DAV\Connector\Sabre\TagList; +use OCA\DAV\Connector\Sabre\TagsPlugin; use OCA\DAV\Upload\UploadFile; use OCP\ITagManager; use OCP\ITags; +use Sabre\DAV\Exception\Locked; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\PropFind; +use Sabre\DAV\PropPatch; +use Sabre\DAV\Server; use Sabre\DAV\Tree; +use Test\TestCase; /** * Copyright (c) 2014 Vincent Petry @@ -43,15 +52,10 @@ * later. * See the COPYING-README file. */ -class TagsPluginTest extends \Test\TestCase { - public const TAGS_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::TAGS_PROPERTYNAME; - public const FAVORITE_PROPERTYNAME = \OCA\DAV\Connector\Sabre\TagsPlugin::FAVORITE_PROPERTYNAME; - public const TAG_FAVORITE = \OCA\DAV\Connector\Sabre\TagsPlugin::TAG_FAVORITE; - - /** - * @var \Sabre\DAV\Server - */ - private $server; +class TagsPluginTest extends TestCase { + public const TAGS_PROPERTYNAME = TagsPlugin::TAGS_PROPERTYNAME; + public const FAVORITE_PROPERTYNAME = TagsPlugin::FAVORITE_PROPERTYNAME; + public const TAG_FAVORITE = TagsPlugin::TAG_FAVORITE; /** * @var Tree @@ -59,47 +63,35 @@ class TagsPluginTest extends \Test\TestCase { private $tree; /** - * @var \OCP\ITagManager - */ - private $tagManager; - - /** - * @var \OCP\ITags + * @var ITags */ private $tagger; /** - * @var \OCA\DAV\Connector\Sabre\TagsPlugin + * @var TagsPlugin */ private $plugin; protected function setUp(): void { parent::setUp(); - $this->server = new \Sabre\DAV\Server(); - $this->tree = $this->getMockBuilder(Tree::class) - ->disableOriginalConstructor() - ->getMock(); - $this->tagger = $this->getMockBuilder(ITags::class) - ->disableOriginalConstructor() - ->getMock(); - $this->tagManager = $this->getMockBuilder(ITagManager::class) - ->disableOriginalConstructor() - ->getMock(); - $this->tagManager->expects($this->any()) + $server = new Server(); + $this->tree = $this->createMock(Tree::class); + $this->tagger = $this->createMock(ITags::class); + $tagManager = $this->createMock(ITagManager::class); + $tagManager->expects($this->any()) ->method('load') ->with('files') ->willReturn($this->tagger); - $this->plugin = new \OCA\DAV\Connector\Sabre\TagsPlugin($this->tree, $this->tagManager); - $this->plugin->initialize($this->server); + $this->plugin = new TagsPlugin($this->tree, $tagManager); + $this->plugin->initialize($server); } /** * @dataProvider tagsGetPropertiesDataProvider + * @throws Locked|Forbidden */ - public function testGetProperties($tags, $requestedProperties, $expectedProperties) { - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + public function testGetProperties(array $tags, array $requestedProperties, array $expectedProperties) { + $node = $this->createMock(Node::class); $node->expects($this->any()) ->method('getId') ->willReturn(123); @@ -114,7 +106,7 @@ public function testGetProperties($tags, $requestedProperties, $expectedProperti ->with($this->equalTo([123])) ->willReturn([123 => $tags]); - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/dummyPath', $requestedProperties, 0 @@ -134,17 +126,14 @@ public function testGetProperties($tags, $requestedProperties, $expectedProperti /** * @dataProvider tagsGetPropertiesDataProvider + * @throws Locked|Forbidden */ - public function testPreloadThenGetProperties($tags, $requestedProperties, $expectedProperties) { - $node1 = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + public function testPreloadThenGetProperties(array $tags, array $requestedProperties, array $expectedProperties) { + $node1 = $this->createMock(File::class); $node1->expects($this->any()) ->method('getId') ->willReturn(111); - $node2 = $this->getMockBuilder(File::class) - ->disableOriginalConstructor() - ->getMock(); + $node2 = $this->createMock(File::class); $node2->expects($this->any()) ->method('getId') ->willReturn(222); @@ -157,9 +146,7 @@ public function testPreloadThenGetProperties($tags, $requestedProperties, $expec $expectedCallCount = 1; } - $node = $this->getMockBuilder(Directory::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Directory::class); $node->expects($this->any()) ->method('getId') ->willReturn(123); @@ -178,17 +165,17 @@ public function testPreloadThenGetProperties($tags, $requestedProperties, $expec ); // simulate sabre recursive PROPFIND traversal - $propFindRoot = new \Sabre\DAV\PropFind( + $propFindRoot = new PropFind( '/subdir', $requestedProperties, 1 ); - $propFind1 = new \Sabre\DAV\PropFind( + $propFind1 = new PropFind( '/subdir/test.txt', $requestedProperties, 0 ); - $propFind2 = new \Sabre\DAV\PropFind( + $propFind2 = new PropFind( '/subdir/test2.txt', $requestedProperties, 0 @@ -214,7 +201,7 @@ public function testPreloadThenGetProperties($tags, $requestedProperties, $expec $this->assertEquals($expectedProperties, $result); } - public function tagsGetPropertiesDataProvider() { + public function tagsGetPropertiesDataProvider(): array { return [ // request both, receive both [ @@ -222,7 +209,7 @@ public function tagsGetPropertiesDataProvider() { [self::TAGS_PROPERTYNAME, self::FAVORITE_PROPERTYNAME], [ 200 => [ - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(['tag1', 'tag2']), + self::TAGS_PROPERTYNAME => new TagList(['tag1', 'tag2']), self::FAVORITE_PROPERTYNAME => true, ] ] @@ -233,7 +220,7 @@ public function tagsGetPropertiesDataProvider() { [self::TAGS_PROPERTYNAME], [ 200 => [ - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(['tag1', 'tag2']), + self::TAGS_PROPERTYNAME => new TagList(['tag1', 'tag2']), ] ] ], @@ -261,7 +248,7 @@ public function tagsGetPropertiesDataProvider() { [self::TAGS_PROPERTYNAME, self::FAVORITE_PROPERTYNAME], [ 200 => [ - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList([]), + self::TAGS_PROPERTYNAME => new TagList([]), self::FAVORITE_PROPERTYNAME => false, ] ] @@ -269,12 +256,14 @@ public function tagsGetPropertiesDataProvider() { ]; } + /** + * @throws Forbidden + * @throws Locked + */ public function testGetPropertiesSkipChunks(): void { - $sabreNode = $this->getMockBuilder(UploadFile::class) - ->disableOriginalConstructor() - ->getMock(); + $sabreNode = $this->createMock(UploadFile::class); - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/dummyPath', [self::TAGS_PROPERTYNAME, self::TAG_FAVORITE], 0 @@ -289,12 +278,13 @@ public function testGetPropertiesSkipChunks(): void { $this->assertCount(2, $result[404]); } + /** + * @throws NotFound + */ public function testUpdateTags() { // this test will replace the existing tags "tagremove" with "tag1" and "tag2" // and keep "tagkeep" - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Node::class); $node->expects($this->any()) ->method('getId') ->willReturn(123); @@ -304,27 +294,27 @@ public function testUpdateTags() { ->with('/dummypath') ->willReturn($node); - $this->tagger->expects($this->at(0)) + $this->tagger->expects($this->once()) ->method('getTagsForObjects') ->with($this->equalTo([123])) ->willReturn([123 => ['tagkeep', 'tagremove', self::TAG_FAVORITE]]); // then tag as tag1 and tag2 - $this->tagger->expects($this->at(1)) + $this->tagger->expects($this->exactly(2)) ->method('tagAs') - ->with(123, 'tag1'); - $this->tagger->expects($this->at(2)) - ->method('tagAs') - ->with(123, 'tag2'); + ->withConsecutive( + [123, 'tag1'], + [123, 'tag2'] + ); // it will untag tag3 - $this->tagger->expects($this->at(3)) + $this->tagger->expects($this->once()) ->method('unTag') ->with(123, 'tagremove'); // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(['tag1', 'tag2', 'tagkeep']) + $propPatch = new PropPatch([ + self::TAGS_PROPERTYNAME => new TagList(['tag1', 'tag2', 'tagkeep']) ]); $this->plugin->handleUpdateProperties( @@ -342,10 +332,11 @@ public function testUpdateTags() { $this->assertFalse(isset($result[self::FAVORITE_PROPERTYNAME])); } + /** + * @throws NotFound + */ public function testUpdateTagsFromScratch() { - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Node::class); $node->expects($this->any()) ->method('getId') ->willReturn(123); @@ -355,22 +346,23 @@ public function testUpdateTagsFromScratch() { ->with('/dummypath') ->willReturn($node); - $this->tagger->expects($this->at(0)) + $this->tagger->expects($this->once()) ->method('getTagsForObjects') ->with($this->equalTo([123])) ->willReturn([]); // then tag as tag1 and tag2 - $this->tagger->expects($this->at(1)) - ->method('tagAs') - ->with(123, 'tag1'); - $this->tagger->expects($this->at(2)) + $this->tagger->expects($this->exactly(3)) ->method('tagAs') - ->with(123, 'tag2'); + ->withConsecutive( + [123, 'tag1'], + [123, 'tag2'], + [123, 'tagkeep'] + ); // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ - self::TAGS_PROPERTYNAME => new \OCA\DAV\Connector\Sabre\TagList(['tag1', 'tag2', 'tagkeep']) + $propPatch = new PropPatch([ + self::TAGS_PROPERTYNAME => new TagList(['tag1', 'tag2', 'tagkeep']) ]); $this->plugin->handleUpdateProperties( @@ -388,12 +380,13 @@ public function testUpdateTagsFromScratch() { $this->assertFalse(false, isset($result[self::FAVORITE_PROPERTYNAME])); } + /** + * @throws NotFound + */ public function testUpdateFav() { // this test will replace the existing tags "tagremove" with "tag1" and "tag2" // and keep "tagkeep" - $node = $this->getMockBuilder(Node::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(Node::class); $node->expects($this->any()) ->method('getId') ->willReturn(123); @@ -409,7 +402,7 @@ public function testUpdateFav() { ->with(123, self::TAG_FAVORITE); // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ + $propPatch = new PropPatch([ self::FAVORITE_PROPERTYNAME => true ]); @@ -434,7 +427,7 @@ public function testUpdateFav() { ->with(123, self::TAG_FAVORITE); // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ + $propPatch = new PropPatch([ self::FAVORITE_PROPERTYNAME => false ]); diff --git a/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php b/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php index 37650e6f1ed90..2ae7aee6616d0 100644 --- a/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php +++ b/apps/dav/tests/unit/Controller/BirthdayCalendarControllerTest.php @@ -30,49 +30,45 @@ use OCA\DAV\BackgroundJob\GenerateBirthdayCalendarBackgroundJob; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\Controller\BirthdayCalendarController; +use OCP\AppFramework\Http\JSONResponse; use OCP\BackgroundJob\IJobList; use OCP\IConfig; use OCP\IDBConnection; use OCP\IRequest; use OCP\IUser; use OCP\IUserManager; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class BirthdayCalendarControllerTest extends TestCase { - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig|MockObject */ private $config; - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ - private $request; - - /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */ - private $db; - - /** @var IJobList|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IJobList|MockObject */ private $jobList; - /** @var IUserManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserManager|MockObject */ private $userManager; - /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend|MockObject */ private $caldav; - /** @var BirthdayCalendarController|\PHPUnit\Framework\MockObject\MockObject */ + /** @var BirthdayCalendarController|MockObject */ private $controller; protected function setUp(): void { parent::setUp(); $this->config = $this->createMock(IConfig::class); - $this->request = $this->createMock(IRequest::class); - $this->db = $this->createMock(IDBConnection::class); + $request = $this->createMock(IRequest::class); + $db = $this->createMock(IDBConnection::class); $this->jobList = $this->createMock(IJobList::class); $this->userManager = $this->createMock(IUserManager::class); $this->caldav = $this->createMock(CalDavBackend::class); $this->controller = new BirthdayCalendarController('dav', - $this->request, $this->db, $this->config, $this->jobList, + $request, $db, $this->config, $this->jobList, $this->userManager, $this->caldav); } @@ -105,7 +101,7 @@ public function testEnable() { ); $response = $this->controller->enable(); - $this->assertInstanceOf('OCP\AppFramework\Http\JSONResponse', $response); + $this->assertInstanceOf(JSONResponse::class, $response); } public function testDisable() { @@ -119,6 +115,6 @@ public function testDisable() { ->method('deleteAllBirthdayCalendars'); $response = $this->controller->disable(); - $this->assertInstanceOf('OCP\AppFramework\Http\JSONResponse', $response); + $this->assertInstanceOf(JSONResponse::class, $response); } } diff --git a/apps/dav/tests/unit/Controller/DirectControllerTest.php b/apps/dav/tests/unit/Controller/DirectControllerTest.php index 00771e7f7a645..328dbf97bf1e2 100644 --- a/apps/dav/tests/unit/Controller/DirectControllerTest.php +++ b/apps/dav/tests/unit/Controller/DirectControllerTest.php @@ -40,23 +40,24 @@ use OCP\IRequest; use OCP\IURLGenerator; use OCP\Security\ISecureRandom; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class DirectControllerTest extends TestCase { - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IRootFolder|MockObject */ private $rootFolder; - /** @var DirectMapper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var DirectMapper|MockObject */ private $directMapper; - /** @var ISecureRandom|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ISecureRandom|MockObject */ private $random; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ private $urlGenerator; /** @var DirectController */ @@ -83,6 +84,9 @@ protected function setUp(): void { ); } + /** + * @throws OCSBadRequestException + */ public function testGetUrlNonExistingFileId() { $userFolder = $this->createMock(Folder::class); $this->rootFolder->method('getUserFolder') @@ -97,6 +101,9 @@ public function testGetUrlNonExistingFileId() { $this->controller->getUrl(101); } + /** + * @throws OCSNotFoundException + */ public function testGetUrlForFolder() { $userFolder = $this->createMock(Folder::class); $this->rootFolder->method('getUserFolder') @@ -113,6 +120,10 @@ public function testGetUrlForFolder() { $this->controller->getUrl(101); } + /** + * @throws OCSBadRequestException + * @throws OCSNotFoundException + */ public function testGetUrlValid() { $userFolder = $this->createMock(Folder::class); $this->rootFolder->method('getUserFolder') diff --git a/apps/dav/tests/unit/Controller/InvitationResponseControllerTest.php b/apps/dav/tests/unit/Controller/InvitationResponseControllerTest.php index cd3269d657c9c..40240bd7196e3 100644 --- a/apps/dav/tests/unit/Controller/InvitationResponseControllerTest.php +++ b/apps/dav/tests/unit/Controller/InvitationResponseControllerTest.php @@ -34,11 +34,14 @@ use OCA\DAV\Controller\InvitationResponseController; use OCP\AppFramework\Http\TemplateResponse; use OCP\AppFramework\Utility\ITimeFactory; +use OCP\DB\Exception; use OCP\DB\IResult; use OCP\DB\QueryBuilder\IExpressionBuilder; use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; use OCP\IRequest; +use PDO; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\VObject\ITip\Message; use Test\TestCase; @@ -47,16 +50,16 @@ class InvitationResponseControllerTest extends TestCase { /** @var InvitationResponseController */ private $controller; - /** @var IDBConnection|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IDBConnection|MockObject */ private $dbConnection; - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IRequest|MockObject */ private $request; - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; - /** @var InvitationResponseServer|\PHPUnit\Framework\MockObject\MockObject */ + /** @var InvitationResponseServer|MockObject */ private $responseServer; protected function setUp(): void { @@ -65,9 +68,7 @@ protected function setUp(): void { $this->dbConnection = $this->createMock(IDBConnection::class); $this->request = $this->createMock(IRequest::class); $this->timeFactory = $this->createMock(ITimeFactory::class); - $this->responseServer = $this->getMockBuilder(InvitationResponseServer::class) - ->disableOriginalConstructor() - ->getMock(); + $this->responseServer = $this->createMock(InvitationResponseServer::class); $this->controller = new InvitationResponseController( 'appName', @@ -87,9 +88,10 @@ public function attendeeProvider(): array { /** * @dataProvider attendeeProvider + * @throws Exception */ public function testAccept(bool $isExternalAttendee): void { - $this->buildQueryExpects('TOKEN123', [ + $this->buildQueryExpects([ 'id' => 0, 'uid' => 'this-is-the-events-uid', 'recurrenceid' => null, @@ -98,7 +100,7 @@ public function testAccept(bool $isExternalAttendee): void { 'sequence' => null, 'token' => 'TOKEN123', 'expiration' => 420000, - ], 1337); + ]); $expected = <<buildQueryExpects('TOKEN123', [ + $this->buildQueryExpects([ 'id' => 0, 'uid' => 'this-is-the-events-uid', 'recurrenceid' => null, @@ -162,7 +165,7 @@ public function testAcceptSequence(bool $isExternalAttendee): void { 'sequence' => 1337, 'token' => 'TOKEN123', 'expiration' => 420000, - ], 1337); + ]); $expected = <<buildQueryExpects('TOKEN123', [ + $this->buildQueryExpects([ 'id' => 0, 'uid' => 'this-is-the-events-uid', 'recurrenceid' => "RECURRENCE-ID;TZID=Europe/Berlin:20180726T150000\n", @@ -226,7 +230,7 @@ public function testAcceptRecurrenceId(bool $isExternalAttendee): void { 'sequence' => null, 'token' => 'TOKEN123', 'expiration' => 420000, - ], 1337); + ]); $expected = <<assertTrue($called); } + /** + * @throws Exception + */ public function testAcceptTokenNotFound() { - $this->buildQueryExpects('TOKEN123', null, 1337); + $this->buildQueryExpects(null); $response = $this->controller->accept('TOKEN123'); $this->assertInstanceOf(TemplateResponse::class, $response); @@ -287,8 +294,11 @@ public function testAcceptTokenNotFound() { $this->assertEquals([], $response->getParams()); } + /** + * @throws Exception + */ public function testAcceptExpiredToken() { - $this->buildQueryExpects('TOKEN123', [ + $this->buildQueryExpects([ 'id' => 0, 'uid' => 'this-is-the-events-uid', 'recurrenceid' => null, @@ -297,7 +307,7 @@ public function testAcceptExpiredToken() { 'sequence' => null, 'token' => 'TOKEN123', 'expiration' => 42, - ], 1337); + ]); $response = $this->controller->accept('TOKEN123'); $this->assertInstanceOf(TemplateResponse::class, $response); @@ -307,9 +317,10 @@ public function testAcceptExpiredToken() { /** * @dataProvider attendeeProvider + * @throws Exception */ public function testDecline(bool $isExternalAttendee): void { - $this->buildQueryExpects('TOKEN123', [ + $this->buildQueryExpects([ 'id' => 0, 'uid' => 'this-is-the-events-uid', 'recurrenceid' => null, @@ -318,7 +329,7 @@ public function testDecline(bool $isExternalAttendee): void { 'sequence' => null, 'token' => 'TOKEN123', 'expiration' => 420000, - ], 1337); + ]); $expected = <<request->expects($this->at(0)) - ->method('getParam') - ->with('partStat') - ->willReturn('TENTATIVE'); - $this->request->expects($this->at(1)) - ->method('getParam') - ->with('guests') - ->willReturn('7'); - $this->request->expects($this->at(2)) + $this->request->expects($this->exactly(3)) ->method('getParam') - ->with('comment') - ->willReturn('Foo bar Bli blub'); + ->withConsecutive(['partStat'], ['guests'], ['comment']) + ->willReturnOnConsecutiveCalls('TENTATIVE', '7', 'Foo bar Bli blub'); - $this->buildQueryExpects('TOKEN123', [ + $this->buildQueryExpects([ 'id' => 0, 'uid' => 'this-is-the-events-uid', 'recurrenceid' => null, @@ -402,7 +406,7 @@ public function testProcessMoreOptionsResult(bool $isExternalAttendee): void { 'sequence' => null, 'token' => 'TOKEN123', 'expiration' => 420000, - ], 1337); + ]); $expected = <<assertTrue($called); } - private function buildQueryExpects($token, $return, $time) { + private function buildQueryExpects(?array $return) { $queryBuilder = $this->createMock(IQueryBuilder::class); $stmt = $this->createMock(IResult::class); $expr = $this->createMock(IExpressionBuilder::class); @@ -469,12 +473,12 @@ private function buildQueryExpects($token, $return, $time) { ->willReturn($expr); $queryBuilder->method('createNamedParameter') ->willReturnMap([ - [$token, \PDO::PARAM_STR, null, 'namedParameterToken'] + ['TOKEN123', PDO::PARAM_STR, null, 'namedParameterToken'] ]); $stmt->expects($this->once()) ->method('fetch') - ->with(\PDO::FETCH_ASSOC) + ->with(PDO::FETCH_ASSOC) ->willReturn($return); $expr->expects($this->once()) @@ -487,24 +491,24 @@ private function buildQueryExpects($token, $return, $time) { ->with() ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(0)) + $queryBuilder->expects($this->once()) ->method('select') ->with('*') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(1)) + $queryBuilder->expects($this->once()) ->method('from') ->with('calendar_invitations') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(4)) + $queryBuilder->expects($this->once()) ->method('where') ->with('EQ STATEMENT') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(5)) - ->method('execute') + $queryBuilder->expects($this->once()) + ->method('executeQuery') ->with() ->willReturn($stmt); $this->timeFactory->method('getTime') - ->willReturn($time); + ->willReturn(1337); } } diff --git a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php index 537c22e74a2d1..1bd4007a690bc 100644 --- a/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php +++ b/apps/dav/tests/unit/DAV/AnonymousOptionsTest.php @@ -29,12 +29,13 @@ use Sabre\DAV\Auth\Backend\BasicCallBack; use Sabre\DAV\Auth\Plugin; use Sabre\DAV\Server; +use Sabre\HTTP\Response; use Sabre\HTTP\ResponseInterface; use Sabre\HTTP\Sapi; use Test\TestCase; class AnonymousOptionsTest extends TestCase { - private function sendRequest($method, $path, $userAgent = '') { + private function sendRequest($method, $path, $userAgent = ''): Response { $server = new Server(); $server->addPlugin(new AnonymousOptionsPlugin()); $server->addPlugin(new Plugin(new BasicCallBack(function () { diff --git a/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php b/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php index a0733a685503c..0262690747e72 100644 --- a/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php +++ b/apps/dav/tests/unit/DAV/BrowserErrorPagePluginTest.php @@ -23,26 +23,29 @@ */ namespace OCA\DAV\Tests\unit\DAV; +use Exception; use OCA\DAV\Files\BrowserErrorPagePlugin; +use PHPUnit\Framework\MockObject\MockObject; +use RuntimeException; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Server; use Sabre\HTTP\Response; +use Test\TestCase; -class BrowserErrorPagePluginTest extends \Test\TestCase { +class BrowserErrorPagePluginTest extends TestCase { /** * @dataProvider providesExceptions - * @param $expectedCode - * @param $exception */ - public function test($expectedCode, $exception) { - /** @var BrowserErrorPagePlugin | \PHPUnit\Framework\MockObject\MockObject $plugin */ - $plugin = $this->getMockBuilder(BrowserErrorPagePlugin::class)->setMethods(['sendResponse', 'generateBody'])->getMock(); + public function test(int $expectedCode, Exception $exception) { + /** @var BrowserErrorPagePlugin | MockObject $plugin */ + $plugin = $this->getMockBuilder(BrowserErrorPagePlugin::class)->onlyMethods(['sendResponse', 'generateBody'])->getMock(); $plugin->expects($this->once())->method('generateBody')->willReturn(':boom:'); $plugin->expects($this->once())->method('sendResponse'); - /** @var \Sabre\DAV\Server | \PHPUnit\Framework\MockObject\MockObject $server */ - $server = $this->getMockBuilder('Sabre\DAV\Server')->disableOriginalConstructor()->getMock(); + /** @var Server | MockObject $server */ + $server = $this->createMock(Server::class); $server->expects($this->once())->method('on'); - $httpResponse = $this->getMockBuilder(Response::class)->disableOriginalConstructor()->getMock(); + $httpResponse = $this->createMock(Response::class); $httpResponse->expects($this->once())->method('addHeaders'); $httpResponse->expects($this->once())->method('setStatus')->with($expectedCode); $httpResponse->expects($this->once())->method('setBody')->with(':boom:'); @@ -51,10 +54,10 @@ public function test($expectedCode, $exception) { $plugin->logException($exception); } - public function providesExceptions() { + public function providesExceptions(): array { return [ [ 404, new NotFound()], - [ 500, new \RuntimeException()], + [ 500, new RuntimeException()], ]; } } diff --git a/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php b/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php index 3ac34d2a18a12..645166426a8ee 100644 --- a/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php +++ b/apps/dav/tests/unit/DAV/CustomPropertiesBackendTest.php @@ -27,9 +27,14 @@ */ namespace OCA\DAV\Tests\DAV; +use OC; use OCA\DAV\DAV\CustomPropertiesBackend; +use OCP\DB\Exception; use OCP\IDBConnection; use OCP\IUser; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; use Sabre\DAV\Tree; @@ -40,18 +45,22 @@ */ class CustomPropertiesBackendTest extends TestCase { - /** @var Tree | \PHPUnit\Framework\MockObject\MockObject */ + /** @var Tree | MockObject */ private $tree; /** @var IDBConnection */ private $dbConnection; - /** @var IUser | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IUser | MockObject */ private $user; - /** @var CustomPropertiesBackend | \PHPUnit\Framework\MockObject\MockObject */ + /** @var CustomPropertiesBackend | MockObject */ private $backend; + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + */ protected function setUp(): void { parent::setUp(); @@ -60,7 +69,7 @@ protected function setUp(): void { $this->user->method('getUID') ->with() ->willReturn('dummy_user_42'); - $this->dbConnection = \OC::$server->get(IDBConnection::class); + $this->dbConnection = OC::$server->get(IDBConnection::class); $this->backend = new CustomPropertiesBackend( $this->tree, @@ -69,10 +78,13 @@ protected function setUp(): void { ); } + /** + * @throws Exception + */ protected function tearDown(): void { $query = $this->dbConnection->getQueryBuilder(); $query->delete('properties'); - $query->execute(); + $query->executeStatement(); parent::tearDown(); } @@ -85,12 +97,18 @@ private function formatPath(string $path): string { } } + /** + * @throws Exception + */ protected function insertProps(string $user, string $path, array $props) { foreach ($props as $name => $value) { $this->insertProp($user, $path, $name, $value); } } + /** + * @throws Exception + */ protected function insertProp(string $user, string $path, string $name, string $value) { $query = $this->dbConnection->getQueryBuilder(); $query->insert('properties') @@ -100,17 +118,20 @@ protected function insertProp(string $user, string $path, string $name, string $ 'propertyname' => $query->createNamedParameter($name), 'propertyvalue' => $query->createNamedParameter($value), ]); - $query->execute(); + $query->executeStatement(); } - protected function getProps(string $user, string $path) { + /** + * @throws Exception + */ + protected function getProps(string $user, string $path): array { $query = $this->dbConnection->getQueryBuilder(); $query->select('propertyname', 'propertyvalue') ->from('properties') ->where($query->expr()->eq('userid', $query->createNamedParameter($user))) ->where($query->expr()->eq('propertypath', $query->createNamedParameter($this->formatPath($path)))); - $result = $query->execute(); + $result = $query->executeQuery(); $data = []; while ($row = $result->fetch()) { $data[$row['propertyname']] = $row['propertyvalue']; @@ -129,7 +150,7 @@ public function testPropFindNoDbCalls() { ); $propFind = $this->createMock(PropFind::class); - $propFind->expects($this->at(0)) + $propFind->expects($this->once()) ->method('get404Properties') ->with() ->willReturn([ @@ -179,7 +200,7 @@ public function testPropFindCalendarCall() { $setProps = []; $propFind->method('set') - ->willReturnCallback(function ($name, $value, $status) use (&$setProps) { + ->willReturnCallback(function ($name, $value) use (&$setProps) { $setProps[$name] = $value; }); @@ -189,6 +210,7 @@ public function testPropFindCalendarCall() { /** * @dataProvider propPatchProvider + * @throws Exception */ public function testPropPatch(string $path, array $existing, array $props, array $result) { $this->insertProps($this->user->getUID(), $path, $existing); @@ -201,7 +223,7 @@ public function testPropPatch(string $path, array $existing, array $props, array $this->assertEquals($result, $storedProps); } - public function propPatchProvider() { + public function propPatchProvider(): array { $longPath = str_repeat('long_path', 100); return [ ['foo_bar_path_1337', [], ['{DAV:}displayname' => 'anything'], ['{DAV:}displayname' => 'anything']], @@ -213,6 +235,7 @@ public function propPatchProvider() { /** * @dataProvider deleteProvider + * @throws Exception */ public function testDelete(string $path) { $this->insertProps('dummy_user_42', $path, ['foo' => 'bar']); @@ -220,7 +243,7 @@ public function testDelete(string $path) { $this->assertEquals([], $this->getProps('dummy_user_42', $path)); } - public function deleteProvider() { + public function deleteProvider(): array { return [ ['foo_bar_path_1337'], [str_repeat('long_path', 100)] @@ -229,6 +252,7 @@ public function deleteProvider() { /** * @dataProvider moveProvider + * @throws Exception */ public function testMove(string $source, string $target) { $this->insertProps('dummy_user_42', $source, ['foo' => 'bar']); @@ -237,7 +261,7 @@ public function testMove(string $source, string $target) { $this->assertEquals(['foo' => 'bar'], $this->getProps('dummy_user_42', $target)); } - public function moveProvider() { + public function moveProvider(): array { return [ ['foo_bar_path_1337', 'foo_bar_path_7333'], [str_repeat('long_path1', 100), str_repeat('long_path2', 100)] diff --git a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php index 8f86961a6af68..adccdd0063913 100644 --- a/apps/dav/tests/unit/DAV/GroupPrincipalTest.php +++ b/apps/dav/tests/unit/DAV/GroupPrincipalTest.php @@ -39,11 +39,11 @@ use OCP\IUserSession; use OCP\Share\IManager; use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception; use Sabre\DAV\PropPatch; +use Test\TestCase; -class GroupPrincipalTest extends \Test\TestCase { - /** @var IConfig|MockObject */ - private $config; +class GroupPrincipalTest extends TestCase { /** @var IGroupManager | MockObject */ private $groupManager; @@ -61,13 +61,13 @@ protected function setUp(): void { $this->groupManager = $this->createMock(IGroupManager::class); $this->userSession = $this->createMock(IUserSession::class); $this->shareManager = $this->createMock(IManager::class); - $this->config = $this->createMock(IConfig::class); + $config = $this->createMock(IConfig::class); $this->connector = new GroupPrincipalBackend( $this->groupManager, $this->userSession, $this->shareManager, - $this->config + $config ); parent::setUp(); } @@ -192,11 +192,17 @@ public function testGetPrincipalsByPathGroupWithHash() { $this->assertSame($expectedResponse, $response); } + /** + * @throws Exception + */ public function testGetGroupMemberSet() { $response = $this->connector->getGroupMemberSet('principals/groups/foo'); $this->assertSame([], $response); } + /** + * @throws Exception + */ public function testGetGroupMembership() { $response = $this->connector->getGroupMembership('principals/groups/foo'); $this->assertSame([], $response); @@ -204,7 +210,7 @@ public function testGetGroupMembership() { public function testSetGroupMembership() { - $this->expectException(\Sabre\DAV\Exception::class); + $this->expectException(Exception::class); $this->expectExceptionMessage('Setting members of the group is not supported yet'); $this->connector->setGroupMemberSet('principals/groups/foo', ['foo']); @@ -288,7 +294,7 @@ public function testSearchPrincipals(bool $sharingEnabled, bool $groupSharingEna ['{DAV:}displayname' => 'Foo'], $test)); } - public function searchPrincipalsDataProvider() { + public function searchPrincipalsDataProvider(): array { return [ [true, true, false, 'allof', ['principals/groups/group1', 'principals/groups/group2', 'principals/groups/group3', 'principals/groups/group4', 'principals/groups/group5']], [true, true, false, 'anyof', ['principals/groups/group1', 'principals/groups/group2', 'principals/groups/group3', 'principals/groups/group4', 'principals/groups/group5']], @@ -329,7 +335,7 @@ public function testFindByUri(bool $sharingEnabled, bool $groupSharingEnabled, b ->method('getUser') ->willReturn($user); - $this->groupManager->expects($this->at(0)) + $this->groupManager->expects($this->once()) ->method('getUserGroupIds') ->with($user) ->willReturn(['group1', 'group2', 'group5']); @@ -344,7 +350,7 @@ public function testFindByUri(bool $sharingEnabled, bool $groupSharingEnabled, b $this->assertEquals($result, $this->connector->findByUri($findUri, 'principals/groups')); } - public function findByUriDataProvider() { + public function findByUriDataProvider(): array { return [ [false, false, false, 'principal:principals/groups/group1', null], [false, false, false, 'principal:principals/groups/group3', null], diff --git a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php index 1c4bb5e12e410..f394da9b91f9b 100644 --- a/apps/dav/tests/unit/DAV/Sharing/PluginTest.php +++ b/apps/dav/tests/unit/DAV/Sharing/PluginTest.php @@ -31,6 +31,8 @@ use OCA\DAV\DAV\Sharing\Plugin; use OCP\IConfig; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception; use Sabre\DAV\Server; use Sabre\DAV\SimpleCollection; use Sabre\HTTP\Request; @@ -41,32 +43,31 @@ class PluginTest extends TestCase { /** @var Plugin */ private $plugin; - /** @var Server */ - private $server; - /** @var IShareable | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IShareable | MockObject */ private $book; + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); - /** @var Auth | \PHPUnit\Framework\MockObject\MockObject $authBackend */ - $authBackend = $this->getMockBuilder(Auth::class)->disableOriginalConstructor()->getMock(); + /** @var Auth | MockObject $authBackend */ + $authBackend = $this->createMock(Auth::class); $authBackend->method('isDavAuthenticated')->willReturn(true); /** @var IRequest $request */ - $request = $this->getMockBuilder(IRequest::class)->disableOriginalConstructor()->getMock(); + $request = $this->createMock(IRequest::class); $config = $this->createMock(IConfig::class); $this->plugin = new Plugin($authBackend, $request, $config); $root = new SimpleCollection('root'); - $this->server = new \Sabre\DAV\Server($root); + $server = new Server($root); /** @var SimpleCollection $node */ - $this->book = $this->getMockBuilder(IShareable::class)-> - disableOriginalConstructor()-> - getMock(); + $this->book = $this->createMock(IShareable::class); $this->book->method('getName')->willReturn('addressbook1.vcf'); $root->addChild($this->book); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } public function testSharing() { diff --git a/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php b/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php index 05e6699cc4c43..d4936dabcdf2f 100644 --- a/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php +++ b/apps/dav/tests/unit/DAV/SystemPrincipalBackendTest.php @@ -26,22 +26,21 @@ namespace OCA\DAV\Tests\unit\DAV; use OCA\DAV\DAV\SystemPrincipalBackend; +use Sabre\DAV\Exception; use Test\TestCase; class SystemPrincipalBackendTest extends TestCase { /** * @dataProvider providesPrefix - * @param $expected - * @param $prefix */ - public function testGetPrincipalsByPrefix($expected, $prefix) { + public function testGetPrincipalsByPrefix(array $expected, string $prefix) { $backend = new SystemPrincipalBackend(); $result = $backend->getPrincipalsByPrefix($prefix); $this->assertEquals($expected, $result); } - public function providesPrefix() { + public function providesPrefix(): array { return [ [[], ''], [[[ @@ -58,16 +57,14 @@ public function providesPrefix() { /** * @dataProvider providesPath - * @param $expected - * @param $path */ - public function testGetPrincipalByPath($expected, $path) { + public function testGetPrincipalByPath(?array $expected, string $path) { $backend = new SystemPrincipalBackend(); $result = $backend->getPrincipalByPath($path); $this->assertEquals($expected, $result); } - public function providesPath() { + public function providesPath(): array { return [ [null, ''], [null, 'principals'], @@ -81,19 +78,17 @@ public function providesPath() { /** * @dataProvider providesPrincipalForGetGroupMemberSet - * - * @param string $principal - * @throws \Sabre\DAV\Exception + * @throws Exception */ - public function testGetGroupMemberSetExceptional($principal) { - $this->expectException(\Sabre\DAV\Exception::class); + public function testGetGroupMemberSetExceptional(?string $principal) { + $this->expectException(Exception::class); $this->expectExceptionMessage('Principal not found'); $backend = new SystemPrincipalBackend(); $backend->getGroupMemberSet($principal); } - public function providesPrincipalForGetGroupMemberSet() { + public function providesPrincipalForGetGroupMemberSet(): array { return [ [null], ['principals/system'], @@ -101,7 +96,7 @@ public function providesPrincipalForGetGroupMemberSet() { } /** - * @throws \Sabre\DAV\Exception + * @throws Exception */ public function testGetGroupMemberSet() { $backend = new SystemPrincipalBackend(); @@ -111,26 +106,24 @@ public function testGetGroupMemberSet() { /** * @dataProvider providesPrincipalForGetGroupMembership - * - * @param string $principal - * @throws \Sabre\DAV\Exception + * @throws Exception */ - public function testGetGroupMembershipExceptional($principal) { - $this->expectException(\Sabre\DAV\Exception::class); + public function testGetGroupMembershipExceptional(string $principal) { + $this->expectException(Exception::class); $this->expectExceptionMessage('Principal not found'); $backend = new SystemPrincipalBackend(); $backend->getGroupMembership($principal); } - public function providesPrincipalForGetGroupMembership() { + public function providesPrincipalForGetGroupMembership(): array { return [ ['principals/system/a'], ]; } /** - * @throws \Sabre\DAV\Exception + * @throws Exception */ public function testGetGroupMembership() { $backend = new SystemPrincipalBackend(); diff --git a/apps/dav/tests/unit/Direct/DirectFileTest.php b/apps/dav/tests/unit/Direct/DirectFileTest.php index 5899b23d0b9d0..59839dc60f1d9 100644 --- a/apps/dav/tests/unit/Direct/DirectFileTest.php +++ b/apps/dav/tests/unit/Direct/DirectFileTest.php @@ -33,53 +33,42 @@ use OCP\Files\File; use OCP\Files\Folder; use OCP\Files\IRootFolder; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\DAV\Exception\Forbidden; use Test\TestCase; class DirectFileTest extends TestCase { - /** @var Direct */ - private $direct; - - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; - - /** @var Folder|\PHPUnit\Framework\MockObject\MockObject */ - private $userFolder; - - /** @var File|\PHPUnit\Framework\MockObject\MockObject */ + /** @var File|MockObject */ private $file; /** @var DirectFile */ private $directFile; - /** @var IEventDispatcher */ - private $eventDispatcher; - protected function setUp(): void { parent::setUp(); - $this->direct = Direct::fromParams([ + $direct = Direct::fromParams([ 'userId' => 'directUser', 'token' => 'directToken', 'fileId' => 42, ]); - $this->rootFolder = $this->createMock(IRootFolder::class); + $rootFolder = $this->createMock(IRootFolder::class); - $this->userFolder = $this->createMock(Folder::class); - $this->rootFolder->method('getUserFolder') + $userFolder = $this->createMock(Folder::class); + $rootFolder->method('getUserFolder') ->with('directUser') - ->willReturn($this->userFolder); + ->willReturn($userFolder); $this->file = $this->createMock(File::class); - $this->userFolder->method('getById') + $userFolder->method('getById') ->with(42) ->willReturn([$this->file]); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); + $eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->directFile = new DirectFile($this->direct, $this->rootFolder, $this->eventDispatcher); + $this->directFile = new DirectFile($direct, $rootFolder, $eventDispatcher); } public function testPut() { diff --git a/apps/dav/tests/unit/Direct/DirectHomeTest.php b/apps/dav/tests/unit/Direct/DirectHomeTest.php index 073aa28f12120..13f40d3055bbb 100644 --- a/apps/dav/tests/unit/Direct/DirectHomeTest.php +++ b/apps/dav/tests/unit/Direct/DirectHomeTest.php @@ -37,6 +37,7 @@ use OCP\EventDispatcher\IEventDispatcher; use OCP\Files\IRootFolder; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; @@ -44,51 +45,39 @@ class DirectHomeTest extends TestCase { - /** @var DirectMapper|\PHPUnit\Framework\MockObject\MockObject */ + /** @var DirectMapper|MockObject */ private $directMapper; - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ - private $rootFolder; - - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ - private $timeFactory; - - /** @var Throttler|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Throttler|MockObject */ private $throttler; - /** @var IRequest */ - private $request; - /** @var DirectHome */ private $directHome; - /** @var IEventDispatcher */ - private $eventDispatcher; - protected function setUp(): void { parent::setUp(); $this->directMapper = $this->createMock(DirectMapper::class); - $this->rootFolder = $this->createMock(IRootFolder::class); - $this->timeFactory = $this->createMock(ITimeFactory::class); + $rootFolder = $this->createMock(IRootFolder::class); + $timeFactory = $this->createMock(ITimeFactory::class); $this->throttler = $this->createMock(Throttler::class); - $this->request = $this->createMock(IRequest::class); - $this->eventDispatcher = $this->createMock(IEventDispatcher::class); + $request = $this->createMock(IRequest::class); + $eventDispatcher = $this->createMock(IEventDispatcher::class); - $this->timeFactory->method('getTime') + $timeFactory->method('getTime') ->willReturn(42); - $this->request->method('getRemoteAddress') + $request->method('getRemoteAddress') ->willReturn('1.2.3.4'); $this->directHome = new DirectHome( - $this->rootFolder, + $rootFolder, $this->directMapper, - $this->timeFactory, + $timeFactory, $this->throttler, - $this->request, - $this->eventDispatcher + $request, + $eventDispatcher ); } @@ -134,6 +123,9 @@ public function testGetLastModified() { $this->assertSame(0, $this->directHome->getLastModified()); } + /** + * @throws NotFound + */ public function testGetChildValid() { $direct = Direct::fromParams([ 'expiration' => 100, diff --git a/apps/dav/tests/unit/Files/FileSearchBackendTest.php b/apps/dav/tests/unit/Files/FileSearchBackendTest.php index dec5db1b1b0cf..4ffb2c1b9ef1a 100644 --- a/apps/dav/tests/unit/Files/FileSearchBackendTest.php +++ b/apps/dav/tests/unit/Files/FileSearchBackendTest.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\Tests\Files; +use InvalidArgumentException; use OC\Files\Search\SearchComparison; use OC\Files\Search\SearchQuery; use OC\Files\View; @@ -42,34 +43,35 @@ use OCP\Files\Search\ISearchQuery; use OCP\IUser; use OCP\Share\IManager; +use PHPUnit\Framework\MockObject\MockObject; use SearchDAV\Backend\SearchPropertyDefinition; use SearchDAV\Query\Limit; +use SearchDAV\Query\Literal; +use SearchDAV\Query\Operator; use SearchDAV\Query\Query; +use SearchDAV\Query\Scope; use Test\TestCase; class FileSearchBackendTest extends TestCase { - /** @var CachingTree|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CachingTree|MockObject */ private $tree; /** @var IUser */ private $user; - /** @var IRootFolder|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IRootFolder|MockObject */ private $rootFolder; - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - private $shareManager; - - /** @var View|\PHPUnit\Framework\MockObject\MockObject */ + /** @var View|MockObject */ private $view; - /** @var Folder|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Folder|MockObject */ private $searchFolder; /** @var FileSearchBackend */ private $search; - /** @var Directory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Directory|MockObject */ private $davFolder; protected function setUp(): void { @@ -80,21 +82,15 @@ protected function setUp(): void { ->method('getUID') ->willReturn('test'); - $this->tree = $this->getMockBuilder(CachingTree::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->view = $this->getMockBuilder(View::class) - ->disableOriginalConstructor() - ->getMock(); - + $this->tree = $this->createMock(CachingTree::class); + $this->view = $this->createMock(View::class); $this->view->expects($this->any()) ->method('getRelativePath') ->willReturnArgument(0); $this->rootFolder = $this->createMock(IRootFolder::class); - $this->shareManager = $this->createMock(IManager::class); + $shareManager = $this->createMock(IManager::class); $this->searchFolder = $this->createMock(Folder::class); @@ -110,7 +106,7 @@ protected function setUp(): void { ->method('get') ->willReturn($this->searchFolder); - $this->search = new FileSearchBackend($this->tree, $this->user, $this->rootFolder, $this->shareManager, $this->view); + $this->search = new FileSearchBackend($this->tree, $this->user, $this->rootFolder, $shareManager, $this->view); } public function testSearchFilename() { @@ -135,7 +131,7 @@ public function testSearchFilename() { new \OC\Files\Node\Folder($this->rootFolder, $this->view, '/test/path') ]); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_EQUAL, '{DAV:}displayname', 'foo'); + $query = $this->getBasicQuery(Operator::OPERATION_EQUAL, '{DAV:}displayname', 'foo'); $result = $this->search->search($query); $this->assertCount(1, $result); @@ -164,7 +160,7 @@ public function testSearchMimetype() { new \OC\Files\Node\Folder($this->rootFolder, $this->view, '/test/path') ]); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_EQUAL, '{DAV:}getcontenttype', 'foo'); + $query = $this->getBasicQuery(Operator::OPERATION_EQUAL, '{DAV:}getcontenttype', 'foo'); $result = $this->search->search($query); $this->assertCount(1, $result); @@ -193,7 +189,7 @@ public function testSearchSize() { new \OC\Files\Node\Folder($this->rootFolder, $this->view, '/test/path') ]); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_GREATER_THAN, FilesPlugin::SIZE_PROPERTYNAME, 10); + $query = $this->getBasicQuery(Operator::OPERATION_GREATER_THAN, FilesPlugin::SIZE_PROPERTYNAME, 10); $result = $this->search->search($query); $this->assertCount(1, $result); @@ -222,7 +218,7 @@ public function testSearchMtime() { new \OC\Files\Node\Folder($this->rootFolder, $this->view, '/test/path') ]); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_GREATER_THAN, '{DAV:}getlastmodified', 10); + $query = $this->getBasicQuery(Operator::OPERATION_GREATER_THAN, '{DAV:}getlastmodified', 10); $result = $this->search->search($query); $this->assertCount(1, $result); @@ -251,7 +247,7 @@ public function testSearchIsCollection() { new \OC\Files\Node\Folder($this->rootFolder, $this->view, '/test/path') ]); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_IS_COLLECTION, 'yes'); + $query = $this->getBasicQuery(Operator::OPERATION_IS_COLLECTION, 'yes'); $result = $this->search->search($query); $this->assertCount(1, $result); @@ -260,7 +256,7 @@ public function testSearchIsCollection() { public function testSearchInvalidProp() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $this->tree->expects($this->any()) ->method('getNodeForPath') @@ -269,25 +265,25 @@ public function testSearchInvalidProp() { $this->searchFolder->expects($this->never()) ->method('search'); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_EQUAL, '{DAV:}getetag', 'foo'); + $query = $this->getBasicQuery(Operator::OPERATION_EQUAL, '{DAV:}getetag', 'foo'); $this->search->search($query); } - private function getBasicQuery($type, $property, $value = null) { - $scope = new \SearchDAV\Query\Scope('/', 'infinite'); + private function getBasicQuery($type, $property, $value = null): Query { + $scope = new Scope('/', 'infinite'); $scope->path = '/'; $from = [$scope]; $orderBy = []; $select = []; if (is_null($value)) { - $where = new \SearchDAV\Query\Operator( + $where = new Operator( $type, - [new \SearchDAV\Query\Literal($property)] + [new Literal($property)] ); } else { - $where = new \SearchDAV\Query\Operator( + $where = new Operator( $type, - [new SearchPropertyDefinition($property, true, true, true), new \SearchDAV\Query\Literal($value)] + [new SearchPropertyDefinition($property, true, true, true), new Literal($value)] ); } $limit = new Limit(); @@ -297,7 +293,7 @@ private function getBasicQuery($type, $property, $value = null) { public function testSearchNonFolder() { - $this->expectException(\InvalidArgumentException::class); + $this->expectException(InvalidArgumentException::class); $davNode = $this->createMock(File::class); @@ -305,7 +301,7 @@ public function testSearchNonFolder() { ->method('getNodeForPath') ->willReturn($davNode); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_EQUAL, '{DAV:}displayname', 'foo'); + $query = $this->getBasicQuery(Operator::OPERATION_EQUAL, '{DAV:}displayname', 'foo'); $this->search->search($query); } @@ -325,7 +321,7 @@ public function testSearchLimitOwnerBasic() { ]; }); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_EQUAL, FilesPlugin::OWNER_ID_PROPERTYNAME, $this->user->getUID()); + $query = $this->getBasicQuery(Operator::OPERATION_EQUAL, FilesPlugin::OWNER_ID_PROPERTYNAME, $this->user->getUID()); $this->search->search($query); $this->assertNotNull($receivedQuery); @@ -354,17 +350,17 @@ public function testSearchLimitOwnerNested() { ]; }); - $query = $this->getBasicQuery(\SearchDAV\Query\Operator::OPERATION_EQUAL, FilesPlugin::OWNER_ID_PROPERTYNAME, $this->user->getUID()); - $query->where = new \SearchDAV\Query\Operator( - \SearchDAV\Query\Operator::OPERATION_AND, + $query = $this->getBasicQuery(Operator::OPERATION_EQUAL, FilesPlugin::OWNER_ID_PROPERTYNAME, $this->user->getUID()); + $query->where = new Operator( + Operator::OPERATION_AND, [ - new \SearchDAV\Query\Operator( - \SearchDAV\Query\Operator::OPERATION_EQUAL, - [new SearchPropertyDefinition('{DAV:}getcontenttype', true, true, true), new \SearchDAV\Query\Literal('image/png')] + new Operator( + Operator::OPERATION_EQUAL, + [new SearchPropertyDefinition('{DAV:}getcontenttype', true, true, true), new Literal('image/png')] ), - new \SearchDAV\Query\Operator( - \SearchDAV\Query\Operator::OPERATION_EQUAL, - [new SearchPropertyDefinition(FilesPlugin::OWNER_ID_PROPERTYNAME, true, true, true), new \SearchDAV\Query\Literal($this->user->getUID())] + new Operator( + Operator::OPERATION_EQUAL, + [new SearchPropertyDefinition(FilesPlugin::OWNER_ID_PROPERTYNAME, true, true, true), new Literal($this->user->getUID())] ) ] ); diff --git a/apps/dav/tests/unit/Files/MultipartRequestParserTest.php b/apps/dav/tests/unit/Files/MultipartRequestParserTest.php index ec9e2d0a3832b..9050633ff3e32 100644 --- a/apps/dav/tests/unit/Files/MultipartRequestParserTest.php +++ b/apps/dav/tests/unit/Files/MultipartRequestParserTest.php @@ -22,11 +22,13 @@ namespace OCA\DAV\Tests\unit\DAV; +use Sabre\DAV\Exception\BadRequest; +use Sabre\HTTP\RequestInterface; use Test\TestCase; -use \OCA\DAV\BulkUpload\MultipartRequestParser; +use OCA\DAV\BulkUpload\MultipartRequestParser; class MultipartRequestParserTest extends TestCase { - private function getValidBodyObject() { + private function getValidBodyObject(): array { return [ [ "headers" => [ @@ -39,11 +41,11 @@ private function getValidBodyObject() { ]; } + /** + * @throws BadRequest + */ private function getMultipartParser(array $parts, array $headers = [], string $boundary = "boundary_azertyuiop"): MultipartRequestParser { - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); $headers = array_merge(['Content-Type' => 'multipart/related; boundary='.$boundary], $headers); $request->expects($this->any()) ->method('getHeader') @@ -79,12 +81,12 @@ private function getMultipartParser(array $parts, array $headers = [], string $b /** * Test validation of the request's body type + * + * @throws BadRequest */ public function testBodyTypeValidation() { $bodyStream = "I am not a stream, but pretend to be"; - $request = $this->getMockBuilder('Sabre\HTTP\RequestInterface') - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); $request->expects($this->any()) ->method('getBody') ->willReturn($bodyStream); @@ -100,6 +102,8 @@ public function testBodyTypeValidation() { * - valid content-length * - valid file content * - valid file path + * + * @throws BadRequest */ public function testValidRequest() { $multipartParser = $this->getMultipartParser( @@ -108,15 +112,17 @@ public function testValidRequest() { [$headers, $content] = $multipartParser->parseNextPart(); - $this->assertSame((int)$headers["content-length"], 7, "Content-Length header should be the same as provided."); - $this->assertSame($headers["x-file-md5"], "4f2377b4d911f7ec46325fe603c3af03", "X-File-MD5 header should be the same as provided."); - $this->assertSame($headers["x-file-path"], "/coucou.txt", "X-File-Path header should be the same as provided."); + $this->assertSame(7, (int)$headers["content-length"], "Content-Length header should be the same as provided."); + $this->assertSame("4f2377b4d911f7ec46325fe603c3af03", $headers["x-file-md5"], "X-File-MD5 header should be the same as provided."); + $this->assertSame("/coucou.txt", $headers["x-file-path"], "X-File-Path header should be the same as provided."); - $this->assertSame($content, "Coucou\n", "Content should be the same"); + $this->assertSame("Coucou\n", $content, "Content should be the same"); } /** * Test with invalid md5 hash. + * + * @throws BadRequest */ public function testInvalidMd5Hash() { $bodyObject = $this->getValidBodyObject(); @@ -131,6 +137,8 @@ public function testInvalidMd5Hash() { /** * Test with a null md5 hash. + * + * @throws BadRequest */ public function testNullMd5Hash() { $bodyObject = $this->getValidBodyObject(); @@ -145,6 +153,8 @@ public function testNullMd5Hash() { /** * Test with a null Content-Length. + * + * @throws BadRequest */ public function testNullContentLength() { $bodyObject = $this->getValidBodyObject(); @@ -159,6 +169,8 @@ public function testNullContentLength() { /** * Test with a lower Content-Length. + * + * @throws BadRequest */ public function testLowerContentLength() { $bodyObject = $this->getValidBodyObject(); @@ -173,6 +185,8 @@ public function testLowerContentLength() { /** * Test with a higher Content-Length. + * + * @throws BadRequest */ public function testHigherContentLength() { $bodyObject = $this->getValidBodyObject(); @@ -187,6 +201,8 @@ public function testHigherContentLength() { /** * Test with wrong boundary in body. + * + * @throws BadRequest */ public function testWrongBoundary() { $bodyObject = $this->getValidBodyObject(); @@ -201,6 +217,8 @@ public function testWrongBoundary() { /** * Test with no boundary in request headers. + * + * @throws BadRequest */ public function testNoBoundaryInHeader() { $bodyObject = $this->getValidBodyObject(); @@ -213,6 +231,8 @@ public function testNoBoundaryInHeader() { /** * Test with no boundary in the request's headers. + * + * @throws BadRequest */ public function testNoBoundaryInBody() { $bodyObject = $this->getValidBodyObject(); @@ -228,6 +248,8 @@ public function testNoBoundaryInBody() { /** * Test with a boundary with quotes in the request's headers. + * + * @throws BadRequest */ public function testBoundaryWithQuotes() { $bodyObject = $this->getValidBodyObject(); @@ -244,6 +266,8 @@ public function testBoundaryWithQuotes() { /** * Test with a wrong Content-Type in the request's headers. + * + * @throws BadRequest */ public function testWrongContentType() { $bodyObject = $this->getValidBodyObject(); @@ -256,6 +280,8 @@ public function testWrongContentType() { /** * Test with a wrong key after the content type in the request's headers. + * + * @throws BadRequest */ public function testWrongKeyInContentType() { $bodyObject = $this->getValidBodyObject(); @@ -268,6 +294,8 @@ public function testWrongKeyInContentType() { /** * Test with a null Content-Type in the request's headers. + * + * @throws BadRequest */ public function testNullContentType() { $bodyObject = $this->getValidBodyObject(); diff --git a/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php b/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php index a24125b68045f..989a8b2b16b19 100644 --- a/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php +++ b/apps/dav/tests/unit/Files/Sharing/FilesDropPluginTest.php @@ -27,6 +27,7 @@ use OC\Files\View; use OCA\DAV\Files\Sharing\FilesDropPlugin; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Server; use Sabre\HTTP\RequestInterface; @@ -35,19 +36,19 @@ class FilesDropPluginTest extends TestCase { - /** @var View|\PHPUnit\Framework\MockObject\MockObject */ + /** @var View|MockObject */ private $view; - /** @var Server|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Server|MockObject */ private $server; /** @var FilesDropPlugin */ private $plugin; - /** @var RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface|MockObject */ private $request; - /** @var ResponseInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResponseInterface|MockObject */ private $response; protected function setUp(): void { @@ -64,6 +65,9 @@ protected function setUp(): void { ->method($this->anything()); } + /** + * @throws MethodNotAllowed + */ public function testInitialize() { $this->server->expects($this->once()) ->method('on') @@ -76,6 +80,9 @@ public function testInitialize() { $this->plugin->initialize($this->server); } + /** + * @throws MethodNotAllowed + */ public function testNotEnabled() { $this->view->expects($this->never()) ->method($this->anything()); @@ -86,6 +93,9 @@ public function testNotEnabled() { $this->plugin->beforeMethod($this->request, $this->response); } + /** + * @throws MethodNotAllowed + */ public function testValid() { $this->plugin->enable(); $this->plugin->setView($this->view); @@ -110,6 +120,9 @@ public function testValid() { $this->plugin->beforeMethod($this->request, $this->response); } + /** + * @throws MethodNotAllowed + */ public function testFileAlreadyExistsValid() { $this->plugin->enable(); $this->plugin->setView($this->view); @@ -151,6 +164,9 @@ public function testNoMKCOL() { $this->plugin->beforeMethod($this->request, $this->response); } + /** + * @throws MethodNotAllowed + */ public function testNoSubdirPut() { $this->plugin->enable(); $this->plugin->setView($this->view); diff --git a/apps/dav/tests/unit/Listener/CalendarContactInteractionListenerTest.php b/apps/dav/tests/unit/Listener/CalendarContactInteractionListenerTest.php index 29058653a479e..af1baedfd9bec 100644 --- a/apps/dav/tests/unit/Listener/CalendarContactInteractionListenerTest.php +++ b/apps/dav/tests/unit/Listener/CalendarContactInteractionListenerTest.php @@ -47,9 +47,6 @@ class CalendarContactInteractionListenerTest extends TestCase { /** @var IUserSession|MockObject */ private $userSession; - /** @var Principal|MockObject */ - private $principalConnector; - /** @var LoggerInterface|MockObject */ private $logger; @@ -64,14 +61,14 @@ protected function setUp(): void { $this->eventDispatcher = $this->createMock(IEventDispatcher::class); $this->userSession = $this->createMock(IUserSession::class); - $this->principalConnector = $this->createMock(Principal::class); + $principalConnector = $this->createMock(Principal::class); $this->mailer = $this->createMock(IMailer::class); $this->logger = $this->createMock(LoggerInterface::class); $this->listener = new CalendarContactInteractionListener( $this->eventDispatcher, $this->userSession, - $this->principalConnector, + $principalConnector, $this->mailer, $this->logger ); diff --git a/apps/dav/tests/unit/Listener/UserChangeListenerTest.php b/apps/dav/tests/unit/Listener/UserChangeListenerTest.php index 6f55980867839..c3d8de79b27ed 100644 --- a/apps/dav/tests/unit/Listener/UserChangeListenerTest.php +++ b/apps/dav/tests/unit/Listener/UserChangeListenerTest.php @@ -41,18 +41,12 @@ class UserChangeListenerTest extends TestCase { - /** @var IUserManager|MockObject */ - private $userManager; - /** @var CalDavBackend|MockObject */ private $calDavBackend; /** @var CardDavBackend|MockObject */ private $cardDavBackend; - /** @var LoggerInterface|MockObject */ - private $logger; - /** @var Defaults|MockObject */ private $defaults; @@ -65,20 +59,20 @@ class UserChangeListenerTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->userManager = $this->createMock(IUserManager::class); + $userManager = $this->createMock(IUserManager::class); $this->calDavBackend = $this->createMock(CalDavBackend::class); $this->cardDavBackend = $this->createMock(CardDavBackend::class); $this->defaults = $this->createMock(Defaults::class); $this->syncService = $this->createMock(SyncService::class); - $this->logger = $this->createMock(LoggerInterface::class); + $logger = $this->createMock(LoggerInterface::class); $this->listener = new UserChangeListener( - $this->userManager, + $userManager, $this->calDavBackend, $this->cardDavBackend, $this->defaults, $this->syncService, - $this->logger + $logger ); } diff --git a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php index e8a9a617fe233..053d52a4ae7a1 100644 --- a/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php +++ b/apps/dav/tests/unit/Migration/CalDAVRemoveEmptyValueTest.php @@ -25,10 +25,15 @@ */ namespace OCA\DAV\Tests\Unit\DAV\Migration; +use Exception; +use OC; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\Migration\CalDAVRemoveEmptyValue; use OCP\IDBConnection; use OCP\Migration\IOutput; +use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\NotFoundExceptionInterface; use Psr\Log\LoggerInterface; use Sabre\VObject\InvalidDataException; use Test\TestCase; @@ -41,13 +46,13 @@ */ class CalDAVRemoveEmptyValueTest extends TestCase { - /** @var LoggerInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var LoggerInterface|MockObject */ private $logger; - /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend|MockObject */ private $backend; - /** @var IOutput|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IOutput|MockObject */ private $output; /** @var string */ @@ -100,15 +105,20 @@ protected function setUp(): void { $this->output = $this->createMock(IOutput::class); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ public function testRunAllValid() { - /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ + /** @var CalDAVRemoveEmptyValue|MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->get(IDBConnection::class), + OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) - ->setMethods(['getInvalidObjects']) + ->onlyMethods(['getInvalidObjects']) ->getMock(); $step->expects($this->once()) @@ -124,15 +134,20 @@ public function testRunAllValid() { $step->run($this->output); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ public function testRunInvalid() { - /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ + /** @var CalDAVRemoveEmptyValue|MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->get(IDBConnection::class), + OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) - ->setMethods(['getInvalidObjects']) + ->onlyMethods(['getInvalidObjects']) ->getMock(); $step->expects($this->once()) @@ -167,15 +182,20 @@ public function testRunInvalid() { $step->run($this->output); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ public function testRunValid() { - /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ + /** @var CalDAVRemoveEmptyValue|MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->get(IDBConnection::class), + OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) - ->setMethods(['getInvalidObjects']) + ->onlyMethods(['getInvalidObjects']) ->getMock(); $step->expects($this->once()) @@ -209,15 +229,20 @@ public function testRunValid() { $step->run($this->output); } + /** + * @throws ContainerExceptionInterface + * @throws NotFoundExceptionInterface + * @throws Exception + */ public function testRunStillInvalid() { - /** @var CalDAVRemoveEmptyValue|\PHPUnit\Framework\MockObject\MockObject $step */ + /** @var CalDAVRemoveEmptyValue|MockObject $step */ $step = $this->getMockBuilder(CalDAVRemoveEmptyValue::class) ->setConstructorArgs([ - \OC::$server->get(IDBConnection::class), + OC::$server->get(IDBConnection::class), $this->backend, $this->logger ]) - ->setMethods(['getInvalidObjects']) + ->onlyMethods(['getInvalidObjects']) ->getMock(); $step->expects($this->once()) diff --git a/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php b/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php index 427bf6da14541..102675fe48129 100644 --- a/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php +++ b/apps/dav/tests/unit/Migration/RefreshWebcalJobRegistrarTest.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\Tests\unit\DAV\Migration; +use Exception; use OCA\DAV\BackgroundJob\RefreshWebcalJob; use OCA\DAV\Migration\RefreshWebcalJobRegistrar; use OCP\BackgroundJob\IJobList; @@ -33,14 +34,16 @@ use OCP\DB\QueryBuilder\IQueryBuilder; use OCP\IDBConnection; use OCP\Migration\IOutput; +use PDO; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RefreshWebcalJobRegistrarTest extends TestCase { - /** @var IDBConnection | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IDBConnection | MockObject */ private $db; - /** @var IJobList | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IJobList | MockObject */ private $jobList; /** @var RefreshWebcalJobRegistrar */ @@ -56,9 +59,12 @@ protected function setUp(): void { } public function testGetName() { - $this->assertEquals($this->migration->getName(), 'Registering background jobs to update cache for webcal calendars'); + $this->assertEquals('Registering background jobs to update cache for webcal calendars', $this->migration->getName()); } + /** + * @throws Exception + */ public function testRun() { $output = $this->createMock(IOutput::class); @@ -69,77 +75,79 @@ public function testRun() { ->method('getQueryBuilder') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(0)) + $queryBuilder->expects($this->once()) ->method('select') ->with(['principaluri', 'uri']) ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(1)) + $queryBuilder->expects($this->once()) ->method('from') ->with('calendarsubscriptions') ->willReturn($queryBuilder); - $queryBuilder->expects($this->at(2)) - ->method('execute') + $queryBuilder->expects($this->once()) + ->method('executeQuery') ->willReturn($statement); - $statement->expects($this->at(0)) + $statement->expects($this->exactly(4)) ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->willReturn([ - 'principaluri' => 'foo1', - 'uri' => 'bar1', - ]); - $statement->expects($this->at(1)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->willReturn([ - 'principaluri' => 'foo2', - 'uri' => 'bar2', - ]); - $statement->expects($this->at(2)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->willReturn([ - 'principaluri' => 'foo3', - 'uri' => 'bar3', - ]); - $statement->expects($this->at(0)) - ->method('fetch') - ->with(\PDO::FETCH_ASSOC) - ->willReturn(null); - - $this->jobList->expects($this->at(0)) - ->method('has') - ->with(RefreshWebcalJob::class, [ - 'principaluri' => 'foo1', - 'uri' => 'bar1', - ]) - ->willReturn(false); - $this->jobList->expects($this->at(1)) - ->method('add') - ->with(RefreshWebcalJob::class, [ - 'principaluri' => 'foo1', - 'uri' => 'bar1', - ]); - $this->jobList->expects($this->at(2)) - ->method('has') - ->with(RefreshWebcalJob::class, [ - 'principaluri' => 'foo2', - 'uri' => 'bar2', - ]) - ->willReturn(true); - $this->jobList->expects($this->at(3)) + ->with(PDO::FETCH_ASSOC) + ->willReturnOnConsecutiveCalls( + [ + 'principaluri' => 'foo1', + 'uri' => 'bar1', + ], + [ + 'principaluri' => 'foo2', + 'uri' => 'bar2', + ], + [ + 'principaluri' => 'foo3', + 'uri' => 'bar3', + ], + null + ); + + $this->jobList->expects($this->exactly(3)) ->method('has') - ->with(RefreshWebcalJob::class, [ - 'principaluri' => 'foo3', - 'uri' => 'bar3', - ]) - ->willReturn(false); - $this->jobList->expects($this->at(4)) + ->withConsecutive( + [ + RefreshWebcalJob::class, [ + 'principaluri' => 'foo1', + 'uri' => 'bar1', + ] + ], + [ + RefreshWebcalJob::class, + [ + 'principaluri' => 'foo2', + 'uri' => 'bar2', + ] + ], + [ + RefreshWebcalJob::class, + [ + 'principaluri' => 'foo3', + 'uri' => 'bar3', + ] + ] + ) + ->willReturnOnConsecutiveCalls(false, true, false); + $this->jobList->expects($this->exactly(2)) ->method('add') - ->with(RefreshWebcalJob::class, [ - 'principaluri' => 'foo3', - 'uri' => 'bar3', - ]); + ->withConsecutive( + [ + RefreshWebcalJob::class, [ + 'principaluri' => 'foo1', + 'uri' => 'bar1', + ] + ], + [ + RefreshWebcalJob::class, + [ + 'principaluri' => 'foo3', + 'uri' => 'bar3', + ] + ] + ); $output->expects($this->once()) ->method('info') diff --git a/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php b/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php index bb5210f18fbe8..e955e8b90868d 100644 --- a/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php +++ b/apps/dav/tests/unit/Migration/RegenerateBirthdayCalendarsTest.php @@ -31,14 +31,15 @@ use OCP\BackgroundJob\IJobList; use OCP\IConfig; use OCP\Migration\IOutput; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RegenerateBirthdayCalendarsTest extends TestCase { - /** @var IJobList | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IJobList | MockObject */ private $jobList; - /** @var IConfig | \PHPUnit\Framework\MockObject\MockObject */ + /** @var IConfig | MockObject */ private $config; /** @var RegenerateBirthdayCalendars */ diff --git a/apps/dav/tests/unit/Migration/RemoveDeletedUsersCalendarSubscriptionsTest.php b/apps/dav/tests/unit/Migration/RemoveDeletedUsersCalendarSubscriptionsTest.php index c0d6518d2051e..72d64da480bbd 100644 --- a/apps/dav/tests/unit/Migration/RemoveDeletedUsersCalendarSubscriptionsTest.php +++ b/apps/dav/tests/unit/Migration/RemoveDeletedUsersCalendarSubscriptionsTest.php @@ -25,6 +25,7 @@ */ namespace OCA\DAV\Tests\unit\DAV\Migration; +use Exception; use OCA\DAV\Migration\RemoveDeletedUsersCalendarSubscriptions; use OCP\DB\IResult; use OCP\DB\QueryBuilder\IExpressionBuilder; @@ -80,7 +81,7 @@ public function testGetName(): void { * @param array $subscriptions * @param array $userExists * @param int $deletions - * @throws \Exception + * @throws Exception */ public function testRun(array $subscriptions, array $userExists, int $deletions): void { $qb = $this->createMock(IQueryBuilder::class); @@ -111,7 +112,7 @@ public function testRun(array $subscriptions, array $userExists, int $deletions) $qb->method('execute') ->willReturn($result); - $result->expects($this->at(0)) + $result->expects($this->once()) ->method('fetchOne') ->willReturn(count($subscriptions)); diff --git a/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningNodeTest.php b/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningNodeTest.php index 2f4728f1966a1..93955d1aeeb60 100644 --- a/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningNodeTest.php +++ b/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningNodeTest.php @@ -24,14 +24,17 @@ */ namespace OCA\DAV\Tests\unit\Provisioning\Apple; +use DateTime; use OCA\DAV\Provisioning\Apple\AppleProvisioningNode; use OCP\AppFramework\Utility\ITimeFactory; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\PropPatch; use Test\TestCase; class AppleProvisioningNodeTest extends TestCase { - /** @var ITimeFactory|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ITimeFactory|MockObject */ private $timeFactory; /** @var AppleProvisioningNode */ @@ -50,7 +53,7 @@ public function testGetName() { public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->expectExceptionMessage('Renaming apple-provisioning.mobileconfig is forbidden'); $this->node->setName('foo'); @@ -62,16 +65,16 @@ public function testGetLastModified() { public function testDelete() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->expectExceptionMessage('apple-provisioning.mobileconfig may not be deleted'); $this->node->delete(); } public function testGetProperties() { - $this->timeFactory->expects($this->at(0)) + $this->timeFactory->expects($this->once()) ->method('getDateTime') - ->willReturn(new \DateTime('2000-01-01')); + ->willReturn(new DateTime('2000-01-01')); $this->assertEquals([ '{DAV:}getcontentlength' => 42, @@ -81,7 +84,7 @@ public function testGetProperties() { public function testGetPropPatch() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->expectExceptionMessage('apple-provisioning.mobileconfig\'s properties may not be altered.'); $propPatch = $this->createMock(PropPatch::class); diff --git a/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php b/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php index 5bff59cbc7c8c..5631cb0b462f6 100644 --- a/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php +++ b/apps/dav/tests/unit/Provisioning/Apple/AppleProvisioningPluginTest.php @@ -33,32 +33,36 @@ use OCP\IURLGenerator; use OCP\IUser; use OCP\IUserSession; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Server; +use Sabre\HTTP\RequestInterface; +use Sabre\HTTP\ResponseInterface; use Test\TestCase; class AppleProvisioningPluginTest extends TestCase { - /** @var \Sabre\DAV\Server|\PHPUnit\Framework\MockObject\MockObject */ + /** @var Server|MockObject */ protected $server; - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IUserSession|MockObject */ protected $userSession; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ protected $urlGenerator; - /** @var ThemingDefaults|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ThemingDefaults|MockObject */ protected $themingDefaults; - /** @var IRequest|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IRequest|MockObject */ protected $request; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N|MockObject */ protected $l10n; - /** @var \Sabre\HTTP\RequestInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface|MockObject */ protected $sabreRequest; - /** @var \Sabre\HTTP\ResponseInterface|\PHPUnit\Framework\MockObject\MockObject */ + /** @var ResponseInterface|MockObject */ protected $sabreResponse; /** @var AppleProvisioningPlugin */ @@ -67,7 +71,7 @@ class AppleProvisioningPluginTest extends TestCase { protected function setUp(): void { parent::setUp(); - $this->server = $this->createMock(\Sabre\DAV\Server::class); + $this->server = $this->createMock(Server::class); $this->userSession = $this->createMock(IUserSession::class); $this->urlGenerator = $this->createMock(IURLGenerator::class); $this->themingDefaults = $this->createMock(ThemingDefaults::class); @@ -84,19 +88,19 @@ function () { } ); - $this->sabreRequest = $this->createMock(\Sabre\HTTP\RequestInterface::class); - $this->sabreResponse = $this->createMock(\Sabre\HTTP\ResponseInterface::class); + $this->sabreRequest = $this->createMock(RequestInterface::class); + $this->sabreResponse = $this->createMock(ResponseInterface::class); } public function testInitialize() { - $server = $this->createMock(\Sabre\DAV\Server::class); + $server = $this->createMock(Server::class); $plugin = new AppleProvisioningPlugin($this->userSession, $this->urlGenerator, $this->themingDefaults, $this->request, $this->l10n, function () { }); - $server->expects($this->at(0)) + $server->expects($this->once()) ->method('on') ->with('method:GET', [$plugin, 'httpGet'], 90); @@ -104,36 +108,36 @@ function () { } public function testHttpGetOnHttp() { - $this->sabreRequest->expects($this->at(0)) + $this->sabreRequest->expects($this->once()) ->method('getPath') ->with() ->willReturn('provisioning/apple-provisioning.mobileconfig'); $user = $this->createMock(IUser::class); - $this->userSession->expects($this->at(0)) + $this->userSession->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->request->expects($this->at(0)) + $this->request->expects($this->once()) ->method('getServerProtocol') ->wilLReturn('http'); - $this->themingDefaults->expects($this->at(0)) + $this->themingDefaults->expects($this->once()) ->method('getName') ->willReturn('InstanceName'); - $this->l10n->expects($this->at(0)) + $this->l10n->expects($this->once()) ->method('t') ->with('Your %s needs to be configured to use HTTPS in order to use CalDAV and CardDAV with iOS/macOS.', ['InstanceName']) ->willReturn('LocalizedErrorMessage'); - $this->sabreResponse->expects($this->at(0)) + $this->sabreResponse->expects($this->once()) ->method('setStatus') ->with(200); - $this->sabreResponse->expects($this->at(1)) + $this->sabreResponse->expects($this->once()) ->method('setHeader') ->with('Content-Type', 'text/plain; charset=utf-8'); - $this->sabreResponse->expects($this->at(2)) + $this->sabreResponse->expects($this->once()) ->method('setBody') ->with('LocalizedErrorMessage'); @@ -143,21 +147,21 @@ public function testHttpGetOnHttp() { } public function testHttpGetOnHttps() { - $this->sabreRequest->expects($this->at(0)) + $this->sabreRequest->expects($this->once()) ->method('getPath') ->with() ->willReturn('provisioning/apple-provisioning.mobileconfig'); $user = $this->createMock(IUser::class); - $user->expects($this->at(0)) + $user->expects($this->once()) ->method('getUID') ->willReturn('userName'); - $this->userSession->expects($this->at(0)) + $this->userSession->expects($this->once()) ->method('getUser') ->willReturn($user); - $this->request->expects($this->at(0)) + $this->request->expects($this->once()) ->method('getServerProtocol') ->wilLReturn('https'); @@ -165,30 +169,25 @@ public function testHttpGetOnHttps() { ->method('getBaseUrl') ->willReturn('https://nextcloud.tld/nextcloud'); - $this->themingDefaults->expects($this->at(0)) + $this->themingDefaults->expects($this->once()) ->method('getName') ->willReturn('InstanceName'); - $this->l10n->expects($this->at(0)) + $this->l10n->expects($this->exactly(2)) ->method('t') - ->with('Configures a CalDAV account') - ->willReturn('LocalizedConfiguresCalDAV'); + ->withConsecutive(['Configures a CalDAV account'], ['Configures a CardDAV account']) + ->willReturnOnConsecutiveCalls('LocalizedConfiguresCalDAV', 'LocalizedConfiguresCardDAV'); - $this->l10n->expects($this->at(1)) - ->method('t') - ->with('Configures a CardDAV account') - ->willReturn('LocalizedConfiguresCardDAV'); - - $this->sabreResponse->expects($this->at(0)) + $this->sabreResponse->expects($this->once()) ->method('setStatus') ->with(200); - $this->sabreResponse->expects($this->at(1)) - ->method('setHeader') - ->with('Content-Disposition', 'attachment; filename="userName-apple-provisioning.mobileconfig"'); - $this->sabreResponse->expects($this->at(2)) + $this->sabreResponse->expects($this->exactly(2)) ->method('setHeader') - ->with('Content-Type', 'application/xml; charset=utf-8'); - $this->sabreResponse->expects($this->at(3)) + ->withConsecutive( + ['Content-Disposition', 'attachment; filename="userName-apple-provisioning.mobileconfig"'], + ['Content-Type', 'application/xml; charset=utf-8'] + ); + $this->sabreResponse->expects($this->once()) ->method('setBody') ->with(<< diff --git a/apps/dav/tests/unit/Search/ContactsSearchProviderTest.php b/apps/dav/tests/unit/Search/ContactsSearchProviderTest.php index b91612ae5becc..79b2810efbac9 100644 --- a/apps/dav/tests/unit/Search/ContactsSearchProviderTest.php +++ b/apps/dav/tests/unit/Search/ContactsSearchProviderTest.php @@ -35,21 +35,22 @@ use OCP\Search\ISearchQuery; use OCP\Search\SearchResult; use OCP\Search\SearchResultEntry; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\VObject\Reader; use Test\TestCase; class ContactsSearchProviderTest extends TestCase { - /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IAppManager|MockObject */ private $appManager; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N|MockObject */ private $l10n; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ private $urlGenerator; - /** @var CardDavBackend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CardDavBackend|MockObject */ private $backend; /** @var ContactsSearchProvider */ @@ -192,7 +193,7 @@ public function testSearch(): void { $this->urlGenerator, $this->backend, ]) - ->setMethods([ + ->onlyMethods([ 'getDavUrlForContact', 'getDeepLinkToContactsApp', 'generateSubline', diff --git a/apps/dav/tests/unit/Search/EventsSearchProviderTest.php b/apps/dav/tests/unit/Search/EventsSearchProviderTest.php index a2f4e66fbdb86..049672da1fd79 100644 --- a/apps/dav/tests/unit/Search/EventsSearchProviderTest.php +++ b/apps/dav/tests/unit/Search/EventsSearchProviderTest.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\Tests\unit\Search; +use DateTime; use OCA\DAV\CalDAV\CalDavBackend; use OCA\DAV\Search\EventsSearchProvider; use OCP\App\IAppManager; @@ -35,21 +36,22 @@ use OCP\Search\ISearchQuery; use OCP\Search\SearchResult; use OCP\Search\SearchResultEntry; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\VObject\Reader; use Test\TestCase; class EventsSearchProviderTest extends TestCase { - /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IAppManager|MockObject */ private $appManager; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N|MockObject */ private $l10n; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ private $urlGenerator; - /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend|MockObject */ private $backend; /** @var EventsSearchProvider */ @@ -361,7 +363,7 @@ public function testSearch(): void { $this->urlGenerator, $this->backend, ]) - ->setMethods([ + ->onlyMethods([ 'getDeepLinkToCalendarApp', 'generateSubline', ]) @@ -420,15 +422,15 @@ public function testSearch(): void { } public function testGetDeepLinkToCalendarApp(): void { - $this->urlGenerator->expects($this->at(0)) + $this->urlGenerator->expects($this->once()) ->method('linkTo') ->with('', 'remote.php') ->willReturn('link-to-remote.php'); - $this->urlGenerator->expects($this->at(1)) + $this->urlGenerator->expects($this->once()) ->method('linkToRoute') ->with('calendar.view.index') ->willReturn('link-to-route-calendar/'); - $this->urlGenerator->expects($this->at(2)) + $this->urlGenerator->expects($this->once()) ->method('getAbsoluteURL') ->with('link-to-route-calendar/edit/bGluay10by1yZW1vdGUucGhwL2Rhdi9jYWxlbmRhcnMvam9obi5kb2UvZm9vL2Jhci5pY3M=') ->willReturn('absolute-url-to-route'); @@ -449,7 +451,7 @@ public function testGenerateSubline(string $ics, string $expectedSubline): void $eventComponent = $vCalendar->VEVENT; $this->l10n->method('l') - ->willReturnCallback(static function (string $type, \DateTime $date, $_):string { + ->willReturnCallback(static function (string $type, DateTime $date):string { if ($type === 'time') { return $date->format('H:i'); } diff --git a/apps/dav/tests/unit/Search/TasksSearchProviderTest.php b/apps/dav/tests/unit/Search/TasksSearchProviderTest.php index 13dc02bb2783f..40044817520c7 100644 --- a/apps/dav/tests/unit/Search/TasksSearchProviderTest.php +++ b/apps/dav/tests/unit/Search/TasksSearchProviderTest.php @@ -35,21 +35,22 @@ use OCP\Search\ISearchQuery; use OCP\Search\SearchResult; use OCP\Search\SearchResultEntry; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\VObject\Reader; use Test\TestCase; class TasksSearchProviderTest extends TestCase { - /** @var IAppManager|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IAppManager|MockObject */ private $appManager; - /** @var IL10N|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IL10N|MockObject */ private $l10n; - /** @var IURLGenerator|\PHPUnit\Framework\MockObject\MockObject */ + /** @var IURLGenerator|MockObject */ private $urlGenerator; - /** @var CalDavBackend|\PHPUnit\Framework\MockObject\MockObject */ + /** @var CalDavBackend|MockObject */ private $backend; /** @var TasksSearchProvider */ @@ -245,7 +246,7 @@ public function testSearch(): void { $this->urlGenerator, $this->backend, ]) - ->setMethods([ + ->onlyMethods([ 'getDeepLinkToTasksApp', 'generateSubline', ]) diff --git a/apps/dav/tests/unit/ServerTest.php b/apps/dav/tests/unit/ServerTest.php index 8cdd52f574575..b7780c9040001 100644 --- a/apps/dav/tests/unit/ServerTest.php +++ b/apps/dav/tests/unit/ServerTest.php @@ -28,6 +28,8 @@ use OCA\DAV\Server; use OCP\IRequest; +use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; /** * Class ServerTest @@ -36,13 +38,13 @@ * * @package OCA\DAV\Tests\Unit */ -class ServerTest extends \Test\TestCase { +class ServerTest extends TestCase { /** * @dataProvider providesUris */ - public function test($uri, array $plugins) { - /** @var IRequest | \PHPUnit\Framework\MockObject\MockObject $r */ + public function test(string $uri, array $plugins) { + /** @var IRequest | MockObject $r */ $r = $this->createMock(IRequest::class); $r->expects($this->any())->method('getRequestUri')->willReturn($uri); $s = new Server($r, '/'); @@ -51,7 +53,7 @@ public function test($uri, array $plugins) { $this->assertNotNull($s->server->getPlugin($plugin)); } } - public function providesUris() { + public function providesUris(): array { return [ 'principals' => ['principals/users/admin', ['caldav', 'oc-resource-sharing', 'carddav']], 'calendars' => ['calendars/admin', ['caldav', 'oc-resource-sharing']], diff --git a/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php b/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php index e39cb0a04d3dd..75432e293fcf0 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagMappingNodeTest.php @@ -25,46 +25,48 @@ */ namespace OCA\DAV\Tests\unit\SystemTag; +use Exception; use OC\SystemTag\SystemTag; +use OCA\DAV\SystemTag\SystemTagMappingNode; use OCP\IUser; use OCP\SystemTag\ISystemTag; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; use OCP\SystemTag\TagNotFoundException; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class SystemTagMappingNodeTest extends \Test\TestCase { +class SystemTagMappingNodeTest extends TestCase { /** - * @var \OCP\SystemTag\ISystemTagManager + * @var ISystemTagManager */ private $tagManager; /** - * @var \OCP\SystemTag\ISystemTagObjectMapper + * @var ISystemTagObjectMapper */ private $tagMapper; /** - * @var \OCP\IUser + * @var IUser */ private $user; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->getMockBuilder(ISystemTagManager::class) - ->getMock(); - $this->tagMapper = $this->getMockBuilder(ISystemTagObjectMapper::class) - ->getMock(); - $this->user = $this->getMockBuilder(IUser::class) - ->getMock(); + $this->tagManager = $this->createMock(ISystemTagManager::class); + $this->tagMapper = $this->createMock(ISystemTagObjectMapper::class); + $this->user = $this->createMock(IUser::class); } - public function getMappingNode($tag = null) { + public function getMappingNode($tag = null): SystemTagMappingNode { if ($tag === null) { $tag = new SystemTag(1, 'Test', true, true); } - return new \OCA\DAV\SystemTag\SystemTagMappingNode( + return new SystemTagMappingNode( $tag, 123, 'files', @@ -83,6 +85,10 @@ public function testGetters() { $this->assertEquals('files', $node->getObjectType()); } + /** + * @throws NotFound + * @throws Forbidden + */ public function testDeleteTag() { $node = $this->getMappingNode(); $this->tagManager->expects($this->once()) @@ -102,17 +108,17 @@ public function testDeleteTag() { $node->delete(); } - public function tagNodeDeleteProviderPermissionException() { + public function tagNodeDeleteProviderPermissionException(): array { return [ [ // cannot unassign invisible tag new SystemTag(1, 'Original', false, true), - 'Sabre\DAV\Exception\NotFound', + NotFound::class, ], [ // cannot unassign non-assignable tag new SystemTag(1, 'Original', true, false), - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], ]; } @@ -120,7 +126,7 @@ public function tagNodeDeleteProviderPermissionException() { /** * @dataProvider tagNodeDeleteProviderPermissionException */ - public function testDeleteTagExpectedException(ISystemTag $tag, $expectedException) { + public function testDeleteTagExpectedException(ISystemTag $tag, string $expectedException) { $this->tagManager->expects($this->any()) ->method('canUserSeeTag') ->with($tag) @@ -137,16 +143,19 @@ public function testDeleteTagExpectedException(ISystemTag $tag, $expectedExcepti $thrown = null; try { $this->getMappingNode($tag)->delete(); - } catch (\Exception $e) { + } catch (Exception $e) { $thrown = $e; } $this->assertInstanceOf($expectedException, $thrown); } - + + /** + * @throws Forbidden + */ public function testDeleteTagNotFound() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); // assuming the tag existed at the time the node was created, // but got deleted concurrently in the database diff --git a/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php b/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php index 409132919a55e..c71f8f17cc985 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagNodeTest.php @@ -25,40 +25,45 @@ */ namespace OCA\DAV\Tests\unit\SystemTag; +use Exception; use OC\SystemTag\SystemTag; +use OCA\DAV\SystemTag\SystemTagNode; use OCP\IUser; use OCP\SystemTag\ISystemTag; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\TagAlreadyExistsException; use OCP\SystemTag\TagNotFoundException; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\Conflict; use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class SystemTagNodeTest extends \Test\TestCase { +class SystemTagNodeTest extends TestCase { /** - * @var \OCP\SystemTag\ISystemTagManager|\PHPUnit\Framework\MockObject\MockObject + * @var ISystemTagManager|MockObject */ private $tagManager; /** - * @var \OCP\IUser + * @var IUser */ private $user; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->getMockBuilder(ISystemTagManager::class) - ->getMock(); - $this->user = $this->getMockBuilder(IUser::class) - ->getMock(); + $this->tagManager = $this->createMock(ISystemTagManager::class); + $this->user = $this->createMock(IUser::class); } - protected function getTagNode($isAdmin = true, $tag = null) { + protected function getTagNode($isAdmin = true, $tag = null): SystemTagNode { if ($tag === null) { $tag = new SystemTag(1, 'Test', true, true); } - return new \OCA\DAV\SystemTag\SystemTagNode( + return new SystemTagNode( $tag, $this->user, $isAdmin, @@ -66,14 +71,14 @@ protected function getTagNode($isAdmin = true, $tag = null) { ); } - public function adminFlagProvider() { + public function adminFlagProvider(): array { return [[true], [false]]; } /** * @dataProvider adminFlagProvider */ - public function testGetters($isAdmin) { + public function testGetters(bool $isAdmin) { $tag = new SystemTag('1', 'Test', true, true); $node = $this->getTagNode($isAdmin, $tag); $this->assertEquals('1', $node->getName()); @@ -82,12 +87,12 @@ public function testGetters($isAdmin) { public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->getTagNode()->setName('2'); } - public function tagNodeProvider() { + public function tagNodeProvider(): array { return [ // admin [ @@ -112,8 +117,11 @@ public function tagNodeProvider() { /** * @dataProvider tagNodeProvider + * @throws Forbidden + * @throws NotFound + * @throws Conflict */ - public function testUpdateTag($isAdmin, ISystemTag $originalTag, $changedArgs) { + public function testUpdateTag(bool $isAdmin, ISystemTag $originalTag, array $changedArgs) { $this->tagManager->expects($this->once()) ->method('canUserSeeTag') ->with($originalTag) @@ -129,43 +137,43 @@ public function testUpdateTag($isAdmin, ISystemTag $originalTag, $changedArgs) { ->update($changedArgs[0], $changedArgs[1], $changedArgs[2]); } - public function tagNodeProviderPermissionException() { + public function tagNodeProviderPermissionException(): array { return [ [ // changing permissions not allowed new SystemTag(1, 'Original', true, true), ['Original', false, true], - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], [ // changing permissions not allowed new SystemTag(1, 'Original', true, true), ['Original', true, false], - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], [ // changing permissions not allowed new SystemTag(1, 'Original', true, true), ['Original', false, false], - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], [ // changing non-assignable not allowed new SystemTag(1, 'Original', true, false), ['Rename', true, false], - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], [ // changing non-assignable not allowed new SystemTag(1, 'Original', true, false), ['Original', true, true], - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], [ // invisible tag does not exist new SystemTag(1, 'Original', false, false), ['Rename', false, false], - 'Sabre\DAV\Exception\NotFound', + NotFound::class, ], ]; } @@ -173,7 +181,7 @@ public function tagNodeProviderPermissionException() { /** * @dataProvider tagNodeProviderPermissionException */ - public function testUpdateTagPermissionException(ISystemTag $originalTag, $changedArgs, $expectedException = null) { + public function testUpdateTagPermissionException(ISystemTag $originalTag, array $changedArgs, string $expectedException) { $this->tagManager->expects($this->any()) ->method('canUserSeeTag') ->with($originalTag) @@ -190,7 +198,7 @@ public function testUpdateTagPermissionException(ISystemTag $originalTag, $chang try { $this->getTagNode(false, $originalTag) ->update($changedArgs[0], $changedArgs[1], $changedArgs[2]); - } catch (\Exception $e) { + } catch (Exception $e) { $thrown = $e; } @@ -198,8 +206,12 @@ public function testUpdateTagPermissionException(ISystemTag $originalTag, $chang } + /** + * @throws Forbidden + * @throws NotFound + */ public function testUpdateTagAlreadyExists() { - $this->expectException(\Sabre\DAV\Exception\Conflict::class); + $this->expectException(Conflict::class); $tag = new SystemTag(1, 'tag1', true, true); $this->tagManager->expects($this->any()) @@ -218,8 +230,12 @@ public function testUpdateTagAlreadyExists() { } + /** + * @throws Conflict + * @throws Forbidden + */ public function testUpdateTagNotFound() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $tag = new SystemTag(1, 'tag1', true, true); $this->tagManager->expects($this->any()) @@ -239,8 +255,9 @@ public function testUpdateTagNotFound() { /** * @dataProvider adminFlagProvider + * @throws NotFound */ - public function testDeleteTag($isAdmin) { + public function testDeleteTag(bool $isAdmin) { $tag = new SystemTag(1, 'tag1', true, true); $this->tagManager->expects($isAdmin ? $this->once() : $this->never()) ->method('canUserSeeTag') @@ -255,25 +272,26 @@ public function testDeleteTag($isAdmin) { $this->getTagNode($isAdmin, $tag)->delete(); } - public function tagNodeDeleteProviderPermissionException() { + public function tagNodeDeleteProviderPermissionException(): array { return [ [ // cannot delete invisible tag new SystemTag(1, 'Original', false, true), - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], [ // cannot delete non-assignable tag new SystemTag(1, 'Original', true, false), - 'Sabre\DAV\Exception\Forbidden', + Forbidden::class, ], ]; } /** * @dataProvider tagNodeDeleteProviderPermissionException + * @throws NotFound|Forbidden */ - public function testDeleteTagPermissionException(ISystemTag $tag, $expectedException) { + public function testDeleteTagPermissionException(ISystemTag $tag, string $expectedException) { $this->tagManager->expects($this->any()) ->method('canUserSeeTag') ->with($tag) @@ -286,8 +304,12 @@ public function testDeleteTagPermissionException(ISystemTag $tag, $expectedExcep } + /** + * @throws Forbidden + * @throws NotFound + */ public function testDeleteTagNotFound() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $tag = new SystemTag(1, 'tag1', true, true); $this->tagManager->expects($this->any()) diff --git a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php index aa7026d38549d..1d4d0d5613540 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagPluginTest.php @@ -29,6 +29,7 @@ use OC\SystemTag\SystemTag; use OCA\DAV\SystemTag\SystemTagNode; +use OCA\DAV\SystemTag\SystemTagPlugin; use OCA\DAV\SystemTag\SystemTagsByIdCollection; use OCA\DAV\SystemTag\SystemTagsObjectMappingCollection; use OCP\IGroupManager; @@ -37,30 +38,34 @@ use OCP\SystemTag\ISystemTag; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\TagAlreadyExistsException; +use Sabre\DAV\Exception; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Conflict; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\PropFind; +use Sabre\DAV\PropPatch; +use Sabre\DAV\Server; use Sabre\DAV\Tree; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; +use Test\TestCase; -class SystemTagPluginTest extends \Test\TestCase { - public const ID_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::ID_PROPERTYNAME; - public const DISPLAYNAME_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::DISPLAYNAME_PROPERTYNAME; - public const USERVISIBLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERVISIBLE_PROPERTYNAME; - public const USERASSIGNABLE_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::USERASSIGNABLE_PROPERTYNAME; - public const CANASSIGN_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::CANASSIGN_PROPERTYNAME; - public const GROUPS_PROPERTYNAME = \OCA\DAV\SystemTag\SystemTagPlugin::GROUPS_PROPERTYNAME; +class SystemTagPluginTest extends TestCase { + public const ID_PROPERTYNAME = SystemTagPlugin::ID_PROPERTYNAME; + public const DISPLAYNAME_PROPERTYNAME = SystemTagPlugin::DISPLAYNAME_PROPERTYNAME; + public const USERVISIBLE_PROPERTYNAME = SystemTagPlugin::USERVISIBLE_PROPERTYNAME; + public const USERASSIGNABLE_PROPERTYNAME = SystemTagPlugin::USERASSIGNABLE_PROPERTYNAME; + public const CANASSIGN_PROPERTYNAME = SystemTagPlugin::CANASSIGN_PROPERTYNAME; + public const GROUPS_PROPERTYNAME = SystemTagPlugin::GROUPS_PROPERTYNAME; /** - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var \Sabre\DAV\Tree + * @var Tree */ private $tree; /** - * @var \OCP\SystemTag\ISystemTagManager + * @var ISystemTagManager */ private $tagManager; @@ -69,55 +74,46 @@ class SystemTagPluginTest extends \Test\TestCase { */ private $groupManager; - /** - * @var IUserSession - */ - private $userSession; - /** * @var IUser */ private $user; /** - * @var \OCA\DAV\SystemTag\SystemTagPlugin + * @var SystemTagPlugin */ private $plugin; + /** + * @throws Exception + */ protected function setUp(): void { parent::setUp(); - $this->tree = $this->getMockBuilder(Tree::class) - ->disableOriginalConstructor() - ->getMock(); - - $this->server = new \Sabre\DAV\Server($this->tree); - - $this->tagManager = $this->getMockBuilder(ISystemTagManager::class) - ->getMock(); - $this->groupManager = $this->getMockBuilder(IGroupManager::class) - ->getMock(); - $this->user = $this->getMockBuilder(IUser::class) - ->getMock(); - $this->userSession = $this->getMockBuilder(IUserSession::class) - ->getMock(); - $this->userSession + $this->tree = $this->createMock(Tree::class); + $server = new Server($this->tree); + + $this->tagManager = $this->createMock(ISystemTagManager::class); + $this->groupManager = $this->createMock(IGroupManager::class); + $this->user = $this->createMock(IUser::class); + $userSession = $this->createMock(IUserSession::class); + $userSession ->expects($this->any()) ->method('getUser') ->willReturn($this->user); - $this->userSession + $userSession ->expects($this->any()) ->method('isLoggedIn') ->willReturn(true); - $this->plugin = new \OCA\DAV\SystemTag\SystemTagPlugin( + $this->plugin = new SystemTagPlugin( $this->tagManager, $this->groupManager, - $this->userSession + $userSession ); - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } - public function getPropertiesDataProvider() { + public function getPropertiesDataProvider(): array { return [ [ new SystemTag(1, 'Test', true, true), @@ -185,8 +181,9 @@ public function getPropertiesDataProvider() { /** * @dataProvider getPropertiesDataProvider + * @throws Forbidden */ - public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProperties, $expectedProperties) { + public function testGetProperties(ISystemTag $systemTag, array $groups, array $requestedProperties, array $expectedProperties) { $this->user->expects($this->any()) ->method('getUID') ->willReturn('admin'); @@ -196,9 +193,7 @@ public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProp ->with('admin') ->willReturn(true); - $node = $this->getMockBuilder(SystemTagNode::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagNode::class); $node->expects($this->any()) ->method('getSystemTag') ->willReturn($systemTag); @@ -216,7 +211,7 @@ public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProp ->with('/systemtag/1') ->willReturn($node); - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/systemtag/1', $requestedProperties, 0 @@ -233,9 +228,9 @@ public function testGetProperties(ISystemTag $systemTag, $groups, $requestedProp $this->assertEquals($expectedProperties, $result[200]); } - + public function testGetPropertiesForbidden() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $systemTag = new SystemTag(1, 'Test', true, false); $requestedProperties = [ @@ -251,9 +246,7 @@ public function testGetPropertiesForbidden() { ->with('admin') ->willReturn(false); - $node = $this->getMockBuilder(SystemTagNode::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagNode::class); $node->expects($this->any()) ->method('getSystemTag') ->willReturn($systemTag); @@ -263,7 +256,7 @@ public function testGetPropertiesForbidden() { ->with('/systemtag/1') ->willReturn($node); - $propFind = new \Sabre\DAV\PropFind( + $propFind = new PropFind( '/systemtag/1', $requestedProperties, 0 @@ -286,9 +279,7 @@ public function testUpdatePropertiesAdmin() { ->with('admin') ->willReturn(true); - $node = $this->getMockBuilder(SystemTagNode::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagNode::class); $node->expects($this->any()) ->method('getSystemTag') ->willReturn($systemTag); @@ -307,7 +298,7 @@ public function testUpdatePropertiesAdmin() { ->with($systemTag, ['group1', 'group2']); // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ + $propPatch = new PropPatch([ self::DISPLAYNAME_PROPERTYNAME => 'Test changed', self::USERVISIBLE_PROPERTYNAME => 'false', self::USERASSIGNABLE_PROPERTYNAME => 'true', @@ -330,9 +321,9 @@ public function testUpdatePropertiesAdmin() { $this->assertEquals(200, $result[self::USERVISIBLE_PROPERTYNAME]); } - + public function testUpdatePropertiesForbidden() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $systemTag = new SystemTag(1, 'Test', true, false); $this->user->expects($this->any()) @@ -344,9 +335,7 @@ public function testUpdatePropertiesForbidden() { ->with('admin') ->willReturn(false); - $node = $this->getMockBuilder(SystemTagNode::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagNode::class); $node->expects($this->any()) ->method('getSystemTag') ->willReturn($systemTag); @@ -363,7 +352,7 @@ public function testUpdatePropertiesForbidden() { ->method('setTagGroups'); // properties to set - $propPatch = new \Sabre\DAV\PropPatch([ + $propPatch = new PropPatch([ self::GROUPS_PROPERTYNAME => 'group1|group2', ]); @@ -375,7 +364,7 @@ public function testUpdatePropertiesForbidden() { $propPatch->commit(); } - public function createTagInsufficientPermissionsProvider() { + public function createTagInsufficientPermissionsProvider(): array { return [ [true, false, ''], [false, true, ''], @@ -385,8 +374,8 @@ public function createTagInsufficientPermissionsProvider() { /** * @dataProvider createTagInsufficientPermissionsProvider */ - public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssignable, $groups) { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + public function testCreateNotAssignableTagAsRegularUser(bool $userVisible, bool $userAssignable, string $groups) { + $this->expectException(BadRequest::class); $this->expectExceptionMessage('Not sufficient permissions'); $this->user->expects($this->once()) @@ -408,9 +397,7 @@ public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssig } $requestData = json_encode($requestData); - $node = $this->getMockBuilder(SystemTagsByIdCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagsByIdCollection::class); $this->tagManager->expects($this->never()) ->method('createTag'); $this->tagManager->expects($this->never()) @@ -421,12 +408,8 @@ public function testCreateNotAssignableTagAsRegularUser($userVisible, $userAssig ->with('/systemtags') ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') @@ -453,9 +436,7 @@ public function testCreateTagInByIdCollectionAsRegularUser() { 'userAssignable' => true, ]); - $node = $this->getMockBuilder(SystemTagsByIdCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagsByIdCollection::class); $this->tagManager->expects($this->once()) ->method('createTag') ->with('Test', true, true) @@ -466,13 +447,8 @@ public function testCreateTagInByIdCollectionAsRegularUser() { ->with('/systemtags') ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/systemtags'); @@ -497,7 +473,7 @@ public function testCreateTagInByIdCollectionAsRegularUser() { $this->plugin->httpPost($request, $response); } - public function createTagProvider() { + public function createTagProvider(): array { return [ [true, false, ''], [false, false, ''], @@ -508,7 +484,7 @@ public function createTagProvider() { /** * @dataProvider createTagProvider */ - public function testCreateTagInByIdCollection($userVisible, $userAssignable, $groups) { + public function testCreateTagInByIdCollection(bool $userVisible, bool $userAssignable, string $groups) { $this->user->expects($this->once()) ->method('getUID') ->willReturn('admin'); @@ -530,14 +506,12 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr } $requestData = json_encode($requestData); - $node = $this->getMockBuilder(SystemTagsByIdCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagsByIdCollection::class); $this->tagManager->expects($this->once()) ->method('createTag') ->with('Test', $userVisible, $userAssignable) ->willReturn($systemTag); - + if (!empty($groups)) { $this->tagManager->expects($this->once()) ->method('setTagGroups') @@ -553,13 +527,8 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr ->with('/systemtags') ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); - + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') ->willReturn('/systemtags'); @@ -584,10 +553,10 @@ public function testCreateTagInByIdCollection($userVisible, $userAssignable, $gr $this->plugin->httpPost($request, $response); } - public function nodeClassProvider() { + public function nodeClassProvider(): array { return [ - ['\OCA\DAV\SystemTag\SystemTagsByIdCollection'], - ['\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection'], + [SystemTagsByIdCollection::class], + [SystemTagsObjectMappingCollection::class], ]; } @@ -609,9 +578,7 @@ public function testCreateTagInMappingCollection() { 'userAssignable' => false, ]); - $node = $this->getMockBuilder(SystemTagsObjectMappingCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagsObjectMappingCollection::class); $this->tagManager->expects($this->once()) ->method('createTag') @@ -627,12 +594,8 @@ public function testCreateTagInMappingCollection() { ->method('createFile') ->with(1); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') @@ -658,17 +621,15 @@ public function testCreateTagInMappingCollection() { $this->plugin->httpPost($request, $response); } - + public function testCreateTagToUnknownNode() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); - $node = $this->getMockBuilder(SystemTagsObjectMappingCollection::class) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock(SystemTagsObjectMappingCollection::class); $this->tree->expects($this->any()) ->method('getNodeForPath') - ->will($this->throwException(new \Sabre\DAV\Exception\NotFound())); + ->will($this->throwException(new NotFound())); $this->tagManager->expects($this->never()) ->method('createTag'); @@ -676,12 +637,8 @@ public function testCreateTagToUnknownNode() { $node->expects($this->never()) ->method('createFile'); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') @@ -693,8 +650,8 @@ public function testCreateTagToUnknownNode() { /** * @dataProvider nodeClassProvider */ - public function testCreateTagConflict($nodeClass) { - $this->expectException(\Sabre\DAV\Exception\Conflict::class); + public function testCreateTagConflict(string $nodeClass) { + $this->expectException(Conflict::class); $this->user->expects($this->once()) ->method('getUID') @@ -711,9 +668,7 @@ public function testCreateTagConflict($nodeClass) { 'userAssignable' => false, ]); - $node = $this->getMockBuilder($nodeClass) - ->disableOriginalConstructor() - ->getMock(); + $node = $this->createMock($nodeClass); $this->tagManager->expects($this->once()) ->method('createTag') ->with('Test', true, false) @@ -724,12 +679,8 @@ public function testCreateTagConflict($nodeClass) { ->with('/systemtags') ->willReturn($node); - $request = $this->getMockBuilder(RequestInterface::class) - ->disableOriginalConstructor() - ->getMock(); - $response = $this->getMockBuilder(ResponseInterface::class) - ->disableOriginalConstructor() - ->getMock(); + $request = $this->createMock(RequestInterface::class); + $response = $this->createMock(ResponseInterface::class); $request->expects($this->once()) ->method('getPath') diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php index 72da59dfcce8c..45d0649bfdbed 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsByIdCollectionTest.php @@ -25,74 +25,76 @@ */ namespace OCA\DAV\Tests\unit\SystemTag; +use InvalidArgumentException; use OC\SystemTag\SystemTag; +use OCA\DAV\SystemTag\SystemTagNode; +use OCA\DAV\SystemTag\SystemTagsByIdCollection; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserSession; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\TagNotFoundException; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class SystemTagsByIdCollectionTest extends \Test\TestCase { +class SystemTagsByIdCollectionTest extends TestCase { /** - * @var \OCP\SystemTag\ISystemTagManager + * @var ISystemTagManager */ private $tagManager; - /** - * @var \OCP\IUser - */ - private $user; - protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->getMockBuilder(ISystemTagManager::class) - ->getMock(); + $this->tagManager = $this->createMock(ISystemTagManager::class); } - public function getNode($isAdmin = true) { - $this->user = $this->getMockBuilder(IUser::class) - ->getMock(); - $this->user->expects($this->any()) + public function getNode($isAdmin = true): SystemTagsByIdCollection { + $user = $this->createMock(IUser::class); + $user->expects($this->any()) ->method('getUID') ->willReturn('testuser'); - $userSession = $this->getMockBuilder(IUserSession::class) - ->getMock(); + $userSession = $this->createMock(IUserSession::class); $userSession->expects($this->any()) ->method('getUser') - ->willReturn($this->user); - $groupManager = $this->getMockBuilder(IGroupManager::class) - ->getMock(); + ->willReturn($user); + $groupManager = $this->createMock(IGroupManager::class); $groupManager->expects($this->any()) ->method('isAdmin') ->with('testuser') ->willReturn($isAdmin); - return new \OCA\DAV\SystemTag\SystemTagsByIdCollection( + return new SystemTagsByIdCollection( $this->tagManager, $userSession, $groupManager ); } - public function adminFlagProvider() { + public function adminFlagProvider(): array { return [[true], [false]]; } - + public function testForbiddenCreateFile() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->getNode()->createFile('555'); } - + public function testForbiddenCreateDirectory() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->getNode()->createDirectory('789'); } + /** + * @throws BadRequest + * @throws NotFound + */ public function testGetChild() { $tag = new SystemTag(123, 'Test', true, false); $this->tagManager->expects($this->once()) @@ -107,26 +109,32 @@ public function testGetChild() { $childNode = $this->getNode()->getChild('123'); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $childNode); + $this->assertInstanceOf(SystemTagNode::class, $childNode); $this->assertEquals('123', $childNode->getName()); $this->assertEquals($tag, $childNode->getSystemTag()); } - + + /** + * @throws NotFound + */ public function testGetChildInvalidName() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->tagManager->expects($this->once()) ->method('getTagsByIds') ->with(['invalid']) - ->will($this->throwException(new \InvalidArgumentException())); + ->will($this->throwException(new InvalidArgumentException())); $this->getNode()->getChild('invalid'); } - + + /** + * @throws BadRequest + */ public function testGetChildNotFound() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->tagManager->expects($this->once()) ->method('getTagsByIds') @@ -136,9 +144,12 @@ public function testGetChildNotFound() { $this->getNode()->getChild('444'); } - + + /** + * @throws BadRequest + */ public function testGetChildUserNotVisible() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $tag = new SystemTag(123, 'Test', false, false); @@ -159,12 +170,12 @@ public function testGetChildrenAdmin() { ->with(null) ->willReturn([$tag1, $tag2]); - $children = $this->getNode(true)->getChildren(); + $children = $this->getNode()->getChildren(); $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertInstanceOf(SystemTagNode::class, $children[0]); + $this->assertInstanceOf(SystemTagNode::class, $children[1]); $this->assertEquals($tag1, $children[0]->getSystemTag()); $this->assertEquals($tag2, $children[1]->getSystemTag()); } @@ -182,8 +193,8 @@ public function testGetChildrenNonAdmin() { $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagNode', $children[1]); + $this->assertInstanceOf(SystemTagNode::class, $children[0]); + $this->assertInstanceOf(SystemTagNode::class, $children[1]); $this->assertEquals($tag1, $children[0]->getSystemTag()); $this->assertEquals($tag2, $children[1]->getSystemTag()); } @@ -196,7 +207,7 @@ public function testGetChildrenEmpty() { $this->assertCount(0, $this->getNode()->getChildren()); } - public function childExistsProvider() { + public function childExistsProvider(): array { return [ [true, true], [false, false], @@ -205,8 +216,9 @@ public function childExistsProvider() { /** * @dataProvider childExistsProvider + * @throws BadRequest */ - public function testChildExists($userVisible, $expectedResult) { + public function testChildExists(bool $userVisible, bool $expectedResult) { $tag = new SystemTag(123, 'One', $userVisible, false); $this->tagManager->expects($this->once()) ->method('canUserSeeTag') @@ -221,6 +233,9 @@ public function testChildExists($userVisible, $expectedResult) { $this->assertEquals($expectedResult, $this->getNode()->childExists('123')); } + /** + * @throws BadRequest + */ public function testChildExistsNotFound() { $this->tagManager->expects($this->once()) ->method('getTagsByIds') @@ -230,14 +245,14 @@ public function testChildExistsNotFound() { $this->assertFalse($this->getNode()->childExists('123')); } - + public function testChildExistsBadRequest() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->tagManager->expects($this->once()) ->method('getTagsByIds') ->with(['invalid']) - ->will($this->throwException(new \InvalidArgumentException())); + ->will($this->throwException(new InvalidArgumentException())); $this->getNode()->childExists('invalid'); } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php index bb71de8ea8e85..4b4a60aa953e9 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectMappingCollectionTest.php @@ -25,43 +25,49 @@ */ namespace OCA\DAV\Tests\unit\SystemTag; +use Exception; +use InvalidArgumentException; use OC\SystemTag\SystemTag; +use OCA\DAV\SystemTag\SystemTagMappingNode; +use OCA\DAV\SystemTag\SystemTagsObjectMappingCollection; use OCP\IUser; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; use OCP\SystemTag\TagNotFoundException; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\PreconditionFailed; +use Test\TestCase; -class SystemTagsObjectMappingCollectionTest extends \Test\TestCase { +class SystemTagsObjectMappingCollectionTest extends TestCase { /** - * @var \OCP\SystemTag\ISystemTagManager + * @var ISystemTagManager */ private $tagManager; /** - * @var \OCP\SystemTag\ISystemTagObjectMapper + * @var ISystemTagObjectMapper */ private $tagMapper; /** - * @var \OCP\IUser + * @var IUser */ private $user; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->getMockBuilder(ISystemTagManager::class) - ->getMock(); - $this->tagMapper = $this->getMockBuilder(ISystemTagObjectMapper::class) - ->getMock(); + $this->tagManager = $this->createMock(ISystemTagManager::class); + $this->tagMapper = $this->createMock(ISystemTagObjectMapper::class); - $this->user = $this->getMockBuilder(IUser::class) - ->getMock(); + $this->user = $this->createMock(IUser::class); } - public function getNode() { - return new \OCA\DAV\SystemTag\SystemTagsObjectMappingCollection( + public function getNode(): SystemTagsObjectMappingCollection { + return new SystemTagsObjectMappingCollection( 111, 'files', $this->user, @@ -70,6 +76,10 @@ public function getNode() { ); } + /** + * @throws PreconditionFailed + * @throws Forbidden + */ public function testAssignTag() { $tag = new SystemTag('1', 'Test', true, true); $this->tagManager->expects($this->once()) @@ -92,19 +102,19 @@ public function testAssignTag() { $this->getNode()->createFile('555'); } - public function permissionsProvider() { + public function permissionsProvider(): array { return [ // invisible, tag does not exist for user - [false, true, '\Sabre\DAV\Exception\PreconditionFailed'], + [false, true, PreconditionFailed::class], // visible but static, cannot assign tag - [true, false, '\Sabre\DAV\Exception\Forbidden'], + [true, false, Forbidden::class], ]; } /** * @dataProvider permissionsProvider */ - public function testAssignTagNoPermission($userVisible, $userAssignable, $expectedException) { + public function testAssignTagNoPermission(bool $userVisible, bool $userAssignable, string $expectedException) { $tag = new SystemTag('1', 'Test', $userVisible, $userAssignable); $this->tagManager->expects($this->once()) ->method('canUserSeeTag') @@ -125,16 +135,19 @@ public function testAssignTagNoPermission($userVisible, $userAssignable, $expect $thrown = null; try { $this->getNode()->createFile('555'); - } catch (\Exception $e) { + } catch (Exception $e) { $thrown = $e; } $this->assertInstanceOf($expectedException, $thrown); } - + + /** + * @throws Forbidden + */ public function testAssignTagNotFound() { - $this->expectException(\Sabre\DAV\Exception\PreconditionFailed::class); + $this->expectException(PreconditionFailed::class); $this->tagManager->expects($this->once()) ->method('getTagsByIds') @@ -144,13 +157,17 @@ public function testAssignTagNotFound() { $this->getNode()->createFile('555'); } - + public function testForbiddenCreateDirectory() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->getNode()->createDirectory('789'); } + /** + * @throws BadRequest + * @throws NotFound + */ public function testGetChild() { $tag = new SystemTag(555, 'TheTag', true, false); $this->tagManager->expects($this->once()) @@ -170,13 +187,16 @@ public function testGetChild() { $childNode = $this->getNode()->getChild('555'); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $childNode); + $this->assertInstanceOf(SystemTagMappingNode::class, $childNode); $this->assertEquals('555', $childNode->getName()); } - + + /** + * @throws BadRequest + */ public function testGetChildNonVisible() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $tag = new SystemTag(555, 'TheTag', false, false); $this->tagManager->expects($this->once()) @@ -197,9 +217,12 @@ public function testGetChildNonVisible() { $this->getNode()->getChild('555'); } - + + /** + * @throws BadRequest + */ public function testGetChildRelationNotFound() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->tagMapper->expects($this->once()) ->method('haveTag') @@ -209,21 +232,27 @@ public function testGetChildRelationNotFound() { $this->getNode()->getChild('777'); } - + + /** + * @throws NotFound + */ public function testGetChildInvalidId() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->tagMapper->expects($this->once()) ->method('haveTag') ->with([111], 'files', 'badid') - ->will($this->throwException(new \InvalidArgumentException())); + ->will($this->throwException(new InvalidArgumentException())); $this->getNode()->getChild('badid'); } - + + /** + * @throws BadRequest + */ public function testGetChildTagDoesNotExist() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->tagMapper->expects($this->once()) ->method('haveTag') @@ -258,8 +287,8 @@ public function testGetChildren() { $this->assertCount(2, $children); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[0]); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagMappingNode', $children[1]); + $this->assertInstanceOf(SystemTagMappingNode::class, $children[0]); + $this->assertInstanceOf(SystemTagMappingNode::class, $children[1]); $this->assertEquals(111, $children[0]->getObjectId()); $this->assertEquals('files', $children[0]->getObjectType()); @@ -270,6 +299,9 @@ public function testGetChildren() { $this->assertEquals($tag2, $children[1]->getSystemTag()); } + /** + * @throws BadRequest + */ public function testChildExistsWithVisibleTag() { $tag = new SystemTag(555, 'TagOne', true, false); @@ -291,6 +323,9 @@ public function testChildExistsWithVisibleTag() { $this->assertTrue($this->getNode()->childExists('555')); } + /** + * @throws BadRequest + */ public function testChildExistsWithInvisibleTag() { $tag = new SystemTag(555, 'TagOne', false, false); @@ -307,6 +342,9 @@ public function testChildExistsWithInvisibleTag() { $this->assertFalse($this->getNode()->childExists('555')); } + /** + * @throws BadRequest + */ public function testChildExistsNotFound() { $this->tagMapper->expects($this->once()) ->method('haveTag') @@ -316,6 +354,9 @@ public function testChildExistsNotFound() { $this->assertFalse($this->getNode()->childExists('555')); } + /** + * @throws BadRequest + */ public function testChildExistsTagNotFound() { $this->tagMapper->expects($this->once()) ->method('haveTag') @@ -325,28 +366,28 @@ public function testChildExistsTagNotFound() { $this->assertFalse($this->getNode()->childExists('555')); } - + public function testChildExistsInvalidId() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->tagMapper->expects($this->once()) ->method('haveTag') ->with([111], 'files', '555') - ->will($this->throwException(new \InvalidArgumentException())); + ->will($this->throwException(new InvalidArgumentException())); $this->getNode()->childExists('555'); } - + public function testDelete() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->getNode()->delete(); } - + public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->getNode()->setName('somethingelse'); } diff --git a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php index 11c9fc5977c8f..3466feef88ecc 100644 --- a/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php +++ b/apps/dav/tests/unit/SystemTag/SystemTagsObjectTypeCollectionTest.php @@ -25,62 +25,52 @@ */ namespace OCA\DAV\Tests\unit\SystemTag; +use OCA\DAV\SystemTag\SystemTagsObjectMappingCollection; +use OCA\DAV\SystemTag\SystemTagsObjectTypeCollection; use OCP\Files\Folder; use OCP\IGroupManager; use OCP\IUser; use OCP\IUserSession; use OCP\SystemTag\ISystemTagManager; use OCP\SystemTag\ISystemTagObjectMapper; +use Sabre\DAV\Exception\Forbidden; +use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\Exception\NotFound; +use Test\TestCase; -class SystemTagsObjectTypeCollectionTest extends \Test\TestCase { +class SystemTagsObjectTypeCollectionTest extends TestCase { /** - * @var \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection + * @var SystemTagsObjectTypeCollection */ private $node; /** - * @var \OCP\SystemTag\ISystemTagManager - */ - private $tagManager; - - /** - * @var \OCP\SystemTag\ISystemTagObjectMapper - */ - private $tagMapper; - - /** - * @var \OCP\Files\Folder + * @var Folder */ private $userFolder; protected function setUp(): void { parent::setUp(); - $this->tagManager = $this->getMockBuilder(ISystemTagManager::class) - ->getMock(); - $this->tagMapper = $this->getMockBuilder(ISystemTagObjectMapper::class) - ->getMock(); + $tagManager = $this->createMock(ISystemTagManager::class); + $tagMapper = $this->createMock(ISystemTagObjectMapper::class); - $user = $this->getMockBuilder(IUser::class) - ->getMock(); + $user = $this->createMock(IUser::class); $user->expects($this->any()) ->method('getUID') ->willReturn('testuser'); - $userSession = $this->getMockBuilder(IUserSession::class) - ->getMock(); + $userSession = $this->createMock(IUserSession::class); $userSession->expects($this->any()) ->method('getUser') ->willReturn($user); - $groupManager = $this->getMockBuilder(IGroupManager::class) - ->getMock(); + $groupManager = $this->createMock(IGroupManager::class); $groupManager->expects($this->any()) ->method('isAdmin') ->with('testuser') ->willReturn(true); - $this->userFolder = $this->getMockBuilder(Folder::class) - ->getMock(); + $this->userFolder = $this->createMock(Folder::class); $userFolder = $this->userFolder; $closure = function ($name) use ($userFolder) { @@ -88,30 +78,33 @@ protected function setUp(): void { return !empty($nodes); }; - $this->node = new \OCA\DAV\SystemTag\SystemTagsObjectTypeCollection( + $this->node = new SystemTagsObjectTypeCollection( 'files', - $this->tagManager, - $this->tagMapper, + $tagManager, + $tagMapper, $userSession, $groupManager, $closure ); } - + public function testForbiddenCreateFile() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->node->createFile('555'); } - + public function testForbiddenCreateDirectory() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->node->createDirectory('789'); } + /** + * @throws NotFound + */ public function testGetChild() { $this->userFolder->expects($this->once()) ->method('getById') @@ -119,13 +112,13 @@ public function testGetChild() { ->willReturn([true]); $childNode = $this->node->getChild('555'); - $this->assertInstanceOf('\OCA\DAV\SystemTag\SystemTagsObjectMappingCollection', $childNode); + $this->assertInstanceOf(SystemTagsObjectMappingCollection::class, $childNode); $this->assertEquals('555', $childNode->getName()); } - + public function testGetChildWithoutAccess() { - $this->expectException(\Sabre\DAV\Exception\NotFound::class); + $this->expectException(NotFound::class); $this->userFolder->expects($this->once()) ->method('getById') @@ -134,9 +127,9 @@ public function testGetChildWithoutAccess() { $this->node->getChild('555'); } - + public function testGetChildren() { - $this->expectException(\Sabre\DAV\Exception\MethodNotAllowed::class); + $this->expectException(MethodNotAllowed::class); $this->node->getChildren(); } @@ -157,16 +150,16 @@ public function testChildExistsWithoutAccess() { $this->assertFalse($this->node->childExists('555')); } - + public function testDelete() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->node->delete(); } - + public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $this->node->setName('somethingelse'); } diff --git a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php index c7d2fea28715a..d15758b2dfa06 100644 --- a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php +++ b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php @@ -28,15 +28,18 @@ */ namespace OCA\DAV\Tests\unit\Upload; +use OCA\DAV\Upload\AssemblyStream; +use PHPUnit\Framework\MockObject\MockObject; use Sabre\DAV\File; +use Test\TestCase; -class AssemblyStreamTest extends \Test\TestCase { +class AssemblyStreamTest extends TestCase { /** * @dataProvider providesNodes() */ - public function testGetContents($expected, $nodes) { - $stream = \OCA\DAV\Upload\AssemblyStream::wrap($nodes); + public function testGetContents(string $expected, array $nodes) { + $stream = AssemblyStream::wrap($nodes); $content = stream_get_contents($stream); $this->assertEquals($expected, $content); @@ -45,8 +48,8 @@ public function testGetContents($expected, $nodes) { /** * @dataProvider providesNodes() */ - public function testGetContentsFread($expected, $nodes) { - $stream = \OCA\DAV\Upload\AssemblyStream::wrap($nodes); + public function testGetContentsFread(string $expected, array $nodes) { + $stream = AssemblyStream::wrap($nodes); $content = ''; while (!feof($stream)) { @@ -59,8 +62,8 @@ public function testGetContentsFread($expected, $nodes) { /** * @dataProvider providesNodes() */ - public function testSeek($expected, $nodes) { - $stream = \OCA\DAV\Upload\AssemblyStream::wrap($nodes); + public function testSeek(string $expected, array $nodes) { + $stream = AssemblyStream::wrap($nodes); $offset = floor(strlen($expected) * 0.6); if (fseek($stream, $offset) === -1) { @@ -71,7 +74,7 @@ public function testSeek($expected, $nodes) { $this->assertEquals(substr($expected, $offset), $content); } - public function providesNodes() { + public function providesNodes(): array { $data8k = $this->makeData(8192); $dataLess8k = $this->makeData(8191); @@ -80,7 +83,7 @@ public function providesNodes() { for ($i = 0; $i < 101; $i++) { $thisdata = rand(0,100); // variable length and content $tonofdata .= $thisdata; - array_push($tonofnodes, $this->buildNode($i,$thisdata)); + $tonofnodes[] = $this->buildNode($i, $thisdata); } return[ @@ -127,7 +130,7 @@ public function providesNodes() { ]; } - private function makeData($count) { + private function makeData(int $count): string { $data = ''; $base = '1234567890'; $j = 0; @@ -141,9 +144,12 @@ private function makeData($count) { return $data; } - private function buildNode($name, $data) { + /** + * @return MockObject|File + */ + private function buildNode(string $name, string $data) { $node = $this->getMockBuilder(File::class) - ->setMethods(['getName', 'get', 'getSize']) + ->onlyMethods(['getName', 'get', 'getSize']) ->getMockForAbstractClass(); $node->expects($this->any()) diff --git a/apps/dav/tests/unit/Upload/ChunkingPluginTest.php b/apps/dav/tests/unit/Upload/ChunkingPluginTest.php index 766b3e1f4572d..16889bd4155b2 100644 --- a/apps/dav/tests/unit/Upload/ChunkingPluginTest.php +++ b/apps/dav/tests/unit/Upload/ChunkingPluginTest.php @@ -27,9 +27,14 @@ namespace OCA\DAV\Tests\unit\Upload; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Connector\Sabre\Exception\Forbidden; use OCA\DAV\Upload\ChunkingPlugin; use OCA\DAV\Upload\FutureFile; +use PHPUnit\Framework\MockObject\MockObject; +use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Server; +use Sabre\DAV\Tree; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; use Test\TestCase; @@ -38,12 +43,7 @@ class ChunkingPluginTest extends TestCase { /** - * @var \Sabre\DAV\Server | \PHPUnit\Framework\MockObject\MockObject - */ - private $server; - - /** - * @var \Sabre\DAV\Tree | \PHPUnit\Framework\MockObject\MockObject + * @var Tree | MockObject */ private $tree; @@ -51,32 +51,32 @@ class ChunkingPluginTest extends TestCase { * @var ChunkingPlugin */ private $plugin; - /** @var RequestInterface | \PHPUnit\Framework\MockObject\MockObject */ + /** @var RequestInterface | MockObject */ private $request; - /** @var ResponseInterface | \PHPUnit\Framework\MockObject\MockObject */ + /** @var ResponseInterface | MockObject */ private $response; protected function setUp(): void { parent::setUp(); - $this->server = $this->getMockBuilder('\Sabre\DAV\Server') - ->disableOriginalConstructor() - ->getMock(); - $this->tree = $this->getMockBuilder('\Sabre\DAV\Tree') - ->disableOriginalConstructor() - ->getMock(); + $server = $this->createMock(Server::class); + $this->tree = $this->createMock(Tree::class); - $this->server->tree = $this->tree; + $server->tree = $this->tree; $this->plugin = new ChunkingPlugin(); $this->request = $this->createMock(RequestInterface::class); $this->response = $this->createMock(ResponseInterface::class); - $this->server->httpRequest = $this->request; - $this->server->httpResponse = $this->response; + $server->httpRequest = $this->request; + $server->httpResponse = $this->response; - $this->plugin->initialize($this->server); + $this->plugin->initialize($server); } + /** + * @throws BadRequest + * @throws NotFound|Forbidden + */ public function testBeforeMoveFutureFileSkip() { $node = $this->createMock(Directory::class); @@ -90,41 +90,40 @@ public function testBeforeMoveFutureFileSkip() { $this->assertNull($this->plugin->beforeMove('source', 'target')); } + /** + * @throws NotFound|Forbidden + */ public function testBeforeMoveDestinationIsDirectory() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('The given destination target is a directory.'); $sourceNode = $this->createMock(FutureFile::class); $targetNode = $this->createMock(Directory::class); - $this->tree->expects($this->at(0)) + $this->tree->expects($this->exactly(2)) ->method('getNodeForPath') - ->with('source') - ->willReturn($sourceNode); - $this->tree->expects($this->at(1)) - ->method('getNodeForPath') - ->with('target') - ->willReturn($targetNode); + ->withConsecutive(['source'], ['target']) + ->willReturnOnConsecutiveCalls($sourceNode, $targetNode); $this->response->expects($this->never()) ->method('setStatus'); $this->assertNull($this->plugin->beforeMove('source', 'target')); } + /** + * @throws BadRequest + * @throws NotFound|Forbidden + */ public function testBeforeMoveFutureFileSkipNonExisting() { $sourceNode = $this->createMock(FutureFile::class); $sourceNode->expects($this->once()) ->method('getSize') ->willReturn(4); - $this->tree->expects($this->at(0)) + $this->tree->expects($this->exactly(2)) ->method('getNodeForPath') - ->with('source') - ->willReturn($sourceNode); - $this->tree->expects($this->at(1)) - ->method('getNodeForPath') - ->with('target') - ->willThrowException(new NotFound()); + ->withConsecutive(['source'], ['target']) + ->willReturnOnConsecutiveCalls($sourceNode, $this->throwException(new NotFound())); $this->tree->expects($this->any()) ->method('nodeExists') ->with('target') @@ -138,25 +137,26 @@ public function testBeforeMoveFutureFileSkipNonExisting() { $this->request->expects($this->once()) ->method('getHeader') ->with('OC-Total-Length') - ->willReturn(4); + ->willReturn('4'); $this->assertFalse($this->plugin->beforeMove('source', 'target')); } + /** + * @throws BadRequest + * @throws NotFound|Forbidden + */ public function testBeforeMoveFutureFileMoveIt() { $sourceNode = $this->createMock(FutureFile::class); $sourceNode->expects($this->once()) ->method('getSize') ->willReturn(4); - $this->tree->expects($this->at(0)) + $this->tree->expects($this->exactly(2)) ->method('getNodeForPath') - ->with('source') - ->willReturn($sourceNode); - $this->tree->expects($this->at(1)) - ->method('getNodeForPath') - ->with('target') - ->willThrowException(new NotFound()); + ->withConsecutive(['source'], ['target']) + ->willReturnOnConsecutiveCalls($sourceNode, $this->throwException(new NotFound())); + $this->tree->expects($this->any()) ->method('nodeExists') ->with('target') @@ -180,8 +180,11 @@ public function testBeforeMoveFutureFileMoveIt() { } + /** + * @throws NotFound|Forbidden + */ public function testBeforeMoveSizeIsWrong() { - $this->expectException(\Sabre\DAV\Exception\BadRequest::class); + $this->expectException(BadRequest::class); $this->expectExceptionMessage('Chunks on server do not sum up to 4 but to 3 bytes'); $sourceNode = $this->createMock(FutureFile::class); @@ -189,14 +192,11 @@ public function testBeforeMoveSizeIsWrong() { ->method('getSize') ->willReturn(3); - $this->tree->expects($this->at(0)) + $this->tree->expects($this->exactly(2)) ->method('getNodeForPath') - ->with('source') - ->willReturn($sourceNode); - $this->tree->expects($this->at(1)) - ->method('getNodeForPath') - ->with('target') - ->willThrowException(new NotFound()); + ->withConsecutive(['source'], ['target']) + ->willReturnOnConsecutiveCalls($sourceNode, $this->throwException(new NotFound())); + $this->request->expects($this->once()) ->method('getHeader') ->with('OC-Total-Length') diff --git a/apps/dav/tests/unit/Upload/FutureFileTest.php b/apps/dav/tests/unit/Upload/FutureFileTest.php index 0c276167e1cc9..24221f2f148fc 100644 --- a/apps/dav/tests/unit/Upload/FutureFileTest.php +++ b/apps/dav/tests/unit/Upload/FutureFileTest.php @@ -26,8 +26,11 @@ namespace OCA\DAV\Tests\unit\Upload; use OCA\DAV\Connector\Sabre\Directory; +use OCA\DAV\Upload\FutureFile; +use Sabre\DAV\Exception\Forbidden; +use Test\TestCase; -class FutureFileTest extends \Test\TestCase { +class FutureFileTest extends TestCase { public function testGetContentType() { $f = $this->mockFutureFile(); $this->assertEquals('application/octet-stream', $f->getContentType()); @@ -62,39 +65,39 @@ public function testGet() { public function testDelete() { $d = $this->getMockBuilder(Directory::class) ->disableOriginalConstructor() - ->setMethods(['delete']) + ->onlyMethods(['delete']) ->getMock(); $d->expects($this->once()) ->method('delete'); - $f = new \OCA\DAV\Upload\FutureFile($d, 'foo.txt'); + $f = new FutureFile($d, 'foo.txt'); $f->delete(); } - + public function testPut() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $f = $this->mockFutureFile(); $f->put(''); } - + public function testSetName() { - $this->expectException(\Sabre\DAV\Exception\Forbidden::class); + $this->expectException(Forbidden::class); $f = $this->mockFutureFile(); $f->setName(''); } /** - * @return \OCA\DAV\Upload\FutureFile + * @return FutureFile */ - private function mockFutureFile() { + private function mockFutureFile(): FutureFile { $d = $this->getMockBuilder(Directory::class) ->disableOriginalConstructor() - ->setMethods(['getETag', 'getLastModified', 'getChildren']) + ->onlyMethods(['getETag', 'getLastModified', 'getChildren']) ->getMock(); $d->expects($this->any()) @@ -109,6 +112,6 @@ private function mockFutureFile() { ->method('getChildren') ->willReturn([]); - return new \OCA\DAV\Upload\FutureFile($d, 'foo.txt'); + return new FutureFile($d, 'foo.txt'); } } From 3d423365f6ab1bf0d787760daaa88c679422828f Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Wed, 26 Jan 2022 14:52:41 +0100 Subject: [PATCH 21/23] Improve CommentsEntityEvent Signed-off-by: Thomas Citharel --- .../Listener/CommentsEntityEventListener.php | 24 ++++++++++++-- lib/public/Comments/CommentsEntityEvent.php | 31 ++++++++----------- 2 files changed, 35 insertions(+), 20 deletions(-) diff --git a/apps/comments/lib/Listener/CommentsEntityEventListener.php b/apps/comments/lib/Listener/CommentsEntityEventListener.php index 5675e1904cc64..e905c2aa1d08a 100644 --- a/apps/comments/lib/Listener/CommentsEntityEventListener.php +++ b/apps/comments/lib/Listener/CommentsEntityEventListener.php @@ -28,8 +28,24 @@ use OCP\Comments\CommentsEntityEvent; use OCP\EventDispatcher\Event; use OCP\EventDispatcher\IEventListener; +use OCP\Files\IRootFolder; +use OCP\IUserSession; class CommentsEntityEventListener implements IEventListener { + /** + * @var IUserSession + */ + private $userSession; + /** + * @var IRootFolder + */ + private $rootFolder; + + public function __construct(IUserSession $userSession, IRootFolder $rootFolder) { + $this->userSession = $userSession; + $this->rootFolder = $rootFolder; + } + public function handle(Event $event): void { if (!($event instanceof CommentsEntityEvent)) { // Unrelated @@ -37,8 +53,12 @@ public function handle(Event $event): void { } $event->addEntityCollection('files', function ($name) { - $nodes = \OC::$server->getUserFolder()->getById((int)$name); - return !empty($nodes); + if ($user = $this->userSession->getUser()) { + $userFolder = $this->rootFolder->getUserFolder($user->getUID()); + $nodes = $userFolder->getById((int)$name); + return !empty($nodes); + } + return false; }); } } diff --git a/lib/public/Comments/CommentsEntityEvent.php b/lib/public/Comments/CommentsEntityEvent.php index e4b4c78f03c07..df56412dd4095 100644 --- a/lib/public/Comments/CommentsEntityEvent.php +++ b/lib/public/Comments/CommentsEntityEvent.php @@ -23,7 +23,9 @@ */ namespace OCP\Comments; +use Closure; use OCP\EventDispatcher\Event; +use OutOfBoundsException; /** * Class CommentsEntityEvent @@ -31,49 +33,42 @@ * @since 9.1.0 */ class CommentsEntityEvent extends Event { - /** - * @deprecated 22.0.0 - */ - public const EVENT_ENTITY = 'OCP\Comments\ICommentsManager::registerEntity'; - - /** @var string */ - protected $event; - /** @var \Closure[] */ + /** @var Closure[] */ protected $collections; /** * DispatcherEvent constructor. * - * @param string $event + * @param Closure[] $collections * @since 9.1.0 */ - public function __construct($event) { - $this->event = $event; - $this->collections = []; + public function __construct(array $collections = []) { + parent::__construct(); + $this->collections = $collections; } /** * @param string $name - * @param \Closure $entityExistsFunction The closure should take one + * @param Closure $entityExistsFunction The closure should take one * argument, which is the id of the entity, that comments * should be handled for. The return should then be bool, * depending on whether comments are allowed (true) or not. - * @throws \OutOfBoundsException when the entity name is already taken + * @throws OutOfBoundsException when the entity name is already taken * @since 9.1.0 */ - public function addEntityCollection($name, \Closure $entityExistsFunction) { + public function addEntityCollection(string $name, Closure $entityExistsFunction) { if (isset($this->collections[$name])) { - throw new \OutOfBoundsException('Duplicate entity name "' . $name . '"'); + throw new OutOfBoundsException('Duplicate entity name "' . $name . '"'); } $this->collections[$name] = $entityExistsFunction; } /** - * @return \Closure[] + * @return Closure[] * @since 9.1.0 */ - public function getEntityCollections() { + public function getEntityCollections(): array { return $this->collections; } } From 9246d0602ac0ecfd37db8dd1cf4bd6d94701808a Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Mon, 14 Feb 2022 19:39:05 +0100 Subject: [PATCH 22/23] Use PHP 7.4 typed properties Signed-off-by: Thomas Citharel --- apps/dav/lib/AppInfo/PluginManager.php | 24 ++--- apps/dav/lib/Avatars/RootCollection.php | 4 +- .../BuildReminderIndexBackgroundJob.php | 20 ++--- .../BackgroundJob/CalendarRetentionJob.php | 3 +- .../BackgroundJob/CleanupDirectLinksJob.php | 3 +- .../CleanupInvitationTokenJob.php | 3 +- .../lib/BackgroundJob/EventReminderJob.php | 18 ++-- .../GenerateBirthdayCalendarBackgroundJob.php | 10 +-- .../lib/BackgroundJob/RefreshWebcalJob.php | 32 ++----- .../RegisterRegenerateBirthdayCalendars.php | 8 +- ...ateCalendarResourcesRoomsBackgroundJob.php | 15 +--- apps/dav/lib/BackgroundJob/UploadCleanup.php | 15 ++-- apps/dav/lib/BulkUpload/BulkUploadPlugin.php | 16 ++-- .../lib/BulkUpload/MultipartRequestParser.php | 19 ++-- apps/dav/lib/CalDAV/Activity/Backend.php | 28 +++--- .../lib/CalDAV/Activity/Filter/Calendar.php | 8 +- apps/dav/lib/CalDAV/Activity/Filter/Todo.php | 8 +- .../dav/lib/CalDAV/Activity/Provider/Base.php | 37 +++----- .../lib/CalDAV/Activity/Provider/Calendar.php | 34 +++---- .../lib/CalDAV/Activity/Provider/Event.php | 43 ++++----- .../dav/lib/CalDAV/Activity/Provider/Todo.php | 21 ++--- .../CalDAV/Activity/Setting/CalDAVSetting.php | 6 +- .../CalDAV/BirthdayCalendar/EnablePlugin.php | 31 +++---- apps/dav/lib/CalDAV/BirthdayService.php | 75 ++++++++-------- apps/dav/lib/CalDAV/CachedSubscription.php | 5 +- apps/dav/lib/CalDAV/CalDavBackend.php | 90 +++++++------------ apps/dav/lib/CalDAV/Calendar.php | 49 +++------- apps/dav/lib/CalDAV/CalendarHome.php | 31 +++---- apps/dav/lib/CalDAV/CalendarImpl.php | 29 ++---- apps/dav/lib/CalDAV/CalendarManager.php | 14 +-- apps/dav/lib/CalDAV/CalendarObject.php | 8 +- apps/dav/lib/CalDAV/CalendarProvider.php | 12 +-- .../ICSExportPlugin/ICSExportPlugin.php | 17 +--- .../CalDAV/Integration/ExternalCalendar.php | 7 +- .../InvitationResponseServer.php | 58 +++++++----- apps/dav/lib/CalDAV/Outbox.php | 8 +- apps/dav/lib/CalDAV/Principal/Collection.php | 3 + apps/dav/lib/CalDAV/Proxy/Proxy.php | 10 +-- apps/dav/lib/CalDAV/Proxy/ProxyMapper.php | 3 + apps/dav/lib/CalDAV/PublicCalendar.php | 3 +- apps/dav/lib/CalDAV/PublicCalendarObject.php | 3 +- apps/dav/lib/CalDAV/PublicCalendarRoot.php | 12 +-- .../lib/CalDAV/Publishing/PublishPlugin.php | 23 ++--- .../lib/CalDAV/Publishing/Xml/Publisher.php | 12 +-- apps/dav/lib/CalDAV/Reminder/Backend.php | 29 +++--- .../NotificationProvider/AbstractProvider.php | 29 ++---- .../NotificationProvider/EmailProvider.php | 29 +++--- .../NotificationProvider/PushProvider.php | 31 +++---- .../Reminder/NotificationProviderManager.php | 2 +- apps/dav/lib/CalDAV/Reminder/Notifier.php | 41 ++++----- .../lib/CalDAV/Reminder/ReminderService.php | 61 +++++-------- .../AbstractPrincipalBackend.php | 78 ++++++---------- .../ResourcePrincipalBackend.php | 9 -- .../ResourceBooking/RoomPrincipalBackend.php | 9 -- apps/dav/lib/CalDAV/RetentionService.php | 15 ++-- apps/dav/lib/CalDAV/Schedule/IMipPlugin.php | 48 +++------- apps/dav/lib/CalDAV/Schedule/Plugin.php | 16 ++-- apps/dav/lib/CalDAV/Search/SearchPlugin.php | 10 ++- .../CalDAV/Search/Xml/Filter/CompFilter.php | 6 +- .../CalDAV/Search/Xml/Filter/LimitFilter.php | 6 +- .../CalDAV/Search/Xml/Filter/OffsetFilter.php | 6 +- .../CalDAV/Search/Xml/Filter/ParamFilter.php | 6 +- .../CalDAV/Search/Xml/Filter/PropFilter.php | 6 +- .../Search/Xml/Filter/SearchTermFilter.php | 6 +- .../Xml/Request/CalendarSearchReport.php | 26 +++--- .../CalDAV/Trashbin/DeletedCalendarObject.php | 15 +--- .../DeletedCalendarObjectsCollection.php | 7 +- apps/dav/lib/CalDAV/Trashbin/Plugin.php | 14 ++- apps/dav/lib/CalDAV/Trashbin/TrashbinHome.php | 8 +- apps/dav/lib/CalDAV/WebcalCaching/Plugin.php | 15 +--- .../WebcalCaching/RefreshWebcalService.php | 27 +++--- apps/dav/lib/Connector/PublicAuth.php | 22 ++--- .../Sabre/AnonymousOptionsPlugin.php | 6 +- .../lib/Connector/Sabre/AppEnabledPlugin.php | 18 +--- apps/dav/lib/Connector/Sabre/Auth.php | 28 +++--- apps/dav/lib/Connector/Sabre/BearerAuth.php | 17 ++-- .../Sabre/BlockLegacyClientPlugin.php | 6 +- apps/dav/lib/Connector/Sabre/ChecksumList.php | 4 +- .../Sabre/CommentPropertiesPlugin.php | 14 +-- .../Connector/Sabre/CopyEtagHeaderPlugin.php | 4 +- apps/dav/lib/Connector/Sabre/DavAclPlugin.php | 7 +- apps/dav/lib/Connector/Sabre/Directory.php | 12 +-- .../Sabre/DummyGetResponsePlugin.php | 3 +- .../Sabre/Exception/EntityTooLarge.php | 4 +- .../Connector/Sabre/Exception/FileLocked.php | 3 +- .../Connector/Sabre/Exception/Forbidden.php | 20 ++--- .../Connector/Sabre/Exception/InvalidPath.php | 14 ++- .../Sabre/Exception/UnsupportedMediaType.php | 4 +- .../Connector/Sabre/ExceptionLoggerPlugin.php | 9 +- .../lib/Connector/Sabre/FakeLockerPlugin.php | 3 +- apps/dav/lib/Connector/Sabre/File.php | 26 +++--- apps/dav/lib/Connector/Sabre/FilesPlugin.php | 73 ++++----------- .../lib/Connector/Sabre/FilesReportPlugin.php | 58 +++--------- apps/dav/lib/Connector/Sabre/LockPlugin.php | 8 +- .../lib/Connector/Sabre/MaintenancePlugin.php | 17 +--- .../lib/Connector/Sabre/MtimeSanitizer.php | 6 +- apps/dav/lib/Connector/Sabre/Node.php | 32 ++----- apps/dav/lib/Connector/Sabre/ObjectTree.php | 20 ++--- apps/dav/lib/Connector/Sabre/Principal.php | 55 ++++-------- .../Sabre/PropfindCompressionPlugin.php | 4 +- apps/dav/lib/Connector/Sabre/QuotaPlugin.php | 16 ++-- .../Connector/Sabre/RequestIdHeaderPlugin.php | 6 +- .../dav/lib/Connector/Sabre/ServerFactory.php | 53 +++++------ .../dav/lib/Connector/Sabre/ShareTypeList.php | 2 +- apps/dav/lib/Connector/Sabre/ShareeList.php | 2 +- apps/dav/lib/Connector/Sabre/SharesPlugin.php | 19 ++-- apps/dav/lib/Connector/Sabre/TagList.php | 12 +-- apps/dav/lib/Connector/Sabre/TagsPlugin.php | 32 +++---- lib/public/Calendar/ICalendar.php | 10 +-- 109 files changed, 762 insertions(+), 1320 deletions(-) diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index 65c1fc189af11..db5eb6ee7e787 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -46,49 +46,41 @@ */ class PluginManager { - /** - * @var ServerContainer - */ - private $container; - - /** - * @var IAppManager - */ - private $appManager; + private ServerContainer $container; + private IAppManager $appManager; /** * App plugins * * @var ServerPlugin[] */ - private $plugins = []; + private array $plugins = []; /** * App collections * * @var Collection[] */ - private $collections = []; + private array $collections = []; /** * Address book plugins * * @var IAddressBookProvider[] */ - private $addressBookPlugins = []; + private array $addressBookPlugins = []; /** * Calendar plugins * * @var ICalendarProvider[] */ - private $calendarPlugins = []; + private array $calendarPlugins = []; - /** @var bool */ - private $populated = false; + private bool $populated = false; /** - * Contstruct a PluginManager + * Construct a PluginManager * * @param ServerContainer $container server container for resolving plugin classes * @param IAppManager $appManager app manager to loading apps and their info diff --git a/apps/dav/lib/Avatars/RootCollection.php b/apps/dav/lib/Avatars/RootCollection.php index e88b29e02531c..42c91344fbde1 100644 --- a/apps/dav/lib/Avatars/RootCollection.php +++ b/apps/dav/lib/Avatars/RootCollection.php @@ -1,4 +1,6 @@ - * diff --git a/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php b/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php index dfc7521024a14..eea63378e1d1a 100644 --- a/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/BuildReminderIndexBackgroundJob.php @@ -40,21 +40,11 @@ * @package OCA\DAV\BackgroundJob */ class BuildReminderIndexBackgroundJob extends QueuedJob { - - /** @var IDBConnection */ - private $db; - - /** @var ReminderService */ - private $reminderService; - - /** @var LoggerInterface */ - private $logger; - - /** @var IJobList */ - private $jobList; - - /** @var ITimeFactory */ - private $timeFactory; + private IDBConnection $db; + private ReminderService $reminderService; + private LoggerInterface $logger; + private IJobList $jobList; + private ITimeFactory $timeFactory; /** * BuildReminderIndexBackgroundJob constructor. diff --git a/apps/dav/lib/BackgroundJob/CalendarRetentionJob.php b/apps/dav/lib/BackgroundJob/CalendarRetentionJob.php index b57ed07d5c247..745758c86ec6c 100644 --- a/apps/dav/lib/BackgroundJob/CalendarRetentionJob.php +++ b/apps/dav/lib/BackgroundJob/CalendarRetentionJob.php @@ -30,8 +30,7 @@ use OCP\BackgroundJob\TimedJob; class CalendarRetentionJob extends TimedJob { - /** @var RetentionService */ - private $service; + private RetentionService $service; public function __construct(ITimeFactory $time, RetentionService $service) { diff --git a/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php b/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php index 073fc53e07ad3..a87adc9399800 100644 --- a/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php +++ b/apps/dav/lib/BackgroundJob/CleanupDirectLinksJob.php @@ -31,8 +31,7 @@ use OCP\BackgroundJob\TimedJob; class CleanupDirectLinksJob extends TimedJob { - /** @var DirectMapper */ - private $mapper; + private DirectMapper $mapper; public function __construct(ITimeFactory $timeFactory, DirectMapper $mapper) { parent::__construct($timeFactory); diff --git a/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php b/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php index 6339e721c9304..f2ab3b241b8e3 100644 --- a/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php +++ b/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php @@ -32,8 +32,7 @@ class CleanupInvitationTokenJob extends TimedJob { - /** @var IDBConnection */ - private $db; + private IDBConnection $db; public function __construct(IDBConnection $db, ITimeFactory $time) { parent::__construct($time); diff --git a/apps/dav/lib/BackgroundJob/EventReminderJob.php b/apps/dav/lib/BackgroundJob/EventReminderJob.php index ab7dadd8c0b2f..7d88ad2835514 100644 --- a/apps/dav/lib/BackgroundJob/EventReminderJob.php +++ b/apps/dav/lib/BackgroundJob/EventReminderJob.php @@ -26,18 +26,16 @@ */ namespace OCA\DAV\BackgroundJob; +use OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException; +use OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException; use OCA\DAV\CalDAV\Reminder\ReminderService; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\TimedJob; use OCP\IConfig; class EventReminderJob extends TimedJob { - - /** @var ReminderService */ - private $reminderService; - - /** @var IConfig */ - private $config; + private ReminderService $reminderService; + private IConfig $config; public function __construct(ITimeFactory $time, ReminderService $reminderService, @@ -52,12 +50,10 @@ public function __construct(ITimeFactory $time, } /** - * @param $arg - * @throws \OCA\DAV\CalDAV\Reminder\NotificationProvider\ProviderNotAvailableException - * @throws \OCA\DAV\CalDAV\Reminder\NotificationTypeDoesNotExistException - * @throws \OC\User\NoUserException + * @throws ProviderNotAvailableException + * @throws NotificationTypeDoesNotExistException */ - public function run($arg):void { + public function run($argument):void { if ($this->config->getAppValue('dav', 'sendEventReminders', 'yes') !== 'yes') { return; } diff --git a/apps/dav/lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php b/apps/dav/lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php index a338a172d66f3..11991a851de14 100644 --- a/apps/dav/lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/GenerateBirthdayCalendarBackgroundJob.php @@ -29,14 +29,11 @@ use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\QueuedJob; use OCP\IConfig; +use Sabre\DAV\Exception\BadRequest; class GenerateBirthdayCalendarBackgroundJob extends QueuedJob { - - /** @var BirthdayService */ - private $birthdayService; - - /** @var IConfig */ - private $config; + private BirthdayService $birthdayService; + private IConfig $config; public function __construct(ITimeFactory $time, BirthdayService $birthdayService, @@ -49,6 +46,7 @@ public function __construct(ITimeFactory $time, /** * @param array $arguments + * @throws BadRequest */ public function run($arguments) { $userId = $arguments['userId']; diff --git a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php index fa3a938dead72..021a11862560d 100644 --- a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php +++ b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php @@ -35,36 +35,18 @@ use OCP\BackgroundJob\Job; use OCP\IConfig; use OCP\ILogger; +use Psr\Log\LoggerInterface; use Sabre\VObject\DateTimeParser; use Sabre\VObject\InvalidDataException; class RefreshWebcalJob extends Job { - /** - * @var RefreshWebcalService - */ - private $refreshWebcalService; - - /** - * @var IConfig - */ - private $config; + private RefreshWebcalService $refreshWebcalService; + private IConfig $config; + private LoggerInterface $logger; + private ITimeFactory $timeFactory; - /** @var ILogger */ - private $logger; - - /** @var ITimeFactory */ - private $timeFactory; - - /** - * RefreshWebcalJob constructor. - * - * @param RefreshWebcalService $refreshWebcalService - * @param IConfig $config - * @param ILogger $logger - * @param ITimeFactory $timeFactory - */ - public function __construct(RefreshWebcalService $refreshWebcalService, IConfig $config, ILogger $logger, ITimeFactory $timeFactory) { + public function __construct(RefreshWebcalService $refreshWebcalService, IConfig $config, LoggerInterface $logger, ITimeFactory $timeFactory) { parent::__construct($timeFactory); $this->refreshWebcalService = $refreshWebcalService; $this->config = $config; @@ -104,7 +86,7 @@ public function execute(IJobList $jobList, ILogger $logger = null) { return; } - parent::execute($jobList, $logger); + parent::execute($jobList); } /** diff --git a/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php b/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php index 85da81b3b91fd..1309a6176b6d2 100644 --- a/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php +++ b/apps/dav/lib/BackgroundJob/RegisterRegenerateBirthdayCalendars.php @@ -34,12 +34,8 @@ use OCP\IUserManager; class RegisterRegenerateBirthdayCalendars extends QueuedJob { - - /** @var IUserManager */ - private $userManager; - - /** @var IJobList */ - private $jobList; + private IUserManager $userManager; + private IJobList $jobList; /** * RegisterRegenerateBirthdayCalendars constructor. diff --git a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php index f7addd58248c7..15be41b794a62 100644 --- a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php @@ -42,17 +42,10 @@ class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { - /** @var IResourceManager */ - private $resourceManager; - - /** @var IRoomManager */ - private $roomManager; - - /** @var IDBConnection */ - private $dbConnection; - - /** @var CalDavBackend */ - private $calDavBackend; + private IResourceManager $resourceManager; + private IRoomManager $roomManager; + private IDBConnection $dbConnection; + private CalDavBackend $calDavBackend; public function __construct(ITimeFactory $time, IResourceManager $resourceManager, diff --git a/apps/dav/lib/BackgroundJob/UploadCleanup.php b/apps/dav/lib/BackgroundJob/UploadCleanup.php index 76906becb54c2..d6f39697d9206 100644 --- a/apps/dav/lib/BackgroundJob/UploadCleanup.php +++ b/apps/dav/lib/BackgroundJob/UploadCleanup.php @@ -34,16 +34,14 @@ use OCP\BackgroundJob\TimedJob; use OCP\Files\File; use OCP\Files\Folder; +use OCP\Files\InvalidPathException; use OCP\Files\IRootFolder; use OCP\Files\NotFoundException; +use OCP\Files\NotPermittedException; class UploadCleanup extends TimedJob { - - /** @var IRootFolder */ - private $rootFolder; - - /** @var IJobList */ - private $jobList; + private IRootFolder $rootFolder; + private IJobList $jobList; public function __construct(ITimeFactory $time, IRootFolder $rootFolder, IJobList $jobList) { parent::__construct($time); @@ -55,6 +53,11 @@ public function __construct(ITimeFactory $time, IRootFolder $rootFolder, IJobLis $this->setTimeSensitivity(IJob::TIME_INSENSITIVE); } + /** + * @throws InvalidPathException + * @throws NotFoundException + * @throws NotPermittedException + */ protected function run($argument) { $uid = $argument['uid']; $folder = $argument['folder']; diff --git a/apps/dav/lib/BulkUpload/BulkUploadPlugin.php b/apps/dav/lib/BulkUpload/BulkUploadPlugin.php index bb6baf48b562a..c15f5e66e996c 100644 --- a/apps/dav/lib/BulkUpload/BulkUploadPlugin.php +++ b/apps/dav/lib/BulkUpload/BulkUploadPlugin.php @@ -22,7 +22,9 @@ namespace OCA\DAV\BulkUpload; +use Exception; use Psr\Log\LoggerInterface; +use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; @@ -32,12 +34,8 @@ use OCA\DAV\Connector\Sabre\MtimeSanitizer; class BulkUploadPlugin extends ServerPlugin { - - /** @var Folder */ - private $userFolder; - - /** @var LoggerInterface */ - private $logger; + private Folder $userFolder; + private LoggerInterface $logger; public function __construct(Folder $userFolder, LoggerInterface $logger) { $this->userFolder = $userFolder; @@ -57,6 +55,8 @@ public function initialize(Server $server): void { * - writing is done with the userFolder service * * Will respond with an object containing an ETag for every written files. + * + * @throws BadRequest */ public function httpPost(RequestInterface $request, ResponseInterface $response): bool { // Limit bulk upload to the /dav/bulk endpoint @@ -70,7 +70,7 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) while (!$multiPartParser->isAtLastBoundary()) { try { [$headers, $content] = $multiPartParser->parseNextPart(); - } catch (\Exception $e) { + } catch (Exception $e) { // Return early if an error occurs during parsing. $this->logger->error($e->getMessage()); $response->setStatus(Http::STATUS_BAD_REQUEST); @@ -95,7 +95,7 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) "error" => false, "etag" => $node->getETag(), ]; - } catch (\Exception $e) { + } catch (Exception $e) { $this->logger->error($e->getMessage(), ['path' => $headers['x-file-path']]); $writtenFiles[$headers['x-file-path']] = [ "error" => true, diff --git a/apps/dav/lib/BulkUpload/MultipartRequestParser.php b/apps/dav/lib/BulkUpload/MultipartRequestParser.php index 7554447fc93b8..eb15e0ac21aea 100644 --- a/apps/dav/lib/BulkUpload/MultipartRequestParser.php +++ b/apps/dav/lib/BulkUpload/MultipartRequestParser.php @@ -32,12 +32,8 @@ class MultipartRequestParser { /** @var resource */ private $stream; - - /** @var string */ - private $boundary = ""; - - /** @var string */ - private $lastBoundary = ""; + private string $boundary = ""; + private string $lastBoundary = ""; /** * @throws BadRequest @@ -117,6 +113,8 @@ private function isAt(string $expectedContent): bool { /** * Check whether the stream's cursor is sitting right before the boundary. + * + * @throws Exception */ private function isAtBoundary(): bool { return $this->isAt($this->boundary); @@ -124,6 +122,8 @@ private function isAtBoundary(): bool { /** * Check whether the stream's cursor is sitting right before the last boundary. + * + * @throws Exception */ public function isAtLastBoundary(): bool { return $this->isAt($this->lastBoundary); @@ -140,6 +140,8 @@ public function isAtLastBoundary(): bool { * Content of * the part * + * @throws BadRequest + * @throws Exception */ public function parseNextPart(): array { $this->readBoundary(); @@ -155,13 +157,14 @@ public function parseNextPart(): array { * Read the boundary and check its content. * * @throws BadRequest + * @throws Exception */ - private function readBoundary(): string { + private function readBoundary(): void { if (!$this->isAtBoundary()) { throw new BadRequest("Boundary not found where it should be."); } - return fread($this->stream, strlen($this->boundary)); + fread($this->stream, strlen($this->boundary)); } /** diff --git a/apps/dav/lib/CalDAV/Activity/Backend.php b/apps/dav/lib/CalDAV/Activity/Backend.php index af2d790e10d05..c2e486c0e4c66 100644 --- a/apps/dav/lib/CalDAV/Activity/Backend.php +++ b/apps/dav/lib/CalDAV/Activity/Backend.php @@ -43,18 +43,10 @@ * @package OCA\DAV\CalDAV\Activity */ class Backend { - - /** @var IActivityManager */ - protected $activityManager; - - /** @var IGroupManager */ - protected $groupManager; - - /** @var IUserSession */ - protected $userSession; - - /** @var IAppManager */ - protected $appManager; + protected IActivityManager $activityManager; + protected IGroupManager $groupManager; + protected IUserSession $userSession; + protected IAppManager $appManager; public function __construct(IActivityManager $activityManager, IGroupManager $groupManager, IUserSession $userSession, IAppManager $appManager) { $this->activityManager = $activityManager; @@ -131,7 +123,7 @@ public function onCalendarPublication(array $calendarData, bool $publishStatus): * @param array $shares * @param array $changedProperties */ - protected function triggerCalendarActivity($action, array $calendarData, array $shares = [], array $changedProperties = []) { + protected function triggerCalendarActivity(string $action, array $calendarData, array $shares = [], array $changedProperties = []) { if (!isset($calendarData['principaluri'])) { return; } @@ -356,7 +348,7 @@ public function onCalendarUpdateShares(array $calendarData, array $shares, array * @param array[] $shares * @return bool */ - protected function isAlreadyShared($principal, $shares) { + protected function isAlreadyShared(string $principal, array $shares): bool { foreach ($shares as $share) { if ($principal === $share['href']) { return true; @@ -374,7 +366,7 @@ protected function isAlreadyShared($principal, $shares) { * @param array $properties * @param string $subject */ - protected function triggerActivityGroup($gid, IEvent $event, array $properties, $subject) { + protected function triggerActivityGroup(string $gid, IEvent $event, array $properties, string $subject) { $group = $this->groupManager->get($gid); if ($group instanceof IGroup) { @@ -396,7 +388,7 @@ protected function triggerActivityGroup($gid, IEvent $event, array $properties, * @param string $subject * @param string $subjectSelf */ - protected function triggerActivityUser($user, IEvent $event, array $properties, $subject, $subjectSelf = '') { + protected function triggerActivityUser(string $user, IEvent $event, array $properties, string $subject, string $subjectSelf = '') { $event->setAffectedUser($user) ->setSubject( $user === $event->getAuthor() && $subjectSelf ? $subjectSelf : $subject, @@ -421,7 +413,7 @@ protected function triggerActivityUser($user, IEvent $event, array $properties, * @param array $shares * @param array $objectData */ - public function onTouchCalendarObject($action, array $calendarData, array $shares, array $objectData) { + public function onTouchCalendarObject(string $action, array $calendarData, array $shares, array $objectData) { if (!isset($calendarData['principaluri'])) { return; } @@ -524,7 +516,7 @@ protected function getObjectNameAndType(array $objectData) { * @param array $shares * @return string[] */ - protected function getUsersForShares(array $shares) { + protected function getUsersForShares(array $shares): array { $users = $groups = []; foreach ($shares as $share) { $principal = explode('/', $share['{http://owncloud.org/ns}principal']); diff --git a/apps/dav/lib/CalDAV/Activity/Filter/Calendar.php b/apps/dav/lib/CalDAV/Activity/Filter/Calendar.php index 06258e3cf746b..858265b35477d 100644 --- a/apps/dav/lib/CalDAV/Activity/Filter/Calendar.php +++ b/apps/dav/lib/CalDAV/Activity/Filter/Calendar.php @@ -28,12 +28,8 @@ use OCP\IURLGenerator; class Calendar implements IFilter { - - /** @var IL10N */ - protected $l; - - /** @var IURLGenerator */ - protected $url; + protected IL10N $l; + protected IURLGenerator $url; public function __construct(IL10N $l, IURLGenerator $url) { $this->l = $l; diff --git a/apps/dav/lib/CalDAV/Activity/Filter/Todo.php b/apps/dav/lib/CalDAV/Activity/Filter/Todo.php index f727c10befe9f..dc4cd5eaf8edf 100644 --- a/apps/dav/lib/CalDAV/Activity/Filter/Todo.php +++ b/apps/dav/lib/CalDAV/Activity/Filter/Todo.php @@ -27,12 +27,8 @@ use OCP\IURLGenerator; class Todo implements IFilter { - - /** @var IL10N */ - protected $l; - - /** @var IURLGenerator */ - protected $url; + protected IL10N $l; + protected IURLGenerator $url; public function __construct(IL10N $l, IURLGenerator $url) { $this->l = $l; diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Base.php b/apps/dav/lib/CalDAV/Activity/Provider/Base.php index 7f70980a72b9f..1bc52f414aa04 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Base.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Base.php @@ -34,27 +34,16 @@ use OCP\IUserManager; abstract class Base implements IProvider { - - /** @var IUserManager */ - protected $userManager; - - /** @var string[] */ - protected $userDisplayNames = []; - - /** @var IGroupManager */ - protected $groupManager; + protected IUserManager $userManager; + protected IGroupManager $groupManager; + protected IURLGenerator $url; /** @var string[] */ - protected $groupDisplayNames = []; + protected array $userDisplayNames = []; - /** @var IURLGenerator */ - protected $url; + /** @var string[] */ + protected array $groupDisplayNames = []; - /** - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param IURLGenerator $urlGenerator - */ public function __construct(IUserManager $userManager, IGroupManager $groupManager, IURLGenerator $urlGenerator) { $this->userManager = $userManager; $this->groupManager = $groupManager; @@ -66,7 +55,7 @@ public function __construct(IUserManager $userManager, IGroupManager $groupManag * @param string $subject * @param array $parameters */ - protected function setSubjects(IEvent $event, $subject, array $parameters) { + protected function setSubjects(IEvent $event, string $subject, array $parameters) { $placeholders = $replacements = []; foreach ($parameters as $placeholder => $parameter) { $placeholders[] = '{' . $placeholder . '}'; @@ -82,7 +71,7 @@ protected function setSubjects(IEvent $event, $subject, array $parameters) { * @param IL10N $l * @return array */ - protected function generateCalendarParameter($data, IL10N $l) { + protected function generateCalendarParameter(array $data, IL10N $l): array { if ($data['uri'] === CalDavBackend::PERSONAL_CALENDAR_URI && $data['name'] === CalDavBackend::PERSONAL_CALENDAR_NAME) { return [ @@ -104,7 +93,7 @@ protected function generateCalendarParameter($data, IL10N $l) { * @param string $name * @return array */ - protected function generateLegacyCalendarParameter($id, $name) { + protected function generateLegacyCalendarParameter(int $id, string $name): array { return [ 'type' => 'calendar', 'id' => $id, @@ -116,7 +105,7 @@ protected function generateLegacyCalendarParameter($id, $name) { * @param string $uid * @return array */ - protected function generateUserParameter($uid) { + protected function generateUserParameter(string $uid): array { if (!isset($this->userDisplayNames[$uid])) { $this->userDisplayNames[$uid] = $this->getUserDisplayName($uid); } @@ -132,7 +121,7 @@ protected function generateUserParameter($uid) { * @param string $uid * @return string */ - protected function getUserDisplayName($uid) { + protected function getUserDisplayName(string $uid): string { $user = $this->userManager->get($uid); if ($user instanceof IUser) { return $user->getDisplayName(); @@ -144,7 +133,7 @@ protected function getUserDisplayName($uid) { * @param string $gid * @return array */ - protected function generateGroupParameter($gid) { + protected function generateGroupParameter(string $gid): array { if (!isset($this->groupDisplayNames[$gid])) { $this->groupDisplayNames[$gid] = $this->getGroupDisplayName($gid); } @@ -160,7 +149,7 @@ protected function generateGroupParameter($gid) { * @param string $gid * @return string */ - protected function getGroupDisplayName($gid) { + protected function getGroupDisplayName(string $gid): string { $group = $this->groupManager->get($gid); if ($group instanceof IGroup) { return $group->getDisplayName(); diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php b/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php index daab7806e4678..339c2c86219dc 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Calendar.php @@ -26,6 +26,7 @@ */ namespace OCA\DAV\CalDAV\Activity\Provider; +use InvalidArgumentException; use OCP\Activity\IEvent; use OCP\Activity\IEventMerger; use OCP\Activity\IManager; @@ -48,26 +49,11 @@ class Calendar extends Base { public const SUBJECT_UNSHARE_USER = 'calendar_user_unshare'; public const SUBJECT_UNSHARE_GROUP = 'calendar_group_unshare'; - /** @var IFactory */ - protected $languageFactory; + protected IFactory $languageFactory; + protected IL10N $l; + protected IManager $activityManager; + protected IEventMerger $eventMerger; - /** @var IL10N */ - protected $l; - - /** @var IManager */ - protected $activityManager; - - /** @var IEventMerger */ - protected $eventMerger; - - /** - * @param IFactory $languageFactory - * @param IURLGenerator $url - * @param IManager $activityManager - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param IEventMerger $eventMerger - */ public function __construct(IFactory $languageFactory, IURLGenerator $url, IManager $activityManager, IUserManager $userManager, IGroupManager $groupManager, IEventMerger $eventMerger) { parent::__construct($userManager, $groupManager, $url); $this->languageFactory = $languageFactory; @@ -80,12 +66,12 @@ public function __construct(IFactory $languageFactory, IURLGenerator $url, IMana * @param IEvent $event * @param IEvent|null $previousEvent * @return IEvent - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @since 11.0.0 */ public function parse($language, IEvent $event, IEvent $previousEvent = null) { if ($event->getApp() !== 'dav' || $event->getType() !== 'calendar') { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $this->l = $this->languageFactory->get('dav', $language); @@ -143,7 +129,7 @@ public function parse($language, IEvent $event, IEvent $previousEvent = null) { } elseif ($event->getSubject() === self::SUBJECT_UNSHARE_GROUP . '_by') { $subject = $this->l->t('{actor} unshared calendar {calendar} from group {group}'); } else { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $parsedParameters = $this->getParameters($event); @@ -168,7 +154,7 @@ public function parse($language, IEvent $event, IEvent $previousEvent = null) { * @param IEvent $event * @return array */ - protected function getParameters(IEvent $event) { + protected function getParameters(IEvent $event): array { $subject = $event->getSubject(); $parameters = $event->getSubjectParameters(); @@ -272,6 +258,6 @@ protected function getParameters(IEvent $event) { ]; } - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } } diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Event.php b/apps/dav/lib/CalDAV/Activity/Provider/Event.php index 96366f5494292..773eefc1efbc2 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Event.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Event.php @@ -26,6 +26,8 @@ */ namespace OCA\DAV\CalDAV\Activity\Provider; +use Exception; +use InvalidArgumentException; use OC_App; use OCP\Activity\IEvent; use OCP\Activity\IEventMerger; @@ -44,20 +46,11 @@ class Event extends Base { public const SUBJECT_OBJECT_RESTORE = 'object_restore'; public const SUBJECT_OBJECT_DELETE = 'object_delete'; - /** @var IFactory */ - protected $languageFactory; - - /** @var IL10N */ - protected $l; - - /** @var IManager */ - protected $activityManager; - - /** @var IEventMerger */ - protected $eventMerger; - - /** @var IAppManager */ - protected $appManager; + protected IFactory $languageFactory; + protected IL10N $l; + protected IManager $activityManager; + protected IEventMerger $eventMerger; + protected IAppManager $appManager; /** * @param IFactory $languageFactory @@ -80,9 +73,9 @@ public function __construct(IFactory $languageFactory, IURLGenerator $url, IMana * @param array $eventData * @return array */ - protected function generateObjectParameter(array $eventData) { + protected function generateObjectParameter(array $eventData): array { if (!isset($eventData['id']) || !isset($eventData['name'])) { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $params = [ @@ -105,7 +98,7 @@ protected function generateObjectParameter(array $eventData) { 'recurrenceId' => 'next' ]; $params['link'] = $this->url->linkToRouteAbsolute('calendar.view.indexview.timerange.edit', $link); - } catch (\Exception $error) { + } catch (Exception $error) { // Do nothing } } @@ -117,12 +110,12 @@ protected function generateObjectParameter(array $eventData) { * @param IEvent $event * @param IEvent|null $previousEvent * @return IEvent - * @throws \InvalidArgumentException + * @throws InvalidArgumentException * @since 11.0.0 */ public function parse($language, IEvent $event, IEvent $previousEvent = null) { if ($event->getApp() !== 'dav' || $event->getType() !== 'calendar_event') { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $this->l = $this->languageFactory->get('dav', $language); @@ -154,22 +147,20 @@ public function parse($language, IEvent $event, IEvent $previousEvent = null) { } elseif ($event->getSubject() === self::SUBJECT_OBJECT_RESTORE . '_event_self') { $subject = $this->l->t('You restored event {event} of calendar {calendar}'); } else { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $parsedParameters = $this->getParameters($event); $this->setSubjects($event, $subject, $parsedParameters); - $event = $this->eventMerger->mergeEvents('event', $event, $previousEvent); - - return $event; + return $this->eventMerger->mergeEvents('event', $event, $previousEvent); } /** * @param IEvent $event * @return array */ - protected function getParameters(IEvent $event) { + protected function getParameters(IEvent $event): array { $subject = $event->getSubject(); $parameters = $event->getSubjectParameters(); @@ -221,10 +212,10 @@ protected function getParameters(IEvent $event) { ]; } - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } - private function generateClassifiedObjectParameter(array $eventData) { + private function generateClassifiedObjectParameter(array $eventData): array { $parameter = $this->generateObjectParameter($eventData); if (!empty($eventData['classified'])) { $parameter['name'] = $this->l->t('Busy'); diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Todo.php b/apps/dav/lib/CalDAV/Activity/Provider/Todo.php index a3ab81e38ae38..4a35f56dea562 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Todo.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Todo.php @@ -24,21 +24,14 @@ */ namespace OCA\DAV\CalDAV\Activity\Provider; +use InvalidArgumentException; use OCP\Activity\IEvent; class Todo extends Event { - /** - * @param string $language - * @param IEvent $event - * @param IEvent|null $previousEvent - * @return IEvent - * @throws \InvalidArgumentException - * @since 11.0.0 - */ public function parse($language, IEvent $event, IEvent $previousEvent = null) { if ($event->getApp() !== 'dav' || $event->getType() !== 'calendar_todo') { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $this->l = $this->languageFactory->get('dav', $language); @@ -70,22 +63,20 @@ public function parse($language, IEvent $event, IEvent $previousEvent = null) { } elseif ($event->getSubject() === self::SUBJECT_OBJECT_UPDATE . '_todo_needs_action_self') { $subject = $this->l->t('You reopened todo {todo} in list {calendar}'); } else { - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } $parsedParameters = $this->getParameters($event); $this->setSubjects($event, $subject, $parsedParameters); - $event = $this->eventMerger->mergeEvents('todo', $event, $previousEvent); - - return $event; + return $this->eventMerger->mergeEvents('todo', $event, $previousEvent); } /** * @param IEvent $event * @return array */ - protected function getParameters(IEvent $event) { + protected function getParameters(IEvent $event): array { $subject = $event->getSubject(); $parameters = $event->getSubjectParameters(); @@ -141,6 +132,6 @@ protected function getParameters(IEvent $event) { ]; } - throw new \InvalidArgumentException(); + throw new InvalidArgumentException(); } } diff --git a/apps/dav/lib/CalDAV/Activity/Setting/CalDAVSetting.php b/apps/dav/lib/CalDAV/Activity/Setting/CalDAVSetting.php index 20325a253f4f1..82143ea4d21ab 100644 --- a/apps/dav/lib/CalDAV/Activity/Setting/CalDAVSetting.php +++ b/apps/dav/lib/CalDAV/Activity/Setting/CalDAVSetting.php @@ -30,12 +30,8 @@ use OCP\IL10N; abstract class CalDAVSetting extends ActivitySettings { - /** @var IL10N */ - protected $l; + protected IL10N $l; - /** - * @param IL10N $l - */ public function __construct(IL10N $l) { $this->l = $l; } diff --git a/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php b/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php index b736d9432bd14..7def73e8a3f9d 100644 --- a/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php +++ b/apps/dav/lib/CalDAV/BirthdayCalendar/EnablePlugin.php @@ -27,10 +27,14 @@ use OCA\DAV\CalDAV\BirthdayService; use OCA\DAV\CalDAV\CalendarHome; use OCP\IConfig; +use OCP\PreConditionNotMetException; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; +use Sabre\Xml\ParseException; /** * Class EnablePlugin @@ -41,27 +45,10 @@ class EnablePlugin extends ServerPlugin { public const NS_Nextcloud = 'http://nextcloud.com/ns'; - /** - * @var IConfig - */ - protected $config; - - /** - * @var BirthdayService - */ - protected $birthdayService; + protected IConfig $config; + protected BirthdayService $birthdayService; + protected Server $server; - /** - * @var Server - */ - protected $server; - - /** - * PublishPlugin constructor. - * - * @param IConfig $config - * @param BirthdayService $birthdayService - */ public function __construct(IConfig $config, BirthdayService $birthdayService) { $this->config = $config; $this->birthdayService = $birthdayService; @@ -114,6 +101,10 @@ public function initialize(Server $server) { * @param ResponseInterface $response * * @return bool|void + * @throws PreConditionNotMetException + * @throws NotFound + * @throws ParseException + * @throws BadRequest */ public function httpPost(RequestInterface $request, ResponseInterface $response) { $node = $this->server->tree->getNodeForPath($this->server->getRequestUri()); diff --git a/apps/dav/lib/CalDAV/BirthdayService.php b/apps/dav/lib/CalDAV/BirthdayService.php index bdcf0796283ef..1e448b2ac88f1 100644 --- a/apps/dav/lib/CalDAV/BirthdayService.php +++ b/apps/dav/lib/CalDAV/BirthdayService.php @@ -38,6 +38,8 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\IL10N; +use Sabre\DAV\Exception\BadRequest; +use Sabre\DAV\Exception\Forbidden; use Sabre\VObject\Component\VCalendar; use Sabre\VObject\Component\VCard; use Sabre\VObject\DateTimeParser; @@ -45,6 +47,8 @@ use Sabre\VObject\InvalidDataException; use Sabre\VObject\Property\VCard\DateAndOrTime; use Sabre\VObject\Reader; +use Sabre\VObject\Recur\MaxInstancesExceededException; +use Sabre\VObject\Recur\NoInstancesException; /** * Class BirthdayService @@ -53,35 +57,13 @@ */ class BirthdayService { public const BIRTHDAY_CALENDAR_URI = 'contact_birthdays'; + private GroupPrincipalBackend $principalBackend; + private CalDavBackend $calDavBackEnd; + private CardDavBackend $cardDavBackEnd; + private IConfig $config; + private IDBConnection $dbConnection; + private IL10N $l10n; - /** @var GroupPrincipalBackend */ - private $principalBackend; - - /** @var CalDavBackend */ - private $calDavBackEnd; - - /** @var CardDavBackend */ - private $cardDavBackEnd; - - /** @var IConfig */ - private $config; - - /** @var IDBConnection */ - private $dbConnection; - - /** @var IL10N */ - private $l10n; - - /** - * BirthdayService constructor. - * - * @param CalDavBackend $calDavBackEnd - * @param CardDavBackend $cardDavBackEnd - * @param GroupPrincipalBackend $principalBackend - * @param IConfig $config - * @param IDBConnection $dbConnection - * @param IL10N $l10n - */ public function __construct(CalDavBackend $calDavBackEnd, CardDavBackend $cardDavBackEnd, GroupPrincipalBackend $principalBackend, @@ -100,6 +82,13 @@ public function __construct(CalDavBackend $calDavBackEnd, * @param int $addressBookId * @param string $cardUri * @param string $cardData + * @throws BadRequest + * @throws Forbidden + * @throws InvalidDataException + * @throws MaxInstancesExceededException + * @throws NoInstancesException + * @throws \OCP\DB\Exception + * @throws \Sabre\DAV\Exception */ public function onCardChanged(int $addressBookId, string $cardUri, @@ -132,6 +121,10 @@ public function onCardChanged(int $addressBookId, /** * @param int $addressBookId * @param string $cardUri + * @throws BadRequest + * @throws \OCP\DB\Exception + * @throws Forbidden + * @throws \Sabre\DAV\Exception */ public function onCardDeleted(int $addressBookId, string $cardUri) { @@ -158,7 +151,8 @@ public function onCardDeleted(int $addressBookId, /** * @param string $principal * @return array|null - * @throws \Sabre\DAV\Exception\BadRequest + * @throws BadRequest| + * @throws \Sabre\DAV\Exception */ public function ensureCalendarExists(string $principal):?array { $calendar = $this->calDavBackEnd->getCalendarByUri($principal, self::BIRTHDAY_CALENDAR_URI); @@ -175,10 +169,6 @@ public function ensureCalendarExists(string $principal):?array { } /** - * @param $cardData - * @param $dateField - * @param $postfix - * @return VCalendar|null * @throws InvalidDataException */ public function buildDateFromContact(string $cardData, @@ -299,6 +289,7 @@ public function buildDateFromContact(string $cardData, /** * @param string $user + * @throws Forbidden */ public function resetForUser(string $user):void { $principal = 'principals/users/'.$user; @@ -312,7 +303,13 @@ public function resetForUser(string $user):void { /** * @param string $user - * @throws \Sabre\DAV\Exception\BadRequest + * @throws BadRequest + * @throws Forbidden + * @throws InvalidDataException + * @throws MaxInstancesExceededException + * @throws NoInstancesException + * @throws \OCP\DB\Exception + * @throws \Sabre\DAV\Exception */ public function syncUser(string $user):void { $principal = 'principals/users/'.$user; @@ -347,9 +344,10 @@ public function birthdayEvenChanged(string $existingCalendarData, /** * @param integer $addressBookId - * @return mixed + * @return string[] + * @throws \Sabre\DAV\Exception */ - protected function getAllAffectedPrincipals(int $addressBookId) { + protected function getAllAffectedPrincipals(int $addressBookId): array { $targetPrincipals = []; $shares = $this->cardDavBackEnd->getShares($addressBookId); foreach ($shares as $share) { @@ -371,8 +369,11 @@ protected function getAllAffectedPrincipals(int $addressBookId) { * @param array $book * @param int $calendarId * @param array $type + * @throws BadRequest + * @throws Forbidden * @throws InvalidDataException - * @throws \Sabre\DAV\Exception\BadRequest + * @throws MaxInstancesExceededException + * @throws NoInstancesException */ private function updateCalendar(string $cardUri, string $cardData, diff --git a/apps/dav/lib/CalDAV/CachedSubscription.php b/apps/dav/lib/CalDAV/CachedSubscription.php index 18e61450ee9b6..0d80006b3c3de 100644 --- a/apps/dav/lib/CalDAV/CachedSubscription.php +++ b/apps/dav/lib/CalDAV/CachedSubscription.php @@ -29,6 +29,7 @@ use OCA\DAV\Exception\UnsupportedLimitOnInitialSyncException; use Sabre\CalDAV\Backend\BackendInterface; +use Sabre\CalDAV\Plugin; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\PropPatch; @@ -111,7 +112,7 @@ public function getOwner() { return parent::getOwner(); } - + public function delete() { $this->caldavBackend->deleteSubscription($this->calendarInfo['id']); } @@ -125,7 +126,7 @@ public function propPatch(PropPatch $propPatch) { /** * @param string $name - * @return CalendarObject|\Sabre\CalDAV\ICalendarObject + * @return CachedSubscriptionObject * @throws NotFound */ public function getChild($name) { diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 4610e381275f7..1710f471d0e61 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -95,6 +95,8 @@ use Sabre\VObject\Property; use Sabre\VObject\Reader; use Sabre\VObject\Recur\EventIterator; +use Sabre\VObject\Recur\MaxInstancesExceededException; +use Sabre\VObject\Recur\NoInstancesException; use function array_merge; use function array_values; use function explode; @@ -147,7 +149,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * * @var array */ - public $propertyMap = [ + public array $propertyMap = [ '{DAV:}displayname' => 'displayname', '{urn:ietf:params:xml:ns:caldav}calendar-description' => 'description', '{urn:ietf:params:xml:ns:caldav}calendar-timezone' => 'timezone', @@ -161,7 +163,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription * * @var array */ - public $subscriptionPropertyMap = [ + public array $subscriptionPropertyMap = [ '{DAV:}displayname' => 'displayname', '{http://apple.com/ns/ical/}refreshrate' => 'refreshrate', '{http://apple.com/ns/ical/}calendar-order' => 'calendarorder', @@ -192,7 +194,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription ]; /** @var array parameters to index */ - public static $indexParameters = [ + public static array $indexParameters = [ 'ATTENDEE' => ['CN'], 'ORGANIZER' => ['CN'], ]; @@ -200,50 +202,19 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription /** * @var string[] Map of uid => display name */ - protected $userDisplayNames; + protected array $userDisplayNames; + + private IDBConnection $db; + private Backend $calendarSharingBackend; + private Principal $principalBackend; + private IUserManager $userManager; + private ISecureRandom $random; + private LoggerInterface $logger; + private IEventDispatcher $dispatcher; + private IConfig $config; + private bool $legacyEndpoint; + private string $dbObjectPropertiesTable = 'calendarobjects_props'; - /** @var IDBConnection */ - private $db; - - /** @var Backend */ - private $calendarSharingBackend; - - /** @var Principal */ - private $principalBackend; - - /** @var IUserManager */ - private $userManager; - - /** @var ISecureRandom */ - private $random; - - /** @var LoggerInterface */ - private $logger; - - /** @var IEventDispatcher */ - private $dispatcher; - - /** @var IConfig */ - private $config; - - /** @var bool */ - private $legacyEndpoint; - - /** @var string */ - private $dbObjectPropertiesTable = 'calendarobjects_props'; - - /** - * CalDavBackend constructor. - * - * @param IDBConnection $db - * @param Principal $principalBackend - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param ISecureRandom $random - * @param LoggerInterface $logger - * @param IEventDispatcher $dispatcher - * @param bool $legacyEndpoint - */ public function __construct(IDBConnection $db, Principal $principalBackend, IUserManager $userManager, @@ -269,11 +240,8 @@ public function __construct(IDBConnection $db, * * By default this excludes the automatically generated birthday calendar * - * @param $principalUri - * @param bool $excludeBirthday - * @return int */ - public function getCalendarsForUserCount($principalUri, $excludeBirthday = true) { + public function getCalendarsForUserCount(string $principalUri, bool $excludeBirthday = true): int { $principalUri = $this->convertPrincipal($principalUri, true); $query = $this->db->getQueryBuilder(); $query->select($query->func()->count('*')) @@ -1263,6 +1231,9 @@ public function getMultipleCalendarObjects($calendarId, array $uris, $calendarTy * @param string $calendarData * @param int $calendarType * @return string + * @throws BadRequest + * @throws MaxInstancesExceededException + * @throws NoInstancesException */ public function createCalendarObject($calendarId, $objectUri, $calendarData, $calendarType = self::CALENDAR_TYPE_CALENDAR) { $extraData = $this->getDenormalizedData($calendarData); @@ -1739,7 +1710,7 @@ public function calendarQuery($calendarId, array $filters, $calendarType = self: * @param integer|null $offset * @return array */ - public function calendarSearch($principalUri, array $filters, $limit = null, $offset = null) { + public function calendarSearch(string $principalUri, array $filters, int $limit = null, int $offset = null): array { $calendars = $this->getCalendarsForUser($principalUri); $ownCalendars = []; $sharedCalendars = []; @@ -2754,8 +2725,11 @@ protected function addChange($calendarId, $objectUri, $operation, $calendarType * * @param string $calendarData * @return array + * @throws NoInstancesException + * @throws MaxInstancesExceededException + * @throws BadRequest */ - public function getDenormalizedData($calendarData) { + public function getDenormalizedData(string $calendarData): array { $vObject = Reader::read($calendarData); $vEvents = []; $componentType = null; @@ -2769,7 +2743,7 @@ public function getDenormalizedData($calendarData) { if ($component->name !== 'VTIMEZONE') { // Finding all VEVENTs, and track them if ($component->name === 'VEVENT') { - array_push($vEvents, $component); + $vEvents[] = $component; if ($component->DTSTART) { $hasDTSTART = true; } @@ -2880,10 +2854,10 @@ public function getShares($resourceId) { /** * @param boolean $value - * @param \OCA\DAV\CalDAV\Calendar $calendar + * @param Calendar $calendar * @return string|null */ - public function setPublishStatus($value, $calendar) { + public function setPublishStatus(bool $value, Calendar $calendar): ?string { $calendarId = $calendar->getResourceId(); $calendarData = $this->getCalendarById($calendarId); @@ -2913,10 +2887,10 @@ public function setPublishStatus($value, $calendar) { } /** - * @param \OCA\DAV\CalDAV\Calendar $calendar + * @param Calendar $calendar * @return mixed */ - public function getPublishStatus($calendar) { + public function getPublishStatus(Calendar $calendar): bool { $query = $this->db->getQueryBuilder(); $result = $query->select('publicuri') ->from('dav_shares') @@ -2934,7 +2908,7 @@ public function getPublishStatus($calendar) { * @param array $acl * @return array */ - public function applyShareAcl($resourceId, $acl) { + public function applyShareAcl(int $resourceId, array $acl) { return $this->calendarSharingBackend->applyShareAcl($resourceId, $acl); } diff --git a/apps/dav/lib/CalDAV/Calendar.php b/apps/dav/lib/CalDAV/Calendar.php index 75c815c3b0adb..5b2f3b244d5ae 100644 --- a/apps/dav/lib/CalDAV/Calendar.php +++ b/apps/dav/lib/CalDAV/Calendar.php @@ -51,27 +51,11 @@ * @property CalDavBackend $caldavBackend */ class Calendar extends \Sabre\CalDAV\Calendar implements IRestorable, IShareable, IMoveTarget { + private IConfig $config; + protected IL10N $l10n; + private bool $useTrashbin = true; + private LoggerInterface $logger; - /** @var IConfig */ - private $config; - - /** @var IL10N */ - protected $l10n; - - /** @var bool */ - private $useTrashbin = true; - - /** @var LoggerInterface */ - private $logger; - - /** - * Calendar constructor. - * - * @param BackendInterface $caldavBackend - * @param $calendarInfo - * @param IL10N $l10n - * @param IConfig $config - */ public function __construct(BackendInterface $caldavBackend, $calendarInfo, IL10N $l10n, IConfig $config, LoggerInterface $logger) { // Convert deletion date to ISO8601 string if (isset($calendarInfo[TrashbinPlugin::PROPERTY_DELETED_AT])) { @@ -140,17 +124,11 @@ public function getShares() { return $this->caldavBackend->getShares($this->getResourceId()); } - /** - * @return int - */ - public function getResourceId() { + public function getResourceId(): int { return $this->calendarInfo['id']; } - /** - * @return string - */ - public function getPrincipalURI() { + public function getPrincipalURI(): string { return $this->calendarInfo['principaluri']; } @@ -372,20 +350,17 @@ public function calendarQuery(array $filters) { * @param boolean $value * @return string|null */ - public function setPublishStatus($value) { + public function setPublishStatus(bool $value): ?string { $publicUri = $this->caldavBackend->setPublishStatus($value, $this); $this->calendarInfo['publicuri'] = $publicUri; return $publicUri; } - /** - * @return mixed $value - */ - public function getPublishStatus() { + public function getPublishStatus(): bool { return $this->caldavBackend->getPublishStatus($this); } - public function canWrite() { + public function canWrite(): bool { if ($this->getName() === BirthdayService::BIRTHDAY_CALENDAR_URI) { return false; } @@ -396,11 +371,11 @@ public function canWrite() { return true; } - private function isPublic() { + private function isPublic(): bool { return isset($this->calendarInfo['{http://owncloud.org/ns}public']); } - protected function isShared() { + protected function isShared(): bool { if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) { return false; } @@ -408,7 +383,7 @@ protected function isShared() { return $this->calendarInfo['{http://owncloud.org/ns}owner-principal'] !== $this->calendarInfo['principaluri']; } - public function isSubscription() { + public function isSubscription(): bool { return isset($this->calendarInfo['{http://calendarserver.org/ns/}source']); } diff --git a/apps/dav/lib/CalDAV/CalendarHome.php b/apps/dav/lib/CalDAV/CalendarHome.php index bb1ca6e2da808..126ad8db7348b 100644 --- a/apps/dav/lib/CalDAV/CalendarHome.php +++ b/apps/dav/lib/CalDAV/CalendarHome.php @@ -33,11 +33,13 @@ use Psr\Log\LoggerInterface; use OCP\App\IAppManager; use OCP\IConfig; +use OCP\IL10N; use OCP\L10N\IFactory; use Sabre\CalDAV\Backend\BackendInterface; use Sabre\CalDAV\Backend\NotificationSupport; use Sabre\CalDAV\Backend\SchedulingSupport; use Sabre\CalDAV\Backend\SubscriptionSupport; +use Sabre\CalDAV\Notifications\Collection; use Sabre\CalDAV\Schedule\Inbox; use Sabre\CalDAV\Subscriptions\Subscription; use Sabre\DAV\Exception\MethodNotAllowed; @@ -46,18 +48,10 @@ use Sabre\DAV\MkCol; class CalendarHome extends \Sabre\CalDAV\CalendarHome { - - /** @var \OCP\IL10N */ - private $l10n; - - /** @var \OCP\IConfig */ - private $config; - - /** @var PluginManager */ - private $pluginManager; - - /** @var bool */ - private $returnCachedSubscriptions = false; + private IL10N $l10n; + private IConfig $config; + private PluginManager $pluginManager; + private bool $returnCachedSubscriptions = false; /** @var LoggerInterface */ private $logger; @@ -73,10 +67,7 @@ public function __construct(BackendInterface $caldavBackend, $principalInfo, Log $this->logger = $logger; } - /** - * @return BackendInterface - */ - public function getCalDAVBackend() { + public function getCalDAVBackend(): BackendInterface { return $this->caldavBackend; } @@ -113,7 +104,7 @@ public function getChildren() { // We're adding a notifications node, if it's supported by the backend. if ($this->caldavBackend instanceof NotificationSupport) { - $objects[] = new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']); + $objects[] = new Collection($this->caldavBackend, $this->principalInfo['uri']); } if ($this->caldavBackend instanceof CalDavBackend) { @@ -132,7 +123,6 @@ public function getChildren() { } foreach ($this->pluginManager->getCalendarPlugins() as $calendarPlugin) { - /** @var ICalendarProvider $calendarPlugin */ $calendars = $calendarPlugin->fetchAllForCalendarHome($this->principalInfo['uri']); foreach ($calendars as $calendar) { $objects[] = $calendar; @@ -156,7 +146,7 @@ public function getChild($name) { return new Outbox($this->config, $this->principalInfo['uri']); } if ($name === 'notifications' && $this->caldavBackend instanceof NotificationSupport) { - return new \Sabre\CalDAV\Notifications\Collection($this->caldavBackend, $this->principalInfo['uri']); + return new Collection($this->caldavBackend, $this->principalInfo['uri']); } if ($name === TrashbinHome::NAME && $this->caldavBackend instanceof CalDavBackend) { return new TrashbinHome($this->caldavBackend, $this->principalInfo); @@ -185,7 +175,6 @@ public function getChild($name) { [$appId, $calendarUri] = ExternalCalendar::splitAppGeneratedCalendarUri($name); foreach ($this->pluginManager->getCalendarPlugins() as $calendarPlugin) { - /** @var ICalendarProvider $calendarPlugin */ if ($calendarPlugin->getAppId() !== $appId) { continue; } @@ -204,7 +193,7 @@ public function getChild($name) { * @param integer|null $limit * @param integer|null $offset */ - public function calendarSearch(array $filters, $limit = null, $offset = null) { + public function calendarSearch(array $filters, int $limit = null, int $offset = null): array { $principalUri = $this->principalInfo['uri']; return $this->caldavBackend->calendarSearch($principalUri, $filters, $limit, $offset); } diff --git a/apps/dav/lib/CalDAV/CalendarImpl.php b/apps/dav/lib/CalDAV/CalendarImpl.php index 406389e3a3dcc..ea23f6d4851ce 100644 --- a/apps/dav/lib/CalDAV/CalendarImpl.php +++ b/apps/dav/lib/CalDAV/CalendarImpl.php @@ -36,23 +36,10 @@ use function Sabre\Uri\split as uriSplit; class CalendarImpl implements ICreateFromString { + private CalDavBackend $backend; + private Calendar $calendar; + private array $calendarInfo; - /** @var CalDavBackend */ - private $backend; - - /** @var Calendar */ - private $calendar; - - /** @var array */ - private $calendarInfo; - - /** - * CalendarImpl constructor. - * - * @param Calendar $calendar - * @param array $calendarInfo - * @param CalDavBackend $backend - */ public function __construct(Calendar $calendar, array $calendarInfo, CalDavBackend $backend) { @@ -65,7 +52,7 @@ public function __construct(Calendar $calendar, * @return string defining the technical unique key * @since 13.0.0 */ - public function getKey() { + public function getKey(): string { return $this->calendarInfo['id']; } @@ -81,7 +68,7 @@ public function getUri(): string { * @return null|string * @since 13.0.0 */ - public function getDisplayName() { + public function getDisplayName(): ?string { return $this->calendarInfo['{DAV:}displayname']; } @@ -90,7 +77,7 @@ public function getDisplayName() { * @return null|string * @since 13.0.0 */ - public function getDisplayColor() { + public function getDisplayColor(): ?string { return $this->calendarInfo['{http://apple.com/ns/ical/}calendar-color']; } @@ -104,7 +91,7 @@ public function getDisplayColor() { * @return array an array of events/journals/todos which are arrays of key-value-pairs * @since 13.0.0 */ - public function search($pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null) { + public function search(string $pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null): array { return $this->backend->search($this->calendarInfo, $pattern, $searchProperties, $options, $limit, $offset); } @@ -113,7 +100,7 @@ public function search($pattern, array $searchProperties = [], array $options = * @return integer build up using \OCP\Constants * @since 13.0.0 */ - public function getPermissions() { + public function getPermissions(): int { $permissions = $this->calendar->getACL(); $result = 0; foreach ($permissions as $permission) { diff --git a/apps/dav/lib/CalDAV/CalendarManager.php b/apps/dav/lib/CalDAV/CalendarManager.php index daa96a5139202..2b4b041c0ccaa 100644 --- a/apps/dav/lib/CalDAV/CalendarManager.php +++ b/apps/dav/lib/CalDAV/CalendarManager.php @@ -30,15 +30,9 @@ use Psr\Log\LoggerInterface; class CalendarManager { - - /** @var CalDavBackend */ - private $backend; - - /** @var IL10N */ - private $l10n; - - /** @var IConfig */ - private $config; + private CalDavBackend $backend; + private IL10N $l10n; + private IConfig $config; /** @var LoggerInterface */ private $logger; @@ -61,7 +55,7 @@ public function __construct(CalDavBackend $backend, IL10N $l10n, IConfig $config * @param IManager $cm * @param string $userId */ - public function setupCalendarProvider(IManager $cm, $userId) { + public function setupCalendarProvider(IManager $cm, string $userId) { $calendars = $this->backend->getCalendarsForUser("principals/users/$userId"); $this->register($cm, $calendars); } diff --git a/apps/dav/lib/CalDAV/CalendarObject.php b/apps/dav/lib/CalDAV/CalendarObject.php index c927254fba369..4f1e9f6e9c097 100644 --- a/apps/dav/lib/CalDAV/CalendarObject.php +++ b/apps/dav/lib/CalDAV/CalendarObject.php @@ -32,9 +32,7 @@ use Sabre\VObject\Reader; class CalendarObject extends \Sabre\CalDAV\CalendarObject { - - /** @var IL10N */ - protected $l10n; + protected IL10N $l10n; /** * CalendarObject constructor. @@ -85,7 +83,7 @@ public function getId(): int { return (int) $this->objectData['id']; } - protected function isShared() { + protected function isShared(): bool { if (!isset($this->calendarInfo['{http://owncloud.org/ns}owner-principal'])) { return false; } @@ -148,7 +146,7 @@ private function removeVAlarms(Component\VCalendar $vObject) { /** * @return bool */ - private function canWrite() { + private function canWrite(): bool { if (isset($this->calendarInfo['{http://owncloud.org/ns}read-only'])) { return !$this->calendarInfo['{http://owncloud.org/ns}read-only']; } diff --git a/apps/dav/lib/CalDAV/CalendarProvider.php b/apps/dav/lib/CalDAV/CalendarProvider.php index f29c601db2d27..19a6b2e658a82 100644 --- a/apps/dav/lib/CalDAV/CalendarProvider.php +++ b/apps/dav/lib/CalDAV/CalendarProvider.php @@ -31,15 +31,9 @@ use Psr\Log\LoggerInterface; class CalendarProvider implements ICalendarProvider { - - /** @var CalDavBackend */ - private $calDavBackend; - - /** @var IL10N */ - private $l10n; - - /** @var IConfig */ - private $config; + private CalDavBackend $calDavBackend; + private IL10N $l10n; + private IConfig $config; /** @var LoggerInterface */ private $logger; diff --git a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php index fa5a418603436..2133b076f1553 100644 --- a/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php +++ b/apps/dav/lib/CalDAV/ICSExportPlugin/ICSExportPlugin.php @@ -35,21 +35,10 @@ * @package OCA\DAV\CalDAV\ICSExportPlugin */ class ICSExportPlugin extends \Sabre\CalDAV\ICSExportPlugin { - - /** @var IConfig */ - private $config; - - /** @var LoggerInterface */ - private $logger; - - /** @var string */ + private IConfig $config; + private LoggerInterface $logger; private const DEFAULT_REFRESH_INTERVAL = 'PT4H'; - /** - * ICSExportPlugin constructor. - * - * @param IConfig $config - */ public function __construct(IConfig $config, LoggerInterface $logger) { $this->config = $config; $this->logger = $logger; @@ -64,7 +53,7 @@ protected function generateResponse($path, $start, $end, $expand, $componentType $properties['{http://nextcloud.com/ns}refresh-interval'] = $value; } - return parent::generateResponse($path, $start, $end, $expand, $componentType, $format, $properties, $response); + parent::generateResponse($path, $start, $end, $expand, $componentType, $format, $properties, $response); } /** diff --git a/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php b/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php index 9c801a08a260d..87768bd9a05c9 100644 --- a/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php +++ b/apps/dav/lib/CalDAV/Integration/ExternalCalendar.php @@ -49,11 +49,8 @@ abstract class ExternalCalendar implements CalDAV\ICalendar, DAV\IProperties { */ private const DELIMITER = '--'; - /** @var string */ - private $appId; - - /** @var string */ - private $calendarUri; + private string $appId; + private string $calendarUri; /** * ExternalCalendar constructor. diff --git a/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php b/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php index 1e35c2f613348..c55ab7181124d 100644 --- a/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php +++ b/apps/dav/lib/CalDAV/InvitationResponse/InvitationResponseServer.php @@ -25,13 +25,19 @@ */ namespace OCA\DAV\CalDAV\InvitationResponse; +use OC; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\Auth\CustomPrincipalPlugin; use OCA\DAV\CalDAV\Auth\PublicPrincipalPlugin; +use OCA\DAV\CalDAV\Plugin as CalDAVPlugin; +use OCA\DAV\CalDAV\Publishing\PublishPlugin; +use OCA\DAV\CalDAV\Schedule\Plugin as SchedulePlugin; use OCA\DAV\Connector\Sabre\AnonymousOptionsPlugin; use OCA\DAV\Connector\Sabre\BlockLegacyClientPlugin; use OCA\DAV\Connector\Sabre\CachingTree; use OCA\DAV\Connector\Sabre\DavAclPlugin; +use OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin; +use OCA\DAV\Connector\Sabre\LockPlugin; use OCA\DAV\Connector\Sabre\MaintenancePlugin; use OCA\DAV\Connector\Sabre\Server; use OCA\DAV\Events\SabrePluginAuthInitEvent; @@ -42,33 +48,39 @@ use OCP\IURLGenerator; use OCP\L10N\IFactory; use Psr\Log\LoggerInterface; +use Sabre\CalDAV\ICSExportPlugin; +use Sabre\CalDAV\Notifications\Plugin as NotificationsPlugin; +use Sabre\CalDAV\Subscriptions\Plugin as SubscriptionsPlugin; +use Sabre\DAV\Exception; +use Sabre\DAV\Sync\Plugin as SyncPlugin; +use Sabre\DAVACL\Plugin; use Sabre\VObject\ITip\Message; class InvitationResponseServer { - - /** @var Server */ - public $server; + public Server $server; /** * InvitationResponseServer constructor. + * + * @throws Exception */ public function __construct(bool $public = true) { - $baseUri = \OC::$WEBROOT . '/remote.php/dav/'; - $logger = \OC::$server->get(LoggerInterface::class); + $baseUri = OC::$WEBROOT . '/remote.php/dav/'; + $logger = OC::$server->get(LoggerInterface::class); /** @var IEventDispatcher $dispatcher */ - $dispatcher = \OC::$server->get(IEventDispatcher::class); + $dispatcher = OC::$server->get(IEventDispatcher::class); $root = new RootCollection(); $this->server = new Server(new CachingTree($root)); // Add maintenance plugin - $this->server->addPlugin(new MaintenancePlugin(\OC::$server->get(IConfig::class), \OC::$server->get(IFactory::class)->get('dav'))); + $this->server->addPlugin(new MaintenancePlugin(OC::$server->get(IConfig::class), OC::$server->get(IFactory::class)->get('dav'))); // Set URL explicitly due to reverse-proxy situations $this->server->httpRequest->setUrl($baseUri); $this->server->setBaseUri($baseUri); - $this->server->addPlugin(new BlockLegacyClientPlugin(\OC::$server->get(IConfig::class))); + $this->server->addPlugin(new BlockLegacyClientPlugin(OC::$server->get(IConfig::class))); $this->server->addPlugin(new AnonymousOptionsPlugin()); // allow custom principal uri option @@ -82,9 +94,9 @@ public function __construct(bool $public = true) { $event = new SabrePluginAuthInitEvent($this->server); $dispatcher->dispatchTyped($event); - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\ExceptionLoggerPlugin('webdav', $logger)); - $this->server->addPlugin(new \OCA\DAV\Connector\Sabre\LockPlugin()); - $this->server->addPlugin(new \Sabre\DAV\Sync\Plugin()); + $this->server->addPlugin(new ExceptionLoggerPlugin('webdav', $logger)); + $this->server->addPlugin(new LockPlugin()); + $this->server->addPlugin(new SyncPlugin()); // acl $acl = new DavAclPlugin(); @@ -94,23 +106,23 @@ public function __construct(bool $public = true) { $this->server->addPlugin($acl); // calendar plugins - $this->server->addPlugin(new \OCA\DAV\CalDAV\Plugin()); - $this->server->addPlugin(new \Sabre\CalDAV\ICSExportPlugin()); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Schedule\Plugin(\OC::$server->get(IConfig::class))); - $this->server->addPlugin(new \Sabre\CalDAV\Subscriptions\Plugin()); - $this->server->addPlugin(new \Sabre\CalDAV\Notifications\Plugin()); + $this->server->addPlugin(new CalDAVPlugin()); + $this->server->addPlugin(new ICSExportPlugin()); + $this->server->addPlugin(new SchedulePlugin(OC::$server->get(IConfig::class))); + $this->server->addPlugin(new SubscriptionsPlugin()); + $this->server->addPlugin(new NotificationsPlugin()); //$this->server->addPlugin(new \OCA\DAV\DAV\Sharing\Plugin($authBackend, \OC::$server->getRequest())); - $this->server->addPlugin(new \OCA\DAV\CalDAV\Publishing\PublishPlugin( - \OC::$server->get(IConfig::class), - \OC::$server->get(IURLGenerator::class) + $this->server->addPlugin(new PublishPlugin( + OC::$server->get(IConfig::class), + OC::$server->get(IURLGenerator::class) )); // wait with registering these until auth is handled and the filesystem is setup $this->server->on('beforeMethod:*', function () use ($root) { // register plugins from apps $pluginManager = new PluginManager( - \OC::$server, - \OC::$server->get(IAppManager::class) + OC::$server, + OC::$server->get(IAppManager::class) ); foreach ($pluginManager->getAppPlugins() as $appPlugin) { $this->server->addPlugin($appPlugin); @@ -126,13 +138,13 @@ public function __construct(bool $public = true) { * @return void */ public function handleITipMessage(Message $iTipMessage) { - /** @var \OCA\DAV\CalDAV\Schedule\Plugin $schedulingPlugin */ + /** @var SchedulePlugin $schedulingPlugin */ $schedulingPlugin = $this->server->getPlugin('caldav-schedule'); $schedulingPlugin->scheduleLocalDelivery($iTipMessage); } public function isExternalAttendee(string $principalUri): bool { - /** @var \Sabre\DAVACL\Plugin $aclPlugin */ + /** @var Plugin $aclPlugin */ $aclPlugin = $this->server->getPlugin('acl'); return $aclPlugin->getPrincipalByUri($principalUri) === null; } diff --git a/apps/dav/lib/CalDAV/Outbox.php b/apps/dav/lib/CalDAV/Outbox.php index eebb48e1294e7..3d1947e480fbf 100644 --- a/apps/dav/lib/CalDAV/Outbox.php +++ b/apps/dav/lib/CalDAV/Outbox.php @@ -32,12 +32,8 @@ * @package OCA\DAV\CalDAV */ class Outbox extends \Sabre\CalDAV\Schedule\Outbox { - - /** @var IConfig */ - private $config; - - /** @var null|bool */ - private $disableFreeBusy = null; + private IConfig $config; + private ?bool $disableFreeBusy = null; /** * Outbox constructor. diff --git a/apps/dav/lib/CalDAV/Principal/Collection.php b/apps/dav/lib/CalDAV/Principal/Collection.php index 279977416093c..0064d1bc181d8 100644 --- a/apps/dav/lib/CalDAV/Principal/Collection.php +++ b/apps/dav/lib/CalDAV/Principal/Collection.php @@ -23,6 +23,8 @@ */ namespace OCA\DAV\CalDAV\Principal; +use Sabre\DAV\Exception; + /** * Class Collection * @@ -35,6 +37,7 @@ class Collection extends \Sabre\CalDAV\Principal\Collection { * * @param array $principalInfo * @return User + * @throws Exception */ public function getChildForPrincipal(array $principalInfo) { return new User($this->principalBackend, $principalInfo); diff --git a/apps/dav/lib/CalDAV/Proxy/Proxy.php b/apps/dav/lib/CalDAV/Proxy/Proxy.php index 8bafe8cc3b31b..9a1327be9cf0a 100644 --- a/apps/dav/lib/CalDAV/Proxy/Proxy.php +++ b/apps/dav/lib/CalDAV/Proxy/Proxy.php @@ -36,13 +36,9 @@ * @method void setPermissions(int $permissions) */ class Proxy extends Entity { - - /** @var string */ - protected $ownerId; - /** @var string */ - protected $proxyId; - /** @var int */ - protected $permissions; + protected string $ownerId; + protected string $proxyId; + protected int $permissions; public function __construct() { $this->addType('ownerId', 'string'); diff --git a/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php b/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php index 19c72ffa0e967..cf5258f243eb4 100644 --- a/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php +++ b/apps/dav/lib/CalDAV/Proxy/ProxyMapper.php @@ -28,6 +28,7 @@ namespace OCA\DAV\CalDAV\Proxy; use OCP\AppFramework\Db\QBMapper; +use OCP\DB\Exception; use OCP\IDBConnection; /** @@ -52,6 +53,7 @@ public function __construct(IDBConnection $db) { * @param string $proxyId The principal uri that can act as a proxy for the resulting calendars * * @return Proxy[] + * @throws Exception */ public function getProxiesFor(string $proxyId): array { $qb = $this->db->getQueryBuilder(); @@ -67,6 +69,7 @@ public function getProxiesFor(string $proxyId): array { * @param string $ownerId The principal uri that has the resulting proxies for their calendars * * @return Proxy[] + * @throws Exception */ public function getProxiesOf(string $ownerId): array { $qb = $this->db->getQueryBuilder(); diff --git a/apps/dav/lib/CalDAV/PublicCalendar.php b/apps/dav/lib/CalDAV/PublicCalendar.php index 4a29c8d237afa..6366fd09b2b97 100644 --- a/apps/dav/lib/CalDAV/PublicCalendar.php +++ b/apps/dav/lib/CalDAV/PublicCalendar.php @@ -82,9 +82,8 @@ public function getMultipleChildren(array $paths) { /** * public calendars are always shared - * @return bool */ - protected function isShared() { + protected function isShared(): bool { return true; } } diff --git a/apps/dav/lib/CalDAV/PublicCalendarObject.php b/apps/dav/lib/CalDAV/PublicCalendarObject.php index 69a5583d8f5fb..9ec2e49e75b70 100644 --- a/apps/dav/lib/CalDAV/PublicCalendarObject.php +++ b/apps/dav/lib/CalDAV/PublicCalendarObject.php @@ -27,9 +27,8 @@ class PublicCalendarObject extends CalendarObject { /** * public calendars are always shared - * @return bool */ - protected function isShared() { + protected function isShared(): bool { return true; } } diff --git a/apps/dav/lib/CalDAV/PublicCalendarRoot.php b/apps/dav/lib/CalDAV/PublicCalendarRoot.php index 55f48b982018f..5d0fa9a83718e 100644 --- a/apps/dav/lib/CalDAV/PublicCalendarRoot.php +++ b/apps/dav/lib/CalDAV/PublicCalendarRoot.php @@ -31,15 +31,9 @@ use Sabre\DAV\Collection; class PublicCalendarRoot extends Collection { - - /** @var CalDavBackend */ - protected $caldavBackend; - - /** @var IL10N */ - protected $l10n; - - /** @var IConfig */ - protected $config; + protected CalDavBackend $caldavBackend; + protected IL10N $l10n; + protected IConfig $config; /** @var LoggerInterface */ private $logger; diff --git a/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php b/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php index 97e942f9da24a..c96d07a00900b 100644 --- a/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php +++ b/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php @@ -32,37 +32,35 @@ use OCP\IConfig; use OCP\IURLGenerator; use Sabre\CalDAV\Xml\Property\AllowedSharingModes; +use Sabre\DAV\Exception\NotAuthenticated; use Sabre\DAV\Exception\NotFound; use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; +use Sabre\DAVACL\Exception\NeedPrivileges; +use Sabre\DAVACL\Plugin as ACLPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; +use Sabre\Xml\ParseException; class PublishPlugin extends ServerPlugin { public const NS_CALENDARSERVER = 'http://calendarserver.org/ns/'; /** * Reference to SabreDAV server object. - * - * @var \Sabre\DAV\Server */ - protected $server; + protected Server $server; /** * Config instance to get instance secret. - * - * @var IConfig */ - protected $config; + protected IConfig $config; /** * URL Generator for absolute URLs. - * - * @var IURLGenerator */ - protected $urlGenerator; + protected IURLGenerator $urlGenerator; /** * PublishPlugin constructor. @@ -150,6 +148,9 @@ public function propFind(PropFind $propFind, INode $node) { * @param ResponseInterface $response * * @return void|bool + * @throws NeedPrivileges + * @throws NotAuthenticated + * @throws ParseException */ public function httpPost(RequestInterface $request, ResponseInterface $response) { $path = $request->getPath(); @@ -195,7 +196,7 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) // If there's no ACL support, we allow everything if ($acl) { - /** @var \Sabre\DAVACL\Plugin $acl */ + /** @var ACLPlugin $acl */ $acl->checkPrivileges($path, '{DAV:}write'); $limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes'; @@ -230,7 +231,7 @@ public function httpPost(RequestInterface $request, ResponseInterface $response) // If there's no ACL support, we allow everything if ($acl) { - /** @var \Sabre\DAVACL\Plugin $acl */ + /** @var ACLPlugin $acl */ $acl->checkPrivileges($path, '{DAV:}write'); $limitSharingToOwner = $this->config->getAppValue('dav', 'limitAddressBookAndCalendarSharingToOwner', 'no') === 'yes'; diff --git a/apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php b/apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php index 35bce872bf818..271177050b712 100644 --- a/apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php +++ b/apps/dav/lib/CalDAV/Publishing/Xml/Publisher.php @@ -31,18 +31,18 @@ class Publisher implements XmlSerializable { /** * @var string $publishUrl */ - protected $publishUrl; + protected string $publishUrl; /** * @var boolean $isPublished */ - protected $isPublished; + protected bool $isPublished; /** * @param string $publishUrl * @param boolean $isPublished */ - public function __construct($publishUrl, $isPublished) { + public function __construct(string $publishUrl, bool $isPublished) { $this->publishUrl = $publishUrl; $this->isPublished = $isPublished; } @@ -50,17 +50,17 @@ public function __construct($publishUrl, $isPublished) { /** * @return string */ - public function getValue() { + public function getValue(): string { return $this->publishUrl; } /** - * The xmlSerialize metod is called during xml writing. + * The xmlSerialize method is called during xml writing. * * Use the $writer argument to write its own xml serialization. * * An important note: do _not_ create a parent element. Any element - * implementing XmlSerializble should only ever write what's considered + * implementing XmlSerializable should only ever write what's considered * its 'inner xml'. * * The parent of the current element is responsible for writing a diff --git a/apps/dav/lib/CalDAV/Reminder/Backend.php b/apps/dav/lib/CalDAV/Reminder/Backend.php index b0476e9594c1e..1af82ccacb1e6 100644 --- a/apps/dav/lib/CalDAV/Reminder/Backend.php +++ b/apps/dav/lib/CalDAV/Reminder/Backend.php @@ -28,6 +28,7 @@ */ namespace OCA\DAV\CalDAV\Reminder; +use Exception; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IDBConnection; @@ -37,12 +38,8 @@ * @package OCA\DAV\CalDAV\Reminder */ class Backend { - - /** @var IDBConnection */ - protected $db; - - /** @var ITimeFactory */ - private $timeFactory; + protected IDBConnection $db; + private ITimeFactory $timeFactory; /** * Backend constructor. @@ -60,7 +57,7 @@ public function __construct(IDBConnection $db, * Get all reminders with a notification date before now * * @return array - * @throws \Exception + * @throws Exception */ public function getRemindersToProcess():array { $query = $this->db->getQueryBuilder(); @@ -82,13 +79,14 @@ public function getRemindersToProcess():array { * * @param int $objectId * @return array + * @throws \OCP\DB\Exception */ public function getAllScheduledRemindersForEvent(int $objectId):array { $query = $this->db->getQueryBuilder(); $query->select('*') ->from('calendar_reminders') ->where($query->expr()->eq('object_id', $query->createNamedParameter($objectId))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); return array_map( [$this, 'fixRowTyping'], @@ -112,6 +110,7 @@ public function getAllScheduledRemindersForEvent(int $objectId):array { * @param int $notificationDate * @param bool $isRepeatBased * @return int The insert id + * @throws \OCP\DB\Exception */ public function insertReminder(int $calendarId, int $objectId, @@ -141,7 +140,7 @@ public function insertReminder(int $calendarId, 'notification_date' => $query->createNamedParameter($notificationDate), 'is_repeat_based' => $query->createNamedParameter($isRepeatBased ? 1 : 0), ]) - ->execute(); + ->executeStatement(); return $query->getLastInsertId(); } @@ -151,6 +150,7 @@ public function insertReminder(int $calendarId, * * @param int $reminderId * @param int $newNotificationDate + * @throws \OCP\DB\Exception */ public function updateReminder(int $reminderId, int $newNotificationDate):void { @@ -158,7 +158,7 @@ public function updateReminder(int $reminderId, $query->update('calendar_reminders') ->set('notification_date', $query->createNamedParameter($newNotificationDate)) ->where($query->expr()->eq('id', $query->createNamedParameter($reminderId))) - ->execute(); + ->executeStatement(); } /** @@ -166,26 +166,28 @@ public function updateReminder(int $reminderId, * * @param integer $reminderId * @return void + * @throws \OCP\DB\Exception */ public function removeReminder(int $reminderId):void { $query = $this->db->getQueryBuilder(); $query->delete('calendar_reminders') ->where($query->expr()->eq('id', $query->createNamedParameter($reminderId))) - ->execute(); + ->executeStatement(); } /** * Cleans reminders in database * * @param int $objectId + * @throws \OCP\DB\Exception */ public function cleanRemindersForEvent(int $objectId):void { $query = $this->db->getQueryBuilder(); $query->delete('calendar_reminders') ->where($query->expr()->eq('object_id', $query->createNamedParameter($objectId))) - ->execute(); + ->executeStatement(); } /** @@ -193,13 +195,14 @@ public function cleanRemindersForEvent(int $objectId):void { * * @param int $calendarId * @return void + * @throws \OCP\DB\Exception */ public function cleanRemindersForCalendar(int $calendarId):void { $query = $this->db->getQueryBuilder(); $query->delete('calendar_reminders') ->where($query->expr()->eq('calendar_id', $query->createNamedParameter($calendarId))) - ->execute(); + ->executeStatement(); } /** diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php index ed9c156b44910..a18533325caae 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/AbstractProvider.php @@ -49,31 +49,14 @@ abstract class AbstractProvider implements INotificationProvider { /** @var string */ public const NOTIFICATION_TYPE = ''; - - /** @var LoggerInterface */ - protected $logger; - - /** @var L10NFactory */ - protected $l10nFactory; - + protected LoggerInterface $logger; + protected L10NFactory $l10nFactory; /** @var IL10N[] */ - private $l10ns; - - /** @var string */ - private $fallbackLanguage; + private array $l10ns; + private string $fallbackLanguage; + protected IURLGenerator $urlGenerator; + protected IConfig $config; - /** @var IURLGenerator */ - protected $urlGenerator; - - /** @var IConfig */ - protected $config; - - /** - * @param LoggerInterface $logger - * @param L10NFactory $l10nFactory - * @param IConfig $config - * @param IUrlGenerator $urlGenerator - */ public function __construct(LoggerInterface $logger, L10NFactory $l10nFactory, IURLGenerator $urlGenerator, diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php index 4a5a32805efe5..124a099a72527 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/EmailProvider.php @@ -32,17 +32,21 @@ namespace OCA\DAV\CalDAV\Reminder\NotificationProvider; use DateTime; +use DateTimeImmutable; +use Exception; use OCP\IConfig; use OCP\IL10N; use OCP\IURLGenerator; use OCP\L10N\IFactory as L10NFactory; use OCP\Mail\IEMailTemplate; use OCP\Mail\IMailer; +use OCP\Util; use Psr\Log\LoggerInterface; use Sabre\VObject; use Sabre\VObject\Component\VEvent; use Sabre\VObject\Parameter; use Sabre\VObject\Property; +use function in_array; /** * Class EmailProvider @@ -54,8 +58,7 @@ class EmailProvider extends AbstractProvider { /** @var string */ public const NOTIFICATION_TYPE = 'EMAIL'; - /** @var IMailer */ - private $mailer; + private IMailer $mailer; /** * @param IConfig $config @@ -79,7 +82,7 @@ public function __construct(IConfig $config, * @param VEvent $vevent * @param string $calendarDisplayName * @param array $users - * @throws \Exception + * @throws Exception */ public function send(VEvent $vevent, string $calendarDisplayName, @@ -105,7 +108,7 @@ public function send(VEvent $vevent, $lang = $fallbackLanguage; } $l10n = $this->getL10NForLang($lang); - $fromEMail = \OCP\Util::getDefaultEmailAddress('reminders-noreply'); + $fromEMail = Util::getDefaultEmailAddress('reminders-noreply'); $template = $this->mailer->createEMailTemplate('dav.calendarReminder'); $template->addHeader(); @@ -132,7 +135,7 @@ public function send(VEvent $vevent, if ($failed) { $this->logger->error('Unable to deliver message to {failed}', ['app' => 'dav', 'failed' => implode(', ', $failed)]); } - } catch (\Exception $ex) { + } catch (Exception $ex) { $this->logger->error('Unable to deliver reminder message', ['app' => 'dav', 'exception' => $ex]); } } @@ -153,7 +156,8 @@ private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, VEv * @param IEMailTemplate $template * @param IL10N $l10n * @param string $calendarDisplayName - * @param array $eventData + * @param VEvent $vevent + * @throws Exception */ private function addBulletList(IEMailTemplate $template, IL10N $l10n, @@ -223,11 +227,7 @@ private function sortEMailAddressesByLanguage(array $emails, $sortedByLanguage = []; foreach ($emails as $emailAddress => $parameters) { - if (isset($parameters['LANG'])) { - $lang = $parameters['LANG']; - } else { - $lang = $defaultLanguage; - } + $lang = $parameters['LANG'] ?? $defaultLanguage; if (!isset($sortedByLanguage[$lang])) { $sortedByLanguage[$lang] = []; @@ -253,7 +253,7 @@ private function getAllEMailAddressesFromEvent(VEvent $vevent):array { } $cuType = $this->getCUTypeOfAttendee($attendee); - if (\in_array($cuType, ['RESOURCE', 'ROOM', 'UNKNOWN'])) { + if (in_array($cuType, ['RESOURCE', 'ROOM', 'UNKNOWN'])) { // Don't send emails to things continue; } @@ -376,16 +376,15 @@ private function getEMailAddressesOfAllUsersWithWriteAccessToCalendar(array $use * @param IL10N $l10n * @param VEvent $vevent * @return string - * @throws \Exception + * @throws Exception */ private function generateDateString(IL10N $l10n, VEvent $vevent):string { $isAllDay = $vevent->DTSTART instanceof Property\ICalendar\Date; /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtstart */ /** @var Property\ICalendar\Date | Property\ICalendar\DateTime $dtend */ - /** @var \DateTimeImmutable $dtstartDt */ + /** @var DateTimeImmutable $dtstartDt */ $dtstartDt = $vevent->DTSTART->getDateTime(); - /** @var \DateTimeImmutable $dtendDt */ $dtendDt = $this->getDTEndFromEvent($vevent)->getDateTime(); $diff = $dtstartDt->diff($dtendDt); diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php index 03c749ac2c18d..d832d9157b8f9 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProvider/PushProvider.php @@ -29,6 +29,8 @@ */ namespace OCA\DAV\CalDAV\Reminder\NotificationProvider; +use DateTimeInterface; +use Exception; use OCA\DAV\AppInfo\Application; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; @@ -36,7 +38,6 @@ use OCP\IUser; use OCP\L10N\IFactory as L10NFactory; use OCP\Notification\IManager; -use OCP\Notification\INotification; use Psr\Log\LoggerInterface; use Sabre\VObject\Component\VEvent; use Sabre\VObject\Property; @@ -51,20 +52,9 @@ class PushProvider extends AbstractProvider { /** @var string */ public const NOTIFICATION_TYPE = 'DISPLAY'; - /** @var IManager */ - private $manager; + private IManager $manager; + private ITimeFactory $timeFactory; - /** @var ITimeFactory */ - private $timeFactory; - - /** - * @param IConfig $config - * @param IManager $manager - * @param LoggerInterface $logger - * @param L10NFactory $l10nFactory - * @param IUrlGenerator $urlGenerator - * @param ITimeFactory $timeFactory - */ public function __construct(IConfig $config, IManager $manager, LoggerInterface $logger, @@ -80,9 +70,9 @@ public function __construct(IConfig $config, * Send push notification to all users. * * @param VEvent $vevent - * @param string $calendarDisplayName + * @param string|null $calendarDisplayName * @param IUser[] $users - * @throws \Exception + * @throws Exception */ public function send(VEvent $vevent, string $calendarDisplayName = null, @@ -96,11 +86,10 @@ public function send(VEvent $vevent, $eventUUID = (string) $vevent->UID; if (!$eventUUID) { return; - }; + } $eventUUIDHash = hash('sha256', $eventUUID, false); foreach ($users as $user) { - /** @var INotification $notification */ $notification = $this->manager->createNotification(); $notification->setApp(Application::APP_ID) ->setUser($user->getUID()) @@ -119,7 +108,7 @@ public function send(VEvent $vevent, /** * @var VEvent $vevent * @return array - * @throws \Exception + * @throws Exception */ protected function extractEventDetails(VEvent $vevent):array { /** @var Property\ICalendar\DateTime $start */ @@ -137,10 +126,10 @@ protected function extractEventDetails(VEvent $vevent):array { ? ((string) $vevent->LOCATION) : null, 'all_day' => $start instanceof Property\ICalendar\Date, - 'start_atom' => $start->getDateTime()->format(\DateTimeInterface::ATOM), + 'start_atom' => $start->getDateTime()->format(DateTimeInterface::ATOM), 'start_is_floating' => $start->isFloating(), 'start_timezone' => $start->getDateTime()->getTimezone()->getName(), - 'end_atom' => $end->getDateTime()->format(\DateTimeInterface::ATOM), + 'end_atom' => $end->getDateTime()->format(DateTimeInterface::ATOM), 'end_is_floating' => $end->isFloating(), 'end_timezone' => $end->getDateTime()->getTimezone()->getName(), ]; diff --git a/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php b/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php index cb11c7d3e2c16..70220ae44affa 100644 --- a/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php +++ b/apps/dav/lib/CalDAV/Reminder/NotificationProviderManager.php @@ -40,7 +40,7 @@ class NotificationProviderManager { /** @var INotificationProvider[] */ - private $providers = []; + private array $providers = []; /** * Checks whether a provider for a given ACTION exists diff --git a/apps/dav/lib/CalDAV/Reminder/Notifier.php b/apps/dav/lib/CalDAV/Reminder/Notifier.php index 8535c55054a90..f54c2489e1e46 100644 --- a/apps/dav/lib/CalDAV/Reminder/Notifier.php +++ b/apps/dav/lib/CalDAV/Reminder/Notifier.php @@ -30,6 +30,9 @@ namespace OCA\DAV\CalDAV\Reminder; use DateTime; +use DateTimeInterface; +use Exception; +use InvalidArgumentException; use OCA\DAV\AppInfo\Application; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IL10N; @@ -46,25 +49,11 @@ */ class Notifier implements INotifier { - /** @var IFactory */ - private $l10nFactory; + private IFactory $l10nFactory; + private IURLGenerator $urlGenerator; + private IL10N $l10n; + private ITimeFactory $timeFactory; - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var IL10N */ - private $l10n; - - /** @var ITimeFactory */ - private $timeFactory; - - /** - * Notifier constructor. - * - * @param IFactory $factory - * @param IURLGenerator $urlGenerator - * @param ITimeFactory $timeFactory - */ public function __construct(IFactory $factory, IURLGenerator $urlGenerator, ITimeFactory $timeFactory) { @@ -99,12 +88,12 @@ public function getName():string { * @param INotification $notification * @param string $languageCode The code of the language that should be used to prepare the notification * @return INotification - * @throws \Exception + * @throws Exception */ public function prepare(INotification $notification, string $languageCode):INotification { if ($notification->getApp() !== Application::APP_ID) { - throw new \InvalidArgumentException('Notification not from this app'); + throw new InvalidArgumentException('Notification not from this app'); } // Read the language from the notification @@ -116,7 +105,7 @@ public function prepare(INotification $notification, return $this->prepareReminderNotification($notification); default: - throw new \InvalidArgumentException('Unknown subject'); + throw new InvalidArgumentException('Unknown subject'); } } @@ -124,6 +113,7 @@ public function prepare(INotification $notification, /** * @param INotification $notification * @return INotification + * @throws Exception */ private function prepareReminderNotification(INotification $notification):INotification { $imagePath = $this->urlGenerator->imagePath('core', 'places/calendar.svg'); @@ -144,7 +134,7 @@ private function prepareReminderNotification(INotification $notification):INotif private function prepareNotificationSubject(INotification $notification): void { $parameters = $notification->getSubjectParameters(); - $startTime = \DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']); + $startTime = DateTime::createFromFormat(DateTimeInterface::ATOM, $parameters['start_atom']); $now = $this->timeFactory->getDateTime(); $title = $this->getTitleFromParameters($parameters); @@ -188,6 +178,7 @@ private function prepareNotificationSubject(INotification $notification): void { * Sets the notification message based on the parameters set in PushProvider * * @param INotification $notification + * @throws Exception */ private function prepareNotificationMessage(INotification $notification): void { $parameters = $notification->getMessageParameters(); @@ -218,11 +209,11 @@ private function getTitleFromParameters(array $parameters):string { /** * @param array $parameters * @return string - * @throws \Exception + * @throws Exception */ private function generateDateString(array $parameters):string { - $startDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['start_atom']); - $endDateTime = DateTime::createFromFormat(\DateTimeInterface::ATOM, $parameters['end_atom']); + $startDateTime = DateTime::createFromFormat(DateTimeInterface::ATOM, $parameters['start_atom']); + $endDateTime = DateTime::createFromFormat(DateTimeInterface::ATOM, $parameters['end_atom']); // If the event has already ended, dismiss the notification if ($endDateTime < $this->timeFactory->getDateTime()) { diff --git a/apps/dav/lib/CalDAV/Reminder/ReminderService.php b/apps/dav/lib/CalDAV/Reminder/ReminderService.php index d6901cc4fb03f..e81341067a16c 100644 --- a/apps/dav/lib/CalDAV/Reminder/ReminderService.php +++ b/apps/dav/lib/CalDAV/Reminder/ReminderService.php @@ -30,10 +30,11 @@ */ namespace OCA\DAV\CalDAV\Reminder; -use DateTimeImmutable; +use DateTime; use OCA\DAV\CalDAV\CalDavBackend; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; +use OCP\DB\Exception; use OCP\IGroup; use OCP\IGroupManager; use OCP\IUser; @@ -49,26 +50,13 @@ class ReminderService { - /** @var Backend */ - private $backend; - - /** @var NotificationProviderManager */ - private $notificationProviderManager; - - /** @var IUserManager */ - private $userManager; - - /** @var IGroupManager */ - private $groupManager; - - /** @var CalDavBackend */ - private $caldavBackend; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var IConfig */ - private $config; + private Backend $backend; + private NotificationProviderManager $notificationProviderManager; + private IUserManager $userManager; + private IGroupManager $groupManager; + private CalDavBackend $caldavBackend; + private ITimeFactory $timeFactory; + private IConfig $config; public const REMINDER_TYPE_EMAIL = 'EMAIL'; public const REMINDER_TYPE_DISPLAY = 'DISPLAY'; @@ -85,17 +73,6 @@ class ReminderService { self::REMINDER_TYPE_AUDIO ]; - /** - * ReminderService constructor. - * - * @param Backend $backend - * @param NotificationProviderManager $notificationProviderManager - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param CalDavBackend $caldavBackend - * @param ITimeFactory $timeFactory - * @param IConfig $config - */ public function __construct(Backend $backend, NotificationProviderManager $notificationProviderManager, IUserManager $userManager, @@ -117,6 +94,7 @@ public function __construct(Backend $backend, * * @throws NotificationProvider\ProviderNotAvailableException * @throws NotificationTypeDoesNotExistException + * @throws \Exception */ public function processReminders():void { $reminders = $this->backend->getRemindersToProcess(); @@ -173,6 +151,7 @@ public function processReminders():void { /** * @param array $objectData * @throws VObject\InvalidDataException + * @throws VObject\Recur\MaxInstancesExceededException */ public function onCalendarObjectCreate(array $objectData):void { // We only support VEvents for now @@ -203,7 +182,7 @@ public function onCalendarObjectCreate(array $objectData):void { $recurrenceExceptions = $this->getRecurrenceExceptionFromListOfVEvents($vevents); $masterItem = $this->getMasterItemFromListOfVEvents($vevents); $now = $this->timeFactory->getDateTime(); - $isRecurring = $masterItem ? $this->isRecurring($masterItem) : false; + $isRecurring = $masterItem && $this->isRecurring($masterItem); foreach ($recurrenceExceptions as $recurrenceException) { $eventHash = $this->getEventHash($recurrenceException); @@ -292,7 +271,7 @@ public function onCalendarObjectCreate(array $objectData):void { continue; } - $alarms = $this->getRemindersForVAlarm($valarm, $objectData, $masterHash, $alarmHash, $isRecurring, false); + $alarms = $this->getRemindersForVAlarm($valarm, $objectData, $masterHash, $alarmHash, $isRecurring); $this->writeRemindersToDatabase($alarms); $processedAlarms[] = $alarmHash; } @@ -317,7 +296,7 @@ public function onCalendarObjectEdit(array $objectData):void { /** * @param array $objectData - * @throws VObject\InvalidDataException + * @throws Exception */ public function onCalendarObjectDelete(array $objectData):void { // We only support VEvents for now @@ -336,6 +315,8 @@ public function onCalendarObjectDelete(array $objectData):void { * @param bool $isRecurring * @param bool $isRecurrenceException * @return array + * @throws InvalidDataException + * @throws \Exception */ private function getRemindersForVAlarm(VAlarm $valarm, array $objectData, @@ -352,9 +333,8 @@ private function getRemindersForVAlarm(VAlarm $valarm, $recurrenceId = $this->getEffectiveRecurrenceIdOfVEvent($valarm->parent); $isRelative = $this->isAlarmRelative($valarm); - /** @var DateTimeImmutable $notificationDate */ $notificationDate = $valarm->getEffectiveTriggerTime(); - $clonedNotificationDate = new \DateTime('now', $notificationDate->getTimezone()); + $clonedNotificationDate = new DateTime('now', $notificationDate->getTimezone()); $clonedNotificationDate->setTimestamp($notificationDate->getTimestamp()); $alarms = []; @@ -402,6 +382,7 @@ private function getRemindersForVAlarm(VAlarm $valarm, /** * @param array $reminders + * @throws Exception */ private function writeRemindersToDatabase(array $reminders): void { foreach ($reminders as $reminder) { @@ -425,6 +406,9 @@ private function writeRemindersToDatabase(array $reminders): void { /** * @param array $reminder * @param VEvent $vevent + * @throws Exception + * @throws InvalidDataException + * @throws VObject\Recur\MaxInstancesExceededException */ private function deleteOrProcessNext(array $reminder, VObject\Component\VEvent $vevent):void { @@ -484,7 +468,7 @@ private function deleteOrProcessNext(array $reminder, $alarms = $this->getRemindersForVAlarm($valarm, [ 'calendarid' => $reminder['calendar_id'], 'id' => $reminder['object_id'], - ], $reminder['event_hash'], $alarmHash, true, false); + ], $reminder['event_hash'], $alarmHash, true); $this->writeRemindersToDatabase($alarms); // Abort generating reminders after creating one successfully @@ -602,6 +586,7 @@ private function getAlarmHash(VAlarm $valarm):string { * @param int $recurrenceId * @param bool $isRecurrenceException * @return VEvent|null + * @throws VObject\Recur\MaxInstancesExceededException */ private function getVEventByRecurrenceId(VObject\Component\VCalendar $vcalendar, int $recurrenceId, diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php index e8f92e90e2f29..84641712186a5 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php @@ -44,46 +44,17 @@ use function array_values; abstract class AbstractPrincipalBackend implements BackendInterface { + private IDBConnection $db; + private IUserSession $userSession; + private IGroupManager $groupManager; + private LoggerInterface $logger; + private ProxyMapper $proxyMapper; + private string $principalPrefix; + private string $dbTableName; + private string $dbMetaDataTableName; + private string $dbForeignKeyName; + private string $cuType; - /** @var IDBConnection */ - private $db; - - /** @var IUserSession */ - private $userSession; - - /** @var IGroupManager */ - private $groupManager; - - /** @var LoggerInterface */ - private $logger; - - /** @var ProxyMapper */ - private $proxyMapper; - - /** @var string */ - private $principalPrefix; - - /** @var string */ - private $dbTableName; - - /** @var string */ - private $dbMetaDataTableName; - - /** @var string */ - private $dbForeignKeyName; - - /** @var string */ - private $cuType; - - /** - * @param IDBConnection $dbConnection - * @param IUserSession $userSession - * @param IGroupManager $groupManager - * @param LoggerInterface $logger - * @param string $principalPrefix - * @param string $dbPrefix - * @param string $cuType - */ public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, @@ -118,6 +89,7 @@ public function __construct(IDBConnection $dbConnection, * * @param string $prefixPath * @return string[] + * @throws Exception */ public function getPrincipalsByPrefix($prefixPath): array { $principals = []; @@ -126,12 +98,12 @@ public function getPrincipalsByPrefix($prefixPath): array { $query = $this->db->getQueryBuilder(); $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname']) ->from($this->dbTableName); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $metaDataQuery = $this->db->getQueryBuilder(); $metaDataQuery->select([$this->dbForeignKeyName, 'key', 'value']) ->from($this->dbMetaDataTableName); - $metaDataStmt = $metaDataQuery->execute(); + $metaDataStmt = $metaDataQuery->executeQuery(); $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); $metaDataById = []; @@ -165,9 +137,10 @@ public function getPrincipalsByPrefix($prefixPath): array { * The returned structure should be the exact same as from * getPrincipalsByPrefix. * - * @param string $prefixPath + * @param string $path * * @return array + * @throws Exception */ public function getPrincipalByPath($path) { if (strpos($path, $this->principalPrefix) !== 0) { @@ -182,7 +155,7 @@ public function getPrincipalByPath($path) { ->from($this->dbTableName) ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId))) ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$row) { @@ -193,7 +166,7 @@ public function getPrincipalByPath($path) { $metaDataQuery->select(['key', 'value']) ->from($this->dbMetaDataTableName) ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id']))); - $metaDataStmt = $metaDataQuery->execute(); + $metaDataStmt = $metaDataQuery->executeQuery(); $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); $metadata = []; @@ -207,13 +180,14 @@ public function getPrincipalByPath($path) { /** * @param int $id * @return string[]|null + * @throws Exception */ - public function getPrincipalById($id): ?array { + public function getPrincipalById(int $id): ?array { $query = $this->db->getQueryBuilder(); $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname']) ->from($this->dbTableName) ->where($query->expr()->eq('id', $query->createNamedParameter($id))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$row) { @@ -224,7 +198,7 @@ public function getPrincipalById($id): ?array { $metaDataQuery->select(['key', 'value']) ->from($this->dbMetaDataTableName) ->where($metaDataQuery->expr()->eq($this->dbForeignKeyName, $metaDataQuery->createNamedParameter($row['id']))); - $metaDataStmt = $metaDataQuery->execute(); + $metaDataStmt = $metaDataQuery->executeQuery(); $metaDataRows = $metaDataStmt->fetchAll(\PDO::FETCH_ASSOC); $metadata = []; @@ -249,6 +223,7 @@ public function updatePrincipal($path, PropPatch $propPatch): int { * @param string $test * * @return array + * @throws Exception */ public function searchPrincipals($prefixPath, array $searchProperties, $test = 'allof') { $results = []; @@ -273,7 +248,7 @@ public function searchPrincipals($prefixPath, array $searchProperties, $test = ' ->from($this->dbTableName) ->where($query->expr()->iLike('email', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%'))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $principals = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if (!$this->isAllowedToAccessResource($row, $usersGroups)) { @@ -292,7 +267,7 @@ public function searchPrincipals($prefixPath, array $searchProperties, $test = ' ->from($this->dbTableName) ->where($query->expr()->iLike('displayname', $query->createNamedParameter('%' . $this->db->escapeLikeParameter($value) . '%'))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $principals = []; while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { if (!$this->isAllowedToAccessResource($row, $usersGroups)) { @@ -411,6 +386,7 @@ private function searchPrincipalsByCapacity(string $key, string $value, array $u * @param IQueryBuilder $query * @param string[] $usersGroups * @return string[] + * @throws Exception */ private function getRows(IQueryBuilder $query, array $usersGroups): array { try { @@ -460,7 +436,7 @@ public function findByUri($uri, $principalPrefix): ?string { ->from($this->dbTableName) ->where($query->expr()->eq('email', $query->createNamedParameter($email))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$row) { @@ -487,7 +463,7 @@ public function findByUri($uri, $principalPrefix): ?string { ->from($this->dbTableName) ->where($query->expr()->eq('backend_id', $query->createNamedParameter($backendId))) ->andWhere($query->expr()->eq('resource_id', $query->createNamedParameter($resourceId))); - $stmt = $query->execute(); + $stmt = $query->executeQuery(); $row = $stmt->fetch(\PDO::FETCH_ASSOC); if (!$row) { diff --git a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php index 7c920de45dbfb..c7d97b328fee6 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php @@ -35,15 +35,6 @@ */ class ResourcePrincipalBackend extends AbstractPrincipalBackend { - /** - * ResourcePrincipalBackend constructor. - * - * @param IDBConnection $dbConnection - * @param IUserSession $userSession - * @param IGroupManager $groupManager - * @param LoggerInterface $logger - * @param ProxyMapper $proxyMapper - */ public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, diff --git a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php index fdc19ff74307f..961965ac67b39 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php @@ -35,15 +35,6 @@ */ class RoomPrincipalBackend extends AbstractPrincipalBackend { - /** - * RoomPrincipalBackend constructor. - * - * @param IDBConnection $dbConnection - * @param IUserSession $userSession - * @param IGroupManager $groupManager - * @param LoggerInterface $logger - * @param ProxyMapper $proxyMapper - */ public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, diff --git a/apps/dav/lib/CalDAV/RetentionService.php b/apps/dav/lib/CalDAV/RetentionService.php index 1d92d847641b6..fd915f33826e1 100644 --- a/apps/dav/lib/CalDAV/RetentionService.php +++ b/apps/dav/lib/CalDAV/RetentionService.php @@ -28,20 +28,16 @@ use OCA\DAV\AppInfo\Application; use OCP\AppFramework\Utility\ITimeFactory; use OCP\IConfig; +use Sabre\DAV\Exception\Forbidden; use function max; class RetentionService { public const RETENTION_CONFIG_KEY = 'calendarRetentionObligation'; private const DEFAULT_RETENTION_SECONDS = 30 * 24 * 60 * 60; - /** @var IConfig */ - private $config; - - /** @var ITimeFactory */ - private $time; - - /** @var CalDavBackend */ - private $calDavBackend; + private IConfig $config; + private ITimeFactory $time; + private CalDavBackend $calDavBackend; public function __construct(IConfig $config, ITimeFactory $time, @@ -62,6 +58,9 @@ public function getDuration(): int { ); } + /** + * @throws Forbidden + */ public function cleanUp(): void { $retentionTime = $this->getDuration(); $now = $this->time->getTime(); diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index 67c1bba219fe2..f9b43b98ced87 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -77,39 +77,17 @@ * @license http://sabre.io/license/ Modified BSD License */ class IMipPlugin extends SabreIMipPlugin { - - /** @var string */ - private $userId; - - /** @var IConfig */ - private $config; - - /** @var IMailer */ - private $mailer; - - /** @var LoggerInterface */ - private $logger; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var L10NFactory */ - private $l10nFactory; - - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var ISecureRandom */ - private $random; - - /** @var IDBConnection */ - private $db; - - /** @var Defaults */ - private $defaults; - - /** @var IUserManager */ - private $userManager; + private string $userId; + private IConfig $config; + private IMailer $mailer; + private LoggerInterface $logger; + private ITimeFactory $timeFactory; + private L10NFactory $l10nFactory; + private IURLGenerator $urlGenerator; + private ISecureRandom $random; + private IDBConnection $db; + private Defaults $defaults; + private IUserManager $userManager; public const MAX_DATE = '2038-01-01'; @@ -623,8 +601,8 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev $attendeeHTML .= ' ✔︎'; $attendeeText .= ' ✔︎'; } - array_push($attendeesHTML, $attendeeHTML); - array_push($attendeesText, $attendeeText); + $attendeesHTML[] = $attendeeHTML; + $attendeesText[] = $attendeeText; } $template->addBodyListItem(implode('
',$attendeesHTML), $l10n->t('Attendees:'), diff --git a/apps/dav/lib/CalDAV/Schedule/Plugin.php b/apps/dav/lib/CalDAV/Schedule/Plugin.php index 921eb4e87de12..a52ecff3cf2ad 100644 --- a/apps/dav/lib/CalDAV/Schedule/Plugin.php +++ b/apps/dav/lib/CalDAV/Schedule/Plugin.php @@ -56,16 +56,11 @@ class Plugin extends \Sabre\CalDAV\Schedule\Plugin { - /** - * @var IConfig - */ - private $config; + private IConfig $config; /** @var ITip\Message[] */ - private $schedulingResponses = []; - - /** @var string|null */ - private $pathOfCalendarObjectChange = null; + private array $schedulingResponses = []; + private ?string $pathOfCalendarObjectChange = null; public const CALENDAR_USER_TYPE = '{' . self::NS_CALDAV . '}calendar-user-type'; public const SCHEDULE_DEFAULT_CALENDAR_URL = '{' . self::NS_CALDAV . '}schedule-default-calendar-URL'; @@ -163,6 +158,7 @@ public function calendarObjectChange(RequestInterface $request, ResponseInterfac /** * @inheritDoc + * @throws NotFound */ public function scheduleLocalDelivery(ITip\Message $iTipMessage):void { parent::scheduleLocalDelivery($iTipMessage); @@ -271,6 +267,7 @@ public function scheduleLocalDelivery(ITip\Message $iTipMessage):void { /** * @param string $uri + * @throws NotFound */ public function dispatchSchedulingResponses(string $uri):void { if ($uri !== $this->pathOfCalendarObjectChange) { @@ -431,6 +428,7 @@ private function isAvailableAtTime(string $email, DateTimeInterface $start, Date // This method is heavily inspired by Sabre\CalDAV\Schedule\Plugin::scheduleLocalDelivery // and Sabre\CalDAV\Schedule\Plugin::getFreeBusyForEmail + /** @var \Sabre\DAVACL\Plugin $aclPlugin */ $aclPlugin = $this->server->getPlugin('acl'); $this->server->removeListener('propFind', [$aclPlugin, 'propFind']); @@ -537,7 +535,7 @@ private function isAvailableAtTime(string $email, DateTimeInterface $start, Date } // If more than one Free-Busy property was returned, it means that an event - // starts or ends inside this time-range, so it's not availabe and we return false + // starts or ends inside this time-range, so it's not available and we return false if (count($freeBusyProperties) > 1) { return false; } diff --git a/apps/dav/lib/CalDAV/Search/SearchPlugin.php b/apps/dav/lib/CalDAV/Search/SearchPlugin.php index a9ca977277cc6..8a67be96c5b2d 100644 --- a/apps/dav/lib/CalDAV/Search/SearchPlugin.php +++ b/apps/dav/lib/CalDAV/Search/SearchPlugin.php @@ -28,6 +28,7 @@ use OCA\DAV\CalDAV\CalendarHome; use OCA\DAV\CalDAV\Search\Xml\Request\CalendarSearchReport; +use Sabre\DAV\Exception\NotFound; use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; @@ -36,10 +37,8 @@ class SearchPlugin extends ServerPlugin { /** * Reference to SabreDAV server object. - * - * @var \Sabre\DAV\Server */ - protected $server; + protected Server $server; /** * This method should return a list of server-features. @@ -92,8 +91,9 @@ public function initialize(Server $server) { * @param mixed $report * @param mixed $path * @return bool + * @throws NotFound */ - public function report($reportName, $report, $path) { + public function report(string $reportName, $report, $path) { switch ($reportName) { case '{' . self::NS_Nextcloud . '}calendar-search': $this->server->transactionType = 'report-nc-calendar-search'; @@ -111,6 +111,7 @@ public function report($reportName, $report, $path) { * * @param string $uri * @return array + * @throws NotFound */ public function getSupportedReportSet($uri) { $node = $this->server->tree->getNodeForPath($uri); @@ -131,6 +132,7 @@ public function getSupportedReportSet($uri) { * * @param Xml\Request\CalendarSearchReport $report * @return void + * @throws NotFound */ private function calendarSearch(CalendarSearchReport $report): void { $node = $this->server->tree->getNodeForPath($this->server->getRequestUri()); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/CompFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/CompFilter.php index d5b7c834e3647..13084e8b3cb47 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/CompFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/CompFilter.php @@ -26,6 +26,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -33,8 +35,10 @@ class CompFilter implements XmlDeserializable { /** * @param Reader $reader - * @throws BadRequest * @return string + * @throws BadRequest + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $att = $reader->parseAttributes(); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/LimitFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/LimitFilter.php index 2c435ba3650ac..c12f2385ee7df 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/LimitFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/LimitFilter.php @@ -27,6 +27,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -34,8 +36,10 @@ class LimitFilter implements XmlDeserializable { /** * @param Reader $reader - * @throws BadRequest * @return int + * @throws BadRequest + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $value = $reader->parseInnerTree(); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/OffsetFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/OffsetFilter.php index a6f41d091617a..74769c909a10e 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/OffsetFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/OffsetFilter.php @@ -27,6 +27,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -34,8 +36,10 @@ class OffsetFilter implements XmlDeserializable { /** * @param Reader $reader - * @throws BadRequest * @return int + * @throws BadRequest + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $value = $reader->parseInnerTree(); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php index c25450a0c9444..06635cf8bb5ba 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/ParamFilter.php @@ -26,6 +26,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -33,8 +35,10 @@ class ParamFilter implements XmlDeserializable { /** * @param Reader $reader + * @return string[] * @throws BadRequest - * @return string + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $att = $reader->parseAttributes(); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/PropFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/PropFilter.php index 990b0ebf73087..1164518cd6555 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/PropFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/PropFilter.php @@ -26,6 +26,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -33,8 +35,10 @@ class PropFilter implements XmlDeserializable { /** * @param Reader $reader - * @throws BadRequest * @return string + * @throws BadRequest + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $att = $reader->parseAttributes(); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php b/apps/dav/lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php index 06fe39a463bde..0a1c3dd843161 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Filter/SearchTermFilter.php @@ -26,6 +26,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -33,8 +35,10 @@ class SearchTermFilter implements XmlDeserializable { /** * @param Reader $reader - * @throws BadRequest * @return string + * @throws BadRequest + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $value = $reader->parseInnerTree(); diff --git a/apps/dav/lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php b/apps/dav/lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php index 98efe36ee43c6..baa869fb9b251 100644 --- a/apps/dav/lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php +++ b/apps/dav/lib/CalDAV/Search/Xml/Request/CalendarSearchReport.php @@ -26,6 +26,8 @@ use OCA\DAV\CalDAV\Search\SearchPlugin; use Sabre\DAV\Exception\BadRequest; +use Sabre\Xml\LibXMLException; +use Sabre\Xml\ParseException; use Sabre\Xml\Reader; use Sabre\Xml\XmlDeserializable; @@ -41,27 +43,16 @@ class CalendarSearchReport implements XmlDeserializable { /** * An array with requested properties. - * - * @var array */ - public $properties; + public array $properties; /** * List of property/component filters. - * - * @var array */ - public $filters; + public array $filters; - /** - * @var int - */ - public $limit; - - /** - * @var int - */ - public $offset; + public int $limit; + public int $offset; /** * The deserialize method is called during xml parsing. @@ -82,7 +73,10 @@ class CalendarSearchReport implements XmlDeserializable { * the next element. * * @param Reader $reader - * @return mixed + * @return CalendarSearchReport + * @throws BadRequest + * @throws LibXMLException + * @throws ParseException */ public static function xmlDeserialize(Reader $reader) { $elems = $reader->parseInnerTree([ diff --git a/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObject.php b/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObject.php index 5730b7a100281..6311a2e55655f 100644 --- a/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObject.php +++ b/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObject.php @@ -35,17 +35,10 @@ class DeletedCalendarObject implements IACL, ICalendarObject, IRestorable { use ACLTrait; - /** @var string */ - private $name; - - /** @var mixed[] */ - private $objectData; - - /** @var string */ - private $principalUri; - - /** @var CalDavBackend */ - private $calDavBackend; + private string $name; + private array $objectData; + private string $principalUri; + private CalDavBackend $calDavBackend; public function __construct(string $name, array $objectData, diff --git a/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php b/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php index 20d05c047b130..f47f3778e7695 100644 --- a/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php +++ b/apps/dav/lib/CalDAV/Trashbin/DeletedCalendarObjectsCollection.php @@ -38,11 +38,8 @@ class DeletedCalendarObjectsCollection implements ICalendarObjectContainer { public const NAME = 'objects'; - /** @var CalDavBackend */ - protected $caldavBackend; - - /** @var mixed[] */ - private $principalInfo; + protected CalDavBackend $caldavBackend; + private array $principalInfo; public function __construct(CalDavBackend $caldavBackend, array $principalInfo) { diff --git a/apps/dav/lib/CalDAV/Trashbin/Plugin.php b/apps/dav/lib/CalDAV/Trashbin/Plugin.php index 58ff76beca1e8..f365cd21a126f 100644 --- a/apps/dav/lib/CalDAV/Trashbin/Plugin.php +++ b/apps/dav/lib/CalDAV/Trashbin/Plugin.php @@ -39,6 +39,7 @@ use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; use function array_slice; +use function count; use function implode; class Plugin extends ServerPlugin { @@ -46,14 +47,9 @@ class Plugin extends ServerPlugin { public const PROPERTY_CALENDAR_URI = '{http://nextcloud.com/ns}calendar-uri'; public const PROPERTY_RETENTION_DURATION = '{http://nextcloud.com/ns}trash-bin-retention-duration'; - /** @var bool */ - private $disableTrashbin; - - /** @var RetentionService */ - private $retentionService; - - /** @var Server */ - private $server; + private bool $disableTrashbin; + private RetentionService $retentionService; + private Server $server; public function __construct(IRequest $request, RetentionService $retentionService) { @@ -74,7 +70,7 @@ public function beforeMethod(RequestInterface $request, ResponseInterface $respo $path = $request->getPath(); $pathParts = explode('/', ltrim($path, '/')); - if (\count($pathParts) < 3) { + if (count($pathParts) < 3) { // We are looking for a path like calendars/username/calendarname return; } diff --git a/apps/dav/lib/CalDAV/Trashbin/TrashbinHome.php b/apps/dav/lib/CalDAV/Trashbin/TrashbinHome.php index 34d11e51eb3ec..e472e49fe48c6 100644 --- a/apps/dav/lib/CalDAV/Trashbin/TrashbinHome.php +++ b/apps/dav/lib/CalDAV/Trashbin/TrashbinHome.php @@ -42,12 +42,8 @@ class TrashbinHome implements IACL, ICollection, IProperties { use ACLTrait; public const NAME = 'trashbin'; - - /** @var CalDavBackend */ - private $caldavBackend; - - /** @var array */ - private $principalInfo; + private CalDavBackend $caldavBackend; + private array $principalInfo; public function __construct(CalDavBackend $caldavBackend, array $principalInfo) { diff --git a/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php b/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php index 3dd8a7c81e5a4..0bfaf1a7391e3 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/Plugin.php @@ -33,6 +33,7 @@ use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; +use function count; class Plugin extends ServerPlugin { @@ -46,16 +47,8 @@ class Plugin extends ServerPlugin { public const ENABLE_FOR_CLIENTS = [ "/^MSFT-WIN-3/" ]; - - /** - * @var bool - */ - private $enabled = false; - - /** - * @var Server - */ - private $server; + private bool $enabled = false; + private Server $server; /** * Plugin constructor. @@ -99,7 +92,7 @@ public function beforeMethod(RequestInterface $request, ResponseInterface $respo $path = $request->getPath(); $pathParts = explode('/', ltrim($path, '/')); - if (\count($pathParts) < 2) { + if (count($pathParts) < 2) { return; } diff --git a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php index 1d07ac8248204..4c9b43846d1f6 100644 --- a/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php +++ b/apps/dav/lib/CalDAV/WebcalCaching/RefreshWebcalService.php @@ -46,6 +46,7 @@ use Sabre\VObject\Component; use Sabre\VObject\DateTimeParser; use Sabre\VObject\InvalidDataException; +use Sabre\VObject\Recur\MaxInstancesExceededException; use Sabre\VObject\Recur\NoInstancesException; use Sabre\VObject\ParseException; use Sabre\VObject\Reader; @@ -54,18 +55,10 @@ use function count; class RefreshWebcalService { - - /** @var CalDavBackend */ - private $calDavBackend; - - /** @var IClientService */ - private $clientService; - - /** @var IConfig */ - private $config; - - /** @var LoggerInterface */ - private $logger; + private CalDavBackend $calDavBackend; + private IClientService $clientService; + private IConfig $config; + private LoggerInterface $logger; public const REFRESH_RATE = '{http://apple.com/ns/ical/}refreshrate'; public const STRIP_ALARMS = '{http://calendarserver.org/ns/}subscribed-strip-alarms'; @@ -142,7 +135,7 @@ public function refreshSubscription(string $principalUri, string $uri) { $calendarData = $vObject->serialize(); try { $this->calDavBackend->createCalendarObject($subscription['id'], $uri, $calendarData, CalDavBackend::CALENDAR_TYPE_SUBSCRIPTION); - } catch (NoInstancesException | BadRequest $ex) { + } catch (NoInstancesException | MaxInstancesExceededException | BadRequest $ex) { $this->logger->error('Error while creating calendar object from subscription', ['exception' => $ex]); } } @@ -167,7 +160,7 @@ public function refreshSubscription(string $principalUri, string $uri) { * @param string $uri * @return array|null */ - public function getSubscription(string $principalUri, string $uri) { + public function getSubscription(string $principalUri, string $uri): ?array { $subscriptions = array_values(array_filter( $this->calDavBackend->getSubscriptionsForUser($principalUri), function ($sub) use ($uri) { @@ -189,7 +182,7 @@ function ($sub) use ($uri) { * @param array &$mutations * @return null|string */ - private function queryWebcalFeed(array $subscription, array &$mutations) { + private function queryWebcalFeed(array $subscription, array &$mutations): ?string { $client = $this->clientService->newClient(); $didBreak301Chain = false; @@ -302,7 +295,7 @@ private function queryWebcalFeed(array $subscription, array &$mutations) { * @param string $webcalData * @return string|null */ - private function checkWebcalDataForRefreshRate($subscription, $webcalData) { + private function checkWebcalDataForRefreshRate(array $subscription, string $webcalData): ?string { // if there is no refreshrate stored in the database, check the webcal feed // whether it suggests any refresh rate and store that in the database if (isset($subscription[self::REFRESH_RATE]) && $subscription[self::REFRESH_RATE] !== null) { @@ -360,7 +353,7 @@ private function updateSubscription(array $subscription, array $mutations) { * @param string $url * @return string|null */ - private function cleanURL(string $url) { + private function cleanURL(string $url): ?string { $parsed = parse_url($url); if ($parsed === false) { return null; diff --git a/apps/dav/lib/Connector/PublicAuth.php b/apps/dav/lib/Connector/PublicAuth.php index f6c185907086e..22fcfc2708870 100644 --- a/apps/dav/lib/Connector/PublicAuth.php +++ b/apps/dav/lib/Connector/PublicAuth.php @@ -30,6 +30,7 @@ namespace OCA\DAV\Connector; use OC\Security\Bruteforce\Throttler; +use OC_User; use OCP\Defaults; use OCP\IRequest; use OCP\ISession; @@ -47,20 +48,11 @@ class PublicAuth extends AbstractBasic { private const BRUTEFORCE_ACTION = 'public_webdav_auth'; - /** @var IShare */ - private $share; - - /** @var IManager */ - private $shareManager; - - /** @var ISession */ - private $session; - - /** @var IRequest */ - private $request; - - /** @var Throttler */ - private $throttler; + private IShare $share; + private IManager $shareManager; + private ISession $session; + private IRequest $request; + private Throttler $throttler; /** * @param IRequest $request @@ -106,7 +98,7 @@ protected function validateUserPass($username, $password) { $this->share = $share; - \OC_User::setIncognitoMode(true); + OC_User::setIncognitoMode(true); // check if the share is password protected if ($share->getPassword() !== null) { diff --git a/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php b/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php index ade63b706c15a..a901fdfe41812 100644 --- a/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AnonymousOptionsPlugin.php @@ -34,11 +34,7 @@ use Sabre\HTTP\ResponseInterface; class AnonymousOptionsPlugin extends ServerPlugin { - - /** - * @var \Sabre\DAV\Server - */ - private $server; + private \Sabre\DAV\Server $server; /** * @param \Sabre\DAV\Server $server diff --git a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php index e56371f504e25..6bfdcdf87ae69 100644 --- a/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php +++ b/apps/dav/lib/Connector/Sabre/AppEnabledPlugin.php @@ -34,26 +34,16 @@ class AppEnabledPlugin extends ServerPlugin { /** * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var string - */ - private $app; - - /** - * @var IAppManager */ - private $appManager; + private \Sabre\DAV\Server $server; + private string $app; + private IAppManager $appManager; /** * @param string $app * @param IAppManager $appManager */ - public function __construct($app, IAppManager $appManager) { + public function __construct(string $app, IAppManager $appManager) { $this->app = $app; $this->appManager = $appManager; } diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index 7057e92d3bbfe..fdc5c0eac5944 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -38,7 +38,7 @@ use OC\Authentication\TwoFactorAuth\Manager; use OC\Security\Bruteforce\Throttler; use OC\User\LoginException; -use OC\User\Session; +use OC_Util; use OCA\DAV\Connector\Sabre\Exception\PasswordLoginForbidden; use OCP\Defaults; use OCP\IRequest; @@ -54,22 +54,16 @@ class Auth extends AbstractBasic { public const DAV_AUTHENTICATED = 'AUTHENTICATED_TO_DAV_BACKEND'; - /** @var ISession */ - private $session; - /** @var Session */ - private $userSession; - /** @var IRequest */ - private $request; - /** @var string */ - private $currentUser; - /** @var Manager */ - private $twoFactorManager; - /** @var Throttler */ - private $throttler; + private ISession $session; + private IUserSession $userSession; + private IRequest $request; + private string $currentUser; + private Manager $twoFactorManager; + private Throttler $throttler; /** * @param ISession $session - * @param Session $userSession + * @param IUserSession $userSession * @param IRequest $request * @param Manager $twoFactorManager * @param Throttler $throttler @@ -124,14 +118,14 @@ protected function validateUserPass($username, $password) { if ($this->userSession->isLoggedIn() && $this->isDavAuthenticated($this->userSession->getUser()->getUID()) ) { - \OC_Util::setupFS($this->userSession->getUser()->getUID()); + OC_Util::setupFS($this->userSession->getUser()->getUID()); $this->session->close(); return true; } else { - \OC_Util::setupFS(); //login hooks may need early access to the filesystem + OC_Util::setupFS(); //login hooks may need early access to the filesystem try { if ($this->userSession->logClientIn($username, $password, $this->request, $this->throttler)) { - \OC_Util::setupFS($this->userSession->getUser()->getUID()); + OC_Util::setupFS($this->userSession->getUser()->getUID()); $this->session->set(self::DAV_AUTHENTICATED, $this->userSession->getUser()->getUID()); $this->session->close(); return true; diff --git a/apps/dav/lib/Connector/Sabre/BearerAuth.php b/apps/dav/lib/Connector/Sabre/BearerAuth.php index e5e423ead43ae..43c669b24be73 100644 --- a/apps/dav/lib/Connector/Sabre/BearerAuth.php +++ b/apps/dav/lib/Connector/Sabre/BearerAuth.php @@ -23,6 +23,7 @@ */ namespace OCA\DAV\Connector\Sabre; +use OC_Util; use OCP\Defaults; use OCP\IRequest; use OCP\ISession; @@ -32,14 +33,10 @@ use Sabre\HTTP\ResponseInterface; class BearerAuth extends AbstractBearer { - /** @var IUserSession */ - private $userSession; - /** @var ISession */ - private $session; - /** @var IRequest */ - private $request; - /** @var string */ - private $principalPrefix; + private IUserSession $userSession; + private ISession $session; + private IRequest $request; + private string $principalPrefix; /** * @param IUserSession $userSession @@ -62,7 +59,7 @@ public function __construct(IUserSession $userSession, } private function setupUserFs(string $userId): string { - \OC_Util::setupFS($userId); + OC_Util::setupFS($userId); $this->session->close(); return $this->principalPrefix . $userId; } @@ -71,7 +68,7 @@ private function setupUserFs(string $userId): string { * {@inheritdoc} */ public function validateBearerToken($bearerToken) { - \OC_Util::setupFS(); + OC_Util::setupFS(); if (!$this->userSession->isLoggedIn()) { $this->userSession->tryTokenLogin($this->request); diff --git a/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php b/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php index 15d4b690d1e87..08ff97cf12cf5 100644 --- a/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php +++ b/apps/dav/lib/Connector/Sabre/BlockLegacyClientPlugin.php @@ -37,10 +37,8 @@ * @package OCA\DAV\Connector\Sabre */ class BlockLegacyClientPlugin extends ServerPlugin { - /** @var \Sabre\DAV\Server */ - protected $server; - /** @var IConfig */ - protected $config; + protected \Sabre\DAV\Server $server; + protected IConfig $config; /** * @param IConfig $config diff --git a/apps/dav/lib/Connector/Sabre/ChecksumList.php b/apps/dav/lib/Connector/Sabre/ChecksumList.php index 636d2821349e3..09692ba8c2f40 100644 --- a/apps/dav/lib/Connector/Sabre/ChecksumList.php +++ b/apps/dav/lib/Connector/Sabre/ChecksumList.php @@ -45,12 +45,12 @@ public function __construct(string $checksum) { } /** - * The xmlSerialize metod is called during xml writing. + * The xmlSerialize method is called during xml writing. * * Use the $writer argument to write its own xml serialization. * * An important note: do _not_ create a parent element. Any element - * implementing XmlSerializble should only ever write what's considered + * implementing XmlSerializable should only ever write what's considered * its 'inner xml'. * * The parent of the current element is responsible for writing a diff --git a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php index ea51695dc6ca4..9d7ecdb4775eb 100644 --- a/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CommentPropertiesPlugin.php @@ -36,16 +36,10 @@ class CommentPropertiesPlugin extends ServerPlugin { public const PROPERTY_NAME_COUNT = '{http://owncloud.org/ns}comments-count'; public const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}comments-unread'; - /** @var \Sabre\DAV\Server */ - protected $server; - - /** @var ICommentsManager */ - private $commentsManager; - - /** @var IUserSession */ - private $userSession; - - private $cachedUnreadCount = []; + protected \Sabre\DAV\Server $server; + private ICommentsManager $commentsManager; + private IUserSession $userSession; + private array $cachedUnreadCount = []; public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) { $this->commentsManager = $commentsManager; diff --git a/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php b/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php index 08ed3da027884..4601a6c5638d9 100644 --- a/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php +++ b/apps/dav/lib/Connector/Sabre/CopyEtagHeaderPlugin.php @@ -35,9 +35,7 @@ * or mangle Etag headers. */ class CopyEtagHeaderPlugin extends ServerPlugin { - - /** @var \Sabre\DAV\Server */ - private $server; + private \Sabre\DAV\Server $server; /** * This initializes the plugin. * diff --git a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php index d2a04bde7e984..207e45e1cf90c 100644 --- a/apps/dav/lib/Connector/Sabre/DavAclPlugin.php +++ b/apps/dav/lib/Connector/Sabre/DavAclPlugin.php @@ -33,6 +33,7 @@ use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAVACL\Exception\NeedPrivileges; +use Sabre\DAVACL\Plugin as ACLPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -44,7 +45,7 @@ * @see https://github.com/owncloud/core/issues/22578 * @package OCA\DAV\Connector\Sabre */ -class DavAclPlugin extends \Sabre\DAVACL\Plugin { +class DavAclPlugin extends ACLPlugin { public function __construct() { $this->hideNodesFromListings = true; $this->allowUnauthenticatedAccess = false; @@ -94,8 +95,8 @@ public function propFind(PropFind $propFind, INode $node) { $readPermissions = $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, false); $writePermissions = $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, false); if ($readPermissions === false && $writePermissions === false) { - $this->checkPrivileges($path, '{DAV:}read', self::R_PARENT, true); - $this->checkPrivileges($path, '{DAV:}write', self::R_PARENT, true); + $this->checkPrivileges($path, '{DAV:}read'); + $this->checkPrivileges($path, '{DAV:}write'); } } diff --git a/apps/dav/lib/Connector/Sabre/Directory.php b/apps/dav/lib/Connector/Sabre/Directory.php index 6611efca8b7af..6a8394ba58109 100644 --- a/apps/dav/lib/Connector/Sabre/Directory.php +++ b/apps/dav/lib/Connector/Sabre/Directory.php @@ -73,19 +73,13 @@ class Directory extends Node implements ICollection, IQuota, IMoveTarget, ICopyT * * @var FileInfo[] */ - private $dirContent; + private array $dirContent; /** * Cached quota info - * - * @var array - */ - private $quotaInfo; - - /** - * @var ObjectTree|null */ - private $tree; + private array $quotaInfo; + private ?ObjectTree $tree; /** * Sets up the node, expects a full path name diff --git a/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php b/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php index 13b79aa39c434..8171c8779dba0 100644 --- a/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php +++ b/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php @@ -44,8 +44,7 @@ * @package OCA\DAV\Connector\Sabre */ class DummyGetResponsePlugin extends ServerPlugin { - /** @var \Sabre\DAV\Server */ - protected $server; + protected \Sabre\DAV\Server $server; /** * @param \Sabre\DAV\Server $server diff --git a/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php b/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php index 4fc3399ca810e..c7963af488e04 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php +++ b/apps/dav/lib/Connector/Sabre/Exception/EntityTooLarge.php @@ -23,13 +23,15 @@ */ namespace OCA\DAV\Connector\Sabre\Exception; +use Sabre\DAV\Exception; + /** * Entity Too Large * * This exception is thrown whenever a user tries to upload a file which exceeds hard limitations * */ -class EntityTooLarge extends \Sabre\DAV\Exception { +class EntityTooLarge extends Exception { /** * Returns the HTTP status code for this exception diff --git a/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php b/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php index 36063da8d6573..b7a9be96bead5 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php +++ b/apps/dav/lib/Connector/Sabre/Exception/FileLocked.php @@ -27,10 +27,11 @@ namespace OCA\DAV\Connector\Sabre\Exception; use Exception; +use OCP\Files\LockNotAcquiredException; class FileLocked extends \Sabre\DAV\Exception { public function __construct($message = "", $code = 0, Exception $previous = null) { - if ($previous instanceof \OCP\Files\LockNotAcquiredException) { + if ($previous instanceof LockNotAcquiredException) { $message = sprintf('Target file %s is locked by another process.', $previous->path); } parent::__construct($message, $code, $previous); diff --git a/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php b/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php index aabd5fda2fb89..f0a30a4efc365 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php +++ b/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php @@ -22,20 +22,20 @@ */ namespace OCA\DAV\Connector\Sabre\Exception; +use DOMElement; +use Exception; +use Sabre\DAV\Server; + class Forbidden extends \Sabre\DAV\Exception\Forbidden { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; - - /** - * @var bool - */ - private $retry; + private bool $retry; /** * @param string $message * @param bool $retry - * @param \Exception $previous + * @param Exception|null $previous */ - public function __construct($message, $retry = false, \Exception $previous = null) { + public function __construct($message, $retry = false, Exception $previous = null) { parent::__construct($message, 0, $previous); $this->retry = $retry; } @@ -44,11 +44,11 @@ public function __construct($message, $retry = false, \Exception $previous = nul * This method allows the exception to include additional information * into the WebDAV error response * - * @param \Sabre\DAV\Server $server - * @param \DOMElement $errorNode + * @param Server $server + * @param DOMElement $errorNode * @return void */ - public function serialize(\Sabre\DAV\Server $server,\DOMElement $errorNode) { + public function serialize(Server $server, DOMElement $errorNode) { // set ownCloud namespace $errorNode->setAttribute('xmlns:o', self::NS_OWNCLOUD); diff --git a/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php b/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php index c504483d45af9..45639f1a88994 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php +++ b/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php @@ -23,15 +23,13 @@ */ namespace OCA\DAV\Connector\Sabre\Exception; +use DOMElement; use Sabre\DAV\Exception; +use Sabre\DAV\Server; class InvalidPath extends Exception { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; - - /** - * @var bool - */ - private $retry; + private bool $retry; /** * @param string $message @@ -56,11 +54,11 @@ public function getHTTPCode() { * This method allows the exception to include additional information * into the WebDAV error response * - * @param \Sabre\DAV\Server $server - * @param \DOMElement $errorNode + * @param Server $server + * @param DOMElement $errorNode * @return void */ - public function serialize(\Sabre\DAV\Server $server,\DOMElement $errorNode) { + public function serialize(Server $server, DOMElement $errorNode) { // set ownCloud namespace $errorNode->setAttribute('xmlns:o', self::NS_OWNCLOUD); diff --git a/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php b/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php index a7e935d249703..3db8a9f124d80 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php +++ b/apps/dav/lib/Connector/Sabre/Exception/UnsupportedMediaType.php @@ -23,13 +23,15 @@ */ namespace OCA\DAV\Connector\Sabre\Exception; +use Sabre\DAV\Exception; + /** * Unsupported Media Type * * This exception is thrown whenever a user tries to upload a file which holds content which is not allowed * */ -class UnsupportedMediaType extends \Sabre\DAV\Exception { +class UnsupportedMediaType extends Exception { /** * Returns the HTTP status code for this exception diff --git a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php index f1b395f6462bb..f0dd80fab55a9 100644 --- a/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/ExceptionLoggerPlugin.php @@ -47,7 +47,7 @@ use Throwable; class ExceptionLoggerPlugin extends ServerPlugin { - protected $nonFatalExceptions = [ + protected array $nonFatalExceptions = [ NotAuthenticated::class => true, // If tokenauth can throw this exception (which is basically as // NotAuthenticated. So not fatal. @@ -86,11 +86,8 @@ class ExceptionLoggerPlugin extends ServerPlugin { RequestedRangeNotSatisfiable::class => true, ]; - /** @var string */ - private $appName; - - /** @var LoggerInterface */ - private $logger; + private string $appName; + private ?LoggerInterface $logger; /** * @param string $loggerAppName app name to use when logging diff --git a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php index 51b0669975313..6fd833b02dac7 100644 --- a/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FakeLockerPlugin.php @@ -47,8 +47,7 @@ * @package OCA\DAV\Connector\Sabre */ class FakeLockerPlugin extends ServerPlugin { - /** @var \Sabre\DAV\Server */ - private $server; + private \Sabre\DAV\Server $server; /** {@inheritDoc} */ public function initialize(\Sabre\DAV\Server $server) { diff --git a/apps/dav/lib/Connector/Sabre/File.php b/apps/dav/lib/Connector/Sabre/File.php index e0e34d2200931..58cdc7758e6bc 100644 --- a/apps/dav/lib/Connector/Sabre/File.php +++ b/apps/dav/lib/Connector/Sabre/File.php @@ -45,6 +45,9 @@ use OC\Files\View; use OCA\DAV\AppInfo\Application; use OC\ServerNotAvailableException; +use OC_FileChunking; +use OC_Helper; +use OC_Hook; use OCA\DAV\Connector\Sabre\Exception\EntityTooLarge; use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCA\DAV\Connector\Sabre\Exception\Forbidden as DAVForbiddenException; @@ -81,6 +84,7 @@ use Sabre\DAV\Exception\NotImplemented; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\IFile; +use function header; class File extends Node implements IFile { protected $request; @@ -257,7 +261,7 @@ public function put($data) { // because we have no clue about the cause we can only throw back a 500/Internal Server Error throw new Exception($this->l10n->t('Could not write file contents')); } - [$count, $result] = \OC_Helper::streamCopy($data, $target); + [$count, $result] = OC_Helper::streamCopy($data, $target); fclose($target); } @@ -430,17 +434,17 @@ private function emitPreHooks(bool $exists, string $path = null): bool { $run = true; if (!$exists) { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [ + OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_create, [ Filesystem::signal_param_path => $hookPath, Filesystem::signal_param_run => &$run, ]); } else { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [ + OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_update, [ Filesystem::signal_param_path => $hookPath, Filesystem::signal_param_run => &$run, ]); } - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [ + OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_write, [ Filesystem::signal_param_path => $hookPath, Filesystem::signal_param_run => &$run, ]); @@ -459,15 +463,15 @@ private function emitPostHooks(bool $exists, string $path = null): void { } $hookPath = Filesystem::getView()->getRelativePath($this->fileView->getAbsolutePath($path)); if (!$exists) { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [ + OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_create, [ Filesystem::signal_param_path => $hookPath ]); } else { - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [ + OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_update, [ Filesystem::signal_param_path => $hookPath ]); } - \OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [ + OC_Hook::emit(Filesystem::CLASSNAME, Filesystem::signal_post_write, [ Filesystem::signal_param_path => $hookPath ]); } @@ -559,7 +563,7 @@ public function getDirectDownload() { if (\OC::$server->get(IAppManager::class)->isEnabledForUser('encryption')) { return []; } - /** @var \OCP\Files\Storage $storage */ + /** @var Storage $storage */ [$storage, $internalPath] = $this->fileView->resolvePath($this->path); if (is_null($storage)) { return []; @@ -579,12 +583,12 @@ public function getDirectDownload() { private function createFileChunked($data): ?string { [$path, $name] = \Sabre\Uri\split($this->path); - $info = \OC_FileChunking::decodeName($name); + $info = OC_FileChunking::decodeName($name); if (empty($info)) { throw new NotImplemented($this->l10n->t('Invalid chunk name')); } - $chunk_handler = new \OC_FileChunking($info); + $chunk_handler = new OC_FileChunking($info); $bytesWritten = $chunk_handler->store($info['index'], $data); //detect aborted upload @@ -758,7 +762,7 @@ public function getChecksum(): ?string { protected function header($string) { if (!\OC::$CLI) { - \header($string); + header($string); } } } diff --git a/apps/dav/lib/Connector/Sabre/FilesPlugin.php b/apps/dav/lib/Connector/Sabre/FilesPlugin.php index 275bc6bd90c95..917c07e81d7a3 100644 --- a/apps/dav/lib/Connector/Sabre/FilesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesPlugin.php @@ -33,7 +33,10 @@ */ namespace OCA\DAV\Connector\Sabre; +use DateTimeImmutable; +use DateTimeInterface; use OC\AppFramework\Http\Request; +use OC_FileChunking; use OCP\Constants; use OCP\Files\ForbiddenException; use OCP\Files\StorageNotAvailableException; @@ -83,57 +86,21 @@ class FilesPlugin extends ServerPlugin { /** * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var Tree - */ - private $tree; - - /** - * @var IUserSession */ - private $userSession; + private \Sabre\DAV\Server $server; + private Tree $tree; + private IUserSession $userSession; /** * Whether this is public webdav. * If true, some returned information will be stripped off. - * - * @var bool - */ - private $isPublic; - - /** - * @var bool */ - private $downloadAttachment; + private bool $isPublic; + private bool $downloadAttachment; + private IConfig $config; + private IRequest $request; + private IPreview $previewManager; - /** - * @var IConfig - */ - private $config; - - /** - * @var IRequest - */ - private $request; - - /** - * @var IPreview - */ - private $previewManager; - - /** - * @param Tree $tree - * @param IConfig $config - * @param IRequest $request - * @param IPreview $previewManager - * @param bool $isPublic - * @param bool $downloadAttachment - */ public function __construct(Tree $tree, IConfig $config, IRequest $request, @@ -303,8 +270,6 @@ public function httpGet(RequestInterface $request, ResponseInterface $response) * @return void */ public function handleGetProperties(PropFind $propFind, INode $node) { - $httpRequest = $this->server->httpRequest; - if ($node instanceof Node) { /** * This was disabled, because it made dir listing throw an exception, @@ -334,7 +299,7 @@ public function handleGetProperties(PropFind $propFind, INode $node) { return $perms; }); - $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest) { + $propFind->handle(self::SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node) { $user = $this->userSession->getUser(); if ($user === null) { return null; @@ -344,7 +309,7 @@ public function handleGetProperties(PropFind $propFind, INode $node) { ); }); - $propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node, $httpRequest) { + $propFind->handle(self::OCM_SHARE_PERMISSIONS_PROPERTYNAME, function () use ($node) { $user = $this->userSession->getUser(); if ($user === null) { return null; @@ -377,7 +342,7 @@ public function handleGetProperties(PropFind $propFind, INode $node) { return $node->getFileInfo()->getMountPoint()->getMountType(); }); - $propFind->handle(self::SHARE_NOTE, function () use ($node, $httpRequest) { + $propFind->handle(self::SHARE_NOTE, function () use ($node) { $user = $this->userSession->getUser(); if ($user === null) { return null; @@ -388,12 +353,12 @@ public function handleGetProperties(PropFind $propFind, INode $node) { }); $propFind->handle(self::DATA_FINGERPRINT_PROPERTYNAME, function () use ($node) { - return $this->config->getSystemValue('data-fingerprint', ''); + return $this->config->getSystemValue('data-fingerprint'); }); $propFind->handle(self::CREATIONDATE_PROPERTYNAME, function () use ($node) { - return (new \DateTimeImmutable()) + return (new DateTimeImmutable()) ->setTimestamp($node->getFileInfo()->getCreationTime()) - ->format(\DateTimeInterface::ATOM); + ->format(DateTimeInterface::ATOM); }); $propFind->handle(self::CREATION_TIME_PROPERTYNAME, function () use ($node) { return $node->getFileInfo()->getCreationTime(); @@ -515,7 +480,7 @@ public function handleUpdateProperties(string $path, PropPatch $propPatch) { if (empty($time)) { return false; } - $dateTime = new \DateTimeImmutable($time); + $dateTime = new DateTimeImmutable($time); $node->setCreationTime($dateTime->getTimestamp()); return true; }); @@ -537,7 +502,7 @@ public function sendFileIdHeader(string $filePath, INode $node = null) { // chunked upload handling if (isset($_SERVER['HTTP_OC_CHUNKED'])) { [$path, $name] = \Sabre\Uri\split($filePath); - $info = \OC_FileChunking::decodeName($name); + $info = OC_FileChunking::decodeName($name); if (!empty($info)) { $filePath = $path . '/' . $info['name']; } diff --git a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php index 9aa8205d88bcd..53efde765e660 100644 --- a/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php +++ b/apps/dav/lib/Connector/Sabre/FilesReportPlugin.php @@ -56,57 +56,21 @@ class FilesReportPlugin extends ServerPlugin { /** * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var Tree - */ - private $tree; - - /** - * @var View - */ - private $fileView; - - /** - * @var ISystemTagManager - */ - private $tagManager; - - /** - * @var ISystemTagObjectMapper */ - private $tagMapper; + private \Sabre\DAV\Server $server; + private Tree $tree; + private View $fileView; + private ISystemTagManager $tagManager; + private ISystemTagObjectMapper $tagMapper; /** * Manager for private tags - * - * @var ITagManager - */ - private $fileTagger; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var Folder - */ - private $userFolder; - - /** - * @var IAppManager */ - private $appManager; + private ITagManager $fileTagger; + private IUserSession $userSession; + private IGroupManager $groupManager; + private Folder $userFolder; + private IAppManager $appManager; /** * @param Tree $tree @@ -214,7 +178,7 @@ public function onReport(string $reportName, $report, string $uri) { try { $resultFileIds = $this->processFilterRules($filterRules); } catch (TagNotFoundException $e) { - throw new PreconditionFailed('Cannot filter by non-existing tag', 0, $e); + throw new PreconditionFailed('Cannot filter by non-existing tag', 0); } // find sabre nodes by file id, restricted to the root node path diff --git a/apps/dav/lib/Connector/Sabre/LockPlugin.php b/apps/dav/lib/Connector/Sabre/LockPlugin.php index 805b98c91e7bd..04a6b6816e4bb 100644 --- a/apps/dav/lib/Connector/Sabre/LockPlugin.php +++ b/apps/dav/lib/Connector/Sabre/LockPlugin.php @@ -36,17 +36,13 @@ class LockPlugin extends ServerPlugin { /** * Reference to main server object - * - * @var \Sabre\DAV\Server */ - private $server; + private \Sabre\DAV\Server $server; /** * State of the lock - * - * @var bool */ - private $isLocked; + private bool $isLocked; /** * {@inheritdoc} diff --git a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php index 87b99158405c3..a40cb93b0fd25 100644 --- a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php +++ b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php @@ -29,32 +29,23 @@ use OCP\IConfig; use OCP\IL10N; -use OCP\L10N\IFactory; use OCP\Util; use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\ServerPlugin; class MaintenancePlugin extends ServerPlugin { - /** @var IConfig */ - private $config; - - /** @var IL10N */ - private $l10n; + private IConfig $config; + private IL10N $l10n; /** * Reference to main server object - * - * @var Server */ - private $server; + private \Sabre\DAV\Server $server; - /** - * @param IConfig $config - */ public function __construct(IConfig $config, IL10N $l10n) { $this->config = $config; - $this->l10n = \OC::$server->get(IFactory::class)->get('dav'); + $this->l10n = $l10n; } diff --git a/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php b/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php index 6700b1eb81b5d..a234db00c44ba 100644 --- a/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php +++ b/apps/dav/lib/Connector/Sabre/MtimeSanitizer.php @@ -22,6 +22,8 @@ namespace OCA\DAV\Connector\Sabre; +use InvalidArgumentException; + class MtimeSanitizer { public static function sanitizeMtime(string $mtimeFromRequest): int { // In PHP 5.X "is_numeric" returns true for strings in hexadecimal @@ -29,12 +31,12 @@ public static function sanitizeMtime(string $mtimeFromRequest): int { // ensures that strings with hexadecimal notations fail too in PHP 5.X. $isHexadecimal = preg_match('/^\s*0[xX]/', $mtimeFromRequest); if ($isHexadecimal || !is_numeric($mtimeFromRequest)) { - throw new \InvalidArgumentException('X-OC-MTime header must be an integer (unix timestamp).'); + throw new InvalidArgumentException('X-OC-MTime header must be an integer (unix timestamp).'); } // Prevent writing invalid mtime (timezone-proof) if ((int)$mtimeFromRequest <= 24 * 60 * 60) { - throw new \InvalidArgumentException('X-OC-MTime header must be a valid positive integer'); + throw new InvalidArgumentException('X-OC-MTime header must be a valid positive integer'); } return (int)$mtimeFromRequest; diff --git a/apps/dav/lib/Connector/Sabre/Node.php b/apps/dav/lib/Connector/Sabre/Node.php index dfd0b1214f4e9..34318902a3cc7 100644 --- a/apps/dav/lib/Connector/Sabre/Node.php +++ b/apps/dav/lib/Connector/Sabre/Node.php @@ -37,6 +37,7 @@ use OC\Files\Mount\MoveableMount; use OC\Files\View; +use OC_Util; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; use OCA\Files_Sharing\SharedStorage; use OCP\Constants; @@ -55,35 +56,18 @@ use Sabre\DAV\INode; abstract class Node implements INode { - - /** - * @var View - */ - protected $fileView; - /** * The path to the current node - * - * @var string|null */ - protected $path; + protected ?string $path; /** * node properties cache - * - * @var array - */ - protected $property_cache = null; - - /** - * @var FileInfo|null - */ - protected $info; - - /** - * @var IManager */ - protected $shareManager; + protected ?array $property_cache = null; + protected View $fileView; + protected ?FileInfo $info; + protected IManager $shareManager; /** * Sets up the node, expects a full path name @@ -245,7 +229,7 @@ public function getId(): ?int { */ public function getFileId(): ?string { if ($this->info->getId()) { - $instanceId = \OC_Util::getInstanceId(); + $instanceId = OC_Util::getInstanceId(); $id = sprintf('%08d', $this->info->getId()); return $id . $instanceId; } @@ -290,7 +274,7 @@ public function getSharePermissions(?string $user): int { } /* - * We can always share non moveable mount points with DELETE and UPDATE + * We can always share non movable mount points with DELETE and UPDATE * Eventually we need to do this properly */ $mountpoint = $this->info->getMountPoint(); diff --git a/apps/dav/lib/Connector/Sabre/ObjectTree.php b/apps/dav/lib/Connector/Sabre/ObjectTree.php index ab296fdccbb5e..d47952c4da14c 100644 --- a/apps/dav/lib/Connector/Sabre/ObjectTree.php +++ b/apps/dav/lib/Connector/Sabre/ObjectTree.php @@ -33,10 +33,12 @@ use OC\Files\Storage\FailedStorage; use OC\Files\Storage\Storage; use OC\Files\View; +use OC_FileChunking; use OCA\DAV\Connector\Sabre\Exception\FileLocked; use OCA\DAV\Connector\Sabre\Exception\Forbidden; use OCA\DAV\Connector\Sabre\Exception\InvalidPath; use OCP\Files\ForbiddenException; +use OCP\Files\InvalidPathException; use OCP\Files\Mount\IMountManager; use OCP\Files\StorageInvalidException; use OCP\Files\StorageNotAvailableException; @@ -47,16 +49,8 @@ use Sabre\DAV\INode; class ObjectTree extends CachingTree { - - /** - * @var View - */ - protected $fileView; - - /** - * @var IMountManager - */ - protected $mountManager; + protected View $fileView; + protected IMountManager $mountManager; /** * @param INode $rootNode @@ -86,7 +80,7 @@ private function resolveChunkFile(string $path): string { $dir = ''; } - $info = \OC_FileChunking::decodeName($name); + $info = OC_FileChunking::decodeName($name); // only replace path if it was really the chunked file if (isset($info['transferid'])) { // getNodePath is called for multiple nodes within a chunk @@ -122,7 +116,7 @@ public function getNodeForPath($path) { if ($path) { try { $this->fileView->verifyPath($path, basename($path)); - } catch (\OCP\Files\InvalidPathException $ex) { + } catch (InvalidPathException $ex) { throw new InvalidPath($ex->getMessage()); } } @@ -224,7 +218,7 @@ public function copy($sourcePath, $destinationPath) { [$destinationDir, $destinationName] = \Sabre\Uri\split($destinationPath); try { $this->fileView->verifyPath($destinationDir, $destinationName); - } catch (\OCP\Files\InvalidPathException $ex) { + } catch (InvalidPathException $ex) { throw new InvalidPath($ex->getMessage()); } diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 8c9696f2850ee..3f88cffd7f93a 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -46,7 +46,6 @@ use OCA\Circles\Exceptions\InvalidIdException; use OCA\Circles\Exceptions\RequestBuilderException; use OCA\Circles\Exceptions\SingleCircleNotFoundException; -use OCA\Circles\Model\Circle; use OCA\DAV\CalDAV\Proxy\ProxyMapper; use OCA\DAV\Traits\PrincipalProxyTrait; use OCP\App\IAppManager; @@ -63,43 +62,21 @@ use Sabre\DAV\Exception; use Sabre\DAV\PropPatch; use Sabre\DAVACL\PrincipalBackend\BackendInterface; +use function array_filter; class Principal implements BackendInterface { - - /** @var IUserManager */ - private $userManager; - - /** @var IGroupManager */ - private $groupManager; - - /** @var IShareManager */ - private $shareManager; - - /** @var IUserSession */ - private $userSession; - - /** @var IAppManager */ - private $appManager; - - /** @var string */ - private $principalPrefix; - - /** @var bool */ - private $hasGroups; - - /** @var bool */ - private $hasCircles; - - /** @var ProxyMapper */ - private $proxyMapper; - - /** @var KnownUserService */ - private $knownUserService; - - /** @var IConfig */ - private $config; - /** @var IFactory */ - private $languageFactory; + private IUserManager $userManager; + private IGroupManager $groupManager; + private IShareManager $shareManager; + private IUserSession $userSession; + private IAppManager $appManager; + private string $principalPrefix; + private bool $hasGroups; + private bool $hasCircles; + private ProxyMapper $proxyMapper; + private KnownUserService $knownUserService; + private IConfig $config; + private IFactory $languageFactory; public function __construct(IUserManager $userManager, IGroupManager $groupManager, @@ -311,7 +288,7 @@ protected function searchUserPrincipals(array $searchProperties, string $test = } } else { $users = $this->userManager->getByEmail($value); - $users = \array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) { + $users = array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) { if ($allowEnumerationFullMatch && $user->getSystemEMailAddress() === $value) { return true; } @@ -354,7 +331,7 @@ protected function searchUserPrincipals(array $searchProperties, string $test = if (!$allowEnumeration) { if ($allowEnumerationFullMatch) { $users = $this->userManager->searchDisplayName($value, $searchLimit); - $users = \array_filter($users, static function (IUser $user) use ($value) { + $users = array_filter($users, static function (IUser $user) use ($value) { return $user->getDisplayName() === $value; }); } else { @@ -362,7 +339,7 @@ protected function searchUserPrincipals(array $searchProperties, string $test = } } else { $users = $this->userManager->searchDisplayName($value, $searchLimit); - $users = \array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) { + $users = array_filter($users, function (IUser $user) use ($currentUser, $value, $limitEnumerationPhone, $limitEnumerationGroup, $allowEnumerationFullMatch, $currentUserGroups) { if ($allowEnumerationFullMatch && $user->getDisplayName() === $value) { return true; } diff --git a/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php b/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php index 5c47d2f68f3fa..679542cc4ffa1 100644 --- a/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php +++ b/apps/dav/lib/Connector/Sabre/PropfindCompressionPlugin.php @@ -33,10 +33,8 @@ class PropfindCompressionPlugin extends ServerPlugin { /** * Reference to main server object - * - * @var Server */ - private $server; + private \Sabre\DAV\Server $server; /** * This initializes the plugin. diff --git a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php index 398ffd0ac77ee..3f5ae3f1c200c 100644 --- a/apps/dav/lib/Connector/Sabre/QuotaPlugin.php +++ b/apps/dav/lib/Connector/Sabre/QuotaPlugin.php @@ -31,6 +31,7 @@ namespace OCA\DAV\Connector\Sabre; use OC\Files\View; +use OC_FileChunking; use OCA\DAV\Upload\FutureFile; use OCP\Files\InvalidPathException; use OCP\Files\StorageNotAvailableException; @@ -48,20 +49,15 @@ * @license http://code.google.com/p/sabredav/wiki/License Modified BSD License */ class QuotaPlugin extends ServerPlugin { - - /** @var View */ - private $view; + private View $view; /** * Reference to main server object * * @var \Sabre\DAV\Server */ - private $server; + private \Sabre\DAV\Server $server; - /** - * @param View $view - */ public function __construct(View $view) { $this->view = $view; } @@ -168,7 +164,7 @@ public function checkQuota(string $path, int $length = null): bool { } $req = $this->server->httpRequest; if ($req->getHeader('OC-Chunked')) { - $info = \OC_FileChunking::decodeName($newName); + $info = OC_FileChunking::decodeName($newName); $chunkHandler = $this->getFileChunking($info); // subtract the already uploaded size to see whether // there is still enough space for the remaining chunks @@ -187,9 +183,9 @@ public function checkQuota(string $path, int $length = null): bool { return true; } - public function getFileChunking($info): \OC_FileChunking { + public function getFileChunking($info): OC_FileChunking { // FIXME: need a factory for better mocking support - return new \OC_FileChunking($info); + return new OC_FileChunking($info); } public function getLength() { diff --git a/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php b/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php index b281a1053b8d5..f874418b212f8 100644 --- a/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php +++ b/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php @@ -22,12 +22,12 @@ namespace OCA\DAV\Connector\Sabre; use OCP\IRequest; +use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; -class RequestIdHeaderPlugin extends \Sabre\DAV\ServerPlugin { - /** @var IRequest */ - private $request; +class RequestIdHeaderPlugin extends ServerPlugin { + private IRequest $request; public function __construct(IRequest $request) { $this->request = $request; diff --git a/apps/dav/lib/Connector/Sabre/ServerFactory.php b/apps/dav/lib/Connector/Sabre/ServerFactory.php index 88b8ad91f388b..185ecf35573ea 100644 --- a/apps/dav/lib/Connector/Sabre/ServerFactory.php +++ b/apps/dav/lib/Connector/Sabre/ServerFactory.php @@ -31,6 +31,7 @@ */ namespace OCA\DAV\Connector\Sabre; +use OC; use OC\Files\View; use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\DAV\CustomPropertiesBackend; @@ -59,26 +60,16 @@ use Sabre\DAV\SimpleCollection; class ServerFactory { - /** @var IConfig */ - private $config; - /** @var LoggerInterface */ - private $logger; - /** @var IDBConnection */ - private $databaseConnection; - /** @var IUserSession */ - private $userSession; - /** @var IMountManager */ - private $mountManager; - /** @var ITagManager */ - private $tagManager; - /** @var IRequest */ - private $request; - /** @var IPreview */ - private $previewManager; - /** @var IEventDispatcher */ - private $eventDispatcher; - /** @var IL10N */ - private $l10n; + private IConfig $config; + private LoggerInterface $logger; + private IDBConnection $databaseConnection; + private IUserSession $userSession; + private IMountManager $mountManager; + private ITagManager $tagManager; + private IRequest $request; + private IPreview $previewManager; + private IEventDispatcher $eventDispatcher; + private IL10N $l10n; /** * @param IConfig $config @@ -163,9 +154,9 @@ public function createServer(string $baseUri, $server->on('beforeMethod:*', function () use ($server, $objectTree, $viewCallBack) { // ensure the skeleton is copied $userFolder = null; - $root = \OC::$server->get(IRootFolder::class); + $root = OC::$server->get(IRootFolder::class); /** @var IUser $user */ - if ($user = \OC::$server->get(IUserSession::class)->getUser()) { + if ($user = OC::$server->get(IUserSession::class)->getUser()) { /** @var IRootFolder $root */ $rootInfo = $root->getUserFolder($user->getUID()); $userFolder = $rootInfo; @@ -203,19 +194,19 @@ public function createServer(string $baseUri, $objectTree, $this->userSession, $userFolder, - \OC::$server->get(IManager::class) + OC::$server->get(IManager::class) )); - $server->addPlugin(new CommentPropertiesPlugin(\OC::$server->get(ICommentsManager::class), $this->userSession)); + $server->addPlugin(new CommentPropertiesPlugin(OC::$server->get(ICommentsManager::class), $this->userSession)); $server->addPlugin(new FilesReportPlugin( $objectTree, $view, - \OC::$server->get(ISystemTagManager::class), - \OC::$server->get(ISystemTagObjectMapper::class), - \OC::$server->get(ITagManager::class), + OC::$server->get(ISystemTagManager::class), + OC::$server->get(ISystemTagObjectMapper::class), + OC::$server->get(ITagManager::class), $this->userSession, - \OC::$server->get(IGroupManager::class), + OC::$server->get(IGroupManager::class), $userFolder, - \OC::$server->get(IAppManager::class) + OC::$server->get(IAppManager::class) )); // custom properties plugin must be the last one $server->addPlugin( @@ -234,8 +225,8 @@ public function createServer(string $baseUri, $event = new SabrePluginEvent($server); $this->eventDispatcher->dispatchTyped($event); $pluginManager = new PluginManager( - \OC::$server, - \OC::$server->get(IAppManager::class) + OC::$server, + OC::$server->get(IAppManager::class) ); foreach ($pluginManager->getAppPlugins() as $appPlugin) { $server->addPlugin($appPlugin); diff --git a/apps/dav/lib/Connector/Sabre/ShareTypeList.php b/apps/dav/lib/Connector/Sabre/ShareTypeList.php index df5caf705ebb3..ab2b93365c76c 100644 --- a/apps/dav/lib/Connector/Sabre/ShareTypeList.php +++ b/apps/dav/lib/Connector/Sabre/ShareTypeList.php @@ -41,7 +41,7 @@ class ShareTypeList implements Element { * * @var int[] */ - private $shareTypes; + private array $shareTypes; /** * @param int[] $shareTypes diff --git a/apps/dav/lib/Connector/Sabre/ShareeList.php b/apps/dav/lib/Connector/Sabre/ShareeList.php index db8c011cc4510..570e5b6efbf96 100644 --- a/apps/dav/lib/Connector/Sabre/ShareeList.php +++ b/apps/dav/lib/Connector/Sabre/ShareeList.php @@ -38,7 +38,7 @@ class ShareeList implements XmlSerializable { public const NS_NEXTCLOUD = 'http://nextcloud.org/ns'; /** @var IShare[] */ - private $shares; + private array $shares; public function __construct(array $shares) { $this->shares = $shares; diff --git a/apps/dav/lib/Connector/Sabre/SharesPlugin.php b/apps/dav/lib/Connector/Sabre/SharesPlugin.php index fb1c429ac1c58..1d1c411237345 100644 --- a/apps/dav/lib/Connector/Sabre/SharesPlugin.php +++ b/apps/dav/lib/Connector/Sabre/SharesPlugin.php @@ -48,23 +48,16 @@ class SharesPlugin extends ServerPlugin { public const SHARETYPES_PROPERTYNAME = '{http://owncloud.org/ns}share-types'; public const SHAREES_PROPERTYNAME = '{http://nextcloud.org/ns}sharees'; - /** @var IManager */ - private $shareManager; - - /** @var Tree */ - private $tree; - - /** @var string */ - private $userId; - - /** @var Folder */ - private $userFolder; + private IManager $shareManager; + private Tree $tree; + private string $userId; + private Folder $userFolder; /** @var IShare[][] */ - private $cachedShares = []; + private array $cachedShares = []; /** @var string[] */ - private $cachedFolders = []; + private array $cachedFolders = []; /** * @param Tree $tree tree diff --git a/apps/dav/lib/Connector/Sabre/TagList.php b/apps/dav/lib/Connector/Sabre/TagList.php index a89fdc6f00682..74fc7d68788db 100644 --- a/apps/dav/lib/Connector/Sabre/TagList.php +++ b/apps/dav/lib/Connector/Sabre/TagList.php @@ -37,16 +37,8 @@ class TagList implements Element { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; - /** - * tags - * - * @var array - */ - private $tags; + private array $tags; - /** - * @param array $tags - */ public function __construct(array $tags) { $this->tags = $tags; } @@ -104,7 +96,7 @@ public static function xmlDeserialize(Reader $reader): ?TagList { * Use the $writer argument to write its own xml serialization. * * An important note: do _not_ create a parent element. Any element - * implementing XmlSerializble should only ever write what's considered + * implementing XmlSerializable should only ever write what's considered * its 'inner xml'. * * The parent of the current element is responsible for writing a diff --git a/apps/dav/lib/Connector/Sabre/TagsPlugin.php b/apps/dav/lib/Connector/Sabre/TagsPlugin.php index 9af78eb6ab878..c8e648e56d5b0 100644 --- a/apps/dav/lib/Connector/Sabre/TagsPlugin.php +++ b/apps/dav/lib/Connector/Sabre/TagsPlugin.php @@ -52,8 +52,10 @@ use OCP\ITagManager; use OCP\ITags; +use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\Locked; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Exception\ServiceUnavailable; use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; @@ -70,33 +72,17 @@ class TagsPlugin extends ServerPlugin { /** * Reference to main server object - * - * @var \Sabre\DAV\Server - */ - private $server; - - /** - * @var ITagManager - */ - private $tagManager; - - /** - * @var ITags */ - private $tagger; + private \Sabre\DAV\Server $server; + private ITagManager $tagManager; + private ?ITags $tagger; /** * Array of file id to tags array * The null value means the cache wasn't initialized. - * - * @var array - */ - private $cachedTags; - - /** - * @var Tree */ - private $tree; + private array $cachedTags; + private Tree $tree; /** * @param Tree $tree tree @@ -216,7 +202,11 @@ private function updateTags(int $fileId, array $tags): void { * @param INode $node * @return void * @throws Exception\Forbidden + * @throws Exception\InvalidPath * @throws Locked + * @throws NotFound + * @throws Forbidden + * @throws ServiceUnavailable */ public function handleGetProperties( PropFind $propFind, diff --git a/lib/public/Calendar/ICalendar.php b/lib/public/Calendar/ICalendar.php index 0d08e2ba268aa..8d1ea359421f2 100644 --- a/lib/public/Calendar/ICalendar.php +++ b/lib/public/Calendar/ICalendar.php @@ -37,7 +37,7 @@ interface ICalendar { * @return string defining the technical unique key * @since 13.0.0 */ - public function getKey(); + public function getKey(): string; /** * @since 24.0.0 @@ -49,14 +49,14 @@ public function getUri(): string; * @return null|string * @since 13.0.0 */ - public function getDisplayName(); + public function getDisplayName(): ?string; /** * Calendar color * @return null|string * @since 13.0.0 */ - public function getDisplayColor(); + public function getDisplayColor(): ?string; /** * @param string $pattern which should match within the $searchProperties @@ -68,11 +68,11 @@ public function getDisplayColor(); * @return array an array of events/journals/todos which are arrays of key-value-pairs * @since 13.0.0 */ - public function search($pattern, array $searchProperties = [], array $options = [], $limit = null, $offset = null); + public function search(string $pattern, array $searchProperties = [], array $options = [], int $limit = null, int $offset = null): array; /** * @return integer build up using \OCP\Constants * @since 13.0.0 */ - public function getPermissions(); + public function getPermissions(): int; } From 6d6008dfd5843cca63a2a9f728c04068696f20a0 Mon Sep 17 00:00:00 2001 From: Thomas Citharel Date: Thu, 24 Mar 2022 20:16:23 +0100 Subject: [PATCH 23/23] Rebasing, cs and more typing Signed-off-by: Thomas Citharel --- apps/dav/appinfo/v1/caldav.php | 2 +- apps/dav/bin/chunkperf.php | 2 +- apps/dav/lib/AppInfo/PluginManager.php | 1 - apps/dav/lib/Avatars/AvatarHome.php | 19 +--- apps/dav/lib/Avatars/AvatarNode.php | 15 +-- apps/dav/lib/Avatars/RootCollection.php | 4 +- .../CleanupInvitationTokenJob.php | 1 - .../lib/BackgroundJob/RefreshWebcalJob.php | 1 - ...ateCalendarResourcesRoomsBackgroundJob.php | 1 - .../dav/lib/CalDAV/Activity/Provider/Todo.php | 1 - apps/dav/lib/CalDAV/CalDavBackend.php | 16 +-- apps/dav/lib/CalDAV/CalendarHome.php | 5 +- apps/dav/lib/CalDAV/CalendarManager.php | 11 +-- apps/dav/lib/CalDAV/CalendarProvider.php | 4 +- apps/dav/lib/CalDAV/CalendarRoot.php | 6 +- apps/dav/lib/CalDAV/PublicCalendarRoot.php | 11 +-- .../lib/CalDAV/Publishing/PublishPlugin.php | 2 +- apps/dav/lib/CalDAV/Reminder/Notifier.php | 1 - .../lib/CalDAV/Reminder/ReminderService.php | 1 - .../AbstractPrincipalBackend.php | 6 +- .../ResourcePrincipalBackend.php | 1 - .../ResourceBooking/RoomPrincipalBackend.php | 1 - apps/dav/lib/CalDAV/Schedule/IMipPlugin.php | 20 ++-- apps/dav/lib/CalDAV/Schedule/Plugin.php | 1 - apps/dav/lib/Capabilities.php | 2 +- apps/dav/lib/CardDAV/Activity/Backend.php | 16 +-- apps/dav/lib/CardDAV/Activity/Filter.php | 8 +- .../CardDAV/Activity/Provider/Addressbook.php | 11 +-- .../lib/CardDAV/Activity/Provider/Base.php | 16 +-- .../lib/CardDAV/Activity/Provider/Card.php | 15 +-- apps/dav/lib/CardDAV/AddressBookImpl.php | 16 +-- apps/dav/lib/CardDAV/AddressBookRoot.php | 18 ++-- apps/dav/lib/CardDAV/CardDavBackend.php | 29 ++---- apps/dav/lib/CardDAV/ContactsManager.php | 31 +----- apps/dav/lib/CardDAV/Converter.php | 4 +- apps/dav/lib/CardDAV/HasPhotoPlugin.php | 4 +- apps/dav/lib/CardDAV/ImageExportPlugin.php | 7 +- .../Integration/ExternalAddressBook.php | 10 +- apps/dav/lib/CardDAV/MultiGetExportPlugin.php | 7 +- apps/dav/lib/CardDAV/PhotoCache.php | 45 ++------- apps/dav/lib/CardDAV/SyncService.php | 98 ++++--------------- apps/dav/lib/CardDAV/SystemAddressbook.php | 5 +- apps/dav/lib/CardDAV/UserAddressBooks.php | 14 +-- apps/dav/lib/CardDAV/Xml/Groups.php | 5 +- apps/dav/lib/Command/CreateAddressBook.php | 12 +-- apps/dav/lib/Command/CreateCalendar.php | 17 +--- apps/dav/lib/Command/DeleteCalendar.php | 25 +---- apps/dav/lib/Command/ListCalendars.php | 12 +-- apps/dav/lib/Command/MoveCalendar.php | 40 ++------ apps/dav/lib/Command/RemoveInvalidShares.php | 16 +-- .../lib/Command/RetentionCleanupCommand.php | 3 +- apps/dav/lib/Command/SendEventReminders.php | 12 +-- apps/dav/lib/Command/SyncBirthdayCalendar.php | 17 +--- .../dav/lib/Command/SyncSystemAddressBook.php | 7 +- apps/dav/lib/Comments/CommentNode.php | 47 +++------ apps/dav/lib/Comments/CommentsPlugin.php | 19 +--- apps/dav/lib/Comments/EntityCollection.php | 40 +++----- .../dav/lib/Comments/EntityTypeCollection.php | 34 ++----- apps/dav/lib/Comments/RootCollection.php | 39 ++------ apps/dav/lib/Connector/Sabre/Auth.php | 2 +- .../Sabre/DummyGetResponsePlugin.php | 2 +- .../Connector/Sabre/Exception/BadGateway.php | 6 +- .../Connector/Sabre/Exception/Forbidden.php | 4 +- .../Connector/Sabre/Exception/InvalidPath.php | 4 +- .../lib/Connector/Sabre/MaintenancePlugin.php | 1 - apps/dav/lib/Connector/Sabre/Principal.php | 2 +- .../Connector/Sabre/RequestIdHeaderPlugin.php | 4 +- .../Controller/BirthdayCalendarController.php | 43 ++------ apps/dav/lib/Controller/DirectController.php | 24 ++--- .../InvitationResponseController.php | 21 +--- apps/dav/lib/DAV/CustomPropertiesBackend.php | 27 ++--- apps/dav/lib/DAV/GroupPrincipalBackend.php | 21 +--- apps/dav/lib/DAV/PublicAuth.php | 2 +- apps/dav/lib/DAV/Sharing/Backend.php | 37 ++----- apps/dav/lib/DAV/Sharing/Plugin.php | 17 ++-- apps/dav/lib/DAV/Sharing/Xml/Invite.php | 10 +- apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php | 11 +-- apps/dav/lib/Db/Direct.php | 15 +-- apps/dav/lib/Direct/DirectFile.php | 14 +-- apps/dav/lib/Direct/DirectHome.php | 22 ++--- apps/dav/lib/Direct/ServerFactory.php | 8 +- .../lib/Events/AddressBookCreatedEvent.php | 8 +- .../lib/Events/AddressBookDeletedEvent.php | 12 +-- .../Events/AddressBookShareUpdatedEvent.php | 27 +---- .../lib/Events/AddressBookUpdatedEvent.php | 22 +---- .../BeforeFileDirectDownloadedEvent.php | 2 +- .../CachedCalendarObjectCreatedEvent.php | 22 +---- .../CachedCalendarObjectDeletedEvent.php | 22 +---- .../CachedCalendarObjectUpdatedEvent.php | 22 +---- apps/dav/lib/Events/CalendarCreatedEvent.php | 8 +- apps/dav/lib/Events/CalendarDeletedEvent.php | 17 +--- .../lib/Events/CalendarMovedToTrashEvent.php | 15 +-- .../lib/Events/CalendarObjectCreatedEvent.php | 22 +---- .../lib/Events/CalendarObjectDeletedEvent.php | 22 +---- .../CalendarObjectMovedToTrashEvent.php | 20 +--- .../Events/CalendarObjectRestoredEvent.php | 20 +--- .../lib/Events/CalendarObjectUpdatedEvent.php | 22 +---- .../dav/lib/Events/CalendarPublishedEvent.php | 17 +--- apps/dav/lib/Events/CalendarRestoredEvent.php | 15 +-- .../lib/Events/CalendarShareUpdatedEvent.php | 27 +---- .../lib/Events/CalendarUnpublishedEvent.php | 12 +-- apps/dav/lib/Events/CalendarUpdatedEvent.php | 22 +---- apps/dav/lib/Events/CardCreatedEvent.php | 22 +---- apps/dav/lib/Events/CardDeletedEvent.php | 22 +---- apps/dav/lib/Events/CardUpdatedEvent.php | 22 +---- apps/dav/lib/Events/SabreAddPluginEvent.php | 4 +- .../lib/Events/SabrePluginAuthInitEvent.php | 4 +- .../lib/Events/SubscriptionCreatedEvent.php | 12 +-- .../lib/Events/SubscriptionDeletedEvent.php | 17 +--- .../lib/Events/SubscriptionUpdatedEvent.php | 22 +---- apps/dav/lib/Files/BrowserErrorPagePlugin.php | 8 +- apps/dav/lib/Files/FileSearchBackend.php | 27 ++--- apps/dav/lib/Files/FilesHome.php | 17 +--- apps/dav/lib/Files/LazySearchBackend.php | 11 +-- .../dav/lib/Files/Sharing/FilesDropPlugin.php | 15 ++- .../Files/Sharing/PublicLinkCheckPlugin.php | 9 +- .../lib/Listener/ActivityUpdaterListener.php | 8 +- apps/dav/lib/Listener/AddressbookListener.php | 7 +- apps/dav/lib/Listener/BirthdayListener.php | 3 +- .../CalendarContactInteractionListener.php | 19 +--- ...CalendarDeletionDefaultUpdaterListener.php | 8 +- .../CalendarObjectReminderUpdaterListener.php | 16 +-- .../Listener/CalendarPublicationListener.php | 8 +- .../Listener/CalendarShareUpdateListener.php | 8 +- .../CalendarUnpublicationListener.php | 8 +- apps/dav/lib/Listener/CardListener.php | 7 +- .../lib/Listener/ClearPhotoCacheListener.php | 3 +- .../Listener/SubscriptionCreationListener.php | 12 +-- .../Listener/SubscriptionDeletionListener.php | 12 +-- apps/dav/lib/Listener/UserChangeListener.php | 40 ++------ .../Migration/BuildCalendarSearchIndex.php | 12 +-- .../BuildCalendarSearchIndexBackgroundJob.php | 38 +++---- .../lib/Migration/BuildSocialSearchIndex.php | 17 +--- .../BuildSocialSearchIndexBackgroundJob.php | 42 +++----- .../lib/Migration/CalDAVRemoveEmptyValue.php | 12 +-- apps/dav/lib/Migration/ChunkCleanup.php | 13 +-- .../FixBirthdayCalendarComponent.php | 4 +- .../Migration/RefreshWebcalJobRegistrar.php | 8 +- .../Migration/RegenerateBirthdayCalendars.php | 8 +- ...egisterBuildReminderIndexBackgroundJob.php | 14 +-- .../RemoveClassifiedEventActivity.php | 4 +- ...emoveDeletedUsersCalendarSubscriptions.php | 15 +-- .../RemoveOrphanEventsAndContacts.php | 20 ++-- .../Version1005Date20180413093149.php | 2 +- .../Version1008Date20181105104826.php | 9 +- .../Version1008Date20181105110300.php | 9 +- .../Apple/AppleProvisioningNode.php | 2 +- .../Apple/AppleProvisioningPlugin.php | 58 ++--------- apps/dav/lib/RootCollection.php | 6 +- .../lib/Search/ACalendarSearchProvider.php | 16 +-- .../dav/lib/Search/ContactsSearchProvider.php | 18 +--- apps/dav/lib/Search/EventsSearchProvider.php | 6 +- apps/dav/lib/Search/TasksSearchProvider.php | 10 +- apps/dav/lib/Server.php | 6 +- apps/dav/lib/Settings/CalDAVSettings.php | 15 +-- apps/dav/lib/Storage/PublicOwnerWrapper.php | 4 +- .../lib/SystemTag/SystemTagMappingNode.php | 67 +++---------- apps/dav/lib/SystemTag/SystemTagNode.php | 29 ++---- apps/dav/lib/SystemTag/SystemTagPlugin.php | 33 ++----- .../SystemTag/SystemTagsByIdCollection.php | 20 +--- .../SystemTagsObjectMappingCollection.php | 40 ++------ .../SystemTagsObjectTypeCollection.php | 48 ++------- .../SystemTagsRelationsCollection.php | 10 -- apps/dav/lib/Traits/PrincipalProxyTrait.php | 10 +- apps/dav/lib/Upload/AssemblyStream.php | 22 ++--- apps/dav/lib/Upload/ChunkingPlugin.php | 7 +- apps/dav/lib/Upload/CleanupService.php | 6 +- apps/dav/lib/Upload/FutureFile.php | 15 +-- apps/dav/lib/Upload/RootCollection.php | 4 +- apps/dav/lib/Upload/UploadFile.php | 4 +- apps/dav/lib/Upload/UploadFolder.php | 7 +- apps/dav/lib/Upload/UploadHome.php | 7 +- .../lib/UserMigration/CalendarMigrator.php | 1 - .../UserMigration/CalendarMigratorTest.php | 1 - .../tests/unit/CalDAV/PublicCalendarTest.php | 4 +- .../AbstractPrincipalBackendTest.php | 10 +- .../unit/CalDAV/Schedule/IMipPluginTest.php | 4 +- .../tests/unit/CalDAV/Schedule/PluginTest.php | 2 +- .../unit/CardDAV/AddressBookImplTest.php | 2 +- .../tests/unit/CardDAV/CardDavBackendTest.php | 4 +- .../Sabre/Exception/ForbiddenTest.php | 4 +- .../Sabre/Exception/InvalidPathTest.php | 4 +- .../Connector/Sabre/FakeLockerPluginTest.php | 1 - .../tests/unit/Connector/Sabre/FileTest.php | 6 +- .../Sabre/RequestTest/DeleteTest.php | 1 - .../unit/Files/MultipartRequestParserTest.php | 2 +- .../unit/Listener/UserChangeListenerTest.php | 8 +- .../tests/unit/Upload/AssemblyStreamTest.php | 2 +- 188 files changed, 646 insertions(+), 1985 deletions(-) diff --git a/apps/dav/appinfo/v1/caldav.php b/apps/dav/appinfo/v1/caldav.php index 4caa355ac21a8..3a7be94747e6d 100644 --- a/apps/dav/appinfo/v1/caldav.php +++ b/apps/dav/appinfo/v1/caldav.php @@ -114,7 +114,7 @@ $principalCollection = new Collection($principalBackend); $principalCollection->disableListing = !$debugging; // Disable listing -$addressBookRoot = new CalendarRoot($principalBackend, $calDavBackend, 'principals', \OC::$server->get(LoggerInterface::class)); +$addressBookRoot = new CalendarRoot($principalBackend, $calDavBackend, \OC::$server->get(LoggerInterface::class), 'principals'); $addressBookRoot->disableListing = !$debugging; // Disable listing $nodes = [ diff --git a/apps/dav/bin/chunkperf.php b/apps/dav/bin/chunkperf.php index 72a204d15eea3..48e48e572dbbc 100644 --- a/apps/dav/bin/chunkperf.php +++ b/apps/dav/bin/chunkperf.php @@ -45,7 +45,7 @@ function request(Client $client, string $method, string $uploadUrl, string $data $result = $client->request($method, $uploadUrl, $data, $headers); $t1 = microtime(true); echo $result['statusCode'] . " - " . ($t1 - $t0) . ' seconds' . PHP_EOL; - if (!in_array($result['statusCode'], [200, 201])) { + if (!in_array($result['statusCode'], [200, 201])) { echo $result['body'] . PHP_EOL; } return $result; diff --git a/apps/dav/lib/AppInfo/PluginManager.php b/apps/dav/lib/AppInfo/PluginManager.php index db5eb6ee7e787..3f24baae74e9f 100644 --- a/apps/dav/lib/AppInfo/PluginManager.php +++ b/apps/dav/lib/AppInfo/PluginManager.php @@ -45,7 +45,6 @@ * to the Sabre server. */ class PluginManager { - private ServerContainer $container; private IAppManager $appManager; diff --git a/apps/dav/lib/Avatars/AvatarHome.php b/apps/dav/lib/Avatars/AvatarHome.php index ba52daeb2b32f..fb68c52754507 100644 --- a/apps/dav/lib/Avatars/AvatarHome.php +++ b/apps/dav/lib/Avatars/AvatarHome.php @@ -32,19 +32,10 @@ use Sabre\Uri; class AvatarHome implements ICollection { + private array $principalInfo; + private IAvatarManager $avatarManager; - /** @var array */ - private $principalInfo; - /** @var IAvatarManager */ - private $avatarManager; - - /** - * AvatarHome constructor. - * - * @param array $principalInfo - * @param IAvatarManager $avatarManager - */ - public function __construct($principalInfo, IAvatarManager $avatarManager) { + public function __construct(array $principalInfo, IAvatarManager $avatarManager) { $this->principalInfo = $principalInfo; $this->avatarManager = $avatarManager; } @@ -59,8 +50,8 @@ public function createDirectory($name) { public function getChild($name) { $elements = pathinfo($name); - $ext = isset($elements['extension']) ? $elements['extension'] : ''; - $size = (int)(isset($elements['filename']) ? $elements['filename'] : '64'); + $ext = $elements['extension'] ?? ''; + $size = (int)($elements['filename'] ?? '64'); if (!in_array($ext, ['jpeg', 'png'], true)) { throw new MethodNotAllowed('File format not allowed'); } diff --git a/apps/dav/lib/Avatars/AvatarNode.php b/apps/dav/lib/Avatars/AvatarNode.php index ade523561f2f9..c49d2960f3181 100644 --- a/apps/dav/lib/Avatars/AvatarNode.php +++ b/apps/dav/lib/Avatars/AvatarNode.php @@ -26,18 +26,11 @@ use Sabre\DAV\File; class AvatarNode extends File { - private $ext; - private $size; - private $avatar; + private string $ext; + private int $size; + private IAvatar $avatar; - /** - * AvatarNode constructor. - * - * @param integer $size - * @param string $ext - * @param IAvatar $avatar - */ - public function __construct($size, $ext, $avatar) { + public function __construct(int $size, string $ext, IAvatar $avatar) { $this->size = $size; $this->ext = $ext; $this->avatar = $avatar; diff --git a/apps/dav/lib/Avatars/RootCollection.php b/apps/dav/lib/Avatars/RootCollection.php index 42c91344fbde1..e88b29e02531c 100644 --- a/apps/dav/lib/Avatars/RootCollection.php +++ b/apps/dav/lib/Avatars/RootCollection.php @@ -1,6 +1,4 @@ - * diff --git a/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php b/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php index f2ab3b241b8e3..2e391fa5f2605 100644 --- a/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php +++ b/apps/dav/lib/BackgroundJob/CleanupInvitationTokenJob.php @@ -31,7 +31,6 @@ use OCP\IDBConnection; class CleanupInvitationTokenJob extends TimedJob { - private IDBConnection $db; public function __construct(IDBConnection $db, ITimeFactory $time) { diff --git a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php index 021a11862560d..43cca4c1aae0e 100644 --- a/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php +++ b/apps/dav/lib/BackgroundJob/RefreshWebcalJob.php @@ -40,7 +40,6 @@ use Sabre\VObject\InvalidDataException; class RefreshWebcalJob extends Job { - private RefreshWebcalService $refreshWebcalService; private IConfig $config; private LoggerInterface $logger; diff --git a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php index 15be41b794a62..384fb7a38f54a 100644 --- a/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php +++ b/apps/dav/lib/BackgroundJob/UpdateCalendarResourcesRoomsBackgroundJob.php @@ -41,7 +41,6 @@ use OCP\IDBConnection; class UpdateCalendarResourcesRoomsBackgroundJob extends TimedJob { - private IResourceManager $resourceManager; private IRoomManager $roomManager; private IDBConnection $dbConnection; diff --git a/apps/dav/lib/CalDAV/Activity/Provider/Todo.php b/apps/dav/lib/CalDAV/Activity/Provider/Todo.php index 4a35f56dea562..885e1344fc574 100644 --- a/apps/dav/lib/CalDAV/Activity/Provider/Todo.php +++ b/apps/dav/lib/CalDAV/Activity/Provider/Todo.php @@ -28,7 +28,6 @@ use OCP\Activity\IEvent; class Todo extends Event { - public function parse($language, IEvent $event, IEvent $previousEvent = null) { if ($event->getApp() !== 'dav' || $event->getType() !== 'calendar_todo') { throw new InvalidArgumentException(); diff --git a/apps/dav/lib/CalDAV/CalDavBackend.php b/apps/dav/lib/CalDAV/CalDavBackend.php index 1710f471d0e61..b5ee99ad91d87 100644 --- a/apps/dav/lib/CalDAV/CalDavBackend.php +++ b/apps/dav/lib/CalDAV/CalDavBackend.php @@ -338,7 +338,7 @@ public function getCalendarsForUser($principalUri) { $row['principaluri'] = (string) $row['principaluri']; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ @@ -415,7 +415,7 @@ public function getCalendarsForUser($principalUri) { $row['displayname'] = $row['displayname'] . ' (' . $this->getUserDisplayName($name) . ')'; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ 'id' => $row['id'], @@ -467,7 +467,7 @@ public function getUsersOwnCalendars($principalUri) { $row['principaluri'] = (string) $row['principaluri']; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ 'id' => $row['id'], @@ -540,7 +540,7 @@ public function getPublicCalendars() { $row['displayname'] = $row['displayname'] . "($name)"; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ 'id' => $row['id'], @@ -608,7 +608,7 @@ public function getPublicCalendar($uri) { $row['displayname'] = $row['displayname'] . ' ' . "($name)"; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ 'id' => $row['id'], @@ -664,7 +664,7 @@ public function getCalendarByUri($principal, $uri) { $row['principaluri'] = (string) $row['principaluri']; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ @@ -716,7 +716,7 @@ public function getCalendarById($calendarId) { $row['principaluri'] = (string) $row['principaluri']; $components = []; if ($row['components']) { - $components = explode(',',$row['components']); + $components = explode(',', $row['components']); } $calendar = [ @@ -811,7 +811,7 @@ public function createCalendar($principalUri, $calendarUri, array $properties) { if (!($properties[$sccs] instanceof SupportedCalendarComponentSet)) { throw new DAV\Exception('The ' . $sccs . ' property must be of type: \Sabre\CalDAV\Property\SupportedCalendarComponentSet'); } - $values['components'] = implode(',',$properties[$sccs]->getValue()); + $values['components'] = implode(',', $properties[$sccs]->getValue()); } elseif (isset($properties['components'])) { // Allow to provide components internally without having // to create a SupportedCalendarComponentSet object diff --git a/apps/dav/lib/CalDAV/CalendarHome.php b/apps/dav/lib/CalDAV/CalendarHome.php index 126ad8db7348b..481e9c0605019 100644 --- a/apps/dav/lib/CalDAV/CalendarHome.php +++ b/apps/dav/lib/CalDAV/CalendarHome.php @@ -28,7 +28,6 @@ use OCA\DAV\AppInfo\PluginManager; use OCA\DAV\CalDAV\Integration\ExternalCalendar; -use OCA\DAV\CalDAV\Integration\ICalendarProvider; use OCA\DAV\CalDAV\Trashbin\TrashbinHome; use Psr\Log\LoggerInterface; use OCP\App\IAppManager; @@ -52,9 +51,7 @@ class CalendarHome extends \Sabre\CalDAV\CalendarHome { private IConfig $config; private PluginManager $pluginManager; private bool $returnCachedSubscriptions = false; - - /** @var LoggerInterface */ - private $logger; + private LoggerInterface $logger; public function __construct(BackendInterface $caldavBackend, $principalInfo, LoggerInterface $logger) { parent::__construct($caldavBackend, $principalInfo); diff --git a/apps/dav/lib/CalDAV/CalendarManager.php b/apps/dav/lib/CalDAV/CalendarManager.php index 2b4b041c0ccaa..a7e2543d2ab6f 100644 --- a/apps/dav/lib/CalDAV/CalendarManager.php +++ b/apps/dav/lib/CalDAV/CalendarManager.php @@ -33,17 +33,8 @@ class CalendarManager { private CalDavBackend $backend; private IL10N $l10n; private IConfig $config; + private LoggerInterface $logger; - /** @var LoggerInterface */ - private $logger; - - /** - * CalendarManager constructor. - * - * @param CalDavBackend $backend - * @param IL10N $l10n - * @param IConfig $config - */ public function __construct(CalDavBackend $backend, IL10N $l10n, IConfig $config, LoggerInterface $logger) { $this->backend = $backend; $this->l10n = $l10n; diff --git a/apps/dav/lib/CalDAV/CalendarProvider.php b/apps/dav/lib/CalDAV/CalendarProvider.php index 19a6b2e658a82..6e8f227dea230 100644 --- a/apps/dav/lib/CalDAV/CalendarProvider.php +++ b/apps/dav/lib/CalDAV/CalendarProvider.php @@ -34,9 +34,7 @@ class CalendarProvider implements ICalendarProvider { private CalDavBackend $calDavBackend; private IL10N $l10n; private IConfig $config; - - /** @var LoggerInterface */ - private $logger; + private LoggerInterface $logger; public function __construct(CalDavBackend $calDavBackend, IL10N $l10n, IConfig $config, LoggerInterface $logger) { $this->calDavBackend = $calDavBackend; diff --git a/apps/dav/lib/CalDAV/CalendarRoot.php b/apps/dav/lib/CalDAV/CalendarRoot.php index e08264b8f5961..2f660a2a541ae 100644 --- a/apps/dav/lib/CalDAV/CalendarRoot.php +++ b/apps/dav/lib/CalDAV/CalendarRoot.php @@ -30,11 +30,9 @@ use Sabre\DAVACL\PrincipalBackend; class CalendarRoot extends \Sabre\CalDAV\CalendarRoot { + private LoggerInterface $logger; - /** @var LoggerInterface */ - private $logger; - - public function __construct(PrincipalBackend\BackendInterface $principalBackend, Backend\BackendInterface $caldavBackend, $principalPrefix = 'principals', LoggerInterface $logger) { + public function __construct(PrincipalBackend\BackendInterface $principalBackend, Backend\BackendInterface $caldavBackend, LoggerInterface $logger, $principalPrefix = 'principals') { parent::__construct($principalBackend, $caldavBackend, $principalPrefix); $this->logger = $logger; } diff --git a/apps/dav/lib/CalDAV/PublicCalendarRoot.php b/apps/dav/lib/CalDAV/PublicCalendarRoot.php index 5d0fa9a83718e..f0de94ebc6878 100644 --- a/apps/dav/lib/CalDAV/PublicCalendarRoot.php +++ b/apps/dav/lib/CalDAV/PublicCalendarRoot.php @@ -34,17 +34,8 @@ class PublicCalendarRoot extends Collection { protected CalDavBackend $caldavBackend; protected IL10N $l10n; protected IConfig $config; + private LoggerInterface $logger; - /** @var LoggerInterface */ - private $logger; - - /** - * PublicCalendarRoot constructor. - * - * @param CalDavBackend $caldavBackend - * @param IL10N $l10n - * @param IConfig $config - */ public function __construct(CalDavBackend $caldavBackend, IL10N $l10n, IConfig $config, LoggerInterface $logger) { $this->caldavBackend = $caldavBackend; diff --git a/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php b/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php index c96d07a00900b..8af068208ebb5 100644 --- a/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php +++ b/apps/dav/lib/CalDAV/Publishing/PublishPlugin.php @@ -112,7 +112,7 @@ public function initialize(Server $server) { $this->server = $server; $this->server->on('method:POST', [$this, 'httpPost']); - $this->server->on('propFind', [$this, 'propFind']); + $this->server->on('propFind', [$this, 'propFind']); } public function propFind(PropFind $propFind, INode $node) { diff --git a/apps/dav/lib/CalDAV/Reminder/Notifier.php b/apps/dav/lib/CalDAV/Reminder/Notifier.php index f54c2489e1e46..96e5bdfdba2f5 100644 --- a/apps/dav/lib/CalDAV/Reminder/Notifier.php +++ b/apps/dav/lib/CalDAV/Reminder/Notifier.php @@ -48,7 +48,6 @@ * @package OCA\DAV\CalDAV\Reminder */ class Notifier implements INotifier { - private IFactory $l10nFactory; private IURLGenerator $urlGenerator; private IL10N $l10n; diff --git a/apps/dav/lib/CalDAV/Reminder/ReminderService.php b/apps/dav/lib/CalDAV/Reminder/ReminderService.php index e81341067a16c..9a59d368bb57d 100644 --- a/apps/dav/lib/CalDAV/Reminder/ReminderService.php +++ b/apps/dav/lib/CalDAV/Reminder/ReminderService.php @@ -49,7 +49,6 @@ use function strcasecmp; class ReminderService { - private Backend $backend; private NotificationProviderManager $notificationProviderManager; private IUserManager $userManager; diff --git a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php index 84641712186a5..db968f14e6d16 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/AbstractPrincipalBackend.php @@ -148,7 +148,7 @@ public function getPrincipalByPath($path) { } [, $name] = \Sabre\Uri\split($path); - [$backendId, $resourceId] = explode('-', $name, 2); + [$backendId, $resourceId] = explode('-', $name, 2); $query = $this->db->getQueryBuilder(); $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname']) @@ -294,7 +294,7 @@ public function searchPrincipals($prefixPath, array $searchProperties, $test = ' case IRoomMetadata::CAPACITY: case IResourceMetadata::VEHICLE_SEATING_CAPACITY: - $results[] = $this->searchPrincipalsByCapacity($prop,$value); + $results[] = $this->searchPrincipalsByCapacity($prop, $value); break; default: @@ -456,7 +456,7 @@ public function findByUri($uri, $principalPrefix): ?string { } [, $name] = \Sabre\Uri\split($path); - [$backendId, $resourceId] = explode('-', $name, 2); + [$backendId, $resourceId] = explode('-', $name, 2); $query = $this->db->getQueryBuilder(); $query->select(['id', 'backend_id', 'resource_id', 'email', 'displayname', 'group_restrictions']) diff --git a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php index c7d97b328fee6..69e61fc50693b 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/ResourcePrincipalBackend.php @@ -34,7 +34,6 @@ * @package OCA\DAV\CalDAV\ResourceBooking */ class ResourcePrincipalBackend extends AbstractPrincipalBackend { - public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, diff --git a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php index 961965ac67b39..415824c571321 100644 --- a/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php +++ b/apps/dav/lib/CalDAV/ResourceBooking/RoomPrincipalBackend.php @@ -34,7 +34,6 @@ * @package OCA\DAV\CalDAV\ResourceBooking */ class RoomPrincipalBackend extends AbstractPrincipalBackend { - public function __construct(IDBConnection $dbConnection, IUserSession $userSession, IGroupManager $groupManager, diff --git a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php index f9b43b98ced87..f92d87a788076 100644 --- a/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php +++ b/apps/dav/lib/CalDAV/Schedule/IMipPlugin.php @@ -507,16 +507,16 @@ private function addSubjectAndHeading(IEMailTemplate $template, IL10N $l10n, str private function addBulletList(IEMailTemplate $template, IL10N $l10n, VEvent $vevent) { if ($vevent->SUMMARY) { $template->addBodyListItem($vevent->SUMMARY, $l10n->t('Title:'), - $this->getAbsoluteImagePath('caldav/title.png'),'','',self::IMIP_INDENT); + $this->getAbsoluteImagePath('caldav/title.png'), '', '', self::IMIP_INDENT); } $meetingWhen = $this->generateWhenString($l10n, $vevent); if ($meetingWhen) { $template->addBodyListItem($meetingWhen, $l10n->t('Time:'), - $this->getAbsoluteImagePath('caldav/time.png'),'','',self::IMIP_INDENT); + $this->getAbsoluteImagePath('caldav/time.png'), '', '', self::IMIP_INDENT); } if ($vevent->LOCATION) { $template->addBodyListItem($vevent->LOCATION, $l10n->t('Location:'), - $this->getAbsoluteImagePath('caldav/location.png'),'','',self::IMIP_INDENT); + $this->getAbsoluteImagePath('caldav/location.png'), '', '', self::IMIP_INDENT); } if ($vevent->URL) { $url = $vevent->URL->getValue(); @@ -525,7 +525,7 @@ private function addBulletList(IEMailTemplate $template, IL10N $l10n, VEvent $ve htmlspecialchars($url)), $l10n->t('Link:'), $this->getAbsoluteImagePath('caldav/link.png'), - $url,'',self::IMIP_INDENT); + $url, '', self::IMIP_INDENT); } $this->addAttendees($template, $l10n, $vevent); @@ -533,7 +533,7 @@ private function addBulletList(IEMailTemplate $template, IL10N $l10n, VEvent $ve /* Put description last, like an email body, since it can be arbitrarily long */ if ($vevent->DESCRIPTION) { $template->addBodyListItem($vevent->DESCRIPTION->getValue(), $l10n->t('Description:'), - $this->getAbsoluteImagePath('caldav/description.png'),'','',self::IMIP_INDENT); + $this->getAbsoluteImagePath('caldav/description.png'), '', '', self::IMIP_INDENT); } } @@ -561,7 +561,7 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev /** @var Property\ICalendar\CalAddress $organizer */ $organizer = $vevent->ORGANIZER; $organizerURI = $organizer->getNormalizedValue(); - [,$organizerEmail] = explode(':',$organizerURI,2); # strip off scheme mailto: + [,$organizerEmail] = explode(':', $organizerURI, 2); # strip off scheme mailto: /** @var string|null $organizerName */ $organizerName = isset($organizer['CN']) ? $organizer['CN'] : null; $organizerHTML = sprintf('%s', @@ -578,7 +578,7 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev } $template->addBodyListItem($organizerHTML, $l10n->t('Organizer:'), $this->getAbsoluteImagePath('caldav/organizer.png'), - $organizerText,'',self::IMIP_INDENT); + $organizerText, '', self::IMIP_INDENT); } $attendees = $vevent->select('ATTENDEE'); @@ -590,7 +590,7 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev $attendeesText = []; foreach ($attendees as $attendee) { $attendeeURI = $attendee->getNormalizedValue(); - [,$attendeeEmail] = explode(':',$attendeeURI,2); # strip off scheme mailto: + [,$attendeeEmail] = explode(':', $attendeeURI, 2); # strip off scheme mailto: $attendeeName = $attendee['CN'] ?? null; $attendeeHTML = sprintf('%s', htmlspecialchars($attendeeURI), @@ -605,9 +605,9 @@ private function addAttendees(IEMailTemplate $template, IL10N $l10n, VEvent $vev $attendeesText[] = $attendeeText; } - $template->addBodyListItem(implode('
',$attendeesHTML), $l10n->t('Attendees:'), + $template->addBodyListItem(implode('
', $attendeesHTML), $l10n->t('Attendees:'), $this->getAbsoluteImagePath('caldav/attendees.png'), - implode("\n",$attendeesText),'',self::IMIP_INDENT); + implode("\n", $attendeesText), '', self::IMIP_INDENT); } /** diff --git a/apps/dav/lib/CalDAV/Schedule/Plugin.php b/apps/dav/lib/CalDAV/Schedule/Plugin.php index a52ecff3cf2ad..931eb1320d992 100644 --- a/apps/dav/lib/CalDAV/Schedule/Plugin.php +++ b/apps/dav/lib/CalDAV/Schedule/Plugin.php @@ -55,7 +55,6 @@ use function \Sabre\Uri\split; class Plugin extends \Sabre\CalDAV\Schedule\Plugin { - private IConfig $config; /** @var ITip\Message[] */ diff --git a/apps/dav/lib/Capabilities.php b/apps/dav/lib/Capabilities.php index 41d1b98358740..f797bda6a6227 100644 --- a/apps/dav/lib/Capabilities.php +++ b/apps/dav/lib/Capabilities.php @@ -25,7 +25,7 @@ use OCP\Capabilities\ICapability; class Capabilities implements ICapability { - public function getCapabilities() { + public function getCapabilities(): array { return [ 'dav' => [ 'chunking' => '1.0', diff --git a/apps/dav/lib/CardDAV/Activity/Backend.php b/apps/dav/lib/CardDAV/Activity/Backend.php index b713284e182d6..a4f9bfabd8db7 100644 --- a/apps/dav/lib/CardDAV/Activity/Backend.php +++ b/apps/dav/lib/CardDAV/Activity/Backend.php @@ -37,18 +37,10 @@ use Sabre\VObject\Reader; class Backend { - - /** @var IActivityManager */ - protected $activityManager; - - /** @var IGroupManager */ - protected $groupManager; - - /** @var IUserSession */ - protected $userSession; - - /** @var IAppManager */ - protected $appManager; + protected IActivityManager $activityManager; + protected IGroupManager $groupManager; + protected IUserSession $userSession; + protected IAppManager $appManager; public function __construct(IActivityManager $activityManager, IGroupManager $groupManager, diff --git a/apps/dav/lib/CardDAV/Activity/Filter.php b/apps/dav/lib/CardDAV/Activity/Filter.php index 3ca4c3367d552..5ccb434518e23 100644 --- a/apps/dav/lib/CardDAV/Activity/Filter.php +++ b/apps/dav/lib/CardDAV/Activity/Filter.php @@ -27,12 +27,8 @@ use OCP\IURLGenerator; class Filter implements IFilter { - - /** @var IL10N */ - protected $l; - - /** @var IURLGenerator */ - protected $url; + protected IL10N $l; + protected IURLGenerator $url; public function __construct(IL10N $l, IURLGenerator $url) { $this->l = $l; diff --git a/apps/dav/lib/CardDAV/Activity/Provider/Addressbook.php b/apps/dav/lib/CardDAV/Activity/Provider/Addressbook.php index be18fba96cc41..48d786fc41af2 100644 --- a/apps/dav/lib/CardDAV/Activity/Provider/Addressbook.php +++ b/apps/dav/lib/CardDAV/Activity/Provider/Addressbook.php @@ -43,14 +43,9 @@ class Addressbook extends Base { public const SUBJECT_UNSHARE_USER = 'addressbook_user_unshare'; public const SUBJECT_UNSHARE_GROUP = 'addressbook_group_unshare'; - /** @var IFactory */ - protected $languageFactory; - - /** @var IManager */ - protected $activityManager; - - /** @var IEventMerger */ - protected $eventMerger; + protected IFactory $languageFactory; + protected IManager $activityManager; + protected IEventMerger $eventMerger; public function __construct(IFactory $languageFactory, IURLGenerator $url, diff --git a/apps/dav/lib/CardDAV/Activity/Provider/Base.php b/apps/dav/lib/CardDAV/Activity/Provider/Base.php index 2f6de31de1578..4645991989faa 100644 --- a/apps/dav/lib/CardDAV/Activity/Provider/Base.php +++ b/apps/dav/lib/CardDAV/Activity/Provider/Base.php @@ -36,21 +36,15 @@ use OCP\IUserManager; abstract class Base implements IProvider { - - /** @var IUserManager */ - protected $userManager; + protected IUserManager $userManager; /** @var string[] */ - protected $userDisplayNames = []; - - /** @var IGroupManager */ - protected $groupManager; + protected array $userDisplayNames = []; + protected IGroupManager $groupManager; /** @var string[] */ - protected $groupDisplayNames = []; - - /** @var IURLGenerator */ - protected $url; + protected array $groupDisplayNames = []; + protected IURLGenerator $url; public function __construct(IUserManager $userManager, IGroupManager $groupManager, diff --git a/apps/dav/lib/CardDAV/Activity/Provider/Card.php b/apps/dav/lib/CardDAV/Activity/Provider/Card.php index 9c909ae9bcd27..10e87e0617838 100644 --- a/apps/dav/lib/CardDAV/Activity/Provider/Card.php +++ b/apps/dav/lib/CardDAV/Activity/Provider/Card.php @@ -40,17 +40,10 @@ class Card extends Base { public const SUBJECT_UPDATE = 'card_update'; public const SUBJECT_DELETE = 'card_delete'; - /** @var IFactory */ - protected $languageFactory; - - /** @var IManager */ - protected $activityManager; - - /** @var IEventMerger */ - protected $eventMerger; - - /** @var IAppManager */ - protected $appManager; + protected IFactory $languageFactory; + protected IManager $activityManager; + protected IEventMerger $eventMerger; + protected IAppManager $appManager; public function __construct(IFactory $languageFactory, IURLGenerator $url, diff --git a/apps/dav/lib/CardDAV/AddressBookImpl.php b/apps/dav/lib/CardDAV/AddressBookImpl.php index 442d8a5472b0c..d0613e7f1dd68 100644 --- a/apps/dav/lib/CardDAV/AddressBookImpl.php +++ b/apps/dav/lib/CardDAV/AddressBookImpl.php @@ -40,18 +40,10 @@ use Sabre\VObject\UUIDUtil; class AddressBookImpl implements IAddressBook { - - /** @var CardDavBackend */ - private $backend; - - /** @var array */ - private $addressBookInfo; - - /** @var AddressBook */ - private $addressBook; - - /** @var IURLGenerator */ - private $urlGenerator; + private CardDavBackend $backend; + private array $addressBookInfo; + private AddressBook $addressBook; + private IURLGenerator $urlGenerator; /** * AddressBookImpl constructor. diff --git a/apps/dav/lib/CardDAV/AddressBookRoot.php b/apps/dav/lib/CardDAV/AddressBookRoot.php index 897ed8190714d..4d7aeb65e7d53 100644 --- a/apps/dav/lib/CardDAV/AddressBookRoot.php +++ b/apps/dav/lib/CardDAV/AddressBookRoot.php @@ -23,20 +23,16 @@ */ namespace OCA\DAV\CardDAV; +use Sabre\CardDAV\Backend\BackendInterface as CardDAVBackendInterface; +use Sabre\DAV\INode; +use Sabre\DAVACL\PrincipalBackend\BackendInterface as DAVACLBackendInterface; use OCA\DAV\AppInfo\PluginManager; class AddressBookRoot extends \Sabre\CardDAV\AddressBookRoot { + private PluginManager $pluginManager; - /** @var PluginManager */ - private $pluginManager; - - /** - * @param \Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend - * @param \Sabre\CardDAV\Backend\BackendInterface $carddavBackend - * @param string $principalPrefix - */ - public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $principalBackend, - \Sabre\CardDAV\Backend\BackendInterface $carddavBackend, + public function __construct(DAVACLBackendInterface $principalBackend, + CardDAVBackendInterface $carddavBackend, PluginManager $pluginManager, $principalPrefix = 'principals') { parent::__construct($principalBackend, $carddavBackend, $principalPrefix); @@ -52,7 +48,7 @@ public function __construct(\Sabre\DAVACL\PrincipalBackend\BackendInterface $pri * * @param array $principal * - * @return \Sabre\DAV\INode + * @return INode */ public function getChildForPrincipal(array $principal) { return new UserAddressBooks($this->carddavBackend, $principal['uri'], $this->pluginManager); diff --git a/apps/dav/lib/CardDAV/CardDavBackend.php b/apps/dav/lib/CardDAV/CardDavBackend.php index ac41c4663060a..8498e2ef18e70 100644 --- a/apps/dav/lib/CardDAV/CardDavBackend.php +++ b/apps/dav/lib/CardDAV/CardDavBackend.php @@ -68,22 +68,22 @@ class CardDavBackend implements BackendInterface, SyncSupport { public const PERSONAL_ADDRESSBOOK_NAME = 'Contacts'; /** @var Principal */ - private $principalBackend; + private Principal $principalBackend; /** @var string */ - private $dbCardsTable = 'cards'; + private string $dbCardsTable = 'cards'; /** @var string */ - private $dbCardsPropertiesTable = 'cards_properties'; + private string $dbCardsPropertiesTable = 'cards_properties'; /** @var IDBConnection */ - private $db; + private IDBConnection $db; /** @var Backend */ - private $sharingBackend; + private Backend $sharingBackend; /** @var array properties to index */ - public static $indexProperties = [ + public static array $indexProperties = [ 'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME', 'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO', 'CLOUD', 'X-SOCIALPROFILE']; @@ -91,25 +91,16 @@ class CardDavBackend implements BackendInterface, SyncSupport { /** * @var string[] Map of uid => display name */ - protected $userDisplayNames; + protected array $userDisplayNames; /** @var IUserManager */ - private $userManager; + private IUserManager $userManager; /** @var IEventDispatcher */ - private $dispatcher; + private IEventDispatcher $dispatcher; - private $etagCache = []; + private array $etagCache = []; - /** - * CardDavBackend constructor. - * - * @param IDBConnection $db - * @param Principal $principalBackend - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param IEventDispatcher $dispatcher - */ public function __construct(IDBConnection $db, Principal $principalBackend, IUserManager $userManager, diff --git a/apps/dav/lib/CardDAV/ContactsManager.php b/apps/dav/lib/CardDAV/ContactsManager.php index 37a361b017b5e..dbb09ecf7f86f 100644 --- a/apps/dav/lib/CardDAV/ContactsManager.php +++ b/apps/dav/lib/CardDAV/ContactsManager.php @@ -30,49 +30,26 @@ use OCP\IURLGenerator; class ContactsManager { - /** @var CardDavBackend */ - private $backend; + private CardDavBackend $backend; + private IL10N $l10n; - /** @var IL10N */ - private $l10n; - - /** - * ContactsManager constructor. - * - * @param CardDavBackend $backend - * @param IL10N $l10n - */ public function __construct(CardDavBackend $backend, IL10N $l10n) { $this->backend = $backend; $this->l10n = $l10n; } - /** - * @param IManager $cm - * @param string $userId - * @param IURLGenerator $urlGenerator - */ - public function setupContactsProvider(IManager $cm, $userId, IURLGenerator $urlGenerator) { + public function setupContactsProvider(IManager $cm, string $userId, IURLGenerator $urlGenerator) { $addressBooks = $this->backend->getAddressBooksForUser("principals/users/$userId"); $this->register($cm, $addressBooks, $urlGenerator); $this->setupSystemContactsProvider($cm, $urlGenerator); } - /** - * @param IManager $cm - * @param IURLGenerator $urlGenerator - */ public function setupSystemContactsProvider(IManager $cm, IURLGenerator $urlGenerator) { $addressBooks = $this->backend->getAddressBooksForUser("principals/system/system"); $this->register($cm, $addressBooks, $urlGenerator); } - /** - * @param IManager $cm - * @param $addressBooks - * @param IURLGenerator $urlGenerator - */ - private function register(IManager $cm, $addressBooks, $urlGenerator) { + private function register(IManager $cm, array $addressBooks, IURLGenerator $urlGenerator) { foreach ($addressBooks as $addressBookInfo) { $addressBook = new AddressBook($this->backend, $addressBookInfo, $this->l10n); $cm->registerAddressBook( diff --git a/apps/dav/lib/CardDAV/Converter.php b/apps/dav/lib/CardDAV/Converter.php index 340e3127f0a76..f41a842240325 100644 --- a/apps/dav/lib/CardDAV/Converter.php +++ b/apps/dav/lib/CardDAV/Converter.php @@ -35,9 +35,7 @@ use Sabre\VObject\Property\Text; class Converter { - - /** @var IAccountManager */ - private $accountManager; + private IAccountManager $accountManager; public function __construct(IAccountManager $accountManager) { $this->accountManager = $accountManager; diff --git a/apps/dav/lib/CardDAV/HasPhotoPlugin.php b/apps/dav/lib/CardDAV/HasPhotoPlugin.php index 528fcb36bf596..e99cd715585d4 100644 --- a/apps/dav/lib/CardDAV/HasPhotoPlugin.php +++ b/apps/dav/lib/CardDAV/HasPhotoPlugin.php @@ -36,9 +36,7 @@ use Sabre\VObject\Reader; class HasPhotoPlugin extends ServerPlugin { - - /** @var Server */ - protected $server; + protected Server $server; /** * Initializes the plugin and registers event handlers diff --git a/apps/dav/lib/CardDAV/ImageExportPlugin.php b/apps/dav/lib/CardDAV/ImageExportPlugin.php index 4caf234e3465b..bacc696e9ae60 100644 --- a/apps/dav/lib/CardDAV/ImageExportPlugin.php +++ b/apps/dav/lib/CardDAV/ImageExportPlugin.php @@ -32,11 +32,8 @@ use Sabre\HTTP\ResponseInterface; class ImageExportPlugin extends ServerPlugin { - - /** @var Server */ - protected $server; - /** @var PhotoCache */ - private $cache; + protected Server $server; + private PhotoCache $cache; /** * ImageExportPlugin constructor. diff --git a/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php b/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php index b1deb638f3daf..929236073ca6a 100644 --- a/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php +++ b/apps/dav/lib/CardDAV/Integration/ExternalAddressBook.php @@ -33,8 +33,6 @@ * @since 19.0.0 */ abstract class ExternalAddressBook implements IAddressBook, DAV\IProperties { - - /** @var string */ private const PREFIX = 'z-app-generated'; /** @@ -49,12 +47,8 @@ abstract class ExternalAddressBook implements IAddressBook, DAV\IProperties { * URI has double dashes, it won't be split */ private const DELIMITER = '--'; - - /** @var string */ - private $appId; - - /** @var string */ - private $uri; + private string $appId; + private string $uri; /** * @param string $appId diff --git a/apps/dav/lib/CardDAV/MultiGetExportPlugin.php b/apps/dav/lib/CardDAV/MultiGetExportPlugin.php index 62c4f7e817878..ffe45917a9eda 100644 --- a/apps/dav/lib/CardDAV/MultiGetExportPlugin.php +++ b/apps/dav/lib/CardDAV/MultiGetExportPlugin.php @@ -32,15 +32,10 @@ use Sabre\HTTP\ResponseInterface; class MultiGetExportPlugin extends DAV\ServerPlugin { - - /** @var Server */ - protected $server; + protected Server $server; /** * Initializes the plugin and registers event handlers - * - * @param Server $server - * @return void */ public function initialize(Server $server) { $this->server = $server; diff --git a/apps/dav/lib/CardDAV/PhotoCache.php b/apps/dav/lib/CardDAV/PhotoCache.php index 42271c3b58c21..676b396ceef54 100644 --- a/apps/dav/lib/CardDAV/PhotoCache.php +++ b/apps/dav/lib/CardDAV/PhotoCache.php @@ -51,33 +51,18 @@ class PhotoCache { 'image/vnd.microsoft.icon' => 'ico', ]; - /** @var IAppData */ - protected $appData; + protected IAppData $appData; + protected LoggerInterface $logger; - /** @var LoggerInterface */ - protected $logger; - - /** - * PhotoCache constructor. - * - * @param IAppData $appData - * @param LoggerInterface $logger - */ public function __construct(IAppData $appData, LoggerInterface $logger) { $this->appData = $appData; $this->logger = $logger; } /** - * @param int $addressBookId - * @param string $cardUri - * @param int $size - * @param Card $card - * - * @return ISimpleFile * @throws NotFoundException */ - public function get($addressBookId, $cardUri, $size, Card $card) { + public function get(int $addressBookId, string $cardUri, int $size, Card $card): ISimpleFile { $folder = $this->getFolder($addressBookId, $cardUri); if ($this->isEmpty($folder)) { @@ -95,17 +80,11 @@ public function get($addressBookId, $cardUri, $size, Card $card) { return $this->getFile($folder, $size); } - /** - * @param ISimpleFolder $folder - * @return bool - */ - private function isEmpty(ISimpleFolder $folder) { + private function isEmpty(ISimpleFolder $folder): bool { return $folder->getDirectoryListing() === []; } /** - * @param ISimpleFolder $folder - * @param Card $card * @throws NotPermittedException */ private function init(ISimpleFolder $folder, Card $card): void { @@ -128,7 +107,7 @@ private function init(ISimpleFolder $folder, Card $card): void { $file->putContent($data['body']); } - private function hasPhoto(ISimpleFolder $folder) { + private function hasPhoto(ISimpleFolder $folder): bool { return !$folder->fileExists('nophoto'); } @@ -269,11 +248,7 @@ public function getPhotoFromVObject(Document $vObject) { return false; } - /** - * @param string $cardData - * @return \Sabre\VObject\Document - */ - private function readCard($cardData) { + private function readCard(string $cardData): Document { return Reader::read($cardData); } @@ -281,11 +256,11 @@ private function readCard($cardData) { * @param Binary $photo * @return string */ - private function getBinaryType(Binary $photo) { + private function getBinaryType(Binary $photo): string { $params = $photo->parameters(); if (isset($params['TYPE']) || isset($params['MEDIATYPE'])) { /** @var Parameter $typeParam */ - $typeParam = isset($params['TYPE']) ? $params['TYPE'] : $params['MEDIATYPE']; + $typeParam = $params['TYPE'] ?? $params['MEDIATYPE']; $type = $typeParam->getValue(); if (strpos($type, 'image/') === 0) { @@ -298,11 +273,9 @@ private function getBinaryType(Binary $photo) { } /** - * @param int $addressBookId - * @param string $cardUri * @throws NotPermittedException */ - public function delete($addressBookId, $cardUri) { + public function delete(int $addressBookId, string $cardUri) { try { $folder = $this->getFolder($addressBookId, $cardUri, false); $folder->delete(); diff --git a/apps/dav/lib/CardDAV/SyncService.php b/apps/dav/lib/CardDAV/SyncService.php index d7cc01c7d861f..614f2bc45b47b 100644 --- a/apps/dav/lib/CardDAV/SyncService.php +++ b/apps/dav/lib/CardDAV/SyncService.php @@ -28,7 +28,6 @@ */ namespace OCA\DAV\CardDAV; -use OC\Accounts\AccountManager; use OCP\AppFramework\Http; use OCP\IUser; use OCP\IUserManager; @@ -38,35 +37,16 @@ use Sabre\DAV\Xml\Service; use Sabre\HTTP\ClientHttpException; use Sabre\VObject\Reader; +use Sabre\Xml\ParseException; class SyncService { + private CardDavBackend $backend; + private IUserManager $userManager; + private LoggerInterface $logger; + private array $localSystemAddressBook; + private Converter $converter; + protected string $certPath; - /** @var CardDavBackend */ - private $backend; - - /** @var IUserManager */ - private $userManager; - - /** @var LoggerInterface */ - private $logger; - - /** @var array */ - private $localSystemAddressBook; - - /** @var Converter */ - private $converter; - - /** @var string */ - protected $certPath; - - /** - * SyncService constructor. - * - * @param CardDavBackend $backend - * @param IUserManager $userManager - * @param LoggerInterface $logger - * @param AccountManager $accountManager - */ public function __construct(CardDavBackend $backend, IUserManager $userManager, LoggerInterface $logger, Converter $converter) { $this->backend = $backend; $this->userManager = $userManager; @@ -76,18 +56,9 @@ public function __construct(CardDavBackend $backend, IUserManager $userManager, } /** - * @param string $url - * @param string $userName - * @param string $addressBookUrl - * @param string $sharedSecret - * @param string $syncToken - * @param int $targetBookId - * @param string $targetPrincipal - * @param array $targetProperties - * @return string * @throws \Exception */ - public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedSecret, $syncToken, $targetBookId, $targetPrincipal, $targetProperties) { + public function syncRemoteAddressBook(string $url, string $userName, string $addressBookUrl, string $sharedSecret, string $syncToken, int $targetBookId, string $targetPrincipal, array $targetProperties): string { // 1. create addressbook $book = $this->ensureSystemAddressBookExists($targetPrincipal, $targetBookId, $targetProperties); $addressBookId = $book['id']; @@ -125,13 +96,9 @@ public function syncRemoteAddressBook($url, $userName, $addressBookUrl, $sharedS } /** - * @param string $principal - * @param string $id - * @param array $properties - * @return array|null * @throws \Sabre\DAV\Exception\BadRequest */ - public function ensureSystemAddressBookExists($principal, $id, $properties) { + public function ensureSystemAddressBookExists(string $principal, string $id, array $properties): ?array { $book = $this->backend->getAddressBooksByUri($principal, $id); if (!is_null($book)) { return $book; @@ -146,7 +113,7 @@ public function ensureSystemAddressBookExists($principal, $id, $properties) { * * @return string */ - protected function getCertPath() { + protected function getCertPath(): string { // we already have a valid certPath if ($this->certPath !== '') { @@ -162,14 +129,7 @@ protected function getCertPath() { return $this->certPath; } - /** - * @param string $url - * @param string $userName - * @param string $addressBookUrl - * @param string $sharedSecret - * @return Client - */ - protected function getClient($url, $userName, $sharedSecret) { + protected function getClient(string $url, string $userName, string $sharedSecret): Client { $settings = [ 'baseUri' => $url . '/', 'userName' => $userName, @@ -186,15 +146,7 @@ protected function getClient($url, $userName, $sharedSecret) { return $client; } - /** - * @param string $url - * @param string $userName - * @param string $addressBookUrl - * @param string $sharedSecret - * @param string $syncToken - * @return array - */ - protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSecret, $syncToken) { + protected function requestSyncReport(string $url, string $userName, string $addressBookUrl, string $sharedSecret, string $syncToken): array { $client = $this->getClient($url, $userName, $sharedSecret); $body = $this->buildSyncCollectionRequestBody($syncToken); @@ -206,23 +158,12 @@ protected function requestSyncReport($url, $userName, $addressBookUrl, $sharedSe return $this->parseMultiStatus($response['body']); } - /** - * @param string $url - * @param string $userName - * @param string $sharedSecret - * @param string $resourcePath - * @return array - */ - protected function download($url, $userName, $sharedSecret, $resourcePath) { + protected function download(string $url, string $userName, string $sharedSecret, string $resourcePath): array { $client = $this->getClient($url, $userName, $sharedSecret); return $client->request('GET', $resourcePath); } - /** - * @param string|null $syncToken - * @return string - */ - private function buildSyncCollectionRequestBody($syncToken) { + private function buildSyncCollectionRequestBody(?string $syncToken): string { $dom = new \DOMDocument('1.0', 'UTF-8'); $dom->formatOutput = true; $root = $dom->createElementNS('DAV:', 'd:sync-collection'); @@ -240,11 +181,9 @@ private function buildSyncCollectionRequestBody($syncToken) { } /** - * @param string $body - * @return array - * @throws \Sabre\Xml\ParseException + * @throws ParseException */ - private function parseMultiStatus($body) { + private function parseMultiStatus(string $body): array { $xml = new Service(); /** @var MultiStatus $multiStatus */ @@ -258,9 +197,6 @@ private function parseMultiStatus($body) { return ['response' => $result, 'token' => $multiStatus->getSyncToken()]; } - /** - * @param IUser $user - */ public function updateUser(IUser $user) { $systemAddressBook = $this->getLocalSystemAddressBook(); $addressBookId = $systemAddressBook['id']; @@ -305,7 +241,7 @@ public function deleteUser($userOrCardId) { /** * @return array|null */ - public function getLocalSystemAddressBook() { + public function getLocalSystemAddressBook(): ?array { if (is_null($this->localSystemAddressBook)) { $systemPrincipal = "principals/system/system"; $this->localSystemAddressBook = $this->ensureSystemAddressBookExists($systemPrincipal, 'system', [ diff --git a/apps/dav/lib/CardDAV/SystemAddressbook.php b/apps/dav/lib/CardDAV/SystemAddressbook.php index 502e353acb313..1ffe9a38fc8f3 100644 --- a/apps/dav/lib/CardDAV/SystemAddressbook.php +++ b/apps/dav/lib/CardDAV/SystemAddressbook.php @@ -32,15 +32,14 @@ use Sabre\CardDAV\Backend\BackendInterface; class SystemAddressbook extends AddressBook { - /** @var IConfig */ - private $config; + private IConfig $config; public function __construct(BackendInterface $carddavBackend, array $addressBookInfo, IL10N $l10n, IConfig $config) { parent::__construct($carddavBackend, $addressBookInfo, $l10n); $this->config = $config; } - public function getChildren() { + public function getChildren(): array { $shareEnumeration = $this->config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes') === 'yes'; $shareEnumerationGroup = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_group', 'no') === 'yes'; $shareEnumerationPhone = $this->config->getAppValue('core', 'shareapi_restrict_user_enumeration_to_phone', 'no') === 'yes'; diff --git a/apps/dav/lib/CardDAV/UserAddressBooks.php b/apps/dav/lib/CardDAV/UserAddressBooks.php index 8d2f66b3b1647..f8ef0dc7cee05 100644 --- a/apps/dav/lib/CardDAV/UserAddressBooks.php +++ b/apps/dav/lib/CardDAV/UserAddressBooks.php @@ -42,15 +42,9 @@ use Sabre\DAV\MkCol; class UserAddressBooks extends AddressBookHome { - - /** @var IL10N|null */ - protected $l10n; - - /** @var IConfig|null */ - protected $config; - - /** @var PluginManager */ - private $pluginManager; + protected ?IL10N $l10n; + protected ?IConfig $config; + private PluginManager $pluginManager; public function __construct(Backend\BackendInterface $carddavBackend, string $principalUri, @@ -64,7 +58,7 @@ public function __construct(Backend\BackendInterface $carddavBackend, * * @return IAddressBook[] */ - public function getChildren() { + public function getChildren(): array { if ($this->l10n === null) { $this->l10n = \OC::$server->get(IFactory::class)->get('dav'); } diff --git a/apps/dav/lib/CardDAV/Xml/Groups.php b/apps/dav/lib/CardDAV/Xml/Groups.php index bde361293826c..d02d56eb6bdf2 100644 --- a/apps/dav/lib/CardDAV/Xml/Groups.php +++ b/apps/dav/lib/CardDAV/Xml/Groups.php @@ -32,10 +32,7 @@ class Groups implements XmlSerializable { /** @var string[] of TYPE:CHECKSUM */ private $groups; - /** - * @param string $groups - */ - public function __construct($groups) { + public function __construct(string $groups) { $this->groups = $groups; } diff --git a/apps/dav/lib/Command/CreateAddressBook.php b/apps/dav/lib/Command/CreateAddressBook.php index 3d56d95868dd1..2d2bf745efa94 100644 --- a/apps/dav/lib/Command/CreateAddressBook.php +++ b/apps/dav/lib/Command/CreateAddressBook.php @@ -32,17 +32,9 @@ use Symfony\Component\Console\Output\OutputInterface; class CreateAddressBook extends Command { + private IUserManager $userManager; + private CardDavBackend $cardDavBackend; - /** @var IUserManager */ - private $userManager; - - /** @var CardDavBackend */ - private $cardDavBackend; - - /** - * @param IUserManager $userManager - * @param CardDavBackend $cardDavBackend - */ public function __construct(IUserManager $userManager, CardDavBackend $cardDavBackend ) { diff --git a/apps/dav/lib/Command/CreateCalendar.php b/apps/dav/lib/Command/CreateCalendar.php index cae3528cad782..27991682c323b 100644 --- a/apps/dav/lib/Command/CreateCalendar.php +++ b/apps/dav/lib/Command/CreateCalendar.php @@ -46,21 +46,10 @@ use Symfony\Component\Console\Output\OutputInterface; class CreateCalendar extends Command { + protected IUserManager $userManager; + private IGroupManager $groupManager; + protected IDBConnection $dbConnection; - /** @var IUserManager */ - protected $userManager; - - /** @var IGroupManager $groupManager */ - private $groupManager; - - /** @var \OCP\IDBConnection */ - protected $dbConnection; - - /** - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param IDBConnection $dbConnection - */ public function __construct(IUserManager $userManager, IGroupManager $groupManager, IDBConnection $dbConnection) { parent::__construct(); $this->userManager = $userManager; diff --git a/apps/dav/lib/Command/DeleteCalendar.php b/apps/dav/lib/Command/DeleteCalendar.php index dd5f11c740f3a..382038b967ca9 100644 --- a/apps/dav/lib/Command/DeleteCalendar.php +++ b/apps/dav/lib/Command/DeleteCalendar.php @@ -38,27 +38,12 @@ use Symfony\Component\Console\Output\OutputInterface; class DeleteCalendar extends Command { - /** @var CalDavBackend */ - private $calDav; + private CalDavBackend $calDav; + private IConfig $config; + private IL10N $l10n; + private IUserManager $userManager; + private LoggerInterface $logger; - /** @var IConfig */ - private $config; - - /** @var IL10N */ - private $l10n; - - /** @var IUserManager */ - private $userManager; - - /** @var LoggerInterface */ - private $logger; - - /** - * @param CalDavBackend $calDav - * @param IConfig $config - * @param IL10N $l10n - * @param IUserManager $userManager - */ public function __construct( CalDavBackend $calDav, IConfig $config, diff --git a/apps/dav/lib/Command/ListCalendars.php b/apps/dav/lib/Command/ListCalendars.php index 35581c2d4b21e..aa8476d7abe1a 100644 --- a/apps/dav/lib/Command/ListCalendars.php +++ b/apps/dav/lib/Command/ListCalendars.php @@ -35,17 +35,9 @@ use Symfony\Component\Console\Output\OutputInterface; class ListCalendars extends Command { + protected IUserManager $userManager; + private CalDavBackend $caldav; - /** @var IUserManager */ - protected $userManager; - - /** @var CalDavBackend */ - private $caldav; - - /** - * @param IUserManager $userManager - * @param CalDavBackend $caldav - */ public function __construct(IUserManager $userManager, CalDavBackend $caldav) { parent::__construct(); $this->userManager = $userManager; diff --git a/apps/dav/lib/Command/MoveCalendar.php b/apps/dav/lib/Command/MoveCalendar.php index 320fe8aeac699..ea6d7fd1eed5c 100644 --- a/apps/dav/lib/Command/MoveCalendar.php +++ b/apps/dav/lib/Command/MoveCalendar.php @@ -42,41 +42,17 @@ use Symfony\Component\Console\Style\SymfonyStyle; class MoveCalendar extends Command { - - /** @var IUserManager */ - private $userManager; - - /** @var IGroupManager */ - private $groupManager; - - /** @var IShareManager */ - private $shareManager; - - /** @var IConfig $config */ - private $config; - - /** @var IL10N */ - private $l10n; - - /** @var SymfonyStyle */ - private $io; - - /** @var CalDavBackend */ - private $calDav; - - /** @var LoggerInterface */ - private $logger; + private IUserManager $userManager; + private IGroupManager $groupManager; + private IShareManager $shareManager; + private IConfig $config; + private IL10N $l10n; + private SymfonyStyle $io; + private CalDavBackend $calDav; + private LoggerInterface $logger; public const URI_USERS = 'principals/users/'; - /** - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param IShareManager $shareManager - * @param IConfig $config - * @param IL10N $l10n - * @param CalDavBackend $calDav - */ public function __construct( IUserManager $userManager, IGroupManager $groupManager, diff --git a/apps/dav/lib/Command/RemoveInvalidShares.php b/apps/dav/lib/Command/RemoveInvalidShares.php index 4f9e4836a722f..4c67059654956 100644 --- a/apps/dav/lib/Command/RemoveInvalidShares.php +++ b/apps/dav/lib/Command/RemoveInvalidShares.php @@ -37,11 +37,8 @@ * have no matching principal. Happened because of a bug in the calendar app. */ class RemoveInvalidShares extends Command { - - /** @var IDBConnection */ - private $connection; - /** @var Principal */ - private $principalBackend; + private IDBConnection $connection; + private Principal $principalBackend; public function __construct(IDBConnection $connection, Principal $principalBackend) { @@ -61,7 +58,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int $query = $this->connection->getQueryBuilder(); $result = $query->selectDistinct('principaluri') ->from('dav_shares') - ->execute(); + ->executeQuery(); while ($row = $result->fetch()) { $principaluri = $row['principaluri']; @@ -75,13 +72,10 @@ protected function execute(InputInterface $input, OutputInterface $output): int return 0; } - /** - * @param string $principaluri - */ - private function deleteSharesForPrincipal($principaluri) { + private function deleteSharesForPrincipal(string $principaluri) { $delete = $this->connection->getQueryBuilder(); $delete->delete('dav_shares') ->where($delete->expr()->eq('principaluri', $delete->createNamedParameter($principaluri))); - $delete->execute(); + $delete->executeStatement(); } } diff --git a/apps/dav/lib/Command/RetentionCleanupCommand.php b/apps/dav/lib/Command/RetentionCleanupCommand.php index c9beabc974a1f..94f60c6836a6b 100644 --- a/apps/dav/lib/Command/RetentionCleanupCommand.php +++ b/apps/dav/lib/Command/RetentionCleanupCommand.php @@ -31,8 +31,7 @@ use Symfony\Component\Console\Output\OutputInterface; class RetentionCleanupCommand extends Command { - /** @var RetentionService */ - private $service; + private RetentionService $service; public function __construct(RetentionService $service) { parent::__construct('dav:retention:clean-up'); diff --git a/apps/dav/lib/Command/SendEventReminders.php b/apps/dav/lib/Command/SendEventReminders.php index 697248d71a00a..f1f371aadb569 100644 --- a/apps/dav/lib/Command/SendEventReminders.php +++ b/apps/dav/lib/Command/SendEventReminders.php @@ -35,17 +35,9 @@ * @package OCA\DAV\Command */ class SendEventReminders extends Command { + protected ReminderService $reminderService; + protected IConfig $config; - /** @var ReminderService */ - protected $reminderService; - - /** @var IConfig */ - protected $config; - - /** - * @param ReminderService $reminderService - * @param IConfig $config - */ public function __construct(ReminderService $reminderService, IConfig $config) { parent::__construct(); diff --git a/apps/dav/lib/Command/SyncBirthdayCalendar.php b/apps/dav/lib/Command/SyncBirthdayCalendar.php index 6de5357bfde77..cfdb6cf2dcf34 100644 --- a/apps/dav/lib/Command/SyncBirthdayCalendar.php +++ b/apps/dav/lib/Command/SyncBirthdayCalendar.php @@ -35,21 +35,10 @@ use Symfony\Component\Console\Output\OutputInterface; class SyncBirthdayCalendar extends Command { + private BirthdayService $birthdayService; + private IConfig $config; + private IUserManager $userManager; - /** @var BirthdayService */ - private $birthdayService; - - /** @var IConfig */ - private $config; - - /** @var IUserManager */ - private $userManager; - - /** - * @param IUserManager $userManager - * @param IConfig $config - * @param BirthdayService $birthdayService - */ public function __construct(IUserManager $userManager, IConfig $config, BirthdayService $birthdayService) { parent::__construct(); diff --git a/apps/dav/lib/Command/SyncSystemAddressBook.php b/apps/dav/lib/Command/SyncSystemAddressBook.php index 272cca5a08ed1..b2e78877641b2 100644 --- a/apps/dav/lib/Command/SyncSystemAddressBook.php +++ b/apps/dav/lib/Command/SyncSystemAddressBook.php @@ -30,13 +30,8 @@ use Symfony\Component\Console\Output\OutputInterface; class SyncSystemAddressBook extends Command { + private SyncService $syncService; - /** @var SyncService */ - private $syncService; - - /** - * @param SyncService $syncService - */ public function __construct(SyncService $syncService) { parent::__construct(); $this->syncService = $syncService; diff --git a/apps/dav/lib/Comments/CommentNode.php b/apps/dav/lib/Comments/CommentNode.php index c4b9d886e6b3f..869016d9b0965 100644 --- a/apps/dav/lib/Comments/CommentNode.php +++ b/apps/dav/lib/Comments/CommentNode.php @@ -32,9 +32,11 @@ use Sabre\DAV\Exception\BadRequest; use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\INode; +use Sabre\DAV\IProperties; use Sabre\DAV\PropPatch; -class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { +class CommentNode implements INode, IProperties { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; public const PROPERTY_NAME_UNREAD = '{http://owncloud.org/ns}isUnread'; @@ -46,33 +48,14 @@ class CommentNode implements \Sabre\DAV\INode, \Sabre\DAV\IProperties { public const PROPERTY_NAME_MENTION_ID = '{http://owncloud.org/ns}mentionId'; public const PROPERTY_NAME_MENTION_DISPLAYNAME = '{http://owncloud.org/ns}mentionDisplayName'; - /** @var IComment */ - public $comment; + public IComment $comment; + protected ICommentsManager $commentsManager; + protected LoggerInterface $logger; + /** list of properties with key being their name and value their setter */ + protected array $properties = []; + protected IUserManager $userManager; + protected IUserSession $userSession; - /** @var ICommentsManager */ - protected $commentsManager; - - /** @var LoggerInterface */ - protected $logger; - - /** @var array list of properties with key being their name and value their setter */ - protected $properties = []; - - /** @var IUserManager */ - protected $userManager; - - /** @var IUserSession */ - protected $userSession; - - /** - * CommentNode constructor. - * - * @param ICommentsManager $commentsManager - * @param IComment $comment - * @param IUserManager $userManager - * @param IUserSession $userSession - * @param LoggerInterface $logger - */ public function __construct( ICommentsManager $commentsManager, IComment $comment, @@ -104,7 +87,7 @@ public function __construct( * * @return array */ - public static function getPropertyNames() { + public static function getPropertyNames(): array { return [ '{http://owncloud.org/ns}id', '{http://owncloud.org/ns}parentId', @@ -182,12 +165,10 @@ public function getLastModified() { /** * update the comment's message * - * @param $propertyValue - * @return bool * @throws BadRequest * @throws \Exception */ - public function updateComment($propertyValue) { + public function updateComment(string $propertyValue): bool { $this->checkWriteAccessOnComment(); try { $this->comment->setMessage($propertyValue); @@ -279,10 +260,8 @@ public function getProperties($properties) { * transforms a mentions array as returned from IComment->getMentions to an * array with DAV-compatible structure that can be assigned to the * PROPERTY_NAME_MENTION property. - * - * @return array */ - protected function composeMentionsPropertyValue() { + protected function composeMentionsPropertyValue(): array { return array_map(function ($mention) { try { $displayName = $this->commentsManager->resolveDisplayName($mention['type'], $mention['id']); diff --git a/apps/dav/lib/Comments/CommentsPlugin.php b/apps/dav/lib/Comments/CommentsPlugin.php index 68c437cca46c0..d2b9e71d852e3 100644 --- a/apps/dav/lib/Comments/CommentsPlugin.php +++ b/apps/dav/lib/Comments/CommentsPlugin.php @@ -52,21 +52,10 @@ class CommentsPlugin extends ServerPlugin { public const REPORT_PARAM_OFFSET = '{http://owncloud.org/ns}offset'; public const REPORT_PARAM_TIMESTAMP = '{http://owncloud.org/ns}datetime'; - /** @var ICommentsManager */ - protected $commentsManager; + protected ICommentsManager $commentsManager; + private Server $server; + protected IUserSession $userSession; - /** @var \Sabre\DAV\Server $server */ - private $server; - - /** @var \OCP\IUserSession */ - protected $userSession; - - /** - * Comments plugin - * - * @param ICommentsManager $commentsManager - * @param IUserSession $userSession - */ public function __construct(ICommentsManager $commentsManager, IUserSession $userSession) { $this->commentsManager = $commentsManager; $this->userSession = $userSession; @@ -247,7 +236,7 @@ private function createComment($objectType, $objectId, $data, $contentType = 'ap throw new BadRequest('Invalid input values', 0, $e); } catch (\OCP\Comments\MessageTooLongException $e) { $msg = 'Message exceeds allowed character limit of '; - throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); + throw new BadRequest($msg . \OCP\Comments\IComment::MAX_MESSAGE_LENGTH, 0, $e); } } } diff --git a/apps/dav/lib/Comments/EntityCollection.php b/apps/dav/lib/Comments/EntityCollection.php index c3769282b0c64..b9dee358a83b7 100644 --- a/apps/dav/lib/Comments/EntityCollection.php +++ b/apps/dav/lib/Comments/EntityCollection.php @@ -29,6 +29,7 @@ use OCP\IUserSession; use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\INode; use Sabre\DAV\IProperties; use Sabre\DAV\PropPatch; @@ -43,23 +44,12 @@ class EntityCollection extends RootCollection implements IProperties { public const PROPERTY_NAME_READ_MARKER = '{http://owncloud.org/ns}readMarker'; - /** @var string */ - protected $id; + protected string $id; + protected LoggerInterface $logger; - /** @var LoggerInterface */ - protected $logger; - - /** - * @param string $id - * @param string $name - * @param ICommentsManager $commentsManager - * @param IUserManager $userManager - * @param IUserSession $userSession - * @param LoggerInterface $logger - */ public function __construct( - $id, - $name, + string $id, + string $name, ICommentsManager $commentsManager, IUserManager $userManager, IUserSession $userSession, @@ -84,7 +74,7 @@ public function __construct( * * @return string */ - public function getId() { + public function getId(): string { return $this->id; } @@ -95,7 +85,7 @@ public function getId() { * exist. * * @param string $name - * @return \Sabre\DAV\INode + * @return INode * @throws NotFound */ public function getChild($name) { @@ -116,9 +106,9 @@ public function getChild($name) { /** * Returns an array with all the child nodes * - * @return \Sabre\DAV\INode[] + * @return INode[] */ - public function getChildren() { + public function getChildren(): array { return $this->findChildren(); } @@ -131,7 +121,7 @@ public function getChildren() { * @param \DateTime|null $datetime * @return CommentNode[] */ - public function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null) { + public function findChildren(int $limit = 0, int $offset = 0, ?\DateTime $datetime = null): array { $comments = $this->commentsManager->getForObject($this->name, $this->id, $limit, $offset, $datetime); $result = []; foreach ($comments as $comment) { @@ -148,11 +138,8 @@ public function findChildren($limit = 0, $offset = 0, \DateTime $datetime = null /** * Checks if a child-node with the specified name exists - * - * @param string $name - * @return bool */ - public function childExists($name) { + public function childExists(string $name): bool { try { $this->commentsManager->get($name); return true; @@ -163,11 +150,8 @@ public function childExists($name) { /** * Sets the read marker to the specified date for the logged in user - * - * @param \DateTime $value - * @return bool */ - public function setReadMarker($value) { + public function setReadMarker(\DateTime $value): bool { $dateTime = new \DateTime($value); $user = $this->userSession->getUser(); $this->commentsManager->setReadMark($this->name, $this->id, $dateTime, $user); diff --git a/apps/dav/lib/Comments/EntityTypeCollection.php b/apps/dav/lib/Comments/EntityTypeCollection.php index 6cd2c43c1d25a..9f11708a7d343 100644 --- a/apps/dav/lib/Comments/EntityTypeCollection.php +++ b/apps/dav/lib/Comments/EntityTypeCollection.php @@ -29,6 +29,7 @@ use Psr\Log\LoggerInterface; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\INode; /** * Class EntityTypeCollection @@ -42,26 +43,12 @@ * @package OCA\DAV\Comments */ class EntityTypeCollection extends RootCollection { + protected LoggerInterface $logger; + protected IUserManager $userManager; + protected \Closure $childExistsFunction; - /** @var LoggerInterface */ - protected $logger; - - /** @var IUserManager */ - protected $userManager; - - /** @var \Closure */ - protected $childExistsFunction; - - /** - * @param string $name - * @param ICommentsManager $commentsManager - * @param IUserManager $userManager - * @param IUserSession $userSession - * @param LoggerInterface $logger - * @param \Closure $childExistsFunction - */ public function __construct( - $name, + string $name, ICommentsManager $commentsManager, IUserManager $userManager, IUserSession $userSession, @@ -69,7 +56,7 @@ public function __construct( \Closure $childExistsFunction ) { $name = trim($name); - if (empty($name) || !is_string($name)) { + if (empty($name)) { throw new \InvalidArgumentException('"name" parameter must be non-empty string'); } $this->name = $name; @@ -87,7 +74,7 @@ public function __construct( * exist. * * @param string $name - * @return \Sabre\DAV\INode + * @return INode * @throws NotFound */ public function getChild($name) { @@ -107,10 +94,10 @@ public function getChild($name) { /** * Returns an array with all the child nodes * - * @return \Sabre\DAV\INode[] + * @return INode[] * @throws MethodNotAllowed */ - public function getChildren() { + public function getChildren(): array { throw new MethodNotAllowed('No permission to list folder contents'); } @@ -118,9 +105,8 @@ public function getChildren() { * Checks if a child-node with the specified name exists * * @param string $name - * @return bool */ - public function childExists($name) { + public function childExists($name): bool { return call_user_func($this->childExistsFunction, $name); } } diff --git a/apps/dav/lib/Comments/RootCollection.php b/apps/dav/lib/Comments/RootCollection.php index d38790d61ef57..08d72b6663062 100644 --- a/apps/dav/lib/Comments/RootCollection.php +++ b/apps/dav/lib/Comments/RootCollection.php @@ -39,33 +39,14 @@ class RootCollection implements ICollection { /** @var EntityTypeCollection[]|null */ - private $entityTypeCollections; + private ?array $entityTypeCollections; + protected ICommentsManager $commentsManager; + protected string $name = 'comments'; + protected LoggerInterface $logger; + protected IUserManager $userManager; + protected IUserSession $userSession; + protected IEventDispatcher $dispatcher; - /** @var ICommentsManager */ - protected $commentsManager; - - /** @var string */ - protected $name = 'comments'; - - /** @var LoggerInterface */ - protected $logger; - - /** @var IUserManager */ - protected $userManager; - - /** @var IUserSession */ - protected $userSession; - - /** @var IEventDispatcher */ - protected $dispatcher; - - /** - * @param ICommentsManager $commentsManager - * @param IUserManager $userManager - * @param IUserSession $userSession - * @param IEventDispatcher $dispatcher - * @param LoggerInterface $logger - */ public function __construct( ICommentsManager $commentsManager, IUserManager $userManager, @@ -119,7 +100,7 @@ protected function initCollections() { * @return null|string * @throws Forbidden */ - public function createFile($name, $data = null) { + public function createFile($name, $data = null): ?string { throw new Forbidden('Cannot create comments by id'); } @@ -158,7 +139,7 @@ public function getChild($name) { * @return INode[] * @throws NotAuthenticated */ - public function getChildren() { + public function getChildren(): ?array { $this->initCollections(); return $this->entityTypeCollections; } @@ -170,7 +151,7 @@ public function getChildren() { * @return bool * @throws NotAuthenticated */ - public function childExists($name) { + public function childExists($name): bool { $this->initCollections(); return isset($this->entityTypeCollections[$name]); } diff --git a/apps/dav/lib/Connector/Sabre/Auth.php b/apps/dav/lib/Connector/Sabre/Auth.php index fdc5c0eac5944..6e561569d3a7f 100644 --- a/apps/dav/lib/Connector/Sabre/Auth.php +++ b/apps/dav/lib/Connector/Sabre/Auth.php @@ -241,7 +241,7 @@ private function auth(RequestInterface $request, ResponseInterface $response): a if (!$this->userSession->isLoggedIn() && in_array('XMLHttpRequest', explode(',', $request->getHeader('X-Requested-With') ?? ''))) { // do not re-authenticate over ajax, use dummy auth name to prevent browser popup - $response->addHeader('WWW-Authenticate','DummyBasic realm="' . $this->realm . '"'); + $response->addHeader('WWW-Authenticate', 'DummyBasic realm="' . $this->realm . '"'); $response->setStatus(401); throw new NotAuthenticated('Cannot authenticate over ajax calls'); } diff --git a/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php b/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php index 8171c8779dba0..f86a7ee1e966b 100644 --- a/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php +++ b/apps/dav/lib/Connector/Sabre/DummyGetResponsePlugin.php @@ -63,7 +63,7 @@ public function initialize(\Sabre\DAV\Server $server) { public function httpGet(RequestInterface $request, ResponseInterface $response): bool { $string = 'This is the WebDAV interface. It can only be accessed by ' . 'WebDAV clients such as the Nextcloud desktop sync client.'; - $stream = fopen('php://memory','r+'); + $stream = fopen('php://memory', 'r+'); fwrite($stream, $string); rewind($stream); diff --git a/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php b/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php index c4cd6db190a45..9626a21d7fa93 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php +++ b/apps/dav/lib/Connector/Sabre/Exception/BadGateway.php @@ -21,20 +21,22 @@ */ namespace OCA\DAV\Connector\Sabre\Exception; +use Sabre\DAV\Exception; + /** * Bad Gateway * * This exception is thrown whenever the server, while acting as a gateway or proxy, received an invalid response from the upstream server. * */ -class BadGateway extends \Sabre\DAV\Exception { +class BadGateway extends Exception { /** * Returns the HTTP status code for this exception * * @return int */ - public function getHTTPCode() { + public function getHTTPCode(): int { return 502; } } diff --git a/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php b/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php index f0a30a4efc365..fae5feb3f24b8 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php +++ b/apps/dav/lib/Connector/Sabre/Exception/Forbidden.php @@ -54,11 +54,11 @@ public function serialize(Server $server, DOMElement $errorNode) { $errorNode->setAttribute('xmlns:o', self::NS_OWNCLOUD); // adding the retry node - $error = $errorNode->ownerDocument->createElementNS('o:','o:retry', var_export($this->retry, true)); + $error = $errorNode->ownerDocument->createElementNS('o:', 'o:retry', var_export($this->retry, true)); $errorNode->appendChild($error); // adding the message node - $error = $errorNode->ownerDocument->createElementNS('o:','o:reason', $this->getMessage()); + $error = $errorNode->ownerDocument->createElementNS('o:', 'o:reason', $this->getMessage()); $errorNode->appendChild($error); } } diff --git a/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php b/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php index 45639f1a88994..491f9747c4b81 100644 --- a/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php +++ b/apps/dav/lib/Connector/Sabre/Exception/InvalidPath.php @@ -64,11 +64,11 @@ public function serialize(Server $server, DOMElement $errorNode) { $errorNode->setAttribute('xmlns:o', self::NS_OWNCLOUD); // adding the retry node - $error = $errorNode->ownerDocument->createElementNS('o:','o:retry', var_export($this->retry, true)); + $error = $errorNode->ownerDocument->createElementNS('o:', 'o:retry', var_export($this->retry, true)); $errorNode->appendChild($error); // adding the message node - $error = $errorNode->ownerDocument->createElementNS('o:','o:reason', $this->getMessage()); + $error = $errorNode->ownerDocument->createElementNS('o:', 'o:reason', $this->getMessage()); $errorNode->appendChild($error); } } diff --git a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php index a40cb93b0fd25..6286dcf3cfc66 100644 --- a/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php +++ b/apps/dav/lib/Connector/Sabre/MaintenancePlugin.php @@ -34,7 +34,6 @@ use Sabre\DAV\ServerPlugin; class MaintenancePlugin extends ServerPlugin { - private IConfig $config; private IL10N $l10n; diff --git a/apps/dav/lib/Connector/Sabre/Principal.php b/apps/dav/lib/Connector/Sabre/Principal.php index 3f88cffd7f93a..d052d43fee5d1 100644 --- a/apps/dav/lib/Connector/Sabre/Principal.php +++ b/apps/dav/lib/Connector/Sabre/Principal.php @@ -197,7 +197,7 @@ public function getPrincipalByPath($path) { * @return array * @throws Exception */ - public function getGroupMembership($principal, $needGroups = false) { + public function getGroupMembership($principal, bool $needGroups = false) { [$prefix, $name] = \Sabre\Uri\split($principal); if ($prefix !== $this->principalPrefix) { diff --git a/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php b/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php index f874418b212f8..6a027c1e9d719 100644 --- a/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php +++ b/apps/dav/lib/Connector/Sabre/RequestIdHeaderPlugin.php @@ -1,4 +1,6 @@ - * diff --git a/apps/dav/lib/Controller/BirthdayCalendarController.php b/apps/dav/lib/Controller/BirthdayCalendarController.php index 4305d6daaef79..a5013bc1bc6a9 100644 --- a/apps/dav/lib/Controller/BirthdayCalendarController.php +++ b/apps/dav/lib/Controller/BirthdayCalendarController.php @@ -36,44 +36,13 @@ use OCP\IUserManager; class BirthdayCalendarController extends Controller { + protected IDBConnection $db; + protected IConfig $config; + protected IUserManager $userManager; + protected CalDavBackend $caldavBackend; + protected IJobList $jobList; - /** - * @var IDBConnection - */ - protected $db; - - /** - * @var IConfig - */ - protected $config; - - /** - * @var IUserManager - */ - protected $userManager; - - /** - * @var CalDavBackend - */ - protected $caldavBackend; - - /** - * @var IJobList - */ - protected $jobList; - - /** - * BirthdayCalendar constructor. - * - * @param string $appName - * @param IRequest $request - * @param IDBConnection $db - * @param IConfig $config - * @param IJobList $jobList - * @param IUserManager $userManager - * @param CalDavBackend $calDavBackend - */ - public function __construct($appName, IRequest $request, + public function __construct(string $appName, IRequest $request, IDBConnection $db, IConfig $config, IJobList $jobList, IUserManager $userManager, diff --git a/apps/dav/lib/Controller/DirectController.php b/apps/dav/lib/Controller/DirectController.php index 955400998cf49..6b0cbdb5f538e 100644 --- a/apps/dav/lib/Controller/DirectController.php +++ b/apps/dav/lib/Controller/DirectController.php @@ -40,24 +40,12 @@ use OCP\Security\ISecureRandom; class DirectController extends OCSController { - - /** @var IRootFolder */ - private $rootFolder; - - /** @var string */ - private $userId; - - /** @var DirectMapper */ - private $mapper; - - /** @var ISecureRandom */ - private $random; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var IURLGenerator */ - private $urlGenerator; + private IRootFolder $rootFolder; + private string $userId; + private DirectMapper $mapper; + private ISecureRandom $random; + private ITimeFactory $timeFactory; + private IURLGenerator $urlGenerator; public function __construct(string $appName, diff --git a/apps/dav/lib/Controller/InvitationResponseController.php b/apps/dav/lib/Controller/InvitationResponseController.php index f69ef09485c9a..a2958247bceee 100644 --- a/apps/dav/lib/Controller/InvitationResponseController.php +++ b/apps/dav/lib/Controller/InvitationResponseController.php @@ -41,25 +41,10 @@ use function in_array; class InvitationResponseController extends Controller { + private IDBConnection $db; + private ITimeFactory $timeFactory; + private InvitationResponseServer $responseServer; - /** @var IDBConnection */ - private $db; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var InvitationResponseServer */ - private $responseServer; - - /** - * InvitationResponseController constructor. - * - * @param string $appName - * @param IRequest $request - * @param IDBConnection $db - * @param ITimeFactory $timeFactory - * @param InvitationResponseServer $responseServer - */ public function __construct(string $appName, IRequest $request, IDBConnection $db, ITimeFactory $timeFactory, InvitationResponseServer $responseServer) { diff --git a/apps/dav/lib/DAV/CustomPropertiesBackend.php b/apps/dav/lib/DAV/CustomPropertiesBackend.php index 5f512995ce85c..5be9ba22e4dbc 100644 --- a/apps/dav/lib/DAV/CustomPropertiesBackend.php +++ b/apps/dav/lib/DAV/CustomPropertiesBackend.php @@ -34,8 +34,6 @@ use function array_intersect; class CustomPropertiesBackend implements BackendInterface { - - /** @var string */ private const TABLE_NAME = 'properties'; /** @@ -59,33 +57,20 @@ class CustomPropertiesBackend implements BackendInterface { /** * Properties set by one user, readable by all others * - * @var array[] + * @var string[] */ private const PUBLISHED_READ_ONLY_PROPERTIES = [ '{urn:ietf:params:xml:ns:caldav}calendar-availability', ]; - /** - * @var Tree - */ - private $tree; - - /** - * @var IDBConnection - */ - private $connection; - - /** - * @var IUser - */ - private $user; + private Tree $tree; + private IDBConnection $connection; + private IUser $user; /** * Properties cache - * - * @var array */ - private $userCache = []; + private array $userCache = []; /** * @param Tree $tree node tree @@ -303,7 +288,7 @@ private function updateProperties(string $path, array $properties) { ); } } else { - if ($propertyValue instanceOf \Sabre\DAV\Xml\Property\Complex) { + if ($propertyValue instanceof \Sabre\DAV\Xml\Property\Complex) { $propertyValue = $propertyValue->getXml(); } elseif (!is_string($propertyValue)) { $propertyValue = (string)$propertyValue; diff --git a/apps/dav/lib/DAV/GroupPrincipalBackend.php b/apps/dav/lib/DAV/GroupPrincipalBackend.php index f1f15fd61a6d7..c13d38b0eeb24 100644 --- a/apps/dav/lib/DAV/GroupPrincipalBackend.php +++ b/apps/dav/lib/DAV/GroupPrincipalBackend.php @@ -42,22 +42,11 @@ class GroupPrincipalBackend implements BackendInterface { public const PRINCIPAL_PREFIX = 'principals/groups'; - /** @var IGroupManager */ - private $groupManager; + private IGroupManager $groupManager; + private IUserSession $userSession; + private IShareManager $shareManager; + private IConfig $config; - /** @var IUserSession */ - private $userSession; - - /** @var IShareManager */ - private $shareManager; - /** @var IConfig */ - private $config; - - /** - * @param IGroupManager $IGroupManager - * @param IUserSession $userSession - * @param IShareManager $shareManager - */ public function __construct( IGroupManager $IGroupManager, IUserSession $userSession, @@ -104,7 +93,7 @@ public function getPrincipalsByPrefix($prefixPath) { * @return array */ public function getPrincipalByPath($path) { - $elements = explode('/', $path, 3); + $elements = explode('/', $path, 3); if ($elements[0] !== 'principals') { return null; } diff --git a/apps/dav/lib/DAV/PublicAuth.php b/apps/dav/lib/DAV/PublicAuth.php index 83874ab0d4d01..e5ef793454378 100644 --- a/apps/dav/lib/DAV/PublicAuth.php +++ b/apps/dav/lib/DAV/PublicAuth.php @@ -29,7 +29,7 @@ class PublicAuth implements BackendInterface { /** @var string[] */ - private $publicURLs; + private array $publicURLs; public function __construct() { $this->publicURLs = [ diff --git a/apps/dav/lib/DAV/Sharing/Backend.php b/apps/dav/lib/DAV/Sharing/Backend.php index 27ca79d0e01dd..20436c7c408f9 100644 --- a/apps/dav/lib/DAV/Sharing/Backend.php +++ b/apps/dav/lib/DAV/Sharing/Backend.php @@ -34,30 +34,17 @@ use OCP\IUserManager; class Backend { - - /** @var IDBConnection */ - private $db; - /** @var IUserManager */ - private $userManager; - /** @var IGroupManager */ - private $groupManager; - /** @var Principal */ - private $principalBackend; - /** @var string */ - private $resourceType; + private IDBConnection $db; + private IUserManager $userManager; + private IGroupManager $groupManager; + private Principal $principalBackend; + private string $resourceType; public const ACCESS_OWNER = 1; public const ACCESS_READ_WRITE = 2; public const ACCESS_READ = 3; - /** - * @param IDBConnection $db - * @param IUserManager $userManager - * @param IGroupManager $groupManager - * @param Principal $principalBackend - * @param string $resourceType - */ - public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, $resourceType) { + public function __construct(IDBConnection $db, IUserManager $userManager, IGroupManager $groupManager, Principal $principalBackend, string $resourceType) { $this->db = $db; $this->userManager = $userManager; $this->groupManager = $groupManager; @@ -67,7 +54,7 @@ public function __construct(IDBConnection $db, IUserManager $userManager, IGroup /** * @param IShareable $shareable - * @param string[] $add + * @param string[][] $add * @param string[] $remove */ public function updateShares(IShareable $shareable, array $add, array $remove) { @@ -87,9 +74,9 @@ public function updateShares(IShareable $shareable, array $add, array $remove) { /** * @param IShareable $shareable - * @param string $element + * @param string[] $element */ - private function shareWith($shareable, $element) { + private function shareWith(IShareable $shareable, array $element) { $user = $element['href']; $parts = explode(':', $user, 2); if ($parts[0] !== 'principal') { @@ -151,11 +138,7 @@ public function deleteAllSharesByUser($principaluri) { ->execute(); } - /** - * @param IShareable $shareable - * @param string $element - */ - private function unshare($shareable, $element) { + private function unshare(IShareable $shareable, string $element) { $parts = explode(':', $element, 2); if ($parts[0] !== 'principal') { return; diff --git a/apps/dav/lib/DAV/Sharing/Plugin.php b/apps/dav/lib/DAV/Sharing/Plugin.php index a4b2cd3681cc7..53d16af62b9cd 100644 --- a/apps/dav/lib/DAV/Sharing/Plugin.php +++ b/apps/dav/lib/DAV/Sharing/Plugin.php @@ -41,14 +41,9 @@ class Plugin extends ServerPlugin { public const NS_OWNCLOUD = 'http://owncloud.org/ns'; public const NS_NEXTCLOUD = 'http://nextcloud.com/ns'; - /** @var Auth */ - private $auth; - - /** @var IRequest */ - private $request; - - /** @var IConfig */ - private $config; + private Auth $auth; + private IRequest $request; + private IConfig $config; /** * Plugin constructor. @@ -66,9 +61,9 @@ public function __construct(Auth $authBackEnd, IRequest $request, IConfig $confi /** * Reference to SabreDAV server object. * - * @var \Sabre\DAV\Server + * @var Server */ - protected $server; + protected Server $server; /** * This method should return a list of server-features. @@ -111,7 +106,7 @@ public function initialize(Server $server) { $this->server->xml->elementMap['{' . Plugin::NS_OWNCLOUD . '}invite'] = Invite::class; $this->server->on('method:POST', [$this, 'httpPost']); - $this->server->on('propFind', [$this, 'propFind']); + $this->server->on('propFind', [$this, 'propFind']); } /** diff --git a/apps/dav/lib/DAV/Sharing/Xml/Invite.php b/apps/dav/lib/DAV/Sharing/Xml/Invite.php index 161a8dd0ebfb5..6126b6d0c232b 100644 --- a/apps/dav/lib/DAV/Sharing/Xml/Invite.php +++ b/apps/dav/lib/DAV/Sharing/Xml/Invite.php @@ -46,18 +46,14 @@ class Invite implements XmlSerializable { /** * The list of users a calendar has been shared to. - * - * @var array */ - protected $users; + protected array $users; /** * The organizer contains information about the person who shared the * object. - * - * @var array|null */ - protected $organizer; + protected ?array $organizer; /** * Creates the property. @@ -82,8 +78,6 @@ class Invite implements XmlSerializable { * * If you wonder why these two structures are so different, I guess a * valid answer is that the current spec is still a draft. - * - * @param array $users */ public function __construct(array $users, array $organizer = null) { $this->users = $users; diff --git a/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php b/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php index eb5d7d4661d10..fffb27133331d 100644 --- a/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php +++ b/apps/dav/lib/DAV/Sharing/Xml/ShareRequest.php @@ -27,16 +27,9 @@ use Sabre\Xml\XmlDeserializable; class ShareRequest implements XmlDeserializable { - public $set = []; + public array $set = []; + public array $remove = []; - public $remove = []; - - /** - * Constructor - * - * @param array $set - * @param array $remove - */ public function __construct(array $set, array $remove) { $this->set = $set; $this->remove = $remove; diff --git a/apps/dav/lib/Db/Direct.php b/apps/dav/lib/Db/Direct.php index ca2586ab2e094..229807c042c11 100644 --- a/apps/dav/lib/Db/Direct.php +++ b/apps/dav/lib/Db/Direct.php @@ -38,17 +38,10 @@ * @method void setExpiration(int $expiration) */ class Direct extends Entity { - /** @var string */ - protected $userId; - - /** @var int */ - protected $fileId; - - /** @var string */ - protected $token; - - /** @var int */ - protected $expiration; + protected string $userId; + protected int $fileId; + protected string $token; + protected int $expiration; public function __construct() { $this->addType('userId', 'string'); diff --git a/apps/dav/lib/Direct/DirectFile.php b/apps/dav/lib/Direct/DirectFile.php index a4a1999aca715..3fc17f387b4f6 100644 --- a/apps/dav/lib/Direct/DirectFile.php +++ b/apps/dav/lib/Direct/DirectFile.php @@ -36,16 +36,10 @@ use Sabre\DAV\IFile; class DirectFile implements IFile { - /** @var Direct */ - private $direct; - - /** @var IRootFolder */ - private $rootFolder; - - /** @var File */ - private $file; - - private $eventDispatcher; + private Direct $direct; + private IRootFolder $rootFolder; + private File $file; + private IEventDispatcher $eventDispatcher; public function __construct(Direct $direct, IRootFolder $rootFolder, IEventDispatcher $eventDispatcher) { $this->direct = $direct; diff --git a/apps/dav/lib/Direct/DirectHome.php b/apps/dav/lib/Direct/DirectHome.php index a385cd8f39dea..444daed0c46f4 100644 --- a/apps/dav/lib/Direct/DirectHome.php +++ b/apps/dav/lib/Direct/DirectHome.php @@ -39,22 +39,12 @@ use Sabre\DAV\ICollection; class DirectHome implements ICollection { - - /** @var IRootFolder */ - private $rootFolder; - - /** @var DirectMapper */ - private $mapper; - - /** @var ITimeFactory */ - private $timeFactory; - - /** @var Throttler */ - private $throttler; - - /** @var IRequest */ - private $request; - private $eventDispatcher; + private IRootFolder $rootFolder; + private DirectMapper $mapper; + private ITimeFactory $timeFactory; + private Throttler $throttler; + private IRequest $request; + private IEventDispatcher $eventDispatcher; public function __construct( IRootFolder $rootFolder, diff --git a/apps/dav/lib/Direct/ServerFactory.php b/apps/dav/lib/Direct/ServerFactory.php index 05587ab4c2cda..8f7c52135586f 100644 --- a/apps/dav/lib/Direct/ServerFactory.php +++ b/apps/dav/lib/Direct/ServerFactory.php @@ -39,11 +39,9 @@ use OCP\L10N\IFactory; class ServerFactory { - /** @var IConfig */ - private $config; - /** @var IL10N */ - private $l10n; - private $eventDispatcher; + private IConfig $config; + private IL10N $l10n; + private IEventDispatcher $eventDispatcher; public function __construct(IConfig $config, IFactory $l10nFactory, IEventDispatcher $eventDispatcher) { $this->config = $config; diff --git a/apps/dav/lib/Events/AddressBookCreatedEvent.php b/apps/dav/lib/Events/AddressBookCreatedEvent.php index 86c4cd23640a4..eb49aadb2aafa 100644 --- a/apps/dav/lib/Events/AddressBookCreatedEvent.php +++ b/apps/dav/lib/Events/AddressBookCreatedEvent.php @@ -34,12 +34,8 @@ * @since 20.0.0 */ class AddressBookCreatedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; + private int $addressBookId; + private array $addressBookData; /** * AddressBookCreatedEvent constructor. diff --git a/apps/dav/lib/Events/AddressBookDeletedEvent.php b/apps/dav/lib/Events/AddressBookDeletedEvent.php index 3c8da6b7bf07e..8783593187da3 100644 --- a/apps/dav/lib/Events/AddressBookDeletedEvent.php +++ b/apps/dav/lib/Events/AddressBookDeletedEvent.php @@ -34,15 +34,9 @@ * @since 20.0.0 */ class AddressBookDeletedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; - - /** @var array */ - private $shares; + private int $addressBookId; + private array $addressBookData; + private array $shares; /** * AddressBookDeletedEvent constructor. diff --git a/apps/dav/lib/Events/AddressBookShareUpdatedEvent.php b/apps/dav/lib/Events/AddressBookShareUpdatedEvent.php index f9f8ff99d40b1..4266ba51e378d 100644 --- a/apps/dav/lib/Events/AddressBookShareUpdatedEvent.php +++ b/apps/dav/lib/Events/AddressBookShareUpdatedEvent.php @@ -34,30 +34,13 @@ * @since 20.0.0 */ class AddressBookShareUpdatedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; - - /** @var array */ - private $oldShares; - - /** @var array */ - private $added; - - /** @var array */ - private $removed; + private int $addressBookId; + private array $addressBookData; + private array $oldShares; + private array $added; + private array $removed; /** - * AddressBookShareUpdatedEvent constructor. - * - * @param int $addressBookId - * @param array $addressBookData - * @param array $oldShares - * @param array $added - * @param array $removed * @since 20.0.0 */ public function __construct(int $addressBookId, diff --git a/apps/dav/lib/Events/AddressBookUpdatedEvent.php b/apps/dav/lib/Events/AddressBookUpdatedEvent.php index c632f1817a83e..47169a23126ab 100644 --- a/apps/dav/lib/Events/AddressBookUpdatedEvent.php +++ b/apps/dav/lib/Events/AddressBookUpdatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class AddressBookUpdatedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; - - /** @var array */ - private $shares; - - /** @var array */ - private $mutations; + private int $addressBookId; + private array $addressBookData; + private array $shares; + private array $mutations; /** - * AddressBookUpdatedEvent constructor. - * - * @param int $addressBookId - * @param array $addressBookData - * @param array $shares - * @param array $mutations * @since 20.0.0 */ public function __construct(int $addressBookId, diff --git a/apps/dav/lib/Events/BeforeFileDirectDownloadedEvent.php b/apps/dav/lib/Events/BeforeFileDirectDownloadedEvent.php index ddb79505ac649..a53cdf5161679 100644 --- a/apps/dav/lib/Events/BeforeFileDirectDownloadedEvent.php +++ b/apps/dav/lib/Events/BeforeFileDirectDownloadedEvent.php @@ -32,7 +32,7 @@ * @since 22.0.0 */ class BeforeFileDirectDownloadedEvent extends Event { - private $file; + private File $file; public function __construct(File $file) { parent::__construct(); diff --git a/apps/dav/lib/Events/CachedCalendarObjectCreatedEvent.php b/apps/dav/lib/Events/CachedCalendarObjectCreatedEvent.php index 29e11ddc1464f..5684402f1a3c9 100644 --- a/apps/dav/lib/Events/CachedCalendarObjectCreatedEvent.php +++ b/apps/dav/lib/Events/CachedCalendarObjectCreatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CachedCalendarObjectCreatedEvent extends Event { - - /** @var int */ - private $subscriptionId; - - /** @var array */ - private $subscriptionData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $subscriptionId; + private array $subscriptionData; + private array $shares; + private array $objectData; /** - * CachedCalendarObjectCreatedEvent constructor. - * - * @param int $subscriptionId - * @param array $subscriptionData - * @param array $shares - * @param array $objectData * @since 20.0.0 */ public function __construct(int $subscriptionId, diff --git a/apps/dav/lib/Events/CachedCalendarObjectDeletedEvent.php b/apps/dav/lib/Events/CachedCalendarObjectDeletedEvent.php index eaf98df60bfde..d9144e1d28bae 100644 --- a/apps/dav/lib/Events/CachedCalendarObjectDeletedEvent.php +++ b/apps/dav/lib/Events/CachedCalendarObjectDeletedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CachedCalendarObjectDeletedEvent extends Event { - - /** @var int */ - private $subscriptionId; - - /** @var array */ - private $subscriptionData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $subscriptionId; + private array $subscriptionData; + private array $shares; + private array $objectData; /** - * CachedCalendarObjectDeletedEvent constructor. - * - * @param int $subscriptionId - * @param array $subscriptionData - * @param array $shares - * @param array $objectData * @since 20.0.0 */ public function __construct(int $subscriptionId, diff --git a/apps/dav/lib/Events/CachedCalendarObjectUpdatedEvent.php b/apps/dav/lib/Events/CachedCalendarObjectUpdatedEvent.php index d47d75ec1d8fc..fa9267f4a82a6 100644 --- a/apps/dav/lib/Events/CachedCalendarObjectUpdatedEvent.php +++ b/apps/dav/lib/Events/CachedCalendarObjectUpdatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CachedCalendarObjectUpdatedEvent extends Event { - - /** @var int */ - private $subscriptionId; - - /** @var array */ - private $subscriptionData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $subscriptionId; + private array $subscriptionData; + private array $shares; + private array $objectData; /** - * CachedCalendarObjectUpdatedEvent constructor. - * - * @param int $subscriptionId - * @param array $subscriptionData - * @param array $shares - * @param array $objectData * @since 20.0.0 */ public function __construct(int $subscriptionId, diff --git a/apps/dav/lib/Events/CalendarCreatedEvent.php b/apps/dav/lib/Events/CalendarCreatedEvent.php index ba51002f82981..ba0314fe96cfb 100644 --- a/apps/dav/lib/Events/CalendarCreatedEvent.php +++ b/apps/dav/lib/Events/CalendarCreatedEvent.php @@ -34,12 +34,8 @@ * @since 20.0.0 */ class CalendarCreatedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; + private int $calendarId; + private array $calendarData; /** * CalendarCreatedEvent constructor. diff --git a/apps/dav/lib/Events/CalendarDeletedEvent.php b/apps/dav/lib/Events/CalendarDeletedEvent.php index d6207ac6ee29a..534326ab52ac7 100644 --- a/apps/dav/lib/Events/CalendarDeletedEvent.php +++ b/apps/dav/lib/Events/CalendarDeletedEvent.php @@ -34,22 +34,11 @@ * @since 20.0.0 */ class CalendarDeletedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; + private int $calendarId; + private array $calendarData; + private array $shares; /** - * CalendarDeletedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param array $shares * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarMovedToTrashEvent.php b/apps/dav/lib/Events/CalendarMovedToTrashEvent.php index c04b383d5bf5a..d0bdc5b63bd58 100644 --- a/apps/dav/lib/Events/CalendarMovedToTrashEvent.php +++ b/apps/dav/lib/Events/CalendarMovedToTrashEvent.php @@ -31,20 +31,11 @@ * @since 22.0.0 */ class CalendarMovedToTrashEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; + private int $calendarId; + private array $calendarData; + private array $shares; /** - * @param int $calendarId - * @param array $calendarData - * @param array $shares * @since 22.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarObjectCreatedEvent.php b/apps/dav/lib/Events/CalendarObjectCreatedEvent.php index 294c778335e56..36e499dbe02d8 100644 --- a/apps/dav/lib/Events/CalendarObjectCreatedEvent.php +++ b/apps/dav/lib/Events/CalendarObjectCreatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CalendarObjectCreatedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $calendarId; + private array $calendarData; + private array $shares; + private array $objectData; /** - * CalendarObjectCreatedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param array $shares - * @param array $objectData * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarObjectDeletedEvent.php b/apps/dav/lib/Events/CalendarObjectDeletedEvent.php index 7a621994b8034..fe8a1758e0bd4 100644 --- a/apps/dav/lib/Events/CalendarObjectDeletedEvent.php +++ b/apps/dav/lib/Events/CalendarObjectDeletedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CalendarObjectDeletedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $calendarId; + private array $calendarData; + private array $shares; + private array $objectData; /** - * CalendarObjectDeletedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param array $shares - * @param array $objectData * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarObjectMovedToTrashEvent.php b/apps/dav/lib/Events/CalendarObjectMovedToTrashEvent.php index d7a3b99de8259..344f0d27c5076 100644 --- a/apps/dav/lib/Events/CalendarObjectMovedToTrashEvent.php +++ b/apps/dav/lib/Events/CalendarObjectMovedToTrashEvent.php @@ -31,24 +31,12 @@ * @since 22.0.0 */ class CalendarObjectMovedToTrashEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $calendarId; + private array $calendarData; + private array $shares; + private array $objectData; /** - * @param int $calendarId - * @param array $calendarData - * @param array $shares - * @param array $objectData * @since 22.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarObjectRestoredEvent.php b/apps/dav/lib/Events/CalendarObjectRestoredEvent.php index 42f296e64cc99..dfd83b90a3dac 100644 --- a/apps/dav/lib/Events/CalendarObjectRestoredEvent.php +++ b/apps/dav/lib/Events/CalendarObjectRestoredEvent.php @@ -31,24 +31,12 @@ * @since 22.0.0 */ class CalendarObjectRestoredEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $calendarId; + private array $calendarData; + private array $shares; + private array $objectData; /** - * @param int $calendarId - * @param array $calendarData - * @param array $shares - * @param array $objectData * @since 22.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarObjectUpdatedEvent.php b/apps/dav/lib/Events/CalendarObjectUpdatedEvent.php index 84157afd20a4b..f13b0fcf05d58 100644 --- a/apps/dav/lib/Events/CalendarObjectUpdatedEvent.php +++ b/apps/dav/lib/Events/CalendarObjectUpdatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CalendarObjectUpdatedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; - - /** @var array */ - private $objectData; + private int $calendarId; + private array $calendarData; + private array $shares; + private array $objectData; /** - * CalendarObjectUpdatedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param array $shares - * @param array $objectData * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarPublishedEvent.php b/apps/dav/lib/Events/CalendarPublishedEvent.php index 7b3b95f2f777a..3200405c4e3d4 100644 --- a/apps/dav/lib/Events/CalendarPublishedEvent.php +++ b/apps/dav/lib/Events/CalendarPublishedEvent.php @@ -34,22 +34,11 @@ * @since 20.0.0 */ class CalendarPublishedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var string */ - private $publicUri; + private int $calendarId; + private array $calendarData; + private string $publicUri; /** - * CalendarPublishedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param string $publicUri * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarRestoredEvent.php b/apps/dav/lib/Events/CalendarRestoredEvent.php index ef477ac1d4823..6089aeb54d665 100644 --- a/apps/dav/lib/Events/CalendarRestoredEvent.php +++ b/apps/dav/lib/Events/CalendarRestoredEvent.php @@ -31,20 +31,11 @@ * @since 22.0.0 */ class CalendarRestoredEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; + private int $calendarId; + private array $calendarData; + private array $shares; /** - * @param int $calendarId - * @param array $calendarData - * @param array $shares * @since 22.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarShareUpdatedEvent.php b/apps/dav/lib/Events/CalendarShareUpdatedEvent.php index a9011bc02735b..69e8c5437c431 100644 --- a/apps/dav/lib/Events/CalendarShareUpdatedEvent.php +++ b/apps/dav/lib/Events/CalendarShareUpdatedEvent.php @@ -34,30 +34,13 @@ * @since 20.0.0 */ class CalendarShareUpdatedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $oldShares; - - /** @var array */ - private $added; - - /** @var array */ - private $removed; + private int $calendarId; + private array $calendarData; + private array $oldShares; + private array $added; + private array $removed; /** - * CalendarShareUpdatedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param array $oldShares - * @param array $added - * @param array $removed * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarUnpublishedEvent.php b/apps/dav/lib/Events/CalendarUnpublishedEvent.php index 0cea53c6f0dc2..8578376e1804e 100644 --- a/apps/dav/lib/Events/CalendarUnpublishedEvent.php +++ b/apps/dav/lib/Events/CalendarUnpublishedEvent.php @@ -34,18 +34,10 @@ * @since 20.0.0 */ class CalendarUnpublishedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; + private int $calendarId; + private array $calendarData; /** - * CalendarUnpublishedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CalendarUpdatedEvent.php b/apps/dav/lib/Events/CalendarUpdatedEvent.php index ec33412b478c6..8f8c7a2c6f939 100644 --- a/apps/dav/lib/Events/CalendarUpdatedEvent.php +++ b/apps/dav/lib/Events/CalendarUpdatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CalendarUpdatedEvent extends Event { - - /** @var int */ - private $calendarId; - - /** @var array */ - private $calendarData; - - /** @var array */ - private $shares; - - /** @var array */ - private $mutations; + private int $calendarId; + private array $calendarData; + private array $shares; + private array $mutations; /** - * CalendarUpdatedEvent constructor. - * - * @param int $calendarId - * @param array $calendarData - * @param array $shares - * @param array $mutations * @since 20.0.0 */ public function __construct(int $calendarId, diff --git a/apps/dav/lib/Events/CardCreatedEvent.php b/apps/dav/lib/Events/CardCreatedEvent.php index 4c6b1714721dd..0778d00e5970c 100644 --- a/apps/dav/lib/Events/CardCreatedEvent.php +++ b/apps/dav/lib/Events/CardCreatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CardCreatedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; - - /** @var array */ - private $shares; - - /** @var array */ - private $cardData; + private int $addressBookId; + private array $addressBookData; + private array $shares; + private array $cardData; /** - * CardCreatedEvent constructor. - * - * @param int $addressBookId - * @param array $addressBookData - * @param array $shares - * @param array $cardData * @since 20.0.0 */ public function __construct(int $addressBookId, diff --git a/apps/dav/lib/Events/CardDeletedEvent.php b/apps/dav/lib/Events/CardDeletedEvent.php index f4d7e21fab131..3ac0d74b15084 100644 --- a/apps/dav/lib/Events/CardDeletedEvent.php +++ b/apps/dav/lib/Events/CardDeletedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CardDeletedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; - - /** @var array */ - private $shares; - - /** @var array */ - private $cardData; + private int $addressBookId; + private array $addressBookData; + private array $shares; + private array $cardData; /** - * CardDeletedEvent constructor. - * - * @param int $addressBookId - * @param array $addressBookData - * @param array $shares - * @param array $cardData * @since 20.0.0 */ public function __construct(int $addressBookId, diff --git a/apps/dav/lib/Events/CardUpdatedEvent.php b/apps/dav/lib/Events/CardUpdatedEvent.php index 213419d51a3a0..ff1bcedfc53e8 100644 --- a/apps/dav/lib/Events/CardUpdatedEvent.php +++ b/apps/dav/lib/Events/CardUpdatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class CardUpdatedEvent extends Event { - - /** @var int */ - private $addressBookId; - - /** @var array */ - private $addressBookData; - - /** @var array */ - private $shares; - - /** @var array */ - private $cardData; + private int $addressBookId; + private array $addressBookData; + private array $shares; + private array $cardData; /** - * CardUpdatedEvent constructor. - * - * @param int $addressBookId - * @param array $addressBookData - * @param array $shares - * @param array $cardData * @since 20.0.0 */ public function __construct(int $addressBookId, diff --git a/apps/dav/lib/Events/SabreAddPluginEvent.php b/apps/dav/lib/Events/SabreAddPluginEvent.php index a434d94066a58..b8f1dd16f39e1 100644 --- a/apps/dav/lib/Events/SabreAddPluginEvent.php +++ b/apps/dav/lib/Events/SabreAddPluginEvent.php @@ -35,9 +35,7 @@ * @since 24.0.0 */ class SabreAddPluginEvent extends Event { - - /** @var Server */ - private $server; + private Server $server; /** * @since 20.0.0 diff --git a/apps/dav/lib/Events/SabrePluginAuthInitEvent.php b/apps/dav/lib/Events/SabrePluginAuthInitEvent.php index ea1bd95a0f723..2578e95dae92a 100644 --- a/apps/dav/lib/Events/SabrePluginAuthInitEvent.php +++ b/apps/dav/lib/Events/SabrePluginAuthInitEvent.php @@ -35,9 +35,7 @@ * @since 20.0.0 */ class SabrePluginAuthInitEvent extends Event { - - /** @var Server */ - private $server; + private Server $server; /** * @since 20.0.0 diff --git a/apps/dav/lib/Events/SubscriptionCreatedEvent.php b/apps/dav/lib/Events/SubscriptionCreatedEvent.php index f7fc210122104..11ebfb3f55464 100644 --- a/apps/dav/lib/Events/SubscriptionCreatedEvent.php +++ b/apps/dav/lib/Events/SubscriptionCreatedEvent.php @@ -34,18 +34,10 @@ * @since 20.0.0 */ class SubscriptionCreatedEvent extends Event { - - /** @var int */ - private $subscriptionId; - - /** @var array */ - private $subscriptionData; + private int $subscriptionId; + private array $subscriptionData; /** - * SubscriptionCreatedEvent constructor. - * - * @param int $subscriptionId - * @param array $subscriptionData * @since 20.0.0 */ public function __construct(int $subscriptionId, diff --git a/apps/dav/lib/Events/SubscriptionDeletedEvent.php b/apps/dav/lib/Events/SubscriptionDeletedEvent.php index fc31005ac0f2f..2cdc852ea86df 100644 --- a/apps/dav/lib/Events/SubscriptionDeletedEvent.php +++ b/apps/dav/lib/Events/SubscriptionDeletedEvent.php @@ -34,22 +34,11 @@ * @since 20.0.0 */ class SubscriptionDeletedEvent extends Event { - - /** @var int */ - private $subscriptionId; - - /** @var array */ - private $subscriptionData; - - /** @var array */ - private $shares; + private int $subscriptionId; + private array $subscriptionData; + private array $shares; /** - * SubscriptionDeletedEvent constructor. - * - * @param int $subscriptionId - * @param array $subscriptionData - * @param array $shares * @since 20.0.0 */ public function __construct(int $subscriptionId, diff --git a/apps/dav/lib/Events/SubscriptionUpdatedEvent.php b/apps/dav/lib/Events/SubscriptionUpdatedEvent.php index 29231d13a7f72..5e517603d6a95 100644 --- a/apps/dav/lib/Events/SubscriptionUpdatedEvent.php +++ b/apps/dav/lib/Events/SubscriptionUpdatedEvent.php @@ -34,26 +34,12 @@ * @since 20.0.0 */ class SubscriptionUpdatedEvent extends Event { - - /** @var int */ - private $subscriptionId; - - /** @var array */ - private $subscriptionData; - - /** @var array */ - private $shares; - - /** @var array */ - private $mutations; + private int $subscriptionId; + private array $subscriptionData; + private array $shares; + private array $mutations; /** - * SubscriptionUpdatedEvent constructor. - * - * @param int $subscriptionId - * @param array $subscriptionData - * @param array $shares - * @param array $mutations * @since 20.0.0 */ public function __construct(int $subscriptionId, diff --git a/apps/dav/lib/Files/BrowserErrorPagePlugin.php b/apps/dav/lib/Files/BrowserErrorPagePlugin.php index b53d1caac5cdf..92882372e7838 100644 --- a/apps/dav/lib/Files/BrowserErrorPagePlugin.php +++ b/apps/dav/lib/Files/BrowserErrorPagePlugin.php @@ -33,8 +33,7 @@ use Sabre\DAV\ServerPlugin; class BrowserErrorPagePlugin extends ServerPlugin { - /** @var Server */ - private $server; + private Server $server; /** * This initializes the plugin. @@ -56,7 +55,7 @@ public function initialize(Server $server) { * @param IRequest $request * @return bool */ - public static function isBrowserRequest(IRequest $request) { + public static function isBrowserRequest(IRequest $request): bool { if ($request->getMethod() !== 'GET') { return false; } @@ -91,9 +90,8 @@ public function logException(\Exception $ex) { /** * @codeCoverageIgnore - * @return bool|string */ - public function generateBody(int $httpCode) { + public function generateBody(int $httpCode): string { $request = \OC::$server->get(IRequest::class); $templateName = 'exception'; diff --git a/apps/dav/lib/Files/FileSearchBackend.php b/apps/dav/lib/Files/FileSearchBackend.php index 7017becc27850..02b219ba687d1 100644 --- a/apps/dav/lib/Files/FileSearchBackend.php +++ b/apps/dav/lib/Files/FileSearchBackend.php @@ -60,20 +60,11 @@ use function array_slice; class FileSearchBackend implements ISearchBackend { - /** @var CachingTree */ - private $tree; - - /** @var IUser */ - private $user; - - /** @var IRootFolder */ - private $rootFolder; - - /** @var IManager */ - private $shareManager; - - /** @var View */ - private $view; + private CachingTree $tree; + private IUser $user; + private IRootFolder $rootFolder; + private IManager $shareManager; + private View $view; /** * FileSearchBackend constructor. @@ -98,11 +89,11 @@ public function __construct(CachingTree $tree, IUser $user, IRootFolder $rootFol * * @return string */ - public function getArbiterPath() { + public function getArbiterPath(): string { return ''; } - public function isValidScope($href, $depth, $path) { + public function isValidScope($href, $depth, $path): bool { // only allow scopes inside the dav server if (is_null($path)) { return false; @@ -116,7 +107,7 @@ public function isValidScope($href, $depth, $path) { } } - public function getPropertyDefinitionsForScope($href, $path) { + public function getPropertyDefinitionsForScope($href, $path): array { // all valid scopes support the same schema //todo dynamically load all propfind properties that are supported @@ -151,7 +142,7 @@ public function getPropertyDefinitionsForScope($href, $path) { * @throws ContainerExceptionInterface * @throws NotFoundExceptionInterface */ - public function search(Query $query) { + public function search(Query $query): array { if (count($query->from) !== 1) { throw new InvalidArgumentException('Searching more than one folder is not supported'); } diff --git a/apps/dav/lib/Files/FilesHome.php b/apps/dav/lib/Files/FilesHome.php index 0a781b5589d0d..97f62bb44f85e 100644 --- a/apps/dav/lib/Files/FilesHome.php +++ b/apps/dav/lib/Files/FilesHome.php @@ -25,26 +25,17 @@ */ namespace OCA\DAV\Files; +use OC\Files\Filesystem; use OCA\DAV\Connector\Sabre\Directory; use OCP\Files\FileInfo; use Sabre\DAV\Exception\Forbidden; class FilesHome extends Directory { + private array $principalInfo; - /** - * @var array - */ - private $principalInfo; - - /** - * FilesHome constructor. - * - * @param array $principalInfo - * @param FileInfo $userFolder - */ - public function __construct($principalInfo, FileInfo $userFolder) { + public function __construct(array $principalInfo, FileInfo $userFolder) { $this->principalInfo = $principalInfo; - $view = \OC\Files\Filesystem::getView(); + $view = Filesystem::getView(); parent::__construct($view, $userFolder); } diff --git a/apps/dav/lib/Files/LazySearchBackend.php b/apps/dav/lib/Files/LazySearchBackend.php index d84c11306e360..82417a1eac3c3 100644 --- a/apps/dav/lib/Files/LazySearchBackend.php +++ b/apps/dav/lib/Files/LazySearchBackend.php @@ -26,16 +26,13 @@ use SearchDAV\Query\Query; class LazySearchBackend implements ISearchBackend { - /** - * @var ISearchBackend $backend - */ - private $backend = null; + private ?ISearchBackend $backend = null; public function setBackend(ISearchBackend $backend) { $this->backend = $backend; } - public function getArbiterPath() { + public function getArbiterPath(): string { if ($this->backend) { return $this->backend->getArbiterPath(); } else { @@ -51,7 +48,7 @@ public function isValidScope($href, $depth, $path) { } } - public function getPropertyDefinitionsForScope($href, $path) { + public function getPropertyDefinitionsForScope($href, $path): array { if ($this->backend) { return $this->backend->getPropertyDefinitionsForScope($href, $path); } else { @@ -59,7 +56,7 @@ public function getPropertyDefinitionsForScope($href, $path) { } } - public function search(Query $query) { + public function search(Query $query): array { if ($this->backend) { return $this->backend->search($query); } else { diff --git a/apps/dav/lib/Files/Sharing/FilesDropPlugin.php b/apps/dav/lib/Files/Sharing/FilesDropPlugin.php index 3ac541bbfd9e0..70b4b6888015f 100644 --- a/apps/dav/lib/Files/Sharing/FilesDropPlugin.php +++ b/apps/dav/lib/Files/Sharing/FilesDropPlugin.php @@ -26,6 +26,7 @@ use OC\Files\View; use Sabre\DAV\Exception\MethodNotAllowed; +use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -34,17 +35,13 @@ * Make sure that the destination is writable */ class FilesDropPlugin extends ServerPlugin { - - /** @var View */ - private $view; - - /** @var bool */ - private $enabled = false; + private View $view; + private bool $enabled = false; /** * @param View $view */ - public function setView($view) { + public function setView(View $view) { $this->view = $view; } @@ -56,12 +53,12 @@ public function enable() { /** * This initializes the plugin. * - * @param \Sabre\DAV\Server $server Sabre server + * @param Server $server Sabre server * * @return void * @throws MethodNotAllowed */ - public function initialize(\Sabre\DAV\Server $server) { + public function initialize(Server $server) { $server->on('beforeMethod:*', [$this, 'beforeMethod'], 999); $this->enabled = false; } diff --git a/apps/dav/lib/Files/Sharing/PublicLinkCheckPlugin.php b/apps/dav/lib/Files/Sharing/PublicLinkCheckPlugin.php index 94cd6d29c6c1e..ba2f169cf772f 100644 --- a/apps/dav/lib/Files/Sharing/PublicLinkCheckPlugin.php +++ b/apps/dav/lib/Files/Sharing/PublicLinkCheckPlugin.php @@ -25,6 +25,7 @@ use OCP\Files\FileInfo; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\Server; use Sabre\DAV\ServerPlugin; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -36,23 +37,23 @@ class PublicLinkCheckPlugin extends ServerPlugin { /** * @var FileInfo */ - private $fileInfo; + private FileInfo $fileInfo; /** * @param FileInfo $fileInfo */ - public function setFileInfo($fileInfo) { + public function setFileInfo(FileInfo $fileInfo) { $this->fileInfo = $fileInfo; } /** * This initializes the plugin. * - * @param \Sabre\DAV\Server $server Sabre server + * @param Server $server Sabre server * * @return void */ - public function initialize(\Sabre\DAV\Server $server) { + public function initialize(Server $server) { $server->on('beforeMethod:*', [$this, 'beforeMethod']); } diff --git a/apps/dav/lib/Listener/ActivityUpdaterListener.php b/apps/dav/lib/Listener/ActivityUpdaterListener.php index 2d06004793c0a..3842d3c67d118 100644 --- a/apps/dav/lib/Listener/ActivityUpdaterListener.php +++ b/apps/dav/lib/Listener/ActivityUpdaterListener.php @@ -47,12 +47,8 @@ * @template-implements IEventListener */ class ActivityUpdaterListener implements IEventListener { - - /** @var ActivityBackend */ - private $activityBackend; - - /** @var LoggerInterface */ - private $logger; + private ActivityBackend $activityBackend; + private LoggerInterface $logger; public function __construct(ActivityBackend $activityBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/AddressbookListener.php b/apps/dav/lib/Listener/AddressbookListener.php index e367fe762de78..cf47eadc36ea4 100644 --- a/apps/dav/lib/Listener/AddressbookListener.php +++ b/apps/dav/lib/Listener/AddressbookListener.php @@ -40,11 +40,8 @@ * @template-implements IEventListener */ class AddressbookListener implements IEventListener { - /** @var ActivityBackend */ - private $activityBackend; - - /** @var LoggerInterface */ - private $logger; + private ActivityBackend $activityBackend; + private LoggerInterface $logger; public function __construct(ActivityBackend $activityBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/BirthdayListener.php b/apps/dav/lib/Listener/BirthdayListener.php index 43e0f5c6274fb..ef8ccfdc30421 100644 --- a/apps/dav/lib/Listener/BirthdayListener.php +++ b/apps/dav/lib/Listener/BirthdayListener.php @@ -36,8 +36,7 @@ * @template-implements IEventListener */ class BirthdayListener implements IEventListener { - /** @var BirthdayService */ - private $birthdayService; + private BirthdayService $birthdayService; public function __construct(BirthdayService $birthdayService) { $this->birthdayService = $birthdayService; diff --git a/apps/dav/lib/Listener/CalendarContactInteractionListener.php b/apps/dav/lib/Listener/CalendarContactInteractionListener.php index b31788e7079c7..23e34067fe40f 100644 --- a/apps/dav/lib/Listener/CalendarContactInteractionListener.php +++ b/apps/dav/lib/Listener/CalendarContactInteractionListener.php @@ -52,20 +52,11 @@ class CalendarContactInteractionListener implements IEventListener { private const URI_USERS = 'principals/users/'; - /** @var IEventDispatcher */ - private $dispatcher; - - /** @var IUserSession */ - private $userSession; - - /** @var Principal */ - private $principalConnector; - - /** @var IMailer */ - private $mailer; - - /** @var LoggerInterface */ - private $logger; + private IEventDispatcher $dispatcher; + private IUserSession $userSession; + private Principal $principalConnector; + private IMailer $mailer; + private LoggerInterface $logger; public function __construct(IEventDispatcher $dispatcher, IUserSession $userSession, diff --git a/apps/dav/lib/Listener/CalendarDeletionDefaultUpdaterListener.php b/apps/dav/lib/Listener/CalendarDeletionDefaultUpdaterListener.php index 7bb535383c05e..254706d077d30 100644 --- a/apps/dav/lib/Listener/CalendarDeletionDefaultUpdaterListener.php +++ b/apps/dav/lib/Listener/CalendarDeletionDefaultUpdaterListener.php @@ -37,12 +37,8 @@ * @template-implements IEventListener<\OCA\DAV\Events\CalendarDeletedEvent> */ class CalendarDeletionDefaultUpdaterListener implements IEventListener { - - /** @var IConfig */ - private $config; - - /** @var LoggerInterface */ - private $logger; + private IConfig $config; + private LoggerInterface $logger; public function __construct(IConfig $config, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php b/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php index 67b38457436ea..f496033fd178f 100644 --- a/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php +++ b/apps/dav/lib/Listener/CalendarObjectReminderUpdaterListener.php @@ -46,18 +46,10 @@ * @template-implements IEventListener */ class CalendarObjectReminderUpdaterListener implements IEventListener { - - /** @var ReminderBackend */ - private $reminderBackend; - - /** @var ReminderService */ - private $reminderService; - - /** @var CalDavBackend */ - private $calDavBackend; - - /** @var LoggerInterface */ - private $logger; + private ReminderBackend $reminderBackend; + private ReminderService $reminderService; + private CalDavBackend $calDavBackend; + private LoggerInterface $logger; public function __construct(ReminderBackend $reminderBackend, ReminderService $reminderService, diff --git a/apps/dav/lib/Listener/CalendarPublicationListener.php b/apps/dav/lib/Listener/CalendarPublicationListener.php index cb89ccf12b637..84e481108d9ed 100644 --- a/apps/dav/lib/Listener/CalendarPublicationListener.php +++ b/apps/dav/lib/Listener/CalendarPublicationListener.php @@ -35,12 +35,8 @@ * @template-implements IEventListener<\OCA\DAV\Events\CalendarPublishedEvent> */ class CalendarPublicationListener implements IEventListener { - - /** @var Backend */ - private $activityBackend; - - /** @var LoggerInterface */ - private $logger; + private Backend $activityBackend; + private LoggerInterface $logger; public function __construct(Backend $activityBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/CalendarShareUpdateListener.php b/apps/dav/lib/Listener/CalendarShareUpdateListener.php index 470c50e7be699..332b76b0e4afa 100644 --- a/apps/dav/lib/Listener/CalendarShareUpdateListener.php +++ b/apps/dav/lib/Listener/CalendarShareUpdateListener.php @@ -35,12 +35,8 @@ * @template-implements IEventListener<\OCA\DAV\Events\CalendarShareUpdatedEvent> */ class CalendarShareUpdateListener implements IEventListener { - - /** @var Backend */ - private $activityBackend; - - /** @var LoggerInterface */ - private $logger; + private Backend $activityBackend; + private LoggerInterface $logger; public function __construct(Backend $activityBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/CalendarUnpublicationListener.php b/apps/dav/lib/Listener/CalendarUnpublicationListener.php index 92e9db22afb0f..3db7906ce5dad 100644 --- a/apps/dav/lib/Listener/CalendarUnpublicationListener.php +++ b/apps/dav/lib/Listener/CalendarUnpublicationListener.php @@ -35,12 +35,8 @@ * @template-implements IEventListener<\OCA\DAV\Events\CalendarUnpublishedEvent> */ class CalendarUnpublicationListener implements IEventListener { - - /** @var Backend */ - private $activityBackend; - - /** @var LoggerInterface */ - private $logger; + private Backend $activityBackend; + private LoggerInterface $logger; public function __construct(Backend $activityBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/CardListener.php b/apps/dav/lib/Listener/CardListener.php index 759b47c051c42..fd5f4b807e234 100644 --- a/apps/dav/lib/Listener/CardListener.php +++ b/apps/dav/lib/Listener/CardListener.php @@ -40,11 +40,8 @@ * @template-implements IEventListener */ class CardListener implements IEventListener { - /** @var ActivityBackend */ - private $activityBackend; - - /** @var LoggerInterface */ - private $logger; + private ActivityBackend $activityBackend; + private LoggerInterface $logger; public function __construct(ActivityBackend $activityBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/ClearPhotoCacheListener.php b/apps/dav/lib/Listener/ClearPhotoCacheListener.php index 1a3ffa2b82686..32daded09922c 100644 --- a/apps/dav/lib/Listener/ClearPhotoCacheListener.php +++ b/apps/dav/lib/Listener/ClearPhotoCacheListener.php @@ -35,8 +35,7 @@ * @template-implements IEventListener */ class ClearPhotoCacheListener implements IEventListener { - /** @var PhotoCache */ - private $photoCache; + private PhotoCache $photoCache; public function __construct(PhotoCache $photoCache) { $this->photoCache = $photoCache; diff --git a/apps/dav/lib/Listener/SubscriptionCreationListener.php b/apps/dav/lib/Listener/SubscriptionCreationListener.php index 7cd01827c38de..9bc8dcf31f75d 100644 --- a/apps/dav/lib/Listener/SubscriptionCreationListener.php +++ b/apps/dav/lib/Listener/SubscriptionCreationListener.php @@ -37,15 +37,9 @@ * @template-implements IEventListener<\OCA\DAV\Events\SubscriptionCreatedEvent> */ class SubscriptionCreationListener implements IEventListener { - - /** @var IJobList */ - private $jobList; - - /** @var RefreshWebcalService */ - private $refreshWebcalService; - - /** @var LoggerInterface */ - private $logger; + private IJobList $jobList; + private RefreshWebcalService $refreshWebcalService; + private LoggerInterface $logger; public function __construct(IJobList $jobList, RefreshWebcalService $refreshWebcalService, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/SubscriptionDeletionListener.php b/apps/dav/lib/Listener/SubscriptionDeletionListener.php index d59314c6f1076..8d444ba9d7700 100644 --- a/apps/dav/lib/Listener/SubscriptionDeletionListener.php +++ b/apps/dav/lib/Listener/SubscriptionDeletionListener.php @@ -37,15 +37,9 @@ * @template-implements IEventListener<\OCA\DAV\Events\SubscriptionDeletedEvent> */ class SubscriptionDeletionListener implements IEventListener { - - /** @var IJobList */ - private $jobList; - - /** @var ReminderBackend */ - private $reminderBackend; - - /** @var LoggerInterface */ - private $logger; + private IJobList $jobList; + private ReminderBackend $reminderBackend; + private LoggerInterface $logger; public function __construct(IJobList $jobList, ReminderBackend $reminderBackend, LoggerInterface $logger) { diff --git a/apps/dav/lib/Listener/UserChangeListener.php b/apps/dav/lib/Listener/UserChangeListener.php index d985a5d519163..3dce6c6ab265f 100644 --- a/apps/dav/lib/Listener/UserChangeListener.php +++ b/apps/dav/lib/Listener/UserChangeListener.php @@ -44,36 +44,16 @@ * @template-implements IEventListener */ class UserChangeListener implements IEventListener { - - /** @var IUserManager */ - private $userManager; - - /** @var CalDavBackend */ - private $calDavBackend; - - /** @var CardDavBackend */ - private $cardDavBackend; - - /** @var Defaults */ - private $defaults; - - /** @var SyncService */ - private $syncService; - - /** @var LoggerInterface */ - private $logger; - - /** @var IUser[] */ - private $usersToDelete = []; - - /** @var array */ - private $calendarsToDelete = []; - - /** @var array */ - private $subscriptionsToDelete = []; - - /** @var array */ - private $addressBooksToDelete = []; + private IUserManager $userManager; + private CalDavBackend $calDavBackend; + private CardDavBackend $cardDavBackend; + private Defaults $defaults; + private SyncService $syncService; + private LoggerInterface $logger; + private array $usersToDelete = []; + private array $calendarsToDelete = []; + private array $subscriptionsToDelete = []; + private array $addressBooksToDelete = []; private const USERS_PRINCIPAL_PREFIX = 'principals/users/'; diff --git a/apps/dav/lib/Migration/BuildCalendarSearchIndex.php b/apps/dav/lib/Migration/BuildCalendarSearchIndex.php index c8a649f3449c1..332a62b2ce278 100644 --- a/apps/dav/lib/Migration/BuildCalendarSearchIndex.php +++ b/apps/dav/lib/Migration/BuildCalendarSearchIndex.php @@ -33,15 +33,9 @@ use OCP\Migration\IRepairStep; class BuildCalendarSearchIndex implements IRepairStep { - - /** @var IDBConnection */ - private $db; - - /** @var IJobList */ - private $jobList; - - /** @var IConfig */ - private $config; + private IDBConnection $db; + private IJobList $jobList; + private IConfig $config; /** * @param IDBConnection $db diff --git a/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php b/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php index b9b973e9fb50f..c9777796c7551 100644 --- a/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/BuildCalendarSearchIndexBackgroundJob.php @@ -23,7 +23,7 @@ */ namespace OCA\DAV\Migration; -use OC\BackgroundJob\QueuedJob; +use OCP\BackgroundJob\QueuedJob; use OCA\DAV\CalDAV\CalDavBackend; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; @@ -31,21 +31,10 @@ use Psr\Log\LoggerInterface; class BuildCalendarSearchIndexBackgroundJob extends QueuedJob { - - /** @var IDBConnection */ - private $db; - - /** @var CalDavBackend */ - private $calDavBackend; - - /** @var LoggerInterface */ - private $logger; - - /** @var IJobList */ - private $jobList; - - /** @var ITimeFactory */ - private $timeFactory; + private IDBConnection $db; + private CalDavBackend $calDavBackend; + private LoggerInterface $logger; + private IJobList $jobList; /** * @param IDBConnection $db @@ -63,17 +52,17 @@ public function __construct(IDBConnection $db, $this->calDavBackend = $calDavBackend; $this->logger = $logger; $this->jobList = $jobList; - $this->timeFactory = $timeFactory; + parent::__construct($timeFactory); } - public function run($arguments) { - $offset = (int) $arguments['offset']; - $stopAt = (int) $arguments['stopAt']; + public function run($argument) { + $offset = (int) $argument['offset']; + $stopAt = (int) $argument['stopAt']; $this->logger->info('Building calendar index (' . $offset .'/' . $stopAt . ')'); - $startTime = $this->timeFactory->getTime(); - while (($this->timeFactory->getTime() - $startTime) < 15) { + $startTime = $this->time->getTime(); + while (($this->time->getTime() - $startTime) < 15) { $offset = $this->buildIndex($offset, $stopAt); if ($offset >= $stopAt) { break; @@ -91,11 +80,6 @@ public function run($arguments) { } } - /** - * @param int $offset - * @param int $stopAt - * @return int - */ private function buildIndex(int $offset, int $stopAt): int { $query = $this->db->getQueryBuilder(); $query->select(['id', 'calendarid', 'uri', 'calendardata']) diff --git a/apps/dav/lib/Migration/BuildSocialSearchIndex.php b/apps/dav/lib/Migration/BuildSocialSearchIndex.php index ae2eb084e2b8c..ecae66c9c7c3b 100644 --- a/apps/dav/lib/Migration/BuildSocialSearchIndex.php +++ b/apps/dav/lib/Migration/BuildSocialSearchIndex.php @@ -30,21 +30,10 @@ use OCP\Migration\IRepairStep; class BuildSocialSearchIndex implements IRepairStep { + private IDBConnection $db; + private IJobList $jobList; + private IConfig $config; - /** @var IDBConnection */ - private $db; - - /** @var IJobList */ - private $jobList; - - /** @var IConfig */ - private $config; - - /** - * @param IDBConnection $db - * @param IJobList $jobList - * @param IConfig $config - */ public function __construct(IDBConnection $db, IJobList $jobList, IConfig $config) { diff --git a/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php b/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php index 50666921296f6..a7dbe84df2214 100644 --- a/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/BuildSocialSearchIndexBackgroundJob.php @@ -22,7 +22,7 @@ */ namespace OCA\DAV\Migration; -use OC\BackgroundJob\QueuedJob; +use OCP\BackgroundJob\QueuedJob; use OCA\DAV\CardDAV\CardDavBackend; use OCP\AppFramework\Utility\ITimeFactory; use OCP\BackgroundJob\IJobList; @@ -30,21 +30,10 @@ use Psr\Log\LoggerInterface; class BuildSocialSearchIndexBackgroundJob extends QueuedJob { - - /** @var IDBConnection */ - private $db; - - /** @var CardDavBackend */ - private $davBackend; - - /** @var LoggerInterface */ - private $logger; - - /** @var IJobList */ - private $jobList; - - /** @var ITimeFactory */ - private $timeFactory; + private IDBConnection $db; + private CardDavBackend $davBackend; + private LoggerInterface $logger; + private IJobList $jobList; /** * @param IDBConnection $db @@ -62,12 +51,12 @@ public function __construct(IDBConnection $db, $this->davBackend = $davBackend; $this->logger = $logger; $this->jobList = $jobList; - $this->timeFactory = $timeFactory; + parent::__construct($timeFactory); } - public function run($arguments) { - $offset = $arguments['offset']; - $stopAt = $arguments['stopAt']; + public function run($argument) { + $offset = $argument['offset']; + $stopAt = $argument['stopAt']; $this->logger->info('Indexing social profile data (' . $offset .'/' . $stopAt . ')'); @@ -84,13 +73,8 @@ public function run($arguments) { } } - /** - * @param int $offset - * @param int $stopAt - * @return int - */ - private function buildIndex($offset, $stopAt) { - $startTime = $this->timeFactory->getTime(); + private function buildIndex(int $offset, int $stopAt): int { + $startTime = $this->time->getTime(); // get contacts with social profiles $query = $this->db->getQueryBuilder(); @@ -99,7 +83,7 @@ private function buildIndex($offset, $stopAt) { ->orderBy('id', 'ASC') ->where($query->expr()->like('carddata', $query->createNamedParameter('%SOCIALPROFILE%'))) ->setMaxResults(100); - $social_cards = $query->execute()->fetchAll(); + $social_cards = $query->executeQuery()->fetchAll(); if (empty($social_cards)) { return $stopAt; @@ -111,7 +95,7 @@ private function buildIndex($offset, $stopAt) { $this->davBackend->updateCard($contact['addressbookid'], $contact['uri'], $contact['carddata']); // stop after 15sec (to be continued with next chunk) - if (($this->timeFactory->getTime() - $startTime) > 15) { + if (($this->time->getTime() - $startTime) > 15) { break; } } diff --git a/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php b/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php index f22ca9ccde017..5e9883c85d0dd 100644 --- a/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php +++ b/apps/dav/lib/Migration/CalDAVRemoveEmptyValue.php @@ -34,15 +34,9 @@ use Sabre\VObject\InvalidDataException; class CalDAVRemoveEmptyValue implements IRepairStep { - - /** @var IDBConnection */ - private $db; - - /** @var CalDavBackend */ - private $calDavBackend; - - /** @var LoggerInterface */ - private $logger; + private IDBConnection $db; + private CalDavBackend $calDavBackend; + private LoggerInterface $logger; /** * @param IDBConnection $db diff --git a/apps/dav/lib/Migration/ChunkCleanup.php b/apps/dav/lib/Migration/ChunkCleanup.php index 918023552da01..51ae8e190b368 100644 --- a/apps/dav/lib/Migration/ChunkCleanup.php +++ b/apps/dav/lib/Migration/ChunkCleanup.php @@ -37,15 +37,10 @@ use OCP\Migration\IRepairStep; class ChunkCleanup implements IRepairStep { - - /** @var IConfig */ - private $config; - /** @var IUserManager */ - private $userManager; - /** @var IRootFolder */ - private $rootFolder; - /** @var IJobList */ - private $jobList; + private IConfig $config; + private IUserManager $userManager; + private IRootFolder $rootFolder; + private IJobList $jobList; public function __construct(IConfig $config, IUserManager $userManager, diff --git a/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php b/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php index 6aa499c8b1a77..92cfc08b3c636 100644 --- a/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php +++ b/apps/dav/lib/Migration/FixBirthdayCalendarComponent.php @@ -27,9 +27,7 @@ use OCP\Migration\IRepairStep; class FixBirthdayCalendarComponent implements IRepairStep { - - /** @var IDBConnection */ - private $connection; + private IDBConnection $connection; /** * FixBirthdayCalendarComponent constructor. diff --git a/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php b/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php index a1c196808386f..454d78b12cde2 100644 --- a/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php +++ b/apps/dav/lib/Migration/RefreshWebcalJobRegistrar.php @@ -33,12 +33,8 @@ use OCP\Migration\IRepairStep; class RefreshWebcalJobRegistrar implements IRepairStep { - - /** @var IDBConnection */ - private $connection; - - /** @var IJobList */ - private $jobList; + private IDBConnection $connection; + private IJobList $jobList; /** * FixBirthdayCalendarComponent constructor. diff --git a/apps/dav/lib/Migration/RegenerateBirthdayCalendars.php b/apps/dav/lib/Migration/RegenerateBirthdayCalendars.php index 29547b09ff731..7d84618884103 100644 --- a/apps/dav/lib/Migration/RegenerateBirthdayCalendars.php +++ b/apps/dav/lib/Migration/RegenerateBirthdayCalendars.php @@ -30,12 +30,8 @@ use OCP\Migration\IRepairStep; class RegenerateBirthdayCalendars implements IRepairStep { - - /** @var IJobList */ - private $jobList; - - /** @var IConfig */ - private $config; + private IJobList $jobList; + private IConfig $config; /** * @param IJobList $jobList diff --git a/apps/dav/lib/Migration/RegisterBuildReminderIndexBackgroundJob.php b/apps/dav/lib/Migration/RegisterBuildReminderIndexBackgroundJob.php index f488d85bde2d1..42e758da247cf 100644 --- a/apps/dav/lib/Migration/RegisterBuildReminderIndexBackgroundJob.php +++ b/apps/dav/lib/Migration/RegisterBuildReminderIndexBackgroundJob.php @@ -41,17 +41,9 @@ * @package OCA\DAV\Migration */ class RegisterBuildReminderIndexBackgroundJob implements IRepairStep { - - /** @var IDBConnection */ - private $db; - - /** @var IJobList */ - private $jobList; - - /** @var IConfig */ - private $config; - - /** @var string */ + private IDBConnection $db; + private IJobList $jobList; + private IConfig $config; private const CONFIG_KEY = 'buildCalendarReminderIndex'; /** diff --git a/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php b/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php index 36108ddadfaac..86cb6401facff 100644 --- a/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php +++ b/apps/dav/lib/Migration/RemoveClassifiedEventActivity.php @@ -32,9 +32,7 @@ use OCP\Migration\IRepairStep; class RemoveClassifiedEventActivity implements IRepairStep { - - /** @var IDBConnection */ - private $connection; + private IDBConnection $connection; public function __construct(IDBConnection $connection) { $this->connection = $connection; diff --git a/apps/dav/lib/Migration/RemoveDeletedUsersCalendarSubscriptions.php b/apps/dav/lib/Migration/RemoveDeletedUsersCalendarSubscriptions.php index 38d395b2c81e0..82c50307c6ba2 100644 --- a/apps/dav/lib/Migration/RemoveDeletedUsersCalendarSubscriptions.php +++ b/apps/dav/lib/Migration/RemoveDeletedUsersCalendarSubscriptions.php @@ -32,17 +32,10 @@ use OCP\Migration\IRepairStep; class RemoveDeletedUsersCalendarSubscriptions implements IRepairStep { - /** @var IDBConnection */ - private $connection; - - /** @var IUserManager */ - private $userManager; - - /** @var int */ - private $progress = 0; - - /** @var int[] */ - private $orphanSubscriptionIds = []; + private IDBConnection $connection; + private IUserManager $userManager; + private int $progress = 0; + private array $orphanSubscriptionIds = []; private const SUBSCRIPTIONS_CHUNK_SIZE = 1000; diff --git a/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php b/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php index 4789a74d98a39..20c7f847cbb6d 100644 --- a/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php +++ b/apps/dav/lib/Migration/RemoveOrphanEventsAndContacts.php @@ -34,9 +34,7 @@ use OCP\Migration\IRepairStep; class RemoveOrphanEventsAndContacts implements IRepairStep { - - /** @var IDBConnection */ - private $connection; + private IDBConnection $connection; public function __construct(IDBConnection $connection) { $this->connection = $connection; @@ -53,23 +51,23 @@ public function getName(): string { * @inheritdoc */ public function run(IOutput $output) { - $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendars', 'calendarid'); + $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendars', 'calendarid'); $output->info(sprintf('%d events without a calendar have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('calendarobjects_props', 'calendarobjects', 'objectid'); + $orphanItems = $this->removeOrphanChildren('calendarobjects_props', 'calendarobjects', 'objectid'); $output->info(sprintf('%d properties without an events have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendars', 'calendarid'); + $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendars', 'calendarid'); $output->info(sprintf('%d changes without a calendar have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendarsubscriptions', 'calendarid'); + $orphanItems = $this->removeOrphanChildren('calendarobjects', 'calendarsubscriptions', 'calendarid'); $output->info(sprintf('%d cached events without a calendar subscription have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendarsubscriptions', 'calendarid'); + $orphanItems = $this->removeOrphanChildren('calendarchanges', 'calendarsubscriptions', 'calendarid'); $output->info(sprintf('%d changes without a calendar subscription have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('cards', 'addressbooks', 'addressbookid'); + $orphanItems = $this->removeOrphanChildren('cards', 'addressbooks', 'addressbookid'); $output->info(sprintf('%d contacts without an addressbook have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('cards_properties', 'cards', 'cardid'); + $orphanItems = $this->removeOrphanChildren('cards_properties', 'cards', 'cardid'); $output->info(sprintf('%d properties without a contact have been cleaned up', $orphanItems)); - $orphanItems = $this->removeOrphanChildren('addressbookchanges', 'addressbooks', 'addressbookid'); + $orphanItems = $this->removeOrphanChildren('addressbookchanges', 'addressbooks', 'addressbookid'); $output->info(sprintf('%d changes without an addressbook have been cleaned up', $orphanItems)); } diff --git a/apps/dav/lib/Migration/Version1005Date20180413093149.php b/apps/dav/lib/Migration/Version1005Date20180413093149.php index 1ee767ce547a6..914c6b52b9589 100644 --- a/apps/dav/lib/Migration/Version1005Date20180413093149.php +++ b/apps/dav/lib/Migration/Version1005Date20180413093149.php @@ -48,7 +48,7 @@ public function changeSchema(IOutput $output, \Closure $schemaClosure, array $op if (!$schema->hasTable('directlink')) { $table = $schema->createTable('directlink'); - $table->addColumn('id',Types::BIGINT, [ + $table->addColumn('id', Types::BIGINT, [ 'autoincrement' => true, 'notnull' => true, 'length' => 11, diff --git a/apps/dav/lib/Migration/Version1008Date20181105104826.php b/apps/dav/lib/Migration/Version1008Date20181105104826.php index 86ce4c33ce548..4d48606be5ba9 100644 --- a/apps/dav/lib/Migration/Version1008Date20181105104826.php +++ b/apps/dav/lib/Migration/Version1008Date20181105104826.php @@ -36,15 +36,8 @@ use OCP\Migration\SimpleMigrationStep; class Version1008Date20181105104826 extends SimpleMigrationStep { + private IDBConnection $connection; - /** @var IDBConnection */ - private $connection; - - /** - * Version1008Date20181105104826 constructor. - * - * @param IDBConnection $connection - */ public function __construct(IDBConnection $connection) { $this->connection = $connection; } diff --git a/apps/dav/lib/Migration/Version1008Date20181105110300.php b/apps/dav/lib/Migration/Version1008Date20181105110300.php index e275b2a8e1e04..7e67aa40c797d 100644 --- a/apps/dav/lib/Migration/Version1008Date20181105110300.php +++ b/apps/dav/lib/Migration/Version1008Date20181105110300.php @@ -36,15 +36,8 @@ use OCP\Migration\SimpleMigrationStep; class Version1008Date20181105110300 extends SimpleMigrationStep { + private IDBConnection $connection; - /** @var IDBConnection */ - private $connection; - - /** - * Version1008Date20181105110300 constructor. - * - * @param IDBConnection $connection - */ public function __construct(IDBConnection $connection) { $this->connection = $connection; } diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php index 614ddabb7efbf..aca3310cb23d0 100644 --- a/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningNode.php @@ -32,7 +32,7 @@ class AppleProvisioningNode implements INode, IProperties { public const FILENAME = 'apple-provisioning.mobileconfig'; - protected $timeFactory; + protected ITimeFactory $timeFactory; /** * @param ITimeFactory $timeFactory diff --git a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php index f92bc4f3a0d4c..c68eec537b875 100644 --- a/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php +++ b/apps/dav/lib/Provisioning/Apple/AppleProvisioningPlugin.php @@ -36,52 +36,14 @@ use Sabre\HTTP\ResponseInterface; class AppleProvisioningPlugin extends ServerPlugin { + protected Server $server; + protected IURLGenerator $urlGenerator; + protected IUserSession $userSession; + protected \OC_Defaults $themingDefaults; + protected IRequest $request; + protected IL10N $l10n; + protected \closure $uuidClosure; - /** - * @var Server - */ - protected $server; - - /** - * @var IURLGenerator - */ - protected $urlGenerator; - - /** - * @var IUserSession - */ - protected $userSession; - - /** - * @var \OC_Defaults - */ - protected $themingDefaults; - - /** - * @var IRequest - */ - protected $request; - - /** - * @var IL10N - */ - protected $l10n; - - /** - * @var \closure - */ - protected $uuidClosure; - - /** - * AppleProvisioningPlugin constructor. - * - * @param IUserSession $userSession - * @param IURLGenerator $urlGenerator - * @param \OC_Defaults $themingDefaults - * @param IRequest $request - * @param IL10N $l10n - * @param \closure $uuidClosure - */ public function __construct(IUserSession $userSession, IURLGenerator $urlGenerator, \OC_Defaults $themingDefaults, IRequest $request, IL10N $l10n, \closure $uuidClosure) { @@ -129,11 +91,7 @@ public function httpGet(RequestInterface $request, ResponseInterface $response): $absoluteURL = $this->urlGenerator->getBaseUrl(); $parsedUrl = parse_url($absoluteURL); - if (isset($parsedUrl['port'])) { - $serverPort = $parsedUrl['port']; - } else { - $serverPort = 443; - } + $serverPort = $parsedUrl['port'] ?? 443; $server_url = $parsedUrl['host']; $description = $this->themingDefaults->getName(); diff --git a/apps/dav/lib/RootCollection.php b/apps/dav/lib/RootCollection.php index 1721431da9e22..10d416a9f1de9 100644 --- a/apps/dav/lib/RootCollection.php +++ b/apps/dav/lib/RootCollection.php @@ -124,12 +124,12 @@ public function __construct() { $dispatcher, $config ); - $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, 'principals/users', $logger); + $userCalendarRoot = new CalendarRoot($userPrincipalBackend, $caldavBackend, $logger, 'principals/users'); $userCalendarRoot->disableListing = $disableListing; - $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, 'principals/calendar-resources', $logger); + $resourceCalendarRoot = new CalendarRoot($calendarResourcePrincipalBackend, $caldavBackend, $logger, 'principals/calendar-resources'); $resourceCalendarRoot->disableListing = $disableListing; - $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $caldavBackend, 'principals/calendar-rooms', $logger); + $roomCalendarRoot = new CalendarRoot($calendarRoomPrincipalBackend, $caldavBackend, $logger, 'principals/calendar-rooms'); $roomCalendarRoot->disableListing = $disableListing; $publicCalendarRoot = new PublicCalendarRoot($caldavBackend, $l10n, $config, $logger); diff --git a/apps/dav/lib/Search/ACalendarSearchProvider.php b/apps/dav/lib/Search/ACalendarSearchProvider.php index 91904d5e8d6ae..565cb149a6e77 100644 --- a/apps/dav/lib/Search/ACalendarSearchProvider.php +++ b/apps/dav/lib/Search/ACalendarSearchProvider.php @@ -39,18 +39,10 @@ * @package OCA\DAV\Search */ abstract class ACalendarSearchProvider implements IProvider { - - /** @var IAppManager */ - protected $appManager; - - /** @var IL10N */ - protected $l10n; - - /** @var IURLGenerator */ - protected $urlGenerator; - - /** @var CalDavBackend */ - protected $backend; + protected IAppManager $appManager; + protected IL10N $l10n; + protected IURLGenerator $urlGenerator; + protected CalDavBackend $backend; /** * ACalendarSearchProvider constructor. diff --git a/apps/dav/lib/Search/ContactsSearchProvider.php b/apps/dav/lib/Search/ContactsSearchProvider.php index a7c2969016b47..bb57f0279bada 100644 --- a/apps/dav/lib/Search/ContactsSearchProvider.php +++ b/apps/dav/lib/Search/ContactsSearchProvider.php @@ -40,23 +40,15 @@ use Sabre\VObject\Reader; class ContactsSearchProvider implements IProvider { - - /** @var IAppManager */ - private $appManager; - - /** @var IL10N */ - private $l10n; - - /** @var IURLGenerator */ - private $urlGenerator; - - /** @var CardDavBackend */ - private $backend; + private IAppManager $appManager; + private IL10N $l10n; + private IURLGenerator $urlGenerator; + private CardDavBackend $backend; /** * @var string[] */ - private static $searchProperties = [ + private static array $searchProperties = [ 'N', 'FN', 'NICKNAME', diff --git a/apps/dav/lib/Search/EventsSearchProvider.php b/apps/dav/lib/Search/EventsSearchProvider.php index 07fc90397ed2d..0602177d22fd0 100644 --- a/apps/dav/lib/Search/EventsSearchProvider.php +++ b/apps/dav/lib/Search/EventsSearchProvider.php @@ -46,7 +46,7 @@ class EventsSearchProvider extends ACalendarSearchProvider { /** * @var string[] */ - private static $searchProperties = [ + private static array $searchProperties = [ 'SUMMARY', 'LOCATION', 'DESCRIPTION', @@ -58,7 +58,7 @@ class EventsSearchProvider extends ACalendarSearchProvider { /** * @var string[] */ - private static $searchParameters = [ + private static array $searchParameters = [ 'ATTENDEE' => ['CN'], 'ORGANIZER' => ['CN'], ]; @@ -66,7 +66,7 @@ class EventsSearchProvider extends ACalendarSearchProvider { /** * @var string */ - private static $componentType = 'VEVENT'; + private static string $componentType = 'VEVENT'; /** * @inheritDoc diff --git a/apps/dav/lib/Search/TasksSearchProvider.php b/apps/dav/lib/Search/TasksSearchProvider.php index 763720ee4ae0a..4b346ab4e6b37 100644 --- a/apps/dav/lib/Search/TasksSearchProvider.php +++ b/apps/dav/lib/Search/TasksSearchProvider.php @@ -45,7 +45,7 @@ class TasksSearchProvider extends ACalendarSearchProvider { /** * @var string[] */ - private static $searchProperties = [ + private static array $searchProperties = [ 'SUMMARY', 'DESCRIPTION', 'CATEGORIES', @@ -54,12 +54,8 @@ class TasksSearchProvider extends ACalendarSearchProvider { /** * @var string[] */ - private static $searchParameters = []; - - /** - * @var string - */ - private static $componentType = 'VTODO'; + private static array $searchParameters = []; + private static string $componentType = 'VTODO'; /** * @inheritDoc diff --git a/apps/dav/lib/Server.php b/apps/dav/lib/Server.php index 994f9727dcac9..a6a0307398b04 100644 --- a/apps/dav/lib/Server.php +++ b/apps/dav/lib/Server.php @@ -111,13 +111,13 @@ class Server { /** @var IRequest */ - private $request; + private IRequest $request; /** @var string */ - private $baseUri; + private string $baseUri; /** @var Connector\Sabre\Server */ - public $server; + public Connector\Sabre\Server $server; /** * @throws ContainerExceptionInterface diff --git a/apps/dav/lib/Settings/CalDAVSettings.php b/apps/dav/lib/Settings/CalDAVSettings.php index 6d60b2611e03f..312326d1ef5d3 100644 --- a/apps/dav/lib/Settings/CalDAVSettings.php +++ b/apps/dav/lib/Settings/CalDAVSettings.php @@ -33,13 +33,8 @@ use OCP\Settings\IDelegatedSettings; class CalDAVSettings implements IDelegatedSettings { - - /** @var IConfig */ - private $config; - - /** @var IInitialState */ - private $initialState; - + private IConfig $config; + private IInitialState $initialState; private IURLGenerator $urlGenerator; private const defaults = [ @@ -50,12 +45,6 @@ class CalDAVSettings implements IDelegatedSettings { 'sendEventRemindersPush' => 'no', ]; - /** - * CalDAVSettings constructor. - * - * @param IConfig $config - * @param IInitialState $initialState - */ public function __construct(IConfig $config, IInitialState $initialState, IURLGenerator $urlGenerator) { $this->config = $config; $this->initialState = $initialState; diff --git a/apps/dav/lib/Storage/PublicOwnerWrapper.php b/apps/dav/lib/Storage/PublicOwnerWrapper.php index 10bcd20de055f..c70cd2690ad73 100644 --- a/apps/dav/lib/Storage/PublicOwnerWrapper.php +++ b/apps/dav/lib/Storage/PublicOwnerWrapper.php @@ -28,9 +28,7 @@ use OC\Files\Storage\Wrapper\Wrapper; class PublicOwnerWrapper extends Wrapper { - - /** @var string */ - private $owner; + private string $owner; /** * @param array $arguments ['storage' => $storage, 'owner' => $owner] diff --git a/apps/dav/lib/SystemTag/SystemTagMappingNode.php b/apps/dav/lib/SystemTag/SystemTagMappingNode.php index 344ff1dbc70a9..0aaf19fcb1847 100644 --- a/apps/dav/lib/SystemTag/SystemTagMappingNode.php +++ b/apps/dav/lib/SystemTag/SystemTagMappingNode.php @@ -32,57 +32,26 @@ use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\INode; /** * Mapping node for system tag to object id */ -class SystemTagMappingNode implements \Sabre\DAV\INode { - /** - * @var ISystemTag - */ - protected $tag; - - /** - * @var string - */ - private $objectId; - - /** - * @var string - */ - private $objectType; - - /** - * User - * - * @var IUser - */ - protected $user; - - /** - * @var ISystemTagManager - */ - protected $tagManager; - - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; +class SystemTagMappingNode implements INode { + protected ISystemTag $tag; + private string $objectId; + private string $objectType; + protected IUser $user; + protected ISystemTagManager $tagManager; + private ISystemTagObjectMapper $tagMapper; /** * Sets up the node, expects a full path name - * - * @param ISystemTag $tag system tag - * @param string $objectId - * @param string $objectType - * @param IUser $user user - * @param ISystemTagManager $tagManager - * @param ISystemTagObjectMapper $tagMapper */ public function __construct( ISystemTag $tag, - $objectId, - $objectType, + string $objectId, + string $objectType, IUser $user, ISystemTagManager $tagManager, ISystemTagObjectMapper $tagMapper @@ -97,37 +66,29 @@ public function __construct( /** * Returns the object id of the relationship - * - * @return string object id */ - public function getObjectId() { + public function getObjectId(): string { return $this->objectId; } /** * Returns the object type of the relationship - * - * @return string object type */ - public function getObjectType() { + public function getObjectType(): string { return $this->objectType; } /** * Returns the system tag represented by this node - * - * @return ISystemTag system tag */ - public function getSystemTag() { + public function getSystemTag(): ISystemTag { return $this->tag; } /** * Returns the id of the tag - * - * @return string */ - public function getName() { + public function getName(): string { return $this->tag->getId(); } diff --git a/apps/dav/lib/SystemTag/SystemTagNode.php b/apps/dav/lib/SystemTag/SystemTagNode.php index a31deb59a93a8..147e49dbb817c 100644 --- a/apps/dav/lib/SystemTag/SystemTagNode.php +++ b/apps/dav/lib/SystemTag/SystemTagNode.php @@ -34,35 +34,20 @@ use Sabre\DAV\Exception\Forbidden; use Sabre\DAV\Exception\MethodNotAllowed; use Sabre\DAV\Exception\NotFound; +use Sabre\DAV\INode; /** * DAV node representing a system tag, with the name being the tag id. */ -class SystemTagNode implements \Sabre\DAV\INode { - - /** - * @var ISystemTag - */ - protected $tag; - - /** - * @var ISystemTagManager - */ - protected $tagManager; - - /** - * User - * - * @var IUser - */ - protected $user; +class SystemTagNode implements INode { + protected ISystemTag $tag; + protected ISystemTagManager $tagManager; + protected IUser $user; /** * Whether to allow permissions for admins - * - * @var bool */ - protected $isAdmin; + protected bool $isAdmin; /** * Sets up the node, expects a full path name @@ -72,7 +57,7 @@ class SystemTagNode implements \Sabre\DAV\INode { * @param bool $isAdmin whether to allow operations for admins * @param ISystemTagManager $tagManager tag manager */ - public function __construct(ISystemTag $tag, IUser $user, $isAdmin, ISystemTagManager $tagManager) { + public function __construct(ISystemTag $tag, IUser $user, bool $isAdmin, ISystemTagManager $tagManager) { $this->tag = $tag; $this->user = $user; $this->isAdmin = $isAdmin; diff --git a/apps/dav/lib/SystemTag/SystemTagPlugin.php b/apps/dav/lib/SystemTag/SystemTagPlugin.php index b6bd7d3b7cdb9..6e9296ad92094 100644 --- a/apps/dav/lib/SystemTag/SystemTagPlugin.php +++ b/apps/dav/lib/SystemTag/SystemTagPlugin.php @@ -36,6 +36,7 @@ use Sabre\DAV\Exception\UnsupportedMediaType; use Sabre\DAV\PropFind; use Sabre\DAV\PropPatch; +use Sabre\DAV\Server; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\ResponseInterface; @@ -57,31 +58,11 @@ class SystemTagPlugin extends \Sabre\DAV\ServerPlugin { public const GROUPS_PROPERTYNAME = '{http://owncloud.org/ns}groups'; public const CANASSIGN_PROPERTYNAME = '{http://owncloud.org/ns}can-assign'; - /** - * @var \Sabre\DAV\Server $server - */ - private $server; + private Server $server; + protected ISystemTagManager $tagManager; + protected IUserSession $userSession; + protected IGroupManager $groupManager; - /** - * @var ISystemTagManager - */ - protected $tagManager; - - /** - * @var IUserSession - */ - protected $userSession; - - /** - * @var IGroupManager - */ - protected $groupManager; - - /** - * @param ISystemTagManager $tagManager tag manager - * @param IGroupManager $groupManager - * @param IUserSession $userSession - */ public function __construct(ISystemTagManager $tagManager, IGroupManager $groupManager, IUserSession $userSession) { @@ -98,10 +79,10 @@ public function __construct(ISystemTagManager $tagManager, * * This method should set up the required event subscriptions. * - * @param \Sabre\DAV\Server $server + * @param Server $server * @return void */ - public function initialize(\Sabre\DAV\Server $server) { + public function initialize(Server $server) { $server->xml->namespaceMap[self::NS_OWNCLOUD] = 'oc'; $server->protectedProperties[] = self::ID_PROPERTYNAME; diff --git a/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php b/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php index 1256c58921e8f..743bcd5821a85 100644 --- a/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsByIdCollection.php @@ -35,21 +35,9 @@ use Sabre\DAV\ICollection; class SystemTagsByIdCollection implements ICollection { - - /** - * @var ISystemTagManager - */ - private $tagManager; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var IUserSession - */ - private $userSession; + private ISystemTagManager $tagManager; + private IGroupManager $groupManager; + private IUserSession $userSession; /** * SystemTagsByIdCollection constructor. @@ -73,7 +61,7 @@ public function __construct( * * @return bool true if the user is an admin */ - private function isAdmin() { + private function isAdmin(): bool { $user = $this->userSession->getUser(); if ($user !== null) { return $this->groupManager->isAdmin($user->getUID()); diff --git a/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php b/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php index 8bb34182b0c2b..a104510a66491 100644 --- a/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsObjectMappingCollection.php @@ -40,33 +40,11 @@ * Collection containing tags by object id */ class SystemTagsObjectMappingCollection implements ICollection { - - /** - * @var string - */ - private $objectId; - - /** - * @var string - */ - private $objectType; - - /** - * @var ISystemTagManager - */ - private $tagManager; - - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; - - /** - * User - * - * @var IUser - */ - private $user; + private string $objectId; + private string $objectType; + private ISystemTagManager $tagManager; + private ISystemTagObjectMapper $tagMapper; + private IUser $user; /** @@ -79,8 +57,8 @@ class SystemTagsObjectMappingCollection implements ICollection { * @param ISystemTagObjectMapper $tagMapper tag mapper */ public function __construct( - $objectId, - $objectType, + string $objectId, + string $objectType, IUser $user, ISystemTagManager $tagManager, ISystemTagObjectMapper $tagMapper @@ -185,7 +163,7 @@ public function setName($name) { * * @return int */ - public function getLastModified() { + public function getLastModified(): ?int { return null; } @@ -197,7 +175,7 @@ public function getLastModified() { * * @return SystemTagMappingNode */ - private function makeNode(ISystemTag $tag) { + private function makeNode(ISystemTag $tag): SystemTagMappingNode { return new SystemTagMappingNode( $tag, $this->objectId, diff --git a/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php b/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php index 1ca45c32ce46b..54f7e513de437 100644 --- a/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsObjectTypeCollection.php @@ -38,49 +38,15 @@ * Collection containing object ids by object type */ class SystemTagsObjectTypeCollection implements ICollection { + private string $objectType; + private ISystemTagManager $tagManager; + private ISystemTagObjectMapper $tagMapper; + private IGroupManager $groupManager; + private IUserSession $userSession; + protected \Closure $childExistsFunction; - /** - * @var string - */ - private $objectType; - - /** - * @var ISystemTagManager - */ - private $tagManager; - - /** - * @var ISystemTagObjectMapper - */ - private $tagMapper; - - /** - * @var IGroupManager - */ - private $groupManager; - - /** - * @var IUserSession - */ - private $userSession; - - /** - * @var \Closure - **/ - protected $childExistsFunction; - - /** - * Constructor - * - * @param string $objectType object type - * @param ISystemTagManager $tagManager - * @param ISystemTagObjectMapper $tagMapper - * @param IUserSession $userSession - * @param IGroupManager $groupManager - * @param \Closure $childExistsFunction - */ public function __construct( - $objectType, + string $objectType, ISystemTagManager $tagManager, ISystemTagObjectMapper $tagMapper, IUserSession $userSession, diff --git a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php index 74dfe4a2cddde..43f3017491472 100644 --- a/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php +++ b/apps/dav/lib/SystemTag/SystemTagsRelationsCollection.php @@ -36,16 +36,6 @@ use Sabre\DAV\SimpleCollection; class SystemTagsRelationsCollection extends SimpleCollection { - - /** - * SystemTagsRelationsCollection constructor. - * - * @param ISystemTagManager $tagManager - * @param ISystemTagObjectMapper $tagMapper - * @param IUserSession $userSession - * @param IGroupManager $groupManager - * @param IEventDispatcher $dispatcher - */ public function __construct( ISystemTagManager $tagManager, ISystemTagObjectMapper $tagMapper, diff --git a/apps/dav/lib/Traits/PrincipalProxyTrait.php b/apps/dav/lib/Traits/PrincipalProxyTrait.php index f2bd02bf1604d..96acb1e2e1587 100644 --- a/apps/dav/lib/Traits/PrincipalProxyTrait.php +++ b/apps/dav/lib/Traits/PrincipalProxyTrait.php @@ -42,7 +42,7 @@ trait PrincipalProxyTrait { * @return string[] * @throws Exception */ - public function getGroupMemberSet($principal) { + public function getGroupMemberSet($principal): array { $members = []; if ($this->isProxyPrincipal($principal)) { @@ -69,13 +69,9 @@ public function getGroupMemberSet($principal) { /** * Returns the list of groups a principal is a member of - * - * @param string $principal - * @param bool $needGroups - * @return array * @throws Exception */ - public function getGroupMembership($principal, $needGroups = false) { + public function getGroupMembership(string $principal, bool $needGroups = false): array { [$prefix, $name] = split($principal); if ($prefix !== $this->principalPrefix) { @@ -111,7 +107,7 @@ public function getGroupMembership($principal, $needGroups = false) { * @param string[] $members * @throws Exception|\OCP\DB\Exception */ - public function setGroupMemberSet($principal, array $members) { + public function setGroupMemberSet(string $principal, array $members) { [$principalUri, $target] = split($principal); if ($target !== 'calendar-proxy-write' && $target !== 'calendar-proxy-read') { diff --git a/apps/dav/lib/Upload/AssemblyStream.php b/apps/dav/lib/Upload/AssemblyStream.php index ef6d39974c0ad..1e8ed3e6d1cb2 100644 --- a/apps/dav/lib/Upload/AssemblyStream.php +++ b/apps/dav/lib/Upload/AssemblyStream.php @@ -28,6 +28,7 @@ */ namespace OCA\DAV\Upload; +use Icewind\Streams\File; use Sabre\DAV\IFile; /** @@ -39,28 +40,21 @@ * * @package OCA\DAV\Upload */ -class AssemblyStream implements \Icewind\Streams\File { +class AssemblyStream implements File { /** @var resource */ private $context; /** @var IFile[] */ - private $nodes; + private array $nodes; - /** @var int */ - private $pos = 0; - - /** @var int */ - private $size = 0; + private int $pos = 0; + private int $size = 0; /** @var resource */ private $currentStream = null; - - /** @var int */ - private $currentNode = 0; - - /** @var int */ - private $currentNodeRead = 0; + private int $currentNode = 0; + private int $currentNodeRead = 0; /** * @param string $path @@ -69,7 +63,7 @@ class AssemblyStream implements \Icewind\Streams\File { * @param string &$opened_path * @return bool */ - public function stream_open($path, $mode, $options, &$opened_path) { + public function stream_open($path, $mode, $options, &$opened_path): bool { $this->loadContext('assembly'); $nodes = $this->nodes; diff --git a/apps/dav/lib/Upload/ChunkingPlugin.php b/apps/dav/lib/Upload/ChunkingPlugin.php index a0ed998bf17ae..fd3b5b9dee8b7 100644 --- a/apps/dav/lib/Upload/ChunkingPlugin.php +++ b/apps/dav/lib/Upload/ChunkingPlugin.php @@ -34,11 +34,8 @@ use Sabre\DAV\ServerPlugin; class ChunkingPlugin extends ServerPlugin { - - /** @var Server */ - private $server; - /** @var FutureFile */ - private $sourceNode; + private Server $server; + private FutureFile $sourceNode; /** * @inheritdoc diff --git a/apps/dav/lib/Upload/CleanupService.php b/apps/dav/lib/Upload/CleanupService.php index 2b6fc965c01b8..8e506191343c5 100644 --- a/apps/dav/lib/Upload/CleanupService.php +++ b/apps/dav/lib/Upload/CleanupService.php @@ -30,10 +30,8 @@ use OCP\IUserSession; class CleanupService { - /** @var IUserSession */ - private $userSession; - /** @var IJobList */ - private $jobList; + private IUserSession $userSession; + private IJobList $jobList; public function __construct(IUserSession $userSession, IJobList $jobList) { $this->userSession = $userSession; diff --git a/apps/dav/lib/Upload/FutureFile.php b/apps/dav/lib/Upload/FutureFile.php index eba550a62daca..c0e4cbfd571ef 100644 --- a/apps/dav/lib/Upload/FutureFile.php +++ b/apps/dav/lib/Upload/FutureFile.php @@ -35,18 +35,11 @@ * * @package OCA\DAV\Upload */ -class FutureFile implements \Sabre\DAV\IFile { +class FutureFile implements IFile { + private Directory $root; + private string $name; - /** @var Directory */ - private $root; - /** @var string */ - private $name; - - /** - * @param Directory $root - * @param string $name - */ - public function __construct(Directory $root, $name) { + public function __construct(Directory $root, string $name) { $this->root = $root; $this->name = $name; } diff --git a/apps/dav/lib/Upload/RootCollection.php b/apps/dav/lib/Upload/RootCollection.php index e3ae22af5e990..0483fee9843e9 100644 --- a/apps/dav/lib/Upload/RootCollection.php +++ b/apps/dav/lib/Upload/RootCollection.php @@ -30,9 +30,7 @@ use Sabre\DAVACL\PrincipalBackend; class RootCollection extends AbstractPrincipalCollection { - - /** @var CleanupService */ - private $cleanupService; + private CleanupService $cleanupService; public function __construct(PrincipalBackend\BackendInterface $principalBackend, string $principalPrefix, diff --git a/apps/dav/lib/Upload/UploadFile.php b/apps/dav/lib/Upload/UploadFile.php index 49a2fadecf6c8..eca00bf3e47a2 100644 --- a/apps/dav/lib/Upload/UploadFile.php +++ b/apps/dav/lib/Upload/UploadFile.php @@ -29,9 +29,7 @@ use Sabre\DAV\IFile; class UploadFile implements IFile { - - /** @var File */ - private $file; + private File $file; public function __construct(File $file) { $this->file = $file; diff --git a/apps/dav/lib/Upload/UploadFolder.php b/apps/dav/lib/Upload/UploadFolder.php index bb7c494cee356..2b6cc13b4c516 100644 --- a/apps/dav/lib/Upload/UploadFolder.php +++ b/apps/dav/lib/Upload/UploadFolder.php @@ -29,11 +29,8 @@ use Sabre\DAV\ICollection; class UploadFolder implements ICollection { - - /** @var Directory */ - private $node; - /** @var CleanupService */ - private $cleanupService; + private Directory $node; + private CleanupService $cleanupService; public function __construct(Directory $node, CleanupService $cleanupService) { $this->node = $node; diff --git a/apps/dav/lib/Upload/UploadHome.php b/apps/dav/lib/Upload/UploadHome.php index ef52c0c15519c..253038786a75a 100644 --- a/apps/dav/lib/Upload/UploadHome.php +++ b/apps/dav/lib/Upload/UploadHome.php @@ -33,11 +33,8 @@ use Sabre\DAV\ICollection; class UploadHome implements ICollection { - - /** @var array */ - private $principalInfo; - /** @var CleanupService */ - private $cleanupService; + private array $principalInfo; + private CleanupService $cleanupService; public function __construct(array $principalInfo, CleanupService $cleanupService) { $this->principalInfo = $principalInfo; diff --git a/apps/dav/lib/UserMigration/CalendarMigrator.php b/apps/dav/lib/UserMigration/CalendarMigrator.php index 16b213146106f..8477660fdab7a 100644 --- a/apps/dav/lib/UserMigration/CalendarMigrator.php +++ b/apps/dav/lib/UserMigration/CalendarMigrator.php @@ -54,7 +54,6 @@ use Throwable; class CalendarMigrator implements IMigrator { - use TMigratorBasicVersionHandling; private CalDavBackend $calDavBackend; diff --git a/apps/dav/tests/integration/UserMigration/CalendarMigratorTest.php b/apps/dav/tests/integration/UserMigration/CalendarMigratorTest.php index f1ad6dda22e28..daf3bfaccacce 100644 --- a/apps/dav/tests/integration/UserMigration/CalendarMigratorTest.php +++ b/apps/dav/tests/integration/UserMigration/CalendarMigratorTest.php @@ -43,7 +43,6 @@ * @group DB */ class CalendarMigratorTest extends TestCase { - private IUserManager $userManager; private CalendarMigrator $migrator; diff --git a/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php b/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php index dbb5a33c834d3..e0d41c75e23f8 100644 --- a/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php +++ b/apps/dav/tests/unit/CalDAV/PublicCalendarTest.php @@ -66,7 +66,7 @@ public function testPrivateClassification(int $expectedChildren, bool $isShared) $config = $this->createMock(IConfig::class); /** @var MockObject | LoggerInterface $logger */ $logger = $this->createMock(LoggerInterface::class); - $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config,$logger); + $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger); $children = $c->getChildren(); $this->assertEquals(2, count($children)); $children = $c->getMultipleChildren(['event-0', 'event-1', 'event-2']); @@ -152,7 +152,7 @@ public function testConfidentialClassification(int $expectedChildren, bool $isSh $config = $this->createMock(IConfig::class); /** @var MockObject | LoggerInterface $logger */ $logger = $this->createMock(LoggerInterface::class); - $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config,$logger); + $c = new PublicCalendar($backend, $calendarInfo, $this->l10n, $config, $logger); $this->assertEquals(count($c->getChildren()), 2); diff --git a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php index bb311fb3b042c..8fef9f6cab5eb 100644 --- a/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php +++ b/apps/dav/tests/unit/CalDAV/ResourceBooking/AbstractPrincipalBackendTest.php @@ -259,14 +259,18 @@ public function testSetGroupMemberSet() { $this->proxyMapper->expects($this->exactly(2)) ->method('insert') ->withConsecutive( - [$this->callback(function ($proxy) { return $this->callbackForTestSetGroupMemberSet($proxy, '/backend1-res2'); })], - [$this->callback(function ($proxy) { return $this->callbackForTestSetGroupMemberSet($proxy, '/backend2-res3'); })] + [$this->callback(function ($proxy) { + return $this->callbackForTestSetGroupMemberSet($proxy, '/backend1-res2'); + })], + [$this->callback(function ($proxy) { + return $this->callbackForTestSetGroupMemberSet($proxy, '/backend2-res3'); + })] ); $this->principalBackend->setGroupMemberSet($this->principalPrefix . '/backend1-res1/calendar-proxy-write', [$this->principalPrefix . '/backend1-res2', $this->principalPrefix . '/backend2-res3']); } - private function callbackForTestSetGroupMemberSet (Proxy $proxy, string $proxyId): bool { + private function callbackForTestSetGroupMemberSet(Proxy $proxy, string $proxyId): bool { if ($proxy->getOwnerId() !== $this->principalPrefix . '/backend1-res1') { return false; } diff --git a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php index d5730d05c2c36..71d2604608693 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/IMipPluginTest.php @@ -251,7 +251,7 @@ public function dataNoMessageSendForPastEvents(): array { * @dataProvider dataIncludeResponseButtons */ public function testIncludeResponseButtons(string $config_setting, string $recipient, bool $has_buttons) { - $message = $this->_testMessage([],$recipient); + $message = $this->_testMessage([], $recipient); $this->mailer->method('validateMailAddress')->willReturn(true); $this->_expectSend($recipient, true, $has_buttons); @@ -288,7 +288,7 @@ public function testMessageSendWhenEventWithoutName() { $this->mailer->method('validateMailAddress')->willReturn(true); $message = $this->_testMessage(['SUMMARY' => '']); - $this->_expectSend('frodo@hobb.it', true, true,'Invitation: Untitled event'); + $this->_expectSend('frodo@hobb.it', true, true, 'Invitation: Untitled event'); $this->emailTemplate->expects($this->once()) ->method('addHeading') ->with('Invitation'); diff --git a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php index d9822263005cb..0987e7e7b519d 100644 --- a/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php +++ b/apps/dav/tests/unit/CalDAV/Schedule/PluginTest.php @@ -346,7 +346,7 @@ public function testPropFindDefaultCalendarUrl(string $principalUri, ?string $ca // https://stackoverflow.com/a/56763373/10204399 protected function generate(array $yield_values): ReturnCallback { - return $this->returnCallback(function() use ($yield_values) { + return $this->returnCallback(function () use ($yield_values) { foreach ($yield_values as $value) { yield $value; } diff --git a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php index a649d7ab9446e..715923cd14fe4 100644 --- a/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php +++ b/apps/dav/tests/unit/CardDAV/AddressBookImplTest.php @@ -228,7 +228,7 @@ public function testUpdateWithTypes(): void { $uri = 'bla.vcf'; $properties = ['URI' => $uri, 'UID' => $uid, 'FN' => 'John Doe', 'ADR' => [['type' => 'HOME', 'value' => ';;street;city;;;country']]]; $vCard = new vCard; - $textProperty = $vCard->createProperty('KEY','value'); + $textProperty = $vCard->createProperty('KEY', 'value'); /** @var MockObject | AddressBookImpl $addressBookImpl */ $addressBookImpl = $this->getMockBuilder(AddressBookImpl::class) diff --git a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php index 7a34ef60dd574..bc8ff02f0a023 100644 --- a/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php +++ b/apps/dav/tests/unit/CardDAV/CardDavBackendTest.php @@ -617,8 +617,8 @@ public function testPurgeProperties(): void { $qResult->closeCursor(); $this->assertCount(1, $result); - $this->assertSame(1 ,(int)$result[0]['addressbookid']); - $this->assertSame(2 ,(int)$result[0]['cardid']); + $this->assertSame(1, (int)$result[0]['addressbookid']); + $this->assertSame(2, (int)$result[0]['cardid']); } /** diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php index 8e50c2e1cd51c..6272354a6fe2d 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/ForbiddenTest.php @@ -35,9 +35,9 @@ class ForbiddenTest extends TestCase { public function testSerialization() { // create xml doc - $DOM = new DOMDocument('1.0','utf-8'); + $DOM = new DOMDocument('1.0', 'utf-8'); $DOM->formatOutput = true; - $error = $DOM->createElementNS('DAV:','d:error'); + $error = $DOM->createElementNS('DAV:', 'd:error'); $error->setAttribute('xmlns:s', Server::NS_SABREDAV); $DOM->appendChild($error); diff --git a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php index 1bf3526ef619d..bec3957761958 100644 --- a/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/Exception/InvalidPathTest.php @@ -36,9 +36,9 @@ class InvalidPathTest extends TestCase { public function testSerialization() { // create xml doc - $DOM = new DOMDocument('1.0','utf-8'); + $DOM = new DOMDocument('1.0', 'utf-8'); $DOM->formatOutput = true; - $error = $DOM->createElementNS('DAV:','d:error'); + $error = $DOM->createElementNS('DAV:', 'd:error'); $error->setAttribute('xmlns:s', Server::NS_SABREDAV); $DOM->appendChild($error); diff --git a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php index 8a69317fb97ee..8cbe0a4e5d57b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FakeLockerPluginTest.php @@ -32,7 +32,6 @@ use Sabre\DAV\INode; use Sabre\DAV\PropFind; use Sabre\DAV\Server; -use Sabre\DAV\Xml\Service; use Sabre\HTTP\RequestInterface; use Sabre\HTTP\Response; use Sabre\HTTP\ResponseInterface; diff --git a/apps/dav/tests/unit/Connector/Sabre/FileTest.php b/apps/dav/tests/unit/Connector/Sabre/FileTest.php index 15bf74e639aa2..e136f194ddd0a 100644 --- a/apps/dav/tests/unit/Connector/Sabre/FileTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/FileTest.php @@ -134,11 +134,11 @@ protected function tearDown(): void { } /** -<<<<<<< HEAD + * <<<<<<< HEAD * @return MockObject|IStorage -======= + * ======= * @return Storage|IStorage|MockObject ->>>>>>> 23922574b5 (Improve tests) + * >>>>>>> 23922574b5 (Improve tests) */ private function getMockStorage() { $storage = $this->createMock(IStorage::class); diff --git a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php index 1e21f3a2d3f72..754eb3919d85c 100644 --- a/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/RequestTest/DeleteTest.php @@ -22,7 +22,6 @@ */ namespace OCA\DAV\Tests\unit\Connector\Sabre\RequestTest; -use Exception; use OCP\AppFramework\Http; use OCP\Files\FileInfo; use OCP\Lock\LockedException; diff --git a/apps/dav/tests/unit/Files/MultipartRequestParserTest.php b/apps/dav/tests/unit/Files/MultipartRequestParserTest.php index 9050633ff3e32..e84265e1c930a 100644 --- a/apps/dav/tests/unit/Files/MultipartRequestParserTest.php +++ b/apps/dav/tests/unit/Files/MultipartRequestParserTest.php @@ -67,7 +67,7 @@ private function getMultipartParser(array $parts, array $headers = [], string $b $body .= '--'.$boundary."--"; - $stream = fopen('php://temp','r+'); + $stream = fopen('php://temp', 'r+'); fwrite($stream, $body); rewind($stream); diff --git a/apps/dav/tests/unit/Listener/UserChangeListenerTest.php b/apps/dav/tests/unit/Listener/UserChangeListenerTest.php index c3d8de79b27ed..7977bd0c05dac 100644 --- a/apps/dav/tests/unit/Listener/UserChangeListenerTest.php +++ b/apps/dav/tests/unit/Listener/UserChangeListenerTest.php @@ -100,10 +100,10 @@ public function testFirstLoginWithBirthdayCalendar() { $this->calDavBackend->expects($this->once())->method('createCalendar')->with( 'principals/users/newUser', 'personal', [ - '{DAV:}displayname' => 'Personal', - '{http://apple.com/ns/ical/}calendar-color' => '#745bca', - 'components' => 'VEVENT' - ]); + '{DAV:}displayname' => 'Personal', + '{http://apple.com/ns/ical/}calendar-color' => '#745bca', + 'components' => 'VEVENT' + ]); $this->cardDavBackend->expects($this->once())->method('getAddressBooksForUserCount')->willReturn(0); $this->cardDavBackend->expects($this->once())->method('createAddressBook')->with( diff --git a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php index d15758b2dfa06..a9c1a16d1063f 100644 --- a/apps/dav/tests/unit/Upload/AssemblyStreamTest.php +++ b/apps/dav/tests/unit/Upload/AssemblyStreamTest.php @@ -81,7 +81,7 @@ public function providesNodes(): array { $tonofnodes = []; $tonofdata = ""; for ($i = 0; $i < 101; $i++) { - $thisdata = rand(0,100); // variable length and content + $thisdata = rand(0, 100); // variable length and content $tonofdata .= $thisdata; $tonofnodes[] = $this->buildNode($i, $thisdata); }