refactor: Add more typing

- repairs job
- database
- redis

And remove Helpertest which was unused outside of some tests.

Signed-off-by: Carl Schwan <carl.schwan@nextcloud.com>
This commit is contained in:
Carl Schwan 2025-12-02 11:39:50 +01:00 committed by Carl Schwan
parent fb3f9fe2de
commit c96ece0bcb
No known key found for this signature in database
GPG key ID: 02325448204E452A
55 changed files with 391 additions and 1140 deletions

View file

@ -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);
}

View file

@ -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')

View file

@ -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')
);
});

View file

@ -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);

View file

@ -2175,31 +2175,6 @@
<code><![CDATA[Response]]></code>
</InvalidReturnType>
</file>
<file src="apps/settings/lib/AppInfo/Application.php">
<DeprecatedInterface>
<code><![CDATA[$serverContainer]]></code>
<code><![CDATA[$serverContainer]]></code>
<code><![CDATA[IAppContainer]]></code>
<code><![CDATA[IAppContainer]]></code>
<code><![CDATA[IAppContainer]]></code>
</DeprecatedInterface>
<DeprecatedMethod>
<code><![CDATA[getConfig]]></code>
<code><![CDATA[getCrypto]]></code>
<code><![CDATA[getL10NFactory]]></code>
<code><![CDATA[getMailer]]></code>
<code><![CDATA[getSecureRandom]]></code>
<code><![CDATA[getURLGenerator]]></code>
<code><![CDATA[query]]></code>
<code><![CDATA[query]]></code>
<code><![CDATA[query]]></code>
<code><![CDATA[query]]></code>
<code><![CDATA[query]]></code>
</DeprecatedMethod>
<UndefinedInterfaceMethod>
<code><![CDATA[getSettingsManager]]></code>
</UndefinedInterfaceMethod>
</file>
<file src="apps/settings/lib/BackgroundJobs/VerifyUserData.php">
<DeprecatedConstant>
<code><![CDATA[IAccountManager::PROPERTY_TWITTER]]></code>
@ -3868,16 +3843,6 @@
<code><![CDATA[array]]></code>
</ImplementedReturnTypeMismatch>
</file>
<file src="lib/private/Remote/Instance.php">
<InvalidScalarArgument>
<code><![CDATA[$response]]></code>
</InvalidScalarArgument>
</file>
<file src="lib/private/Repair/Owncloud/CleanPreviews.php">
<InvalidArgument>
<code><![CDATA[false]]></code>
</InvalidArgument>
</file>
<file src="lib/private/Repair/RemoveLinkShares.php">
<InvalidPropertyAssignmentValue>
<code><![CDATA[$this->userToNotify]]></code>

View file

@ -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('<error>Redis command failed</error>');

View file

@ -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',

View file

@ -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',

View file

@ -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;

View file

@ -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 {

View file

@ -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;
}

View file

@ -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;
}
}

View file

@ -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);
}
}
}

View file

@ -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');

View file

@ -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')

View file

@ -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);
}

View file

@ -21,17 +21,10 @@ use function OCP\Log\logger;
* @template-implements \ArrayAccess<string,mixed>
*/
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,

View file

@ -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;
}
}

View file

@ -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 {

View file

@ -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'];

View file

@ -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;

View file

@ -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 {

View file

@ -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;

View file

@ -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'

View file

@ -1,143 +0,0 @@
<?php
/**
* SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OC\Share;
use OC\Core\AppInfo\ConfigLexicon;
use OCP\IAppConfig;
use OCP\IConfig;
use OCP\Server;
use OCP\Util;
class Helper extends Constants {
/**
* get default expire settings defined by the admin
* @return array contains 'defaultExpireDateSet', 'enforceExpireDate', 'expireAfterDays'
*/
public static function getDefaultExpireSetting() {
$config = Server::get(IConfig::class);
$appConfig = Server::get(IAppConfig::class);
$defaultExpireSettings = ['defaultExpireDateSet' => 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));
}
}

View file

@ -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.');
}
}

View file

@ -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');
}

View file

@ -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

View file

@ -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
}
}

View file

@ -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;
}

View file

@ -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;

View file

@ -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();

View file

@ -41,7 +41,7 @@ class LazyUser implements IUser {
return $this->user;
}
public function getUID() {
public function getUID(): string {
return $this->uid;
}

View file

@ -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);

View file

@ -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]);

View file

@ -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)) {

View file

@ -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()) {

View file

@ -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;

View file

@ -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

View file

@ -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;
}

View file

@ -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();

View file

@ -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')

View file

@ -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();

View file

@ -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;

View file

@ -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();

View file

@ -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();

View file

@ -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 = [];

View file

@ -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();

View file

@ -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;
}
}

View file

@ -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));
}

View file

@ -1,74 +0,0 @@
<?php
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace Test\Share;
use OC\Share\Helper;
#[\PHPUnit\Framework\Attributes\Group('DB')]
class HelperTest extends \Test\TestCase {
public static function expireDateProvider(): array {
return [
// no default expire date, we take the users expire date
[['defaultExpireDateSet' => 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],
];
}
}

View file

@ -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);

View file

@ -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')

View file

@ -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);

View file

@ -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';
}
}