From c96ece0bcb6aaaba6f2dc6f6e9426fc115e4221d Mon Sep 17 00:00:00 2001 From: Carl Schwan Date: Tue, 2 Dec 2025 11:39:50 +0100 Subject: [PATCH] refactor: Add more typing - repairs job - database - redis And remove Helpertest which was unused outside of some tests. Signed-off-by: Carl Schwan --- .../unit/Connector/LegacyPublicAuthTest.php | 14 +- .../unit/Connector/Sabre/PrincipalTest.php | 8 +- apps/settings/lib/AppInfo/Application.php | 48 ++-- .../lib/Middleware/SubadminMiddleware.php | 23 +- build/psalm-baseline.xml | 35 --- core/Command/Memcache/RedisCommand.php | 4 +- lib/composer/composer/autoload_classmap.php | 1 - lib/composer/composer/autoload_static.php | 1 - lib/private/NavigationManager.php | 14 +- lib/private/Preview/WatcherConnector.php | 8 +- lib/private/RedisFactory.php | 21 +- lib/private/Remote/Instance.php | 62 ++--- lib/private/Repair/Owncloud/CleanPreviews.php | 11 +- .../Repair/Owncloud/UpdateLanguageCodes.php | 3 + lib/private/Repair/RemoveLinkShares.php | 3 - lib/private/Server.php | 31 +-- lib/private/Session/CryptoSessionData.php | 11 +- lib/private/Settings/Section.php | 48 +--- lib/private/Setup.php | 5 +- lib/private/Setup/AbstractDatabase.php | 25 +- lib/private/Setup/MySQL.php | 18 +- lib/private/Setup/OCI.php | 9 +- lib/private/Setup/PostgreSQL.php | 10 +- lib/private/Setup/Sqlite.php | 8 +- lib/private/Share/Helper.php | 143 ---------- lib/private/Share20/Manager.php | 14 +- lib/private/StreamImage.php | 32 ++- lib/private/Support/Subscription/Registry.php | 18 +- .../RemoveOldTasksBackgroundJob.php | 9 +- lib/private/TempManager.php | 13 +- lib/private/URLGenerator.php | 6 +- lib/private/User/Database.php | 8 +- lib/private/User/LazyUser.php | 2 +- lib/private/User/Manager.php | 6 +- lib/private/User/User.php | 88 ++---- lib/private/legacy/OC_App.php | 39 +-- lib/private/legacy/OC_User.php | 46 ++-- lib/public/Files/Cache/IUpdater.php | 4 - lib/public/IServerContainer.php | 2 +- lib/public/Remote/IInstance.php | 15 +- .../TwoFactorAuth/RegistryTest.php | 11 +- .../Collaborators/MailPluginTest.php | 90 ++----- tests/lib/ContactsManagerTest.php | 3 +- tests/lib/DateTimeFormatterTest.php | 3 +- tests/lib/Diagnostics/EventLoggerTest.php | 3 +- tests/lib/Diagnostics/QueryLoggerTest.php | 3 +- tests/lib/Encryption/Keys/StorageTest.php | 19 +- tests/lib/Files/Cache/HomeCacheTest.php | 46 +--- tests/lib/Files/Storage/HomeTest.php | 12 +- .../lib/Repair/Owncloud/CleanPreviewsTest.php | 35 ++- tests/lib/Share/HelperTest.php | 74 ----- .../lib/Support/Subscription/RegistryTest.php | 9 +- tests/lib/User/ManagerTest.php | 14 +- tests/lib/User/UserTest.php | 252 +++--------------- tests/lib/Util/User/Dummy.php | 91 +------ 55 files changed, 391 insertions(+), 1140 deletions(-) delete mode 100644 lib/private/Share/Helper.php delete mode 100644 tests/lib/Share/HelperTest.php diff --git a/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php b/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php index 01b67d7d543..8fc54de645a 100644 --- a/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php +++ b/apps/dav/tests/unit/Connector/LegacyPublicAuthTest.php @@ -15,16 +15,12 @@ use OCP\Security\Bruteforce\IThrottler; use OCP\Share\Exceptions\ShareNotFound; use OCP\Share\IManager; use OCP\Share\IShare; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; +use Test\TestCase; -/** - * Class LegacyPublicAuthTest - * - * - * @package OCA\DAV\Tests\unit\Connector - */ -#[\PHPUnit\Framework\Attributes\Group(name: 'DB')] -class LegacyPublicAuthTest extends \Test\TestCase { +#[Group(name: 'DB')] +class LegacyPublicAuthTest extends TestCase { private ISession&MockObject $session; private IRequest&MockObject $request; private IManager&MockObject $shareManager; @@ -55,7 +51,7 @@ class LegacyPublicAuthTest extends \Test\TestCase { \OC_User::setIncognitoMode(false); // Set old user - \OC_User::setUserId($this->oldUser); + \OC_User::setUserId($this->oldUser ?: null); if ($this->oldUser !== false) { \OC_Util::setupFS($this->oldUser); } diff --git a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php index eb517690243..1be48b85c3b 100644 --- a/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php +++ b/apps/dav/tests/unit/Connector/Sabre/PrincipalTest.php @@ -78,7 +78,7 @@ class PrincipalTest extends TestCase { } public function testGetPrincipalsByPrefixWithUsers(): void { - $fooUser = $this->createMock(User::class); + $fooUser = $this->createMock(IUser::class); $fooUser ->expects($this->once()) ->method('getUID') @@ -91,7 +91,7 @@ class PrincipalTest extends TestCase { ->expects($this->once()) ->method('getSystemEMailAddress') ->willReturn(''); - $barUser = $this->createMock(User::class); + $barUser = $this->createMock(IUser::class); $barUser ->expects($this->once()) ->method('getUID') @@ -183,7 +183,7 @@ class PrincipalTest extends TestCase { } public function testGetPrincipalsByPathWithoutMail(): void { - $fooUser = $this->createMock(User::class); + $fooUser = $this->createMock(IUser::class); $fooUser ->expects($this->once()) ->method('getUID') @@ -211,7 +211,7 @@ class PrincipalTest extends TestCase { } public function testGetPrincipalsByPathWithMail(): void { - $fooUser = $this->createMock(User::class); + $fooUser = $this->createMock(IUser::class); $fooUser ->expects($this->once()) ->method('getSystemEMailAddress') diff --git a/apps/settings/lib/AppInfo/Application.php b/apps/settings/lib/AppInfo/Application.php index bf823a172af..ebdcf144717 100644 --- a/apps/settings/lib/AppInfo/Application.php +++ b/apps/settings/lib/AppInfo/Application.php @@ -11,7 +11,7 @@ namespace OCA\Settings\AppInfo; use OC\AppFramework\Utility\TimeFactory; use OC\Authentication\Events\AppPasswordCreatedEvent; use OC\Authentication\Token\IProvider; -use OC\Server; +use OC\Settings\Manager; use OCA\Settings\ConfigLexicon; use OCA\Settings\Hooks; use OCA\Settings\Listener\AppPasswordCreatedActivityListener; @@ -85,25 +85,28 @@ use OCP\AppFramework\App; use OCP\AppFramework\Bootstrap\IBootContext; use OCP\AppFramework\Bootstrap\IBootstrap; use OCP\AppFramework\Bootstrap\IRegistrationContext; -use OCP\AppFramework\IAppContainer; use OCP\Defaults; use OCP\Group\Events\GroupDeletedEvent; use OCP\Group\Events\UserAddedEvent; use OCP\Group\Events\UserRemovedEvent; -use OCP\IServerContainer; +use OCP\IConfig; +use OCP\IURLGenerator; +use OCP\L10N\IFactory; +use OCP\Mail\IMailer; +use OCP\Security\ICrypto; +use OCP\Security\ISecureRandom; +use OCP\Server; use OCP\Settings\Events\DeclarativeSettingsGetValueEvent; use OCP\Settings\Events\DeclarativeSettingsSetValueEvent; use OCP\Settings\IManager; use OCP\User\Events\PasswordUpdatedEvent; use OCP\User\Events\UserChangedEvent; use OCP\Util; +use Psr\Container\ContainerInterface; class Application extends App implements IBootstrap { public const APP_ID = 'settings'; - /** - * @param array $urlParams - */ public function __construct(array $urlParams = []) { parent::__construct(self::APP_ID, $urlParams); } @@ -140,32 +143,23 @@ class Application extends App implements IBootstrap { /** * Core class wrappers */ - $context->registerService(IProvider::class, function (IAppContainer $appContainer) { - /** @var IServerContainer $serverContainer */ - $serverContainer = $appContainer->query(IServerContainer::class); - return $serverContainer->query(IProvider::class); + $context->registerService(IProvider::class, function (): IProvider { + return Server::get(IProvider::class); }); - $context->registerService(IManager::class, function (IAppContainer $appContainer) { - /** @var IServerContainer $serverContainer */ - $serverContainer = $appContainer->query(IServerContainer::class); - return $serverContainer->getSettingsManager(); + $context->registerService(IManager::class, function (): Manager { + return Server::get(Manager::class); }); - $context->registerService(NewUserMailHelper::class, function (IAppContainer $appContainer) { - /** @var Server $server */ - $server = $appContainer->query(IServerContainer::class); - /** @var Defaults $defaults */ - $defaults = $server->query(Defaults::class); - + $context->registerService(NewUserMailHelper::class, function (ContainerInterface $appContainer) { return new NewUserMailHelper( - $defaults, - $server->getURLGenerator(), - $server->getL10NFactory(), - $server->getMailer(), - $server->getSecureRandom(), + Server::get(Defaults::class), + $appContainer->get(IURLGenerator::class), + $appContainer->get(IFactory::class), + $appContainer->get(IMailer::class), + $appContainer->get(ISecureRandom::class), new TimeFactory(), - $server->getConfig(), - $server->getCrypto(), + $appContainer->get(IConfig::class), + $appContainer->get(ICrypto::class), Util::getDefaultEmailAddress('no-reply') ); }); diff --git a/apps/settings/lib/Middleware/SubadminMiddleware.php b/apps/settings/lib/Middleware/SubadminMiddleware.php index 02d68e138da..d7be892d163 100644 --- a/apps/settings/lib/Middleware/SubadminMiddleware.php +++ b/apps/settings/lib/Middleware/SubadminMiddleware.php @@ -19,9 +19,10 @@ use OCP\AppFramework\Middleware; use OCP\Group\ISubAdmin; use OCP\IL10N; use OCP\IUserSession; +use Override; /** - * Verifies whether an user has at least subadmin rights. + * Verifies whether a user has at least sub-admin rights. * To bypass use the `@NoSubAdminRequired` annotation */ class SubadminMiddleware extends Middleware { @@ -41,13 +42,8 @@ class SubadminMiddleware extends Middleware { return $this->subAdminManager->isSubAdmin($userObject); } - /** - * Check if sharing is enabled before the controllers is executed - * @param Controller $controller - * @param string $methodName - * @throws \Exception - */ - public function beforeController($controller, $methodName) { + #[Override] + public function beforeController(Controller $controller, string $methodName): void { if (!$this->reflector->hasAnnotation('NoSubAdminRequired') && !$this->reflector->hasAnnotation('AuthorizedAdminSetting')) { if (!$this->isSubAdmin()) { throw new NotAdminException($this->l10n->t('Logged in account must be a sub admin')); @@ -55,15 +51,8 @@ class SubadminMiddleware extends Middleware { } } - /** - * Return 403 page in case of an exception - * @param Controller $controller - * @param string $methodName - * @param \Exception $exception - * @return TemplateResponse - * @throws \Exception - */ - public function afterException($controller, $methodName, \Exception $exception) { + #[Override] + public function afterException(Controller $controller, string $methodName, \Exception $exception): TemplateResponse { if ($exception instanceof NotAdminException) { $response = new TemplateResponse('core', '403', [], 'guest'); $response->setStatus(Http::STATUS_FORBIDDEN); diff --git a/build/psalm-baseline.xml b/build/psalm-baseline.xml index 86a70ac3c5e..04c44c1d9b9 100644 --- a/build/psalm-baseline.xml +++ b/build/psalm-baseline.xml @@ -2175,31 +2175,6 @@ - - - - - - - - - - - - - - - - - - - - - - - - - @@ -3868,16 +3843,6 @@ - - - - - - - - - - userToNotify]]> diff --git a/core/Command/Memcache/RedisCommand.php b/core/Command/Memcache/RedisCommand.php index 429dd28f3b3..1d1a7243d21 100644 --- a/core/Command/Memcache/RedisCommand.php +++ b/core/Command/Memcache/RedisCommand.php @@ -44,7 +44,9 @@ class RedisCommand extends Base { return 1; } - $redis->setOption(\Redis::OPT_REPLY_LITERAL, true); + if ($redis instanceof \Redis) { + $redis->setOption(\Redis::OPT_REPLY_LITERAL, true); + } $result = $redis->rawCommand(...$command); if ($result === false) { $output->writeln('Redis command failed'); diff --git a/lib/composer/composer/autoload_classmap.php b/lib/composer/composer/autoload_classmap.php index 3a092d675e6..89f12a775b0 100644 --- a/lib/composer/composer/autoload_classmap.php +++ b/lib/composer/composer/autoload_classmap.php @@ -2182,7 +2182,6 @@ return array( 'OC\\Share20\\UserDeletedListener' => $baseDir . '/lib/private/Share20/UserDeletedListener.php', 'OC\\Share20\\UserRemovedListener' => $baseDir . '/lib/private/Share20/UserRemovedListener.php', 'OC\\Share\\Constants' => $baseDir . '/lib/private/Share/Constants.php', - 'OC\\Share\\Helper' => $baseDir . '/lib/private/Share/Helper.php', 'OC\\Share\\Share' => $baseDir . '/lib/private/Share/Share.php', 'OC\\Snowflake\\APCuSequence' => $baseDir . '/lib/private/Snowflake/APCuSequence.php', 'OC\\Snowflake\\FileSequence' => $baseDir . '/lib/private/Snowflake/FileSequence.php', diff --git a/lib/composer/composer/autoload_static.php b/lib/composer/composer/autoload_static.php index 16c37947128..b43d17d10cc 100644 --- a/lib/composer/composer/autoload_static.php +++ b/lib/composer/composer/autoload_static.php @@ -2223,7 +2223,6 @@ class ComposerStaticInit749170dad3f5e7f9ca158f5a9f04f6a2 'OC\\Share20\\UserDeletedListener' => __DIR__ . '/../../..' . '/lib/private/Share20/UserDeletedListener.php', 'OC\\Share20\\UserRemovedListener' => __DIR__ . '/../../..' . '/lib/private/Share20/UserRemovedListener.php', 'OC\\Share\\Constants' => __DIR__ . '/../../..' . '/lib/private/Share/Constants.php', - 'OC\\Share\\Helper' => __DIR__ . '/../../..' . '/lib/private/Share/Helper.php', 'OC\\Share\\Share' => __DIR__ . '/../../..' . '/lib/private/Share/Share.php', 'OC\\Snowflake\\APCuSequence' => __DIR__ . '/../../..' . '/lib/private/Snowflake/APCuSequence.php', 'OC\\Snowflake\\FileSequence' => __DIR__ . '/../../..' . '/lib/private/Snowflake/FileSequence.php', diff --git a/lib/private/NavigationManager.php b/lib/private/NavigationManager.php index d801877ee7f..eb88c5d7d65 100644 --- a/lib/private/NavigationManager.php +++ b/lib/private/NavigationManager.php @@ -22,17 +22,15 @@ use OCP\Navigation\Events\LoadAdditionalEntriesEvent; use Psr\Log\LoggerInterface; /** - * Manages the ownCloud navigation + * Manages the Nextcloud navigation */ - class NavigationManager implements INavigationManager { - protected $entries = []; - protected $closureEntries = []; + protected array $entries = []; + protected array $closureEntries = []; + /** @var string $activeEntry */ protected $activeEntry; - protected $unreadCounters = []; - - /** @var bool */ - protected $init = false; + protected array $unreadCounters = []; + protected bool $init = false; /** User defined app order (cached for the `add` function) */ private array $customAppOrder; diff --git a/lib/private/Preview/WatcherConnector.php b/lib/private/Preview/WatcherConnector.php index f54607bb0ff..1331cd670d0 100644 --- a/lib/private/Preview/WatcherConnector.php +++ b/lib/private/Preview/WatcherConnector.php @@ -16,6 +16,8 @@ use OCP\Files\Node; use OCP\Server; class WatcherConnector { + private ?Watcher $watcher = null; + public function __construct( private IRootFolder $root, private SystemConfig $config, @@ -24,7 +26,11 @@ class WatcherConnector { } private function getWatcher(): Watcher { - return Server::get(Watcher::class); + if ($this->watcher !== null) { + return $this->watcher; + } + $this->watcher = Server::get(Watcher::class); + return $this->watcher; } public function connectWatcher(): void { diff --git a/lib/private/RedisFactory.php b/lib/private/RedisFactory.php index 839e6a9a048..4c8160d81d1 100644 --- a/lib/private/RedisFactory.php +++ b/lib/private/RedisFactory.php @@ -13,21 +13,15 @@ class RedisFactory { public const REDIS_MINIMAL_VERSION = '4.0.0'; public const REDIS_EXTRA_PARAMETERS_MINIMAL_VERSION = '5.3.0'; - /** @var \Redis|\RedisCluster */ - private $instance; + private \Redis|\RedisCluster|null $instance = null; - /** - * RedisFactory constructor. - * - * @param SystemConfig $config - */ public function __construct( private SystemConfig $config, private IEventLogger $eventLogger, ) { } - private function create() { + private function create(): void { $isCluster = in_array('redis.cluster', $this->config->getKeys(), true); $config = $isCluster ? $this->config->getValue('redis.cluster', []) @@ -121,10 +115,9 @@ class RedisFactory { * Get the ssl context config * * @param array $config the current config - * @return array|null * @throws \UnexpectedValueException */ - private function getSslContext($config) { + private function getSslContext(array $config): ?array { if (isset($config['ssl_context'])) { if (!$this->isConnectionParametersSupported()) { throw new \UnexpectedValueException(\sprintf( @@ -137,14 +130,18 @@ class RedisFactory { return null; } - public function getInstance() { + public function getInstance(): \Redis|\RedisCluster { if (!$this->isAvailable()) { throw new \Exception('Redis support is not available'); } - if (!$this->instance instanceof \Redis) { + if ($this->instance === null) { $this->create(); } + if ($this->instance === null) { + throw new \Exception('Redis support is not available'); + } + return $this->instance; } diff --git a/lib/private/Remote/Instance.php b/lib/private/Remote/Instance.php index 0f3311c3dfc..9807c6b5b1b 100644 --- a/lib/private/Remote/Instance.php +++ b/lib/private/Remote/Instance.php @@ -10,24 +10,17 @@ use OC\Remote\Api\NotFoundException; use OCP\Http\Client\IClientService; use OCP\ICache; use OCP\Remote\IInstance; +use Override; /** * Provides some basic info about a remote Nextcloud instance */ class Instance implements IInstance { - /** @var string */ - private $url; + private string $url; + private ?array $status = null; - /** @var array|null */ - private $status; - - /** - * @param string $url - * @param ICache $cache - * @param IClientService $clientService - */ public function __construct( - $url, + string $url, private ICache $cache, private IClientService $clientService, ) { @@ -35,52 +28,35 @@ class Instance implements IInstance { $this->url = str_replace('http://', '', $url); } - /** - * @return string The url of the remote server without protocol - */ - public function getUrl() { + #[Override] + public function getUrl(): string { return $this->url; } - /** - * @return string The of the remote server with protocol - */ - public function getFullUrl() { + #[Override] + public function getFullUrl(): string { return $this->getProtocol() . '://' . $this->getUrl(); } - /** - * @return string The full version string in '13.1.2.3' format - */ - public function getVersion() { + #[Override] + public function getVersion(): string { $status = $this->getStatus(); return $status['version']; } - /** - * @return string 'http' or 'https' - */ - public function getProtocol() { + #[Override] + public function getProtocol(): string { $status = $this->getStatus(); return $status['protocol']; } - /** - * Check that the remote server is installed and not in maintenance mode - * - * @return bool - */ - public function isActive() { + #[Override] + public function isActive(): bool { $status = $this->getStatus(); return $status['installed'] && !$status['maintenance']; } - /** - * @return array - * @throws NotFoundException - * @throws \Exception - */ - private function getStatus() { + private function getStatus(): array { if ($this->status) { return $this->status; } @@ -113,11 +89,7 @@ class Instance implements IInstance { return $status; } - /** - * @param string $url - * @return bool|string - */ - private function downloadStatus($url) { + private function downloadStatus(string $url): false|string { try { $request = $this->clientService->newClient()->get($url); $content = $request->getBody(); @@ -127,7 +99,7 @@ class Instance implements IInstance { assert(is_string($content)); return $content; - } catch (\Exception $e) { + } catch (\Exception) { return false; } } diff --git a/lib/private/Repair/Owncloud/CleanPreviews.php b/lib/private/Repair/Owncloud/CleanPreviews.php index 8764929669a..63bec39859b 100644 --- a/lib/private/Repair/Owncloud/CleanPreviews.php +++ b/lib/private/Repair/Owncloud/CleanPreviews.php @@ -7,30 +7,33 @@ namespace OC\Repair\Owncloud; use OCP\BackgroundJob\IJobList; -use OCP\IConfig; +use OCP\IAppConfig; use OCP\IUser; use OCP\IUserManager; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use Override; class CleanPreviews implements IRepairStep { public function __construct( private readonly IJobList $jobList, private readonly IUserManager $userManager, - private readonly IConfig $config, + private readonly IAppConfig $appConfig, ) { } + #[Override] public function getName(): string { return 'Add preview cleanup background jobs'; } + #[Override] public function run(IOutput $output): void { - if (!$this->config->getAppValue('core', 'previewsCleanedUp', false)) { + if (!$this->appConfig->getValueBool('core', 'previewsCleanedUp')) { $this->userManager->callForSeenUsers(function (IUser $user): void { $this->jobList->add(CleanPreviewsBackgroundJob::class, ['uid' => $user->getUID()]); }); - $this->config->setAppValue('core', 'previewsCleanedUp', '1'); + $this->appConfig->setValueBool('core', 'previewsCleanedUp', true); } } } diff --git a/lib/private/Repair/Owncloud/UpdateLanguageCodes.php b/lib/private/Repair/Owncloud/UpdateLanguageCodes.php index 1088ea6e623..611e33602dd 100644 --- a/lib/private/Repair/Owncloud/UpdateLanguageCodes.php +++ b/lib/private/Repair/Owncloud/UpdateLanguageCodes.php @@ -11,6 +11,7 @@ use OCP\IConfig; use OCP\IDBConnection; use OCP\Migration\IOutput; use OCP\Migration\IRepairStep; +use Override; class UpdateLanguageCodes implements IRepairStep { public function __construct( @@ -19,10 +20,12 @@ class UpdateLanguageCodes implements IRepairStep { ) { } + #[Override] public function getName(): string { return 'Repair language codes'; } + #[Override] public function run(IOutput $output): void { $versionFromBeforeUpdate = $this->config->getSystemValueString('version', '0.0.0'); diff --git a/lib/private/Repair/RemoveLinkShares.php b/lib/private/Repair/RemoveLinkShares.php index c2f0516af08..5ea1d4b9258 100644 --- a/lib/private/Repair/RemoveLinkShares.php +++ b/lib/private/Repair/RemoveLinkShares.php @@ -51,9 +51,6 @@ class RemoveLinkShares implements IRepairStep { return false; } - /** - * Delete the share - */ private function deleteShare(int $id): void { $qb = $this->connection->getQueryBuilder(); $qb->delete('share') diff --git a/lib/private/Server.php b/lib/private/Server.php index 22c6a81d715..a0c309e5f12 100644 --- a/lib/private/Server.php +++ b/lib/private/Server.php @@ -290,12 +290,8 @@ use Psr\Log\LoggerInterface; * TODO: hookup all manager classes */ class Server extends ServerContainer implements IServerContainer { - /** - * @param string $webRoot - * @param Config $config - */ public function __construct( - private $webRoot, + private string $webRoot, Config $config, ) { parent::__construct(); @@ -1047,7 +1043,10 @@ class Server extends ServerContainer implements IServerContainer { $classExists = false; } - if ($classExists && $c->get(IConfig::class)->getSystemValueBool('installed', false) && $c->get(IAppManager::class)->isEnabledForAnyone('theming') && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) { + if ($classExists + && $c->get(IConfig::class)->getSystemValueBool('installed', false) + && $c->get(IAppManager::class)->isEnabledForAnyone('theming') + && $c->get(TrustedDomainHelper::class)->isTrustedDomain($c->getRequest()->getInsecureServerHost())) { $backgroundService = new BackgroundService( $c->get(IRootFolder::class), $c->get(IAppDataFactory::class)->get('theming'), @@ -1394,7 +1393,7 @@ class Server extends ServerContainer implements IServerContainer { * @return Folder|null * @deprecated 20.0.0 */ - public function getUserFolder($userId = null) { + public function getUserFolder($userId = null): ?Folder { if ($userId === null) { $user = $this->get(IUserSession::class)->getUser(); if (!$user) { @@ -1428,44 +1427,36 @@ class Server extends ServerContainer implements IServerContainer { } /** - * @return ISession * @deprecated 20.0.0 */ - public function getSession() { + public function getSession(): ISession { return $this->get(Session::class)->getSession(); } - /** - * @param ISession $session - * @return void - */ - public function setSession(ISession $session) { + public function setSession(ISession $session): void { $this->get(SessionStorage::class)->setSession($session); $this->get(Session::class)->setSession($session); $this->get(Store::class)->setSession($session); } /** - * @return IConfig * @deprecated 20.0.0 */ - public function getConfig() { + public function getConfig(): IConfig { return $this->get(AllConfig::class); } /** - * @return SystemConfig * @deprecated 20.0.0 */ - public function getSystemConfig() { + public function getSystemConfig(): SystemConfig { return $this->get(SystemConfig::class); } /** - * @return IFactory * @deprecated 20.0.0 */ - public function getL10NFactory() { + public function getL10NFactory(): IFactory { return $this->get(IFactory::class); } diff --git a/lib/private/Session/CryptoSessionData.php b/lib/private/Session/CryptoSessionData.php index 1420cd94d59..f25d2234335 100644 --- a/lib/private/Session/CryptoSessionData.php +++ b/lib/private/Session/CryptoSessionData.php @@ -21,17 +21,10 @@ use function OCP\Log\logger; * @template-implements \ArrayAccess */ class CryptoSessionData implements \ArrayAccess, ISession { - /** @var array */ - protected $sessionValues; - /** @var bool */ - protected $isModified = false; + protected array $sessionValues = []; + protected bool $isModified = false; public const encryptedSessionName = 'encrypted_session_data'; - /** - * @param ISession $session - * @param ICrypto $crypto - * @param string $passphrase - */ public function __construct( protected ISession $session, protected ICrypto $crypto, diff --git a/lib/private/Settings/Section.php b/lib/private/Settings/Section.php index 1a54eb84a51..c67c4c07708 100644 --- a/lib/private/Settings/Section.php +++ b/lib/private/Settings/Section.php @@ -7,56 +7,34 @@ namespace OC\Settings; use OCP\Settings\IIconSection; +use Override; class Section implements IIconSection { - /** - * @param string $id - * @param string $name - * @param int $priority - * @param string $icon - */ public function __construct( - private $id, - private $name, - private $priority, - private $icon = '', + private string $id, + private string $name, + private int $priority, + private string $icon = '', ) { } - /** - * @return string The ID of the section. It is supposed to be a lower case string, - * e.g. 'ldap' - */ - public function getID() { + #[Override] + public function getID(): string { return $this->id; } - /** - * @return string The translated name as it should be displayed, e.g. 'LDAP / AD - * integration'. Use the L10N service to translate it. - */ - public function getName() { + #[Override] + public function getName(): string { return $this->name; } - /** - * @return int whether the form should be rather on the top or bottom of - * the settings navigation. The sections are arranged in ascending order of - * the priority values. It is required to return a value between 0 and 99. - * - * E.g.: 70 - */ - public function getPriority() { + #[Override] + public function getPriority(): int { return $this->priority; } - /** - * @return string The relative path to an 16*16 icon describing the section. - * e.g. '/core/img/places/files.svg' - * - * @since 12 - */ - public function getIcon() { + #[Override] + public function getIcon(): string { return $this->icon; } } diff --git a/lib/private/Setup.php b/lib/private/Setup.php index 4fc8e622814..b5b79ebd769 100644 --- a/lib/private/Setup.php +++ b/lib/private/Setup.php @@ -262,12 +262,10 @@ class Setup { /** * Check if the .htaccess file is working * - * @param IConfig $config - * @return bool * @throws Exception * @throws HintException If the test file can't get written. */ - public function isHtaccessWorking(string $dataDir) { + public function isHtaccessWorking(string $dataDir): bool { $config = Server::get(IConfig::class); if (\OC::$CLI || !$config->getSystemValueBool('check_for_working_htaccess', true)) { @@ -563,7 +561,6 @@ class Setup { /** * Append the correct ErrorDocument path for Apache hosts * - * @return bool True when success, False otherwise * @throws QueryException */ public static function updateHtaccess(): bool { diff --git a/lib/private/Setup/AbstractDatabase.php b/lib/private/Setup/AbstractDatabase.php index a679866acf4..d07d4af91a6 100644 --- a/lib/private/Setup/AbstractDatabase.php +++ b/lib/private/Setup/AbstractDatabase.php @@ -18,20 +18,13 @@ use OCP\Server; use Psr\Log\LoggerInterface; abstract class AbstractDatabase { - /** @var string */ - protected $dbUser; - /** @var string */ - protected $dbPassword; - /** @var string */ - protected $dbName; - /** @var string */ - protected $dbHost; - /** @var string */ - protected $dbPort; - /** @var string */ - protected $tablePrefix; - /** @var bool */ - protected $tryCreateDbUser; + protected string $dbUser; + protected string $dbPassword; + protected string $dbName; + protected string $dbHost; + protected string $dbPort; + protected string $tablePrefix; + protected bool $tryCreateDbUser; public function __construct( protected IL10N $trans, @@ -41,7 +34,7 @@ abstract class AbstractDatabase { ) { } - public function validate($config) { + public function validate(array $config): array { $errors = []; if (empty($config['dbuser']) && empty($config['dbname'])) { $errors[] = $this->trans->t('Enter the database Login and name for %s', [$this->dbprettyname]); @@ -56,7 +49,7 @@ abstract class AbstractDatabase { return $errors; } - public function initialize($config) { + public function initialize(array $config): void { $dbUser = $config['dbuser']; $dbPass = $config['dbpass']; $dbName = $config['dbname']; diff --git a/lib/private/Setup/MySQL.php b/lib/private/Setup/MySQL.php index 7f8ea73a1f4..24093ae97a4 100644 --- a/lib/private/Setup/MySQL.php +++ b/lib/private/Setup/MySQL.php @@ -16,9 +16,9 @@ use OCP\IDBConnection; use OCP\Security\ISecureRandom; class MySQL extends AbstractDatabase { - public $dbprettyname = 'MySQL/MariaDB'; + public string $dbprettyname = 'MySQL/MariaDB'; - public function setupDatabase() { + public function setupDatabase(): void { //check if the database user has admin right $connection = $this->connect(['dbname' => null]); @@ -58,10 +58,7 @@ class MySQL extends AbstractDatabase { } } - /** - * @param \OC\DB\Connection $connection - */ - private function createDatabase($connection): void { + private function createDatabase(\OC\DB\Connection $connection): void { try { $name = $this->dbName; $user = $this->dbUser; @@ -90,10 +87,9 @@ class MySQL extends AbstractDatabase { } /** - * @param IDBConnection $connection * @throws DatabaseSetupException */ - private function createDBUser($connection): void { + private function createDBUser(IDBConnection $connection): void { $name = $this->dbUser; $password = $this->dbPassword; @@ -127,11 +123,7 @@ class MySQL extends AbstractDatabase { } } - /** - * @param string $username - * @param IDBConnection $connection - */ - private function createSpecificUser($username, $connection): void { + private function createSpecificUser(string $username, IDBConnection $connection): void { $rootUser = $this->dbUser; $rootPassword = $this->dbPassword; diff --git a/lib/private/Setup/OCI.php b/lib/private/Setup/OCI.php index 72f3bd04027..7bde42c1ace 100644 --- a/lib/private/Setup/OCI.php +++ b/lib/private/Setup/OCI.php @@ -14,7 +14,7 @@ class OCI extends AbstractDatabase { protected $dbtablespace; - public function initialize($config) { + public function initialize(array $config): void { parent::initialize($config); if (array_key_exists('dbtablespace', $config)) { $this->dbtablespace = $config['dbtablespace']; @@ -30,7 +30,7 @@ class OCI extends AbstractDatabase { ]); } - public function validate($config) { + public function validate(array $config): array { $errors = []; if (empty($config['dbuser']) && empty($config['dbname'])) { $errors[] = $this->trans->t('Enter the database Login and name for %s', [$this->dbprettyname]); @@ -42,7 +42,7 @@ class OCI extends AbstractDatabase { return $errors; } - public function setupDatabase() { + public function setupDatabase(): void { try { $this->connect(); } catch (\Exception $e) { @@ -72,9 +72,8 @@ class OCI extends AbstractDatabase { /** * @param resource $connection - * @return string */ - protected function getLastError($connection = null) { + protected function getLastError($connection = null): string { if ($connection) { $error = oci_error($connection); } else { diff --git a/lib/private/Setup/PostgreSQL.php b/lib/private/Setup/PostgreSQL.php index e0564b00c60..5ace7f6bcbe 100644 --- a/lib/private/Setup/PostgreSQL.php +++ b/lib/private/Setup/PostgreSQL.php @@ -20,7 +20,7 @@ class PostgreSQL extends AbstractDatabase { /** * @throws DatabaseSetupException */ - public function setupDatabase() { + public function setupDatabase(): void { try { $connection = $this->connect([ 'dbname' => 'postgres' @@ -103,7 +103,7 @@ class PostgreSQL extends AbstractDatabase { } } - private function createDatabase(Connection $connection) { + private function createDatabase(Connection $connection): void { if (!$this->databaseExists($connection)) { //The database does not exists... let's create it $query = $connection->prepare('CREATE DATABASE ' . addslashes($this->dbName) . ' OWNER "' . addslashes($this->dbUser) . '"'); @@ -126,7 +126,7 @@ class PostgreSQL extends AbstractDatabase { } } - private function userExists(Connection $connection) { + private function userExists(Connection $connection): bool { $builder = $connection->getQueryBuilder(); $builder->automaticTablePrefix(false); $query = $builder->select('*') @@ -136,7 +136,7 @@ class PostgreSQL extends AbstractDatabase { return $result->rowCount() > 0; } - private function databaseExists(Connection $connection) { + private function databaseExists(Connection $connection): bool { $builder = $connection->getQueryBuilder(); $builder->automaticTablePrefix(false); $query = $builder->select('datname') @@ -146,7 +146,7 @@ class PostgreSQL extends AbstractDatabase { return $result->rowCount() > 0; } - private function createDBUser(Connection $connection) { + private function createDBUser(Connection $connection): void { $dbUser = $this->dbUser; try { $i = 1; diff --git a/lib/private/Setup/Sqlite.php b/lib/private/Setup/Sqlite.php index b34b1e32ede..325a26ce896 100644 --- a/lib/private/Setup/Sqlite.php +++ b/lib/private/Setup/Sqlite.php @@ -10,13 +10,13 @@ namespace OC\Setup; use OC\DB\ConnectionFactory; class Sqlite extends AbstractDatabase { - public $dbprettyname = 'Sqlite'; + public string $dbprettyname = 'Sqlite'; - public function validate($config) { + public function validate(array $config): array { return []; } - public function initialize($config) { + public function initialize(array $config): void { /* * Web: When using web based installer its not possible to set dbname * or dbtableprefix. Defaults used from ConnectionFactory and dbtype = 'sqlite' @@ -45,7 +45,7 @@ class Sqlite extends AbstractDatabase { } } - public function setupDatabase() { + public function setupDatabase(): void { $datadir = $this->config->getValue( 'datadirectory', \OC::$SERVERROOT . '/data' diff --git a/lib/private/Share/Helper.php b/lib/private/Share/Helper.php deleted file mode 100644 index 58a33b5620d..00000000000 --- a/lib/private/Share/Helper.php +++ /dev/null @@ -1,143 +0,0 @@ - false]; - - // get default expire settings - if ($appConfig->getValueBool('core', ConfigLexicon::SHARE_LINK_EXPIRE_DATE_DEFAULT)) { - $defaultExpireSettings['defaultExpireDateSet'] = true; - $defaultExpireSettings['expireAfterDays'] = (int)$config->getAppValue('core', 'shareapi_expire_after_n_days', '7'); - $defaultExpireSettings['enforceExpireDate'] = $appConfig->getValueBool('core', ConfigLexicon::SHARE_LINK_EXPIRE_DATE_ENFORCED); - } - - return $defaultExpireSettings; - } - - public static function calcExpireDate() { - $expireAfter = Share::getExpireInterval() * 24 * 60 * 60; - $expireAt = time() + $expireAfter; - $date = new \DateTime(); - $date->setTimestamp($expireAt); - $date->setTime(0, 0, 0); - //$dateString = $date->format('Y-m-d') . ' 00:00:00'; - - return $date; - } - - /** - * calculate expire date - * @param array $defaultExpireSettings contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays' - * @param int $creationTime timestamp when the share was created - * @param int $userExpireDate expire timestamp set by the user - * @return mixed integer timestamp or False - */ - public static function calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate = null) { - $expires = false; - $defaultExpires = null; - - if (!empty($defaultExpireSettings['defaultExpireDateSet'])) { - $defaultExpires = $creationTime + $defaultExpireSettings['expireAfterDays'] * 86400; - } - - - if (isset($userExpireDate)) { - // if the admin decided to enforce the default expire date then we only take - // the user defined expire date of it is before the default expire date - if ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) { - $expires = min($userExpireDate, $defaultExpires); - } else { - $expires = $userExpireDate; - } - } elseif ($defaultExpires && !empty($defaultExpireSettings['enforceExpireDate'])) { - $expires = $defaultExpires; - } - - return $expires; - } - - /** - * Strips away a potential file names and trailing slashes: - * - http://localhost - * - http://localhost/ - * - http://localhost/index.php - * - http://localhost/index.php/s/{shareToken} - * - * all return: http://localhost - * - * @param string $remote - * @return string - */ - protected static function fixRemoteURL($remote) { - $remote = str_replace('\\', '/', $remote); - if ($fileNamePosition = strpos($remote, '/index.php')) { - $remote = substr($remote, 0, $fileNamePosition); - } - $remote = rtrim($remote, '/'); - - return $remote; - } - - /** - * check if two federated cloud IDs refer to the same user - * - * @param string $user1 - * @param string $server1 - * @param string $user2 - * @param string $server2 - * @return bool true if both users and servers are the same - */ - public static function isSameUserOnSameServer($user1, $server1, $user2, $server2) { - $normalizedServer1 = strtolower(Share::removeProtocolFromUrl($server1)); - $normalizedServer2 = strtolower(Share::removeProtocolFromUrl($server2)); - - if (rtrim($normalizedServer1, '/') === rtrim($normalizedServer2, '/')) { - // FIXME this should be a method in the user management instead - Util::emitHook( - '\OCA\Files_Sharing\API\Server2Server', - 'preLoginNameUsedAsUserName', - ['uid' => &$user1] - ); - Util::emitHook( - '\OCA\Files_Sharing\API\Server2Server', - 'preLoginNameUsedAsUserName', - ['uid' => &$user2] - ); - - if ($user1 === $user2) { - return true; - } - } - - return false; - } - - public static function getTokenLength(): int { - $config = Server::get(IAppConfig::class); - $tokenLength = $config->getValueInt('core', 'shareapi_token_length', self::DEFAULT_TOKEN_LENGTH); - $tokenLength = $tokenLength ?: self::DEFAULT_TOKEN_LENGTH; - - // Token length should be within the defined min and max limits - return max(self::MIN_TOKEN_LENGTH, min($tokenLength, self::MAX_TOKEN_LENGTH)); - } -} diff --git a/lib/private/Share20/Manager.php b/lib/private/Share20/Manager.php index a1442a77211..1d72ec63cb0 100644 --- a/lib/private/Share20/Manager.php +++ b/lib/private/Share20/Manager.php @@ -12,7 +12,7 @@ use OC\Core\AppInfo\ConfigLexicon; use OC\Files\Filesystem; use OC\Files\Mount\MoveableMount; use OC\KnownUser\KnownUserService; -use OC\Share\Helper; +use OC\Share\Constants as ShareConstants; use OC\Share20\Exception\ProviderException; use OCA\Circles\Api\v1\Circles; use OCA\Files_Sharing\AppInfo\Application; @@ -1884,10 +1884,18 @@ class Manager implements IManager { } } + private function getTokenLength(): int { + $tokenLength = $this->appConfig->getValueInt('core', 'shareapi_token_length', ShareConstants::DEFAULT_TOKEN_LENGTH); + $tokenLength = $tokenLength ?: ShareConstants::DEFAULT_TOKEN_LENGTH; + + // Token length should be within the defined min and max limits + return max(ShareConstants::MIN_TOKEN_LENGTH, min($tokenLength, ShareConstants::MAX_TOKEN_LENGTH)); + } + #[Override] public function generateToken(): string { // Initial token length - $tokenLength = Helper::getTokenLength(); + $tokenLength = $this->getTokenLength(); do { $tokenExists = false; @@ -1915,7 +1923,7 @@ class Manager implements IManager { $tokenLength++; // Check if the token length exceeds the maximum allowed length - if ($tokenLength > \OC\Share\Constants::MAX_TOKEN_LENGTH) { + if ($tokenLength > ShareConstants::MAX_TOKEN_LENGTH) { throw new ShareTokenException('Unable to generate a unique share token. Maximum token length exceeded.'); } } diff --git a/lib/private/StreamImage.php b/lib/private/StreamImage.php index 511a67bdc8a..00f14212c57 100644 --- a/lib/private/StreamImage.php +++ b/lib/private/StreamImage.php @@ -9,6 +9,7 @@ namespace OC; use OCP\IImage; use OCP\IStreamImage; +use Override; /** * Only useful when dealing with transferring streamed previews from an external @@ -21,112 +22,133 @@ class StreamImage implements IStreamImage { /** @param resource $stream */ public function __construct( private $stream, - private string $mimeType, + private ?string $mimeType, private int $width, private int $height, ) { } - /** @inheritDoc */ + #[Override] public function valid(): bool { return is_resource($this->stream); } - /** @inheritDoc */ + #[Override] public function mimeType(): ?string { return $this->mimeType; } - /** @inheritDoc */ + #[Override] public function width(): int { return $this->width; } - /** @inheritDoc */ + #[Override] public function height(): int { return $this->height; } + #[Override] public function widthTopLeft(): int { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function heightTopLeft(): int { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function show(?string $mimeType = null): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function save(?string $filePath = null, ?string $mimeType = null): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function resource() { return $this->stream; } + #[Override] public function dataMimeType(): ?string { return $this->mimeType; } + #[Override] public function data(): ?string { return ''; } + #[Override] public function getOrientation(): int { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function fixOrientation(): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function resize(int $maxSize): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function preciseResize(int $width, int $height): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function centerCrop(int $size = 0): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function crop(int $x, int $y, int $w, int $h): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function fitIn(int $maxWidth, int $maxHeight): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function scaleDownToFit(int $maxWidth, int $maxHeight): bool { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function copy(): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function cropCopy(int $x, int $y, int $w, int $h): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function preciseResizeCopy(int $width, int $height): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function resizeCopy(int $maxSize): IImage { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function loadFromData(string $str): \GdImage|false { throw new \BadMethodCallException('Not implemented'); } + #[Override] public function readExif(string $data): void { throw new \BadMethodCallException('Not implemented'); } diff --git a/lib/private/Support/Subscription/Registry.php b/lib/private/Support/Subscription/Registry.php index dec641966b3..862f5647cf1 100644 --- a/lib/private/Support/Subscription/Registry.php +++ b/lib/private/Support/Subscription/Registry.php @@ -8,28 +8,25 @@ declare(strict_types=1); */ namespace OC\Support\Subscription; -use OCP\AppFramework\QueryException; use OCP\IConfig; use OCP\IGroupManager; -use OCP\IServerContainer; use OCP\IUserManager; use OCP\Notification\IManager; use OCP\Support\Subscription\Exception\AlreadyRegisteredException; use OCP\Support\Subscription\IRegistry; use OCP\Support\Subscription\ISubscription; use OCP\Support\Subscription\ISupportedApps; +use Psr\Container\ContainerExceptionInterface; +use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; class Registry implements IRegistry { - /** @var ISubscription */ - private $subscription = null; - - /** @var string */ - private $subscriptionService = null; + private ?ISubscription $subscription = null; + private ?string $subscriptionService = null; public function __construct( private IConfig $config, - private IServerContainer $container, + private ContainerInterface $container, private IUserManager $userManager, private IGroupManager $groupManager, private LoggerInterface $logger, @@ -39,8 +36,8 @@ class Registry implements IRegistry { private function getSubscription(): ?ISubscription { if ($this->subscription === null && $this->subscriptionService !== null) { try { - $this->subscription = $this->container->query($this->subscriptionService); - } catch (QueryException $e) { + $this->subscription = $this->container->get($this->subscriptionService); + } catch (ContainerExceptionInterface) { // Ignore this } } @@ -52,7 +49,6 @@ class Registry implements IRegistry { * Register a subscription instance. In case it is called multiple times the * first one is used. * - * @param ISubscription $subscription * @throws AlreadyRegisteredException * * @since 17.0.0 diff --git a/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php b/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php index 1f1f991de3f..48a2cd256a8 100644 --- a/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php +++ b/lib/private/TaskProcessing/RemoveOldTasksBackgroundJob.php @@ -12,6 +12,7 @@ use OCP\BackgroundJob\TimedJob; use OCP\Files\AppData\IAppDataFactory; use OCP\Files\IAppData; use OCP\Files\NotFoundException; +use Override; use Psr\Log\LoggerInterface; class RemoveOldTasksBackgroundJob extends TimedJob { @@ -31,9 +32,7 @@ class RemoveOldTasksBackgroundJob extends TimedJob { $this->appData = $appDataFactory->get('core'); } - /** - * @inheritDoc - */ + #[Override] protected function run($argument): void { try { iterator_to_array($this->taskProcessingManager->cleanupTaskProcessingTaskFiles()); @@ -47,12 +46,12 @@ class RemoveOldTasksBackgroundJob extends TimedJob { } try { iterator_to_array($this->taskProcessingManager->clearFilesOlderThan($this->appData->getFolder('text2image'))); - } catch (NotFoundException $e) { + } catch (NotFoundException) { // noop } try { iterator_to_array($this->taskProcessingManager->clearFilesOlderThan($this->appData->getFolder('audio2text'))); - } catch (NotFoundException $e) { + } catch (NotFoundException) { // noop } } diff --git a/lib/private/TempManager.php b/lib/private/TempManager.php index 29c4ea7ccfa..052b1845add 100644 --- a/lib/private/TempManager.php +++ b/lib/private/TempManager.php @@ -17,11 +17,9 @@ use Psr\Log\LoggerInterface; class TempManager implements ITempManager { /** @var string[] Current temporary files and folders, used for cleanup */ - protected $current = []; - /** @var string i.e. /tmp on linux systems */ - protected $tmpBaseDir; - /** @var IniGetWrapper */ - protected $iniGetWrapper; + protected array $current = []; + /** @var ?string i.e. /tmp on linux systems */ + protected ?string $tmpBaseDir = null; /** Prefix */ public const TMP_PREFIX = 'oc_tmp_'; @@ -29,9 +27,8 @@ class TempManager implements ITempManager { public function __construct( protected LoggerInterface $log, protected IConfig $config, - IniGetWrapper $iniGetWrapper, + protected IniGetWrapper $iniGetWrapper, ) { - $this->iniGetWrapper = $iniGetWrapper; $this->tmpBaseDir = $this->getTempBaseDir(); } @@ -149,7 +146,7 @@ class TempManager implements ITempManager { * @return string Path to the temporary directory or null * @throws \UnexpectedValueException */ - public function getTempBaseDir() { + public function getTempBaseDir(): string { if ($this->tmpBaseDir) { return $this->tmpBaseDir; } diff --git a/lib/private/URLGenerator.php b/lib/private/URLGenerator.php index 5269f31019a..0debd9ba99a 100644 --- a/lib/private/URLGenerator.php +++ b/lib/private/URLGenerator.php @@ -21,12 +21,8 @@ use OCP\IUserSession; use OCP\Server; use RuntimeException; -/** - * Class to generate URLs - */ class URLGenerator implements IURLGenerator { - /** @var null|string */ - private $baseUrl = null; + private ?string $baseUrl = null; private ?IAppManager $appManager = null; private ?INavigationManager $navigationManager = null; diff --git a/lib/private/User/Database.php b/lib/private/User/Database.php index e64a1cc88f9..7877deff62f 100644 --- a/lib/private/User/Database.php +++ b/lib/private/User/Database.php @@ -52,14 +52,8 @@ class Database extends ABackend implements use TTransactional; - /** - * \OC\User\Database constructor. - * - * @param IEventDispatcher $eventDispatcher - * @param string $table - */ public function __construct( - $eventDispatcher = null, + ?IEventDispatcher $eventDispatcher = null, private string $table = 'users', ) { $this->cache = new CappedMemoryCache(); diff --git a/lib/private/User/LazyUser.php b/lib/private/User/LazyUser.php index a3a681a8fcf..f7b0dd23c6c 100644 --- a/lib/private/User/LazyUser.php +++ b/lib/private/User/LazyUser.php @@ -41,7 +41,7 @@ class LazyUser implements IUser { return $this->user; } - public function getUID() { + public function getUID(): string { return $this->uid; } diff --git a/lib/private/User/Manager.php b/lib/private/User/Manager.php index 6fae93226da..36b9f80dd99 100644 --- a/lib/private/User/Manager.php +++ b/lib/private/User/Manager.php @@ -375,7 +375,7 @@ class Manager extends PublicEmitter implements IUserManager { * @throws \InvalidArgumentException * @throws HintException */ - public function createUser($uid, $password) { + public function createUser($uid, $password): IUser|false { // DI injection is not used here as IRegistry needs the user manager itself for user count and thus it would create a cyclic dependency /** @var IAssertion $assertion */ $assertion = Server::get(IAssertion::class); @@ -406,11 +406,9 @@ class Manager extends PublicEmitter implements IUserManager { /** * @param string $uid * @param string $password - * @param UserInterface $backend - * @return IUser|false * @throws \InvalidArgumentException */ - public function createUserFromBackend($uid, $password, UserInterface $backend) { + public function createUserFromBackend($uid, $password, UserInterface $backend): IUser|false { $l = Util::getL10N('lib'); $this->validateUserId($uid, true); diff --git a/lib/private/User/User.php b/lib/private/User/User.php index 14ac2c48926..8de3486a9b9 100644 --- a/lib/private/User/User.php +++ b/lib/private/User/User.php @@ -52,33 +52,21 @@ class User implements IUser { private IConfig $config; private IURLGenerator $urlGenerator; + protected ?IAccountManager $accountManager = null; - /** @var IAccountManager */ - protected $accountManager; - - /** @var string|null */ - private $displayName; - - /** @var bool|null */ - private $enabled; - - /** @var string */ - private $home; + private ?string $displayName = null; + private ?bool $enabled = null; + private ?string $home = null; private ?int $lastLogin = null; private ?int $firstLogin = null; + private ?IAvatarManager $avatarManager = null; - /** @var IAvatarManager */ - private $avatarManager; - - /** - * @param Emitter|\OC\User\Manager|null $emitter - */ public function __construct( private string $uid, private ?UserInterface $backend, private IEventDispatcher $dispatcher, - private $emitter = null, + private Emitter|Manager|null $emitter = null, ?IConfig $config = null, $urlGenerator = null, ) { @@ -86,21 +74,14 @@ class User implements IUser { $this->urlGenerator = $urlGenerator ?? Server::get(IURLGenerator::class); } - /** - * get the user id - * - * @return string - */ - public function getUID() { + public function getUID(): string { return $this->uid; } /** - * get the display name for the user, if no specific display name is set it will fallback to the user id - * - * @return string + * Get the display name for the user, if no specific display name is set it will fallback to the user id */ - public function getDisplayName() { + public function getDisplayName(): string { if ($this->displayName === null) { $displayName = ''; if ($this->backend && $this->backend->implementsActions(Backend::GET_DISPLAYNAME)) { @@ -121,15 +102,14 @@ class User implements IUser { } /** - * set the displayname for the user + * Set the displayname for the user * * @param string $displayName - * @return bool * * @since 25.0.0 Throw InvalidArgumentException * @throws \InvalidArgumentException */ - public function setDisplayName($displayName) { + public function setDisplayName($displayName): bool { $displayName = trim($displayName); $oldDisplayName = $this->getDisplayName(); if ($this->backend->implementsActions(Backend::SET_DISPLAYNAME) && !empty($displayName) && $displayName !== $oldDisplayName) { @@ -148,7 +128,7 @@ class User implements IUser { /** * @inheritDoc */ - public function setEMailAddress($mailAddress) { + public function setEMailAddress($mailAddress): void { $this->setSystemEMailAddress($mailAddress); } @@ -254,10 +234,8 @@ class User implements IUser { /** * Delete the user - * - * @return bool */ - public function delete() { + public function delete(): bool { if ($this->backend === null) { Server::get(LoggerInterface::class)->error('Cannot delete user: No backend set'); return false; @@ -344,9 +322,8 @@ class User implements IUser { * * @param string $password * @param string $recoveryPassword for the encryption app to reset encryption keys - * @return bool */ - public function setPassword($password, $recoveryPassword = null) { + public function setPassword($password, $recoveryPassword = null): bool { $this->dispatcher->dispatchTyped(new BeforePasswordUpdatedEvent($this, $password, $recoveryPassword)); if ($this->emitter) { $this->emitter->emit('\OC\User', 'preSetPassword', [$this, $password, $recoveryPassword]); @@ -384,11 +361,9 @@ class User implements IUser { } /** - * get the users home folder to mount - * - * @return string + * Get the users home folder to mount */ - public function getHome() { + public function getHome(): string { if (!$this->home) { /** @psalm-suppress UndefinedInterfaceMethod Once we get rid of the legacy implementsActions, psalm won't complain anymore */ if (($this->backend instanceof IGetHomeBackend || $this->backend->implementsActions(Backend::GET_HOME)) && $home = $this->backend->getHome($this->uid)) { @@ -402,10 +377,8 @@ class User implements IUser { /** * Get the name of the backend class the user is connected with - * - * @return string */ - public function getBackendClassName() { + public function getBackendClassName(): string { if ($this->backend instanceof IUserBackend) { return $this->backend->getBackendName(); } @@ -463,11 +436,9 @@ class User implements IUser { } /** - * check if the user is enabled - * - * @return bool + * Check if the user is enabled */ - public function isEnabled() { + public function isEnabled(): bool { $queryDatabaseValue = function (): bool { if ($this->enabled === null) { $enabled = $this->config->getUserValue($this->uid, 'core', 'enabled', 'true'); @@ -512,12 +483,11 @@ class User implements IUser { } /** - * get the users email address + * Get the users email address * - * @return string|null * @since 9.0.0 */ - public function getEMailAddress() { + public function getEMailAddress(): ?string { return $this->getPrimaryEMailAddress() ?? $this->getSystemEMailAddress(); } @@ -540,10 +510,9 @@ class User implements IUser { /** * get the users' quota * - * @return string * @since 9.0.0 */ - public function getQuota() { + public function getQuota(): string { // allow apps to modify the user quota by hooking into the event $event = new GetQuotaEvent($this); $this->dispatcher->dispatchTyped($event); @@ -585,14 +554,13 @@ class User implements IUser { } /** - * set the users' quota + * Set the users' quota * * @param string $quota - * @return void * @throws InvalidArgumentException * @since 9.0.0 */ - public function setQuota($quota) { + public function setQuota($quota): void { $oldQuota = $this->config->getUserValue($this->uid, 'files', 'quota', ''); if ($quota !== 'none' && $quota !== 'default') { $bytesQuota = Util::computerFileSize($quota); @@ -633,10 +601,9 @@ class User implements IUser { * get the avatar image if it exists * * @param int $size - * @return IImage|null * @since 9.0.0 */ - public function getAvatarImage($size) { + public function getAvatarImage($size): ?IImage { // delay the initialization if (is_null($this->avatarManager)) { $this->avatarManager = Server::get(IAvatarManager::class); @@ -654,10 +621,9 @@ class User implements IUser { /** * get the federation cloud id * - * @return string * @since 9.0.0 */ - public function getCloudId() { + public function getCloudId(): string { $uid = $this->getUID(); $server = rtrim($this->urlGenerator->getAbsoluteURL('/'), '/'); if (str_ends_with($server, '/index.php')) { @@ -675,7 +641,7 @@ class User implements IUser { return $url; } - public function triggerChange($feature, $value = null, $oldValue = null) { + public function triggerChange($feature, $value = null, $oldValue = null): void { $this->dispatcher->dispatchTyped(new UserChangedEvent($this, $feature, $value, $oldValue)); if ($this->emitter) { $this->emitter->emit('\OC\User', 'changeUser', [$this, $feature, $value, $oldValue]); diff --git a/lib/private/legacy/OC_App.php b/lib/private/legacy/OC_App.php index 2529c1dce5c..5dd7bfe3b7d 100644 --- a/lib/private/legacy/OC_App.php +++ b/lib/private/legacy/OC_App.php @@ -41,8 +41,8 @@ use function OCP\Log\logger; * upgrading and removing apps. */ class OC_App { - private static $altLogin = []; - private static $alreadyRegistered = []; + private static array $altLogin = []; + private static array $alreadyRegistered = []; public const supportedApp = 300; public const officialApp = 200; @@ -63,8 +63,6 @@ class OC_App { /** * Check if an app is loaded * - * @param string $app - * @return bool * @deprecated 27.0.0 use IAppManager::isAppLoaded */ public static function isAppLoaded(string $app): bool { @@ -75,7 +73,6 @@ class OC_App { * loads all apps * * @param string[] $types - * @return bool * * This function walks through the Nextcloud directory and loads all apps * it can find. A directory contains an app if the file /appinfo/info.xml @@ -96,7 +93,6 @@ class OC_App { /** * load a single app * - * @param string $app * @throws Exception * @deprecated 27.0.0 use IAppManager::loadApp */ @@ -106,11 +102,8 @@ class OC_App { /** * @internal - * @param string $app - * @param string $path - * @param bool $force */ - public static function registerAutoloading(string $app, string $path, bool $force = false) { + public static function registerAutoloading(string $app, string $path, bool $force = false): void { $key = $app . '-' . $path; if (!$force && isset(self::$alreadyRegistered[$key])) { return; @@ -135,11 +128,8 @@ class OC_App { } /** - * check if an app is of a specific type + * Check if an app is of a specific type * - * @param string $app - * @param array $types - * @return bool * @deprecated 27.0.0 use IAppManager::isType */ public static function isType(string $app, array $types): bool { @@ -149,7 +139,7 @@ class OC_App { /** * read app types from info.xml and cache them in the database */ - public static function setAppTypes(string $app) { + public static function setAppTypes(string $app): void { $appManager = Server::get(IAppManager::class); $appData = $appManager->getAppInfo($app); if (!is_array($appData)) { @@ -211,16 +201,13 @@ class OC_App { /** * enables an app * - * @param string $appId * @param array $groups (optional) when set, only these groups will have access to the app * @throws \Exception - * @return void * @deprecated 32.0.0 Use the installer and the app manager instead * * This function set an app as enabled in appconfig. */ - public function enable(string $appId, - array $groups = []) { + public function enable(string $appId, array $groups = []): void { // Check if app is already downloaded /** @var Installer $installer */ $installer = Server::get(Installer::class); @@ -274,8 +261,6 @@ class OC_App { /** * get the id of loaded app - * - * @return string */ public static function getCurrentApp(): string { if (\OC::$CLI) { @@ -306,10 +291,9 @@ class OC_App { } /** - * @param array $entry * @deprecated 20.0.0 Please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface */ - public static function registerLogIn(array $entry) { + public static function registerLogIn(array $entry): void { Server::get(LoggerInterface::class)->debug('OC_App::registerLogIn() is deprecated, please register your alternative login option using the registerAlternativeLogin() on the RegistrationContext in your Application class implementing the OCP\Authentication\IAlternativeLogin interface'); self::$altLogin[] = $entry; } @@ -387,8 +371,6 @@ class OC_App { /** * List all apps, this is used in apps.php - * - * @return array */ public function listAllApps(): array { $appManager = Server::get(IAppManager::class); @@ -559,7 +541,7 @@ class OC_App { /** * @deprecated 32.0.0 Use the IJobList directly instead */ - public static function setupBackgroundJobs(array $jobs) { + public static function setupBackgroundJobs(array $jobs): void { $queue = Server::get(IJobList::class); foreach ($jobs as $job) { $queue->add($job); @@ -567,12 +549,9 @@ class OC_App { } /** - * @param IConfig $config - * @param IL10N $l - * @param array $info * @throws \Exception */ - public static function checkAppDependencies(IConfig $config, IL10N $l, array $info, bool $ignoreMax) { + public static function checkAppDependencies(IConfig $config, IL10N $l, array $info, bool $ignoreMax): void { $dependencyAnalyzer = Server::get(DependencyAnalyzer::class); $missing = $dependencyAnalyzer->analyze($info, $ignoreMax); if (!empty($missing)) { diff --git a/lib/private/legacy/OC_User.php b/lib/private/legacy/OC_User.php index 8d0f7033208..abdb37b737c 100644 --- a/lib/private/legacy/OC_User.php +++ b/lib/private/legacy/OC_User.php @@ -142,11 +142,8 @@ class OC_User { * has already happened (e.g. via Single Sign On). * * Log in a user and regenerate a new session. - * - * @param IApacheBackend $backend - * @return bool */ - public static function loginWithApache(IApacheBackend $backend) { + public static function loginWithApache(IApacheBackend $backend): bool { $uid = $backend->getCurrentUserId(); $run = true; OC_Hook::emit('OC_User', 'pre_login', ['run' => &$run, 'uid' => $uid, 'backend' => $backend]); @@ -225,12 +222,12 @@ class OC_User { /** * Verify with Apache whether user is authenticated. * - * @return boolean|null - * true: authenticated - * false: not authenticated - * null: not handled / no backend available + * @return bool|null + * true: authenticated + * false: not authenticated + * null: not handled / no backend available */ - public static function handleApacheAuth() { + public static function handleApacheAuth(): ?bool { $backend = self::findFirstActiveUsedBackend(); if ($backend) { OC_App::loadApps(); @@ -250,10 +247,8 @@ class OC_User { /** * Sets user id for session and triggers emit - * - * @param string $uid */ - public static function setUserId($uid) { + public static function setUserId(?string $uid): void { $userSession = Server::get(IUserSession::class); $userManager = Server::get(IUserManager::class); if ($user = $userManager->get($uid)) { @@ -264,30 +259,23 @@ class OC_User { } /** - * set incognito mode, e.g. if a user wants to open a public link - * - * @param bool $status + * Set incognito mode, e.g. if a user wants to open a public link */ - public static function setIncognitoMode($status) { + public static function setIncognitoMode(bool $status): void { self::$incognitoMode = $status; } /** - * get incognito mode status - * - * @return bool + * Get incognito mode status */ - public static function isIncognitoMode() { + public static function isIncognitoMode(): bool { return self::$incognitoMode; } /** * Returns the current logout URL valid for the currently logged-in user - * - * @param IURLGenerator $urlGenerator - * @return string */ - public static function getLogoutUrl(IURLGenerator $urlGenerator) { + public static function getLogoutUrl(IURLGenerator $urlGenerator): string { $backend = self::findFirstActiveUsedBackend(); if ($backend) { return $backend->getLogoutUrl(); @@ -311,9 +299,8 @@ class OC_User { * Check if the user is an admin user * * @param string $uid uid of the admin - * @return bool */ - public static function isAdminUser($uid) { + public static function isAdminUser(string $uid): bool { $user = Server::get(IUserManager::class)->get($uid); $isAdmin = $user && Server::get(IGroupManager::class)->isAdmin($user->getUID()); return $isAdmin && self::$incognitoMode === false; @@ -325,7 +312,7 @@ class OC_User { * * @return string|false uid or false */ - public static function getUser() { + public static function getUser(): string|false { $uid = Server::get(ISession::class)?->get('user_id'); if (!is_null($uid) && self::$incognitoMode === false) { return $uid; @@ -340,11 +327,10 @@ class OC_User { * @param string $uid The username * @param string $password The new password * @param string $recoveryPassword for the encryption app to reset encryption keys - * @return bool * * Change the password of a user */ - public static function setPassword($uid, $password, $recoveryPassword = null) { + public static function setPassword(string $uid, string $password, ?string $recoveryPassword = null): bool { $user = Server::get(IUserManager::class)->get($uid); if ($user) { return $user->setPassword($password, $recoveryPassword); @@ -358,7 +344,7 @@ class OC_User { * * @return IApacheBackend|null if no backend active, otherwise OCP\Authentication\IApacheBackend */ - private static function findFirstActiveUsedBackend() { + private static function findFirstActiveUsedBackend(): ?IApacheBackend { foreach (Server::get(IUserManager::class)->getBackends() as $backend) { if ($backend instanceof IApacheBackend) { if ($backend->isSessionActive()) { diff --git a/lib/public/Files/Cache/IUpdater.php b/lib/public/Files/Cache/IUpdater.php index 2224da5c67c..65c4ce3bfdb 100644 --- a/lib/public/Files/Cache/IUpdater.php +++ b/lib/public/Files/Cache/IUpdater.php @@ -40,7 +40,6 @@ interface IUpdater { /** * Remove $path from the cache and update the size, etag and mtime of the parent folders * - * @param string $path * @since 9.0.0 */ public function remove(string $path): void; @@ -48,9 +47,6 @@ interface IUpdater { /** * Rename a file or folder in the cache and update the size, etag and mtime of the parent folders * - * @param IStorage $sourceStorage - * @param string $source - * @param string $target * @since 9.0.0 */ public function renameFromStorage(IStorage $sourceStorage, string $source, string $target): void; diff --git a/lib/public/IServerContainer.php b/lib/public/IServerContainer.php index 1d314f72dc8..8cab6bc437e 100644 --- a/lib/public/IServerContainer.php +++ b/lib/public/IServerContainer.php @@ -45,7 +45,7 @@ interface IServerContainer extends ContainerInterface, IContainer { public function getRequest(); /** - * Returns the root folder of ownCloud's data directory + * Returns the root folder of Nextcloud's data directory * * @return \OCP\Files\IRootFolder * @since 6.0.0 - between 6.0.0 and 8.0.0 this returned \OCP\Files\Folder diff --git a/lib/public/Remote/IInstance.php b/lib/public/Remote/IInstance.php index 6186c2e1819..f25328841c0 100644 --- a/lib/public/Remote/IInstance.php +++ b/lib/public/Remote/IInstance.php @@ -6,12 +6,15 @@ */ namespace OCP\Remote; +use OCP\AppFramework\Attribute\Consumable; + /** * Provides some basic info about a remote Nextcloud instance * * @since 13.0.0 * @deprecated 23.0.0 */ +#[Consumable(since: '13.0.0')] interface IInstance { /** * @return string The url of the remote server without protocol @@ -19,7 +22,7 @@ interface IInstance { * @since 13.0.0 * @deprecated 23.0.0 */ - public function getUrl(); + public function getUrl(): string; /** * @return string The of the remote server with protocol @@ -27,7 +30,7 @@ interface IInstance { * @since 13.0.0 * @deprecated 23.0.0 */ - public function getFullUrl(); + public function getFullUrl(): string; /** * @return string The full version string in '13.1.2.3' format @@ -35,15 +38,15 @@ interface IInstance { * @since 13.0.0 * @deprecated 23.0.0 */ - public function getVersion(); + public function getVersion(): string; /** - * @return string 'http' or 'https' + * @return 'http'|'https' * * @since 13.0.0 * @deprecated 23.0.0 */ - public function getProtocol(); + public function getProtocol(): string; /** * Check that the remote server is installed and not in maintenance mode @@ -53,5 +56,5 @@ interface IInstance { * * @return bool */ - public function isActive(); + public function isActive(): bool; } diff --git a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php index 2018dc1a634..0de94ded006 100644 --- a/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php +++ b/tests/lib/Authentication/TwoFactorAuth/RegistryTest.php @@ -24,14 +24,9 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class RegistryTest extends TestCase { - /** @var ProviderUserAssignmentDao|MockObject */ - private $dao; - - /** @var IEventDispatcher|MockObject */ - private $dispatcher; - - /** @var Registry */ - private $registry; + private ProviderUserAssignmentDao&MockObject $dao; + private IEventDispatcher&MockObject $dispatcher; + private Registry $registry; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Collaboration/Collaborators/MailPluginTest.php b/tests/lib/Collaboration/Collaborators/MailPluginTest.php index 9672bbfcd6b..cf39642280c 100644 --- a/tests/lib/Collaboration/Collaborators/MailPluginTest.php +++ b/tests/lib/Collaboration/Collaborators/MailPluginTest.php @@ -23,35 +23,22 @@ use OCP\IUser; use OCP\IUserManager; use OCP\IUserSession; use OCP\Share\IShare; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; use Test\Traits\EmailValidatorTrait; class MailPluginTest extends TestCase { use EmailValidatorTrait; - /** @var IConfig|\PHPUnit\Framework\MockObject\MockObject */ - protected $config; - - /** @var IManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $contactsManager; - - /** @var ICloudIdManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $cloudIdManager; - - /** @var MailPlugin */ - protected $plugin; - - /** @var SearchResult */ - protected $searchResult; - - /** @var IGroupManager|\PHPUnit\Framework\MockObject\MockObject */ - protected $groupManager; - - /** @var KnownUserService|\PHPUnit\Framework\MockObject\MockObject */ - protected $knownUserService; - - /** @var IUserSession|\PHPUnit\Framework\MockObject\MockObject */ - protected $userSession; + protected IConfig&MockObject $config; + protected IManager&MockObject $contactsManager; + protected ICloudIdManager $cloudIdManager; + protected MailPlugin $plugin; + protected SearchResult $searchResult; + protected IGroupManager&MockObject $groupManager; + protected KnownUserService&MockObject $knownUserService; + protected IUserSession&MockObject $userSession; protected function setUp(): void { parent::setUp(); @@ -86,18 +73,8 @@ class MailPluginTest extends TestCase { ); } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param bool $shareeEnumeration - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - * @param bool $validEmail - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchEmail')] - public function testSearchEmail($searchTerm, $contacts, $shareeEnumeration, $expectedResult, $expectedExactIdMatch, $expectedMoreResults, $validEmail): void { + #[DataProvider('dataSearchEmail')] + public function testSearchEmail(string $searchTerm, array $contacts, bool $shareeEnumeration, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults, bool $validEmail): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -564,17 +541,8 @@ class MailPluginTest extends TestCase { ]; } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param bool $shareeEnumeration - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchUser')] - public function testSearchUser($searchTerm, $contacts, $shareeEnumeration, $expectedResult, $expectedExactIdMatch, $expectedMoreResults): void { + #[DataProvider('dataSearchUser')] + public function testSearchUser(string $searchTerm, array $contacts, bool $shareeEnumeration, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -860,18 +828,8 @@ class MailPluginTest extends TestCase { ]; } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - * @param array $userToGroupMapping - * @param bool $validEmail - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchEmailGroupsOnly')] - public function testSearchEmailGroupsOnly($searchTerm, $contacts, $expectedResult, $expectedExactIdMatch, $expectedMoreResults, $userToGroupMapping, $validEmail): void { + #[DataProvider('dataSearchEmailGroupsOnly')] + public function testSearchEmailGroupsOnly(string $searchTerm, array $contacts, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults, array $userToGroupMapping, bool $validEmail): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -995,17 +953,8 @@ class MailPluginTest extends TestCase { ]; } - /** - * - * @param string $searchTerm - * @param array $contacts - * @param array $expectedResult - * @param bool $expectedExactIdMatch - * @param bool $expectedMoreResults - * @param array $userToGroupMapping - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataSearchUserGroupsOnly')] - public function testSearchUserGroupsOnly($searchTerm, $contacts, $expectedResult, $expectedExactIdMatch, $expectedMoreResults, $userToGroupMapping): void { + #[DataProvider('dataSearchUserGroupsOnly')] + public function testSearchUserGroupsOnly(string $searchTerm, array $contacts, array $expectedResult, bool $expectedExactIdMatch, bool $expectedMoreResults, array $userToGroupMapping): void { $this->config->expects($this->any()) ->method('getAppValue') ->willReturnCallback( @@ -1021,8 +970,7 @@ class MailPluginTest extends TestCase { $this->instantiatePlugin(IShare::TYPE_USER); - /** @var IUser|\PHPUnit\Framework\MockObject\MockObject */ - $currentUser = $this->createMock('\OCP\IUser'); + $currentUser = $this->createMock(\OCP\IUser::class); $currentUser->expects($this->any()) ->method('getUID') diff --git a/tests/lib/ContactsManagerTest.php b/tests/lib/ContactsManagerTest.php index ab18d820447..32aa1141ff0 100644 --- a/tests/lib/ContactsManagerTest.php +++ b/tests/lib/ContactsManagerTest.php @@ -12,8 +12,7 @@ use OCP\Constants; use OCP\IAddressBook; class ContactsManagerTest extends \Test\TestCase { - /** @var ContactsManager */ - private $cm; + private ContactsManager $cm; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/DateTimeFormatterTest.php b/tests/lib/DateTimeFormatterTest.php index 0d4117fcbc2..26ff381bf0a 100644 --- a/tests/lib/DateTimeFormatterTest.php +++ b/tests/lib/DateTimeFormatterTest.php @@ -12,8 +12,7 @@ use OC\DateTimeFormatter; use OCP\Util; class DateTimeFormatterTest extends TestCase { - /** @var DateTimeFormatter */ - protected $formatter; + protected DateTimeFormatter $formatter; protected static $oneMinute = 60; protected static $oneHour = 3600; protected static $oneDay; diff --git a/tests/lib/Diagnostics/EventLoggerTest.php b/tests/lib/Diagnostics/EventLoggerTest.php index 8bb7b0f9b81..aca536170db 100644 --- a/tests/lib/Diagnostics/EventLoggerTest.php +++ b/tests/lib/Diagnostics/EventLoggerTest.php @@ -15,8 +15,7 @@ use Psr\Log\LoggerInterface; use Test\TestCase; class EventLoggerTest extends TestCase { - /** @var EventLogger */ - private $logger; + private EventLogger $logger; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Diagnostics/QueryLoggerTest.php b/tests/lib/Diagnostics/QueryLoggerTest.php index e122ebcee05..9f869919e51 100644 --- a/tests/lib/Diagnostics/QueryLoggerTest.php +++ b/tests/lib/Diagnostics/QueryLoggerTest.php @@ -12,8 +12,7 @@ use OC\Diagnostics\QueryLogger; use Test\TestCase; class QueryLoggerTest extends TestCase { - /** @var QueryLogger */ - private $logger; + private QueryLogger $logger; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Encryption/Keys/StorageTest.php b/tests/lib/Encryption/Keys/StorageTest.php index d3fa79eac81..a1e6f6d351a 100644 --- a/tests/lib/Encryption/Keys/StorageTest.php +++ b/tests/lib/Encryption/Keys/StorageTest.php @@ -17,20 +17,11 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class StorageTest extends TestCase { - /** @var Storage */ - protected $storage; - - /** @var MockObject|Util */ - protected $util; - - /** @var MockObject|View */ - protected $view; - - /** @var MockObject|IConfig */ - protected $config; - - /** @var MockObject|ICrypto */ - protected $crypto; + protected Storage $storage; + protected Util&MockObject $util; + protected View&MockObject $view; + protected IConfig&MockObject $config; + protected ICrypto&MockObject $crypto; private array $mkdirStack = []; diff --git a/tests/lib/Files/Cache/HomeCacheTest.php b/tests/lib/Files/Cache/HomeCacheTest.php index 4bbae9aaa87..1aa8e93173d 100644 --- a/tests/lib/Files/Cache/HomeCacheTest.php +++ b/tests/lib/Files/Cache/HomeCacheTest.php @@ -8,60 +8,38 @@ namespace Test\Files\Cache; -use OC\Files\Cache\HomeCache; use OC\Files\Storage\Home; use OC\User\User; +use OCP\Files\Cache\ICache; use OCP\ITempManager; use OCP\Server; +use PHPUnit\Framework\Attributes\Group; +use Test\TestCase; class DummyUser extends User { - /** - * @param string $uid - * @param string $home - */ public function __construct( - private $uid, - private $home, + private string $uid, + private string $home, ) { } - /** - * @return string - */ - public function getHome() { + public function getHome(): string { return $this->home; } /** * @return string */ - public function getUID() { + public function getUID(): string { return $this->uid; } } -/** - * Class HomeCacheTest - * - * - * @package Test\Files\Cache - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] -class HomeCacheTest extends \Test\TestCase { - /** - * @var Home $storage - */ - private $storage; - - /** - * @var HomeCache $cache - */ - private $cache; - - /** - * @var User $user - */ - private $user; +#[Group('DB')] +class HomeCacheTest extends TestCase { + private Home $storage; + private ICache $cache; + private User $user; protected function setUp(): void { parent::setUp(); diff --git a/tests/lib/Files/Storage/HomeTest.php b/tests/lib/Files/Storage/HomeTest.php index 2ca9737bf79..be1b435afb9 100644 --- a/tests/lib/Files/Storage/HomeTest.php +++ b/tests/lib/Files/Storage/HomeTest.php @@ -15,21 +15,17 @@ use OCP\ITempManager; use OCP\Server; class DummyUser extends User { - /** - * @param string $uid - * @param string $home - */ public function __construct( - private $uid, - private $home, + private readonly string $uid, + private readonly string $home, ) { } - public function getHome() { + public function getHome(): string { return $this->home; } - public function getUID() { + public function getUID(): string { return $this->uid; } } diff --git a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php index e5a4441a4fa..6e86ee71762 100644 --- a/tests/lib/Repair/Owncloud/CleanPreviewsTest.php +++ b/tests/lib/Repair/Owncloud/CleanPreviewsTest.php @@ -9,7 +9,7 @@ namespace Test\Repair\Owncloud; use OC\Repair\Owncloud\CleanPreviews; use OC\Repair\Owncloud\CleanPreviewsBackgroundJob; use OCP\BackgroundJob\IJobList; -use OCP\IConfig; +use OCP\IAppConfig; use OCP\IUser; use OCP\IUserManager; use OCP\Migration\IOutput; @@ -17,25 +17,22 @@ use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; class CleanPreviewsTest extends TestCase { - private IJobList&MockObject $jobList; private IUserManager&MockObject $userManager; - private IConfig&MockObject $config; - - /** @var CleanPreviews */ - private $repair; + private IAppConfig&MockObject $appConfig; + private CleanPreviews $repair; public function setUp(): void { parent::setUp(); $this->jobList = $this->createMock(IJobList::class); $this->userManager = $this->createMock(IUserManager::class); - $this->config = $this->createMock(IConfig::class); + $this->appConfig = $this->createMock(IAppConfig::class); $this->repair = new CleanPreviews( $this->jobList, $this->userManager, - $this->config + $this->appConfig ); } @@ -65,19 +62,18 @@ class CleanPreviewsTest extends TestCase { $jobListCalls[] = func_get_args(); }); - $this->config->expects($this->once()) - ->method('getAppValue') + $this->appConfig->expects($this->once()) + ->method('getValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), - $this->equalTo(false) )->willReturn(false); - $this->config->expects($this->once()) - ->method('setAppValue') + $this->appConfig->expects($this->once()) + ->method('setValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), - $this->equalTo(1) + $this->equalTo(true) ); $this->repair->run($this->createMock(IOutput::class)); @@ -95,15 +91,14 @@ class CleanPreviewsTest extends TestCase { $this->jobList->expects($this->never()) ->method($this->anything()); - $this->config->expects($this->once()) - ->method('getAppValue') + $this->appConfig->expects($this->once()) + ->method('getValueBool') ->with( $this->equalTo('core'), $this->equalTo('previewsCleanedUp'), - $this->equalTo(false) - )->willReturn('1'); - $this->config->expects($this->never()) - ->method('setAppValue'); + )->willReturn(true); + $this->appConfig->expects($this->never()) + ->method('setValueBool'); $this->repair->run($this->createMock(IOutput::class)); } diff --git a/tests/lib/Share/HelperTest.php b/tests/lib/Share/HelperTest.php deleted file mode 100644 index de3b407612b..00000000000 --- a/tests/lib/Share/HelperTest.php +++ /dev/null @@ -1,74 +0,0 @@ - false], 2000000000, 2000010000, 2000010000], - // no default expire date and no user defined expire date, return false - [['defaultExpireDateSet' => false], 2000000000, null, false], - // unenforced expire data and no user defined expire date, return false (because the default is not enforced) - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, null, false], - // enforced expire date and no user defined expire date, take default expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, null, 2000086400], - // unenforced expire date and user defined date > default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, 2000100000, 2000100000], - // unenforced expire date and user expire date < default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => false], 2000000000, 2000010000, 2000010000], - // enforced expire date and user expire date < default expire date, take users expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, 2000010000, 2000010000], - // enforced expire date and users expire date > default expire date, take default expire date - [['defaultExpireDateSet' => true, 'expireAfterDays' => 1, 'enforceExpireDate' => true], 2000000000, 2000100000, 2000086400], - ]; - } - - #[\PHPUnit\Framework\Attributes\DataProvider('expireDateProvider')] - public function testCalculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate, $expected): void { - $result = Helper::calculateExpireDate($defaultExpireSettings, $creationTime, $userExpireDate); - $this->assertSame($expected, $result); - } - - /** - * - * @param string $server1 - * @param string $server2 - * @param bool $expected - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataTestCompareServerAddresses')] - public function testIsSameUserOnSameServer($user1, $server1, $user2, $server2, $expected): void { - $this->assertSame($expected, - Helper::isSameUserOnSameServer($user1, $server1, $user2, $server2) - ); - } - - public static function dataTestCompareServerAddresses(): array { - return [ - ['user1', 'http://server1', 'user1', 'http://server1', true], - ['user1', 'https://server1', 'user1', 'http://server1', true], - ['user1', 'http://serVer1', 'user1', 'http://server1', true], - ['user1', 'http://server1/', 'user1', 'http://server1', true], - ['user1', 'server1', 'user1', 'http://server1', true], - ['user1', 'http://server1', 'user1', 'http://server2', false], - ['user1', 'https://server1', 'user1', 'http://server2', false], - ['user1', 'http://serVer1', 'user1', 'http://serer2', false], - ['user1', 'http://server1/', 'user1', 'http://server2', false], - ['user1', 'server1', 'user1', 'http://server2', false], - ['user1', 'http://server1', 'user2', 'http://server1', false], - ['user1', 'https://server1', 'user2', 'http://server1', false], - ['user1', 'http://serVer1', 'user2', 'http://server1', false], - ['user1', 'http://server1/', 'user2', 'http://server1', false], - ['user1', 'server1', 'user2', 'http://server1', false], - ]; - } -} diff --git a/tests/lib/Support/Subscription/RegistryTest.php b/tests/lib/Support/Subscription/RegistryTest.php index e6e83d6038b..52014200932 100644 --- a/tests/lib/Support/Subscription/RegistryTest.php +++ b/tests/lib/Support/Subscription/RegistryTest.php @@ -11,21 +11,20 @@ use OC\Support\Subscription\Registry; use OCP\IConfig; use OCP\IGroup; use OCP\IGroupManager; -use OCP\IServerContainer; use OCP\IUserManager; use OCP\Notification\IManager; use OCP\Support\Subscription\Exception\AlreadyRegisteredException; use OCP\Support\Subscription\ISubscription; use OCP\Support\Subscription\ISupportedApps; use PHPUnit\Framework\MockObject\MockObject; +use Psr\Container\ContainerInterface; use Psr\Log\LoggerInterface; use Test\TestCase; class RegistryTest extends TestCase { private Registry $registry; - private MockObject&IConfig $config; - private MockObject&IServerContainer $serverContainer; + private MockObject&ContainerInterface $serverContainer; private MockObject&IUserManager $userManager; private MockObject&IGroupManager $groupManager; private MockObject&LoggerInterface $logger; @@ -35,7 +34,7 @@ class RegistryTest extends TestCase { parent::setUp(); $this->config = $this->createMock(IConfig::class); - $this->serverContainer = $this->createMock(IServerContainer::class); + $this->serverContainer = $this->createMock(ContainerInterface::class); $this->userManager = $this->createMock(IUserManager::class); $this->groupManager = $this->createMock(IGroupManager::class); $this->logger = $this->createMock(LoggerInterface::class); @@ -119,7 +118,7 @@ class RegistryTest extends TestCase { } public function testSubscriptionService(): void { - $this->serverContainer->method('query') + $this->serverContainer->method('get') ->with(DummySubscription::class) ->willReturn(new DummySubscription(true, false, false)); $this->registry->registerService(DummySubscription::class); diff --git a/tests/lib/User/ManagerTest.php b/tests/lib/User/ManagerTest.php index 17007aa8a24..f606ac4d805 100644 --- a/tests/lib/User/ManagerTest.php +++ b/tests/lib/User/ManagerTest.php @@ -21,17 +21,12 @@ use OCP\IConfig; use OCP\IUser; use OCP\IUserManager; use OCP\Server; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; use Psr\Log\LoggerInterface; use Test\TestCase; -/** - * Class ManagerTest - * - * - * @package Test\User - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] +#[Group('DB')] class ManagerTest extends TestCase { private IConfig&MockObject $config; private IEventDispatcher&MockObject $eventDispatcher; @@ -151,7 +146,7 @@ class ManagerTest extends TestCase { $backend->expects($this->once()) ->method('checkPassword') ->with($this->equalTo('foo'), $this->equalTo('bar')) - ->willReturn(true); + ->willReturn('foo'); $backend->expects($this->any()) ->method('implementsActions') @@ -345,7 +340,8 @@ class ManagerTest extends TestCase { $backend->expects($this->once()) ->method('createUser') - ->with($this->equalTo('foo'), $this->equalTo('bar')); + ->with($this->equalTo('foo'), $this->equalTo('bar')) + ->willReturn(true); $backend->expects($this->once()) ->method('userExists') diff --git a/tests/lib/User/UserTest.php b/tests/lib/User/UserTest.php index c1e07a0f153..750b99db420 100644 --- a/tests/lib/User/UserTest.php +++ b/tests/lib/User/UserTest.php @@ -23,20 +23,14 @@ use OCP\IUser; use OCP\Notification\IManager as INotificationManager; use OCP\Notification\INotification; use OCP\Server; -use OCP\UserInterface; +use PHPUnit\Framework\Attributes\DataProvider; +use PHPUnit\Framework\Attributes\Group; use PHPUnit\Framework\MockObject\MockObject; use Test\TestCase; -/** - * Class UserTest - * - * - * @package Test\User - */ -#[\PHPUnit\Framework\Attributes\Group('DB')] +#[Group('DB')] class UserTest extends TestCase { - /** @var IEventDispatcher|MockObject */ - protected $dispatcher; + protected IEventDispatcher $dispatcher; protected function setUp(): void { parent::setUp(); @@ -44,9 +38,6 @@ class UserTest extends TestCase { } public function testDisplayName(): void { - /** - * @var \OC\User\Backend | MockObject $backend - */ $backend = $this->createMock(\OC\User\Backend::class); $backend->expects($this->once()) ->method('getDisplayName') @@ -66,9 +57,6 @@ class UserTest extends TestCase { * if the display name contain whitespaces only, we expect the uid as result */ public function testDisplayNameEmpty(): void { - /** - * @var \OC\User\Backend | MockObject $backend - */ $backend = $this->createMock(\OC\User\Backend::class); $backend->expects($this->once()) ->method('getDisplayName') @@ -85,9 +73,6 @@ class UserTest extends TestCase { } public function testDisplayNameNotSupported(): void { - /** - * @var \OC\User\Backend | MockObject $backend - */ $backend = $this->createMock(\OC\User\Backend::class); $backend->expects($this->never()) ->method('getDisplayName'); @@ -102,32 +87,22 @@ class UserTest extends TestCase { } public function testSetPassword(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('setPassword') - ->with($this->equalTo('foo'), $this->equalTo('bar')); + ->with($this->equalTo('foo'), $this->equalTo('bar')) + ->willReturn(true); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_PASSWORD); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->setPassword('bar', '')); } public function testSetPasswordNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->never()) ->method('setPassword'); @@ -141,9 +116,6 @@ class UserTest extends TestCase { } public function testChangeAvatarSupportedYes(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(AvatarUserDummy::class); $backend->expects($this->once()) ->method('canChangeAvatar') @@ -165,9 +137,6 @@ class UserTest extends TestCase { } public function testChangeAvatarSupportedNo(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(AvatarUserDummy::class); $backend->expects($this->once()) ->method('canChangeAvatar') @@ -189,9 +158,6 @@ class UserTest extends TestCase { } public function testChangeAvatarNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(AvatarUserDummy::class); $backend->expects($this->never()) ->method('canChangeAvatar'); @@ -205,20 +171,18 @@ class UserTest extends TestCase { } public function testDelete(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('deleteUser') - ->with($this->equalTo('foo')); + ->with($this->equalTo('foo')) + ->willReturn(true); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->delete()); } public function testDeleteWithDifferentHome(): void { - /** @var ObjectHomeMountProvider $homeProvider */ $homeProvider = Server::get(ObjectHomeMountProvider::class); $user = $this->createMock(IUser::class); $user->method('getUID') @@ -227,20 +191,12 @@ class UserTest extends TestCase { $this->markTestSkipped('Skipping test for non local home storage'); } - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::GET_HOME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::GET_HOME); // important: getHome MUST be called before deleteUser because // once the user is deleted, getHome implementations might not @@ -252,16 +208,14 @@ class UserTest extends TestCase { $backend->expects($this->once()) ->method('deleteUser') - ->with($this->equalTo('foo')); + ->with($this->equalTo('foo')) + ->willReturn(true); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->delete()); } public function testGetHome(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->once()) ->method('getHome') @@ -270,13 +224,7 @@ class UserTest extends TestCase { $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::GET_HOME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::GET_HOME); $user = new User('foo', $backend, $this->dispatcher); $this->assertEquals('/home/foo', $user->getHome()); @@ -290,9 +238,6 @@ class UserTest extends TestCase { } public function testGetHomeNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->never()) ->method('getHome'); @@ -317,29 +262,17 @@ class UserTest extends TestCase { } public function testCanChangePassword(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_PASSWORD); $user = new User('foo', $backend, $this->dispatcher); $this->assertTrue($user->canChangePassword()); } public function testCanChangePasswordNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) @@ -351,20 +284,11 @@ class UserTest extends TestCase { } public function testCanChangeDisplayName(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_DISPLAYNAME); $config = $this->createMock(IConfig::class); $config->method('getSystemValueBool') @@ -376,9 +300,6 @@ class UserTest extends TestCase { } public function testCanChangeDisplayNameNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $backend->expects($this->any()) @@ -390,20 +311,11 @@ class UserTest extends TestCase { } public function testSetDisplayNameSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_DISPLAYNAME); $backend->expects($this->once()) ->method('setDisplayName') @@ -419,20 +331,11 @@ class UserTest extends TestCase { * don't allow display names containing whitespaces only */ public function testSetDisplayNameEmpty(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(Database::class); $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_DISPLAYNAME) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_DISPLAYNAME); $user = new User('foo', $backend, $this->dispatcher); $this->assertFalse($user->setDisplayName(' ')); @@ -440,9 +343,6 @@ class UserTest extends TestCase { } public function testSetDisplayNameNotSupported(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(Database::class); $backend->expects($this->any()) @@ -461,18 +361,13 @@ class UserTest extends TestCase { $hooksCalled = 0; $test = $this; - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) - ->method('setPassword'); + ->method('setPassword') + ->willReturn(true); - /** - * @param User $user - * @param string $password - */ - $hook = function ($user, $password) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $password) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('foo', $user->getUID()); $test->assertEquals('bar', $password); @@ -484,13 +379,7 @@ class UserTest extends TestCase { $backend->expects($this->any()) ->method('implementsActions') - ->willReturnCallback(function ($actions) { - if ($actions === \OC\User\Backend::SET_PASSWORD) { - return true; - } else { - return false; - } - }); + ->willReturnCallback(static fn (int $actions): bool => $actions === \OC\User\Backend::SET_PASSWORD); $user = new User('foo', $backend, $this->dispatcher, $emitter); @@ -505,19 +394,13 @@ class UserTest extends TestCase { ]; } - /** - * @param bool $result - * @param int $expectedHooks - */ - #[\PHPUnit\Framework\Attributes\DataProvider('dataDeleteHooks')] - public function testDeleteHooks($result, $expectedHooks): void { + #[DataProvider('dataDeleteHooks')] + public function testDeleteHooks(bool $result, int $expectedHooks): void { $hooksCalled = 0; $test = $this; - /** - * @var UserInterface&MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('deleteUser') ->willReturn($result); @@ -535,10 +418,7 @@ class UserTest extends TestCase { $emitter = new PublicEmitter(); $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); - /** - * @param User $user - */ - $hook = function ($user) use ($test, &$hooksCalled): void { + $hook = function (IUser $user) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('foo', $user->getUID()); }; @@ -601,6 +481,7 @@ class UserTest extends TestCase { public function testDeleteRecoverState() { $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $backend->expects($this->once()) ->method('deleteUser') ->willReturn(true); @@ -659,9 +540,8 @@ class UserTest extends TestCase { ]; } - #[\PHPUnit\Framework\Attributes\DataProvider('dataGetCloudId')] + #[DataProvider('dataGetCloudId')] public function testGetCloudId(string $absoluteUrl, string $cloudId): void { - /** @var Backend|MockObject $backend */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $urlGenerator = $this->createMock(IURLGenerator::class); $urlGenerator->method('getAbsoluteURL') @@ -672,20 +552,13 @@ class UserTest extends TestCase { } public function testSetEMailAddressEmpty(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $test = $this; $hooksCalled = 0; - /** - * @param IUser $user - * @param string $feature - * @param string $value - */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $feature, string $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('eMailAddress', $feature); $test->assertEquals('', $value); @@ -704,24 +577,17 @@ class UserTest extends TestCase { ); $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); - $user->setEMailAddress(''); + $user->setSystemEMailAddress(''); } public function testSetEMailAddress(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $test = $this; $hooksCalled = 0; - /** - * @param IUser $user - * @param string $feature - * @param string $value - */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $feature, string $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('eMailAddress', $feature); $test->assertEquals('foo@bar.com', $value); @@ -741,16 +607,13 @@ class UserTest extends TestCase { ); $user = new User('foo', $backend, $this->dispatcher, $emitter, $config); - $user->setEMailAddress('foo@bar.com'); + $user->setSystemEMailAddress('foo@bar.com'); } public function testSetEMailAddressNoChange(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); - /** @var PublicEmitter|MockObject $emitter */ $emitter = $this->createMock(PublicEmitter::class); $emitter->expects($this->never()) ->method('emit'); @@ -767,24 +630,17 @@ class UserTest extends TestCase { ->method('setUserValue'); $user = new User('foo', $backend, $dispatcher, $emitter, $config); - $user->setEMailAddress('foo@bar.com'); + $user->setSystemEMailAddress('foo@bar.com'); } public function testSetQuota(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $test = $this; $hooksCalled = 0; - /** - * @param IUser $user - * @param string $feature - * @param string $value - */ - $hook = function (IUser $user, $feature, $value) use ($test, &$hooksCalled): void { + $hook = function (IUser $user, string $feature, string $value) use ($test, &$hooksCalled): void { $hooksCalled++; $test->assertEquals('quota', $feature); $test->assertEquals('23 TB', $value); @@ -808,10 +664,8 @@ class UserTest extends TestCase { } public function testGetDefaultUnlimitedQuota(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); /** @var PublicEmitter|MockObject $emitter */ $emitter = $this->createMock(PublicEmitter::class); @@ -839,9 +693,6 @@ class UserTest extends TestCase { } public function testGetDefaultUnlimitedQuotaForbidden(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); /** @var PublicEmitter|MockObject $emitter */ @@ -873,9 +724,6 @@ class UserTest extends TestCase { } public function testSetQuotaAddressNoChange(): void { - /** - * @var UserInterface | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); /** @var PublicEmitter|MockObject $emitter */ @@ -895,9 +743,6 @@ class UserTest extends TestCase { } public function testGetLastLogin(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); @@ -915,10 +760,8 @@ class UserTest extends TestCase { } public function testSetEnabled(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); + $backend->method('getBackendName')->willReturn('foo'); $config = $this->createMock(IConfig::class); $config->expects($this->once()) @@ -941,9 +784,6 @@ class UserTest extends TestCase { } public function testSetDisabled(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); @@ -981,9 +821,6 @@ class UserTest extends TestCase { } public function testSetDisabledAlreadyDisabled(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); @@ -1011,9 +848,6 @@ class UserTest extends TestCase { } public function testGetEMailAddress(): void { - /** - * @var Backend | MockObject $backend - */ $backend = $this->createMock(\Test\Util\User\Dummy::class); $config = $this->createMock(IConfig::class); diff --git a/tests/lib/Util/User/Dummy.php b/tests/lib/Util/User/Dummy.php index 6ecd378c1de..4a85f92981c 100644 --- a/tests/lib/Util/User/Dummy.php +++ b/tests/lib/Util/User/Dummy.php @@ -15,20 +15,10 @@ use OCP\IUserBackend; * dummy user backend, does not keep state, only for testing use */ class Dummy extends Backend implements IUserBackend { - private $users = []; - private $displayNames = []; + private array $users = []; + private array $displayNames = []; - /** - * Create a new user - * - * @param string $uid The username of the user to create - * @param string $password The password of the new user - * @return bool - * - * Creates a new user. Basic checking of username is done in OC_User - * itself, not in its subclasses. - */ - public function createUser($uid, $password) { + public function createUser($uid, $password): bool { if (isset($this->users[$uid])) { return false; } else { @@ -37,15 +27,7 @@ class Dummy extends Backend implements IUserBackend { } } - /** - * delete a user - * - * @param string $uid The username of the user to delete - * @return bool - * - * Deletes a user - */ - public function deleteUser($uid) { + public function deleteUser($uid): bool { if (isset($this->users[$uid])) { unset($this->users[$uid]); return true; @@ -54,16 +36,7 @@ class Dummy extends Backend implements IUserBackend { } } - /** - * Set password - * - * @param string $uid The username - * @param string $password The new password - * @return bool - * - * Change the password of a user - */ - public function setPassword($uid, $password) { + public function setPassword($uid, $password): bool { if (isset($this->users[$uid])) { $this->users[$uid] = $password; return true; @@ -72,17 +45,7 @@ class Dummy extends Backend implements IUserBackend { } } - /** - * Check if the password is correct - * - * @param string $uid The username - * @param string $password The password - * @return string|bool - * - * Check if the password is correct without logging in the user - * returns the user id or false - */ - public function checkPassword($uid, $password) { + public function checkPassword($uid, $password): string|false { if (isset($this->users[$uid]) && $this->users[$uid] === $password) { return $uid; } @@ -90,22 +53,14 @@ class Dummy extends Backend implements IUserBackend { return false; } - public function loginName2UserName($loginName) { + public function loginName2UserName($loginName): string|false { if (isset($this->users[strtolower($loginName)])) { return strtolower($loginName); } return false; } - /** - * Get a list of all users - * - * @param string $search - * @param null|int $limit - * @param null|int $offset - * @return string[] an array of all uids - */ - public function getUsers($search = '', $limit = null, $offset = null) { + public function getUsers($search = '', $limit = null, $offset = null): array { if (empty($search)) { return array_keys($this->users); } @@ -118,46 +73,28 @@ class Dummy extends Backend implements IUserBackend { return $result; } - /** - * check if a user exists - * - * @param string $uid the username - * @return boolean - */ - public function userExists($uid) { + public function userExists($uid): bool { return isset($this->users[$uid]); } - /** - * @return bool - */ - public function hasUserListings() { + public function hasUserListings(): bool { return true; } - /** - * counts the users in the database - * - * @return int|bool - */ - public function countUsers() { + public function countUsers(): int { return 0; } - public function setDisplayName($uid, $displayName) { + public function setDisplayName($uid, $displayName): bool { $this->displayNames[$uid] = $displayName; return true; } - public function getDisplayName($uid) { + public function getDisplayName($uid): string { return $this->displayNames[$uid] ?? $uid; } - /** - * Backend name to be shown in user management - * @return string the name of the backend to be shown - */ - public function getBackendName() { + public function getBackendName(): string { return 'Dummy'; } }