Merge pull request #59159 from nextcloud/fix/remove-static-vars-batch
Some checks are pending
CodeQL Advanced / Analyze (actions) (push) Waiting to run
CodeQL Advanced / Analyze (javascript-typescript) (push) Waiting to run
Integration sqlite / changes (push) Waiting to run
Integration sqlite / integration-sqlite (master, 8.4, main, --tags ~@large files_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, capabilities_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, collaboration_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, comments_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, dav_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, federation_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, file_conversions) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, files_reminders) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, filesdrop_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, ldap_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, openldap_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, openldap_numerical_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, remoteapi_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, routing_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, setup_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, sharees_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, sharing_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, theming_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite (master, 8.4, main, videoverification_features) (push) Blocked by required conditions
Integration sqlite / integration-sqlite-summary (push) Blocked by required conditions
Psalm static code analysis / static-code-analysis (push) Waiting to run
Psalm static code analysis / static-code-analysis-security (push) Waiting to run
Psalm static code analysis / static-code-analysis-ocp (push) Waiting to run
Psalm static code analysis / static-code-analysis-ncu (push) Waiting to run
Psalm static code analysis / static-code-analysis-strict (push) Waiting to run

Remove static vars, first batch
This commit is contained in:
Côme Chilliet 2026-03-24 14:20:10 +01:00 committed by GitHub
commit 5a7d38b22c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
26 changed files with 97 additions and 166 deletions

View file

@ -190,7 +190,7 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
];
/** @var array parameters to index */
public static array $indexParameters = [
private const INDEXED_PARAMETERS = [
'ATTENDEE' => ['CN'],
'ORGANIZER' => ['CN'],
];
@ -3386,9 +3386,9 @@ class CalDavBackend extends AbstractBackend implements SyncSupport, Subscription
$query->executeStatement();
}
if (array_key_exists($property->name, self::$indexParameters)) {
if (array_key_exists($property->name, self::INDEXED_PARAMETERS)) {
$parameters = $property->parameters();
$indexedParametersForProperty = self::$indexParameters[$property->name];
$indexedParametersForProperty = self::INDEXED_PARAMETERS[$property->name];
foreach ($parameters as $key => $value) {
if (in_array($key, $indexedParametersForProperty)) {

View file

@ -42,7 +42,7 @@ class CardDavBackend implements BackendInterface, SyncSupport {
private string $dbCardsPropertiesTable = 'cards_properties';
/** @var array properties to index */
public static array $indexProperties = [
private const INDEXED_PROPERTIES = [
'BDAY', 'UID', 'N', 'FN', 'TITLE', 'ROLE', 'NOTE', 'NICKNAME',
'ORG', 'CATEGORIES', 'EMAIL', 'TEL', 'IMPP', 'ADR', 'URL', 'GEO',
'CLOUD', 'X-SOCIALPROFILE'];
@ -1384,7 +1384,7 @@ class CardDavBackend implements BackendInterface, SyncSupport {
);
foreach ($vCard->children() as $property) {
if (!in_array($property->name, self::$indexProperties)) {
if (!in_array($property->name, self::INDEXED_PROPERTIES)) {
continue;
}
$preferred = 0;

View file

@ -23,14 +23,14 @@ use Sabre\VObject\Component\VCard;
use Sabre\VObject\Reader;
class ContactsSearchProvider implements IFilteringProvider {
private static array $searchPropertiesRestricted = [
private const SEARCH_PROPERTIES_RESTRICTED = [
'N',
'FN',
'NICKNAME',
'EMAIL',
];
private static array $searchProperties = [
private const SEARCH_PROPERTIES = [
'N',
'FN',
'NICKNAME',
@ -87,7 +87,7 @@ class ContactsSearchProvider implements IFilteringProvider {
$searchResults = $this->backend->searchPrincipalUri(
$principalUri,
$query->getFilter('term')?->get() ?? '',
$query->getFilter('title-only')?->get() ? self::$searchPropertiesRestricted : self::$searchProperties,
$query->getFilter('title-only')?->get() ? self::SEARCH_PROPERTIES_RESTRICTED : self::SEARCH_PROPERTIES,
[
'limit' => $query->getLimit(),
'offset' => $query->getCursor(),

View file

@ -32,7 +32,7 @@ class EventsSearchProvider extends ACalendarSearchProvider implements IFiltering
/**
* @var string[]
*/
private static $searchProperties = [
private const SEARCH_PROPERTIES = [
'SUMMARY',
'LOCATION',
'DESCRIPTION',
@ -42,9 +42,9 @@ class EventsSearchProvider extends ACalendarSearchProvider implements IFiltering
];
/**
* @var string[]
* @var array<string, string[]>
*/
private static $searchParameters = [
private const SEARCH_PARAMETERS = [
'ATTENDEE' => ['CN'],
'ORGANIZER' => ['CN'],
];
@ -52,7 +52,7 @@ class EventsSearchProvider extends ACalendarSearchProvider implements IFiltering
/**
* @var string
*/
private static $componentType = 'VEVENT';
private const COMPONENT_TYPE = 'VEVENT';
/**
* @inheritDoc
@ -102,9 +102,9 @@ class EventsSearchProvider extends ACalendarSearchProvider implements IFiltering
$searchResults = $this->backend->searchPrincipalUri(
$principalUri,
$term,
[self::$componentType],
self::$searchProperties,
self::$searchParameters,
[self::COMPONENT_TYPE],
self::SEARCH_PROPERTIES,
self::SEARCH_PARAMETERS,
[
'limit' => $query->getLimit(),
'offset' => $query->getCursor(),
@ -122,9 +122,9 @@ class EventsSearchProvider extends ACalendarSearchProvider implements IFiltering
$attendeeSearchResults = $this->backend->searchPrincipalUri(
$principalUri,
$personDisplayName,
[self::$componentType],
[self::COMPONENT_TYPE],
['ATTENDEE'],
self::$searchParameters,
self::SEARCH_PARAMETERS,
[
'limit' => $query->getLimit(),
'offset' => $query->getCursor(),
@ -148,7 +148,7 @@ class EventsSearchProvider extends ACalendarSearchProvider implements IFiltering
}
}
$formattedResults = \array_map(function (array $eventRow) use ($calendarsById, $subscriptionsById): SearchResultEntry {
$component = $this->getPrimaryComponent($eventRow['calendardata'], self::$componentType);
$component = $this->getPrimaryComponent($eventRow['calendardata'], self::COMPONENT_TYPE);
$title = (string)($component->SUMMARY ?? $this->l10n->t('Untitled event'));
if ($eventRow['calendartype'] === CalDavBackend::CALENDAR_TYPE_CALENDAR) {

View file

@ -24,7 +24,7 @@ class TasksSearchProvider extends ACalendarSearchProvider {
/**
* @var string[]
*/
private static $searchProperties = [
private const SEARCH_PROPERTIES = [
'SUMMARY',
'DESCRIPTION',
'CATEGORIES',
@ -33,12 +33,12 @@ class TasksSearchProvider extends ACalendarSearchProvider {
/**
* @var string[]
*/
private static $searchParameters = [];
private const SEARCH_PARAMETERS = [];
/**
* @var string
*/
private static $componentType = 'VTODO';
private const COMPONENT_TYPE = 'VTODO';
/**
* @inheritDoc
@ -83,9 +83,9 @@ class TasksSearchProvider extends ACalendarSearchProvider {
$searchResults = $this->backend->searchPrincipalUri(
$principalUri,
$query->getFilter('term')?->get() ?? '',
[self::$componentType],
self::$searchProperties,
self::$searchParameters,
[self::COMPONENT_TYPE],
self::SEARCH_PROPERTIES,
self::SEARCH_PARAMETERS,
[
'limit' => $query->getLimit(),
'offset' => $query->getCursor(),
@ -94,7 +94,7 @@ class TasksSearchProvider extends ACalendarSearchProvider {
]
);
$formattedResults = \array_map(function (array $taskRow) use ($calendarsById, $subscriptionsById):SearchResultEntry {
$component = $this->getPrimaryComponent($taskRow['calendardata'], self::$componentType);
$component = $this->getPrimaryComponent($taskRow['calendardata'], self::COMPONENT_TYPE);
$title = (string)($component->SUMMARY ?? $this->l10n->t('Untitled task'));
if ($taskRow['calendartype'] === CalDavBackend::CALENDAR_TYPE_CALENDAR) {

View file

@ -21,9 +21,8 @@ use OCP\IUserSession;
use Psr\Log\LoggerInterface;
class PassphraseService {
/** @var array<string, bool> */
private static array $passwordResetUsers = [];
private array $passwordResetUsers = [];
public function __construct(
private Util $util,
@ -39,9 +38,9 @@ class PassphraseService {
public function setProcessingReset(string $uid, bool $processing = true): void {
if ($processing) {
self::$passwordResetUsers[$uid] = true;
$this->passwordResetUsers[$uid] = true;
} else {
unset(self::$passwordResetUsers[$uid]);
unset($this->passwordResetUsers[$uid]);
}
}
@ -51,7 +50,7 @@ class PassphraseService {
public function setPassphraseForUser(string $userId, string $password, ?string $recoveryPassword = null): bool {
// if we are in the process to resetting a user password, we have nothing
// to do here
if (isset(self::$passwordResetUsers[$userId])) {
if (isset($this->passwordResetUsers[$userId])) {
return true;
}

View file

@ -7,43 +7,9 @@
*/
namespace OCA\Files;
use OC\NavigationManager;
use OCA\Files\Service\ChunkedUploadConfig;
use OCP\App\IAppManager;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\IGroupManager;
use OCP\INavigationManager;
use OCP\IURLGenerator;
use OCP\IUserSession;
use OCP\L10N\IFactory;
use OCP\Server;
use Psr\Log\LoggerInterface;
class App {
private static ?INavigationManager $navigationManager = null;
/**
* Returns the app's navigation manager
*/
public static function getNavigationManager(): INavigationManager {
// TODO: move this into a service in the Application class
if (self::$navigationManager === null) {
self::$navigationManager = new NavigationManager(
Server::get(IAppManager::class),
Server::get(IUrlGenerator::class),
Server::get(IFactory::class),
Server::get(IUserSession::class),
Server::get(IGroupManager::class),
Server::get(IConfig::class),
Server::get(LoggerInterface::class),
Server::get(IEventDispatcher::class),
);
self::$navigationManager->clear(false);
}
return self::$navigationManager;
}
public static function extendJsConfig($settings): void {
$appConfig = json_decode($settings['array']['oc_appconfig'], true);

View file

@ -17,7 +17,7 @@ use OCP\Security\IHasher;
use OCP\Security\ISecureRandom;
class BackupCodeStorage {
private static $CODE_LENGTH = 16;
private const CODE_LENGTH = 16;
public function __construct(
private BackupCodeMapper $mapper,
@ -40,7 +40,7 @@ class BackupCodeStorage {
$uid = $user->getUID();
foreach (range(1, min([$number, 20])) as $i) {
$code = $this->random->generate(self::$CODE_LENGTH, ISecureRandom::CHAR_HUMAN_READABLE);
$code = $this->random->generate(self::CODE_LENGTH, ISecureRandom::CHAR_HUMAN_READABLE);
$dbCode = new BackupCode();
$dbCode->setUserId($uid);

View file

@ -444,13 +444,9 @@ class Configuration {
}
protected function getValue(string $varName): string {
static $defaults;
if (is_null($defaults)) {
$defaults = $this->getDefaults();
}
return Server::get(IConfig::class)->getAppValue('user_ldap',
$this->configPrefix . $varName,
$defaults[$varName]);
$this->getDefaults()[$varName]);
}
/**
@ -571,7 +567,7 @@ class Configuration {
*/
public function getConfigTranslationArray(): array {
//TODO: merge them into one representation
static $array = [
return [
'ldap_host' => 'ldapHost',
'ldap_port' => 'ldapPort',
'ldap_backup_host' => 'ldapBackupHost',
@ -644,7 +640,6 @@ class Configuration {
'ldap_attr_anniversarydate' => 'ldapAttributeAnniversaryDate',
'ldap_attr_pronouns' => 'ldapAttributePronouns',
];
return $array;
}
/**

View file

@ -1,10 +1,13 @@
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2019-2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-FileCopyrightText: 2016 ownCloud, Inc.
* SPDX-License-Identifier: AGPL-3.0-only
*/
namespace OCA\User_LDAP\Mapping;
use OCP\HintException;
@ -12,7 +15,6 @@ use OCP\IAppConfig;
use OCP\ICacheFactory;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\Server;
use OCP\Support\Subscription\IAssertion;
/**
@ -30,6 +32,7 @@ class UserMapping extends AbstractMapping {
IAppConfig $config,
bool $isCLI,
private IAssertion $assertion,
private IRequest $request,
) {
parent::__construct($dbc, $cacheFactory, $config, $isCLI);
}
@ -41,13 +44,7 @@ class UserMapping extends AbstractMapping {
try {
$this->assertion->createUserIsLegit();
} catch (HintException $e) {
static $isProvisioningApi = null;
if ($isProvisioningApi === null) {
$request = Server::get(IRequest::class);
$isProvisioningApi = \preg_match(self::PROV_API_REGEX, $request->getRequestUri()) === 1;
}
if ($isProvisioningApi) {
if (\preg_match(self::PROV_API_REGEX, $this->request->getRequestUri()) === 1) {
// only throw when prov API is being used, since functionality
// should not break for end users (e.g. when sharing).
// On direct API usage, e.g. on users page, this is desired.

View file

@ -16,7 +16,7 @@ use OCP\Util;
use Psr\Log\LoggerInterface;
class Wizard extends LDAPUtility {
protected static ?IL10N $l = null;
private IL10N $l;
protected ?\LDAP\Connection $cr = null;
protected WizardResult $result;
protected LoggerInterface $logger;
@ -40,9 +40,7 @@ class Wizard extends LDAPUtility {
protected Access $access,
) {
parent::__construct($ldap);
if (is_null(static::$l)) {
static::$l = Server::get(IL10NFactory::class)->get('user_ldap');
}
$this->l = Server::get(IL10NFactory::class)->get('user_ldap');
$this->result = new WizardResult();
$this->logger = Server::get(LoggerInterface::class);
}
@ -94,7 +92,7 @@ class Wizard extends LDAPUtility {
$filter = $this->configuration->ldapGroupFilter;
if (empty($filter)) {
$output = self::$l->n('%n group found', '%n groups found', 0);
$output = $this->l->n('%n group found', '%n groups found', 0);
$this->result->addChange('ldap_group_count', $output);
return $this->result;
}
@ -110,9 +108,9 @@ class Wizard extends LDAPUtility {
}
if ($groupsTotal > 1000) {
$output = self::$l->t('> 1000 groups found');
$output = $this->l->t('> 1000 groups found');
} else {
$output = self::$l->n(
$output = $this->l->n(
'%n group found',
'%n groups found',
$groupsTotal
@ -130,9 +128,9 @@ class Wizard extends LDAPUtility {
$usersTotal = $this->countEntries($filter, 'users');
if ($usersTotal > 1000) {
$output = self::$l->t('> 1000 users found');
$output = $this->l->t('> 1000 users found');
} else {
$output = self::$l->n(
$output = $this->l->n(
'%n user found',
'%n users found',
$usersTotal
@ -216,7 +214,7 @@ class Wizard extends LDAPUtility {
}
}
throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
throw new \Exception($this->l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
}
/**
@ -431,7 +429,7 @@ class Wizard extends LDAPUtility {
natsort($groupNames);
$this->result->addOptions($dbKey, array_values($groupNames));
} else {
throw new \Exception(self::$l->t('Could not find the desired feature'));
throw new \Exception($this->l->t('Could not find the desired feature'));
}
$setFeatures = $this->configuration->$confKey;
@ -1024,7 +1022,7 @@ class Wizard extends LDAPUtility {
$host = $this->configuration->ldapHost;
$hostInfo = parse_url((string)$host);
if (!is_string($host) || !$hostInfo) {
throw new \Exception(self::$l->t('Invalid Host'));
throw new \Exception($this->l->t('Invalid Host'));
}
$this->logger->debug(
'Wiz: Attempting to connect',
@ -1032,7 +1030,7 @@ class Wizard extends LDAPUtility {
);
$cr = $this->ldap->connect($host, (string)$port);
if (!$this->ldap->isResource($cr)) {
throw new \Exception(self::$l->t('Invalid Host'));
throw new \Exception($this->l->t('Invalid Host'));
}
/** @var \LDAP\Connection $cr */
@ -1219,7 +1217,7 @@ class Wizard extends LDAPUtility {
//sorting in the web UI. Therefore: array_values
$this->result->addOptions($dbkey, array_values($availableFeatures));
} else {
throw new \Exception(self::$l->t('Could not find the desired feature'));
throw new \Exception($this->l->t('Could not find the desired feature'));
}
$setFeatures = $this->configuration->$confkey;
@ -1307,7 +1305,7 @@ class Wizard extends LDAPUtility {
* @return array<array{port:int,tls:bool}>
*/
private function getDefaultLdapPortSettings(): array {
static $settings = [
return [
['port' => 7636, 'tls' => false],
['port' => 636, 'tls' => false],
['port' => 7389, 'tls' => true],
@ -1315,7 +1313,6 @@ class Wizard extends LDAPUtility {
['port' => 7389, 'tls' => false],
['port' => 389, 'tls' => false],
];
return $settings;
}
/**

View file

@ -12,6 +12,7 @@ use OCA\User_LDAP\Mapping\UserMapping;
use OCP\IAppConfig;
use OCP\ICacheFactory;
use OCP\IDBConnection;
use OCP\IRequest;
use OCP\Support\Subscription\IAssertion;
/**
@ -23,6 +24,6 @@ use OCP\Support\Subscription\IAssertion;
#[\PHPUnit\Framework\Attributes\Group(name: 'DB')]
class UserMappingTest extends AbstractMappingTestCase {
public function getMapper(IDBConnection $dbMock, ICacheFactory $cacheFactory, IAppConfig $appConfig): UserMapping {
return new UserMapping($dbMock, $cacheFactory, $appConfig, true, $this->createMock(IAssertion::class));
return new UserMapping($dbMock, $cacheFactory, $appConfig, true, $this->createMock(IAssertion::class), $this->createMock(IRequest::class));
}
}

View file

@ -6,6 +6,7 @@ declare(strict_types=1);
* SPDX-FileCopyrightText: 2019 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OCA\WorkflowEngine\Command;
use OCA\WorkflowEngine\Helper\ScopeContext;
@ -43,11 +44,11 @@ class Index extends Command {
}
protected function mappedScope(string $scope): int {
static $scopes = [
return match($scope) {
'admin' => IManager::SCOPE_ADMIN,
'user' => IManager::SCOPE_USER,
];
return $scopes[$scope] ?? -1;
default => -1,
};
}
protected function execute(InputInterface $input, OutputInterface $output): int {

View file

@ -65,6 +65,9 @@ class Manager implements IManager {
/** @var CappedMemoryCache<int[]> */
protected CappedMemoryCache $operationsByScope;
/** @var array<class-string<IOperation>, ScopeContext[]> $scopesByOperation */
private array $scopesByOperation = [];
public function __construct(
protected readonly IDBConnection $connection,
protected readonly ContainerInterface $container,
@ -128,10 +131,8 @@ class Manager implements IManager {
* @return ScopeContext[]
*/
public function getAllConfiguredScopesForOperation(string $operationClass): array {
/** @var array<class-string<IOperation>, ScopeContext[]> $scopesByOperation */
static $scopesByOperation = [];
if (isset($scopesByOperation[$operationClass])) {
return $scopesByOperation[$operationClass];
if (isset($this->scopesByOperation[$operationClass])) {
return $this->scopesByOperation[$operationClass];
}
try {
@ -152,7 +153,7 @@ class Manager implements IManager {
$query->setParameters(['operationClass' => $operationClass]);
$result = $query->executeQuery();
$scopesByOperation[$operationClass] = [];
$this->scopesByOperation[$operationClass] = [];
while ($row = $result->fetchAssociative()) {
$scope = new ScopeContext($row['type'], $row['value']);
@ -160,10 +161,10 @@ class Manager implements IManager {
continue;
}
$scopesByOperation[$operationClass][$scope->getHash()] = $scope;
$this->scopesByOperation[$operationClass][$scope->getHash()] = $scope;
}
return $scopesByOperation[$operationClass];
return $this->scopesByOperation[$operationClass];
}
public function getAllOperations(ScopeContext $scopeContext): array {

View file

@ -831,12 +831,6 @@
<InvalidOperand>
<code><![CDATA[$query->getCursor()]]></code>
</InvalidOperand>
<InvalidPropertyAssignmentValue>
<code><![CDATA[[
'ATTENDEE' => ['CN'],
'ORGANIZER' => ['CN'],
]]]></code>
</InvalidPropertyAssignmentValue>
<UndefinedMethod>
<code><![CDATA[getDateTime]]></code>
<code><![CDATA[getDateTime]]></code>

View file

@ -23,7 +23,7 @@ use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
class GenerateCommand extends Command implements CompletionAwareInterface {
protected static $_templateSimple
private const TEMPLATE
= '<?php
declare(strict_types=1);
@ -197,7 +197,7 @@ class {{classname}} extends SimpleMigrationStep {
$schemaBody,
date('Y')
];
$code = str_replace($placeHolders, $replacements, self::$_templateSimple);
$code = str_replace($placeHolders, $replacements, self::TEMPLATE);
$dir = $ms->getMigrationsDirectory();
$this->ensureMigrationDirExists($dir);

View file

@ -368,7 +368,7 @@ class AccountManager implements IAccountManager {
}
protected function updateVerificationStatus(IAccount $updatedAccount, array $oldData): void {
static $propertiesVerifiableByLookupServer = [
$propertiesVerifiableByLookupServer = [
self::PROPERTY_TWITTER,
self::PROPERTY_FEDIVERSE,
self::PROPERTY_WEBSITE,

View file

@ -54,6 +54,9 @@ class AppManager implements IAppManager {
/** @var string[] $appId => $enabled */
private array $enabledAppsCache = [];
/** @var array<string, array{path: string, url: string}> $appId => approot information */
private array $appsDirCache = [];
/** @var string[]|null */
private ?array $shippedApps = null;
@ -743,11 +746,9 @@ class AppManager implements IAppManager {
if ($sanitizedAppId !== $appId) {
return false;
}
// FIXME replace by a property or a cache
static $app_dir = [];
if (isset($app_dir[$appId]) && !$ignoreCache) {
return $app_dir[$appId];
if (isset($this->appsDirCache[$appId]) && !$ignoreCache) {
return $this->appsDirCache[$appId];
}
$possibleApps = [];
@ -761,7 +762,7 @@ class AppManager implements IAppManager {
return false;
} elseif (count($possibleApps) === 1) {
$dir = array_shift($possibleApps);
$app_dir[$appId] = $dir;
$this->appsDirCache[$appId] = $dir;
return $dir;
} else {
$versionToLoad = [];
@ -778,7 +779,7 @@ class AppManager implements IAppManager {
if (!isset($versionToLoad['dir'])) {
return false;
}
$app_dir[$appId] = $versionToLoad['dir'];
$this->appsDirCache[$appId] = $versionToLoad['dir'];
return $versionToLoad['dir'];
}
}

View file

@ -127,7 +127,7 @@ class PlatformRepository {
return null;
}
private static string $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?(\d+))?)?([.-]?dev)?';
private const MODIFIER_REGEX = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?(\d+))?)?([.-]?dev)?';
/**
* Normalizes a version string to be able to perform comparisons on it
@ -154,16 +154,16 @@ class PlatformRepository {
return 'dev-' . substr($version, 4);
}
// match classical versioning
if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?' . self::$modifierRegex . '$}i', $version, $matches)) {
if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?' . self::MODIFIER_REGEX . '$}i', $version, $matches)) {
$version = $matches[1]
. (!empty($matches[2]) ? $matches[2] : '.0')
. (!empty($matches[3]) ? $matches[3] : '.0')
. (!empty($matches[4]) ? $matches[4] : '.0');
$index = 5;
} elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::$modifierRegex . '$}i', $version, $matches)) { // match date-based versioning
} elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)' . self::MODIFIER_REGEX . '$}i', $version, $matches)) { // match date-based versioning
$version = preg_replace('{\D}', '-', $matches[1]);
$index = 2;
} elseif (preg_match('{^v?(\d{4,})(\.\d+)?(\.\d+)?(\.\d+)?' . self::$modifierRegex . '$}i', $version, $matches)) {
} elseif (preg_match('{^v?(\d{4,})(\.\d+)?(\.\d+)?(\.\d+)?' . self::MODIFIER_REGEX . '$}i', $version, $matches)) {
$version = $matches[1]
. (!empty($matches[2]) ? $matches[2] : '.0')
. (!empty($matches[3]) ? $matches[3] : '.0')

View file

@ -28,18 +28,12 @@ use Psr\Log\LoggerInterface;
* @package OC\Files\Cache
*/
class Storage {
private static ?StorageGlobal $globalCache = null;
private string $storageId;
private int $numericId;
public static function getGlobalCache(): StorageGlobal {
if (is_null(self::$globalCache)) {
self::$globalCache = new StorageGlobal(Server::get(IDBConnection::class));
}
return self::$globalCache;
return Server::get(StorageGlobal::class);
}
/**

View file

@ -95,6 +95,8 @@ class SetupManager implements ISetupManager {
private const SETUP_WITH_CHILDREN = 1;
private const SETUP_WITHOUT_CHILDREN = 0;
private bool $updatingProviders = false;
public function __construct(
private IEventLogger $eventLogger,
private MountProviderCollection $mountProviderCollection,
@ -245,11 +247,10 @@ class SetupManager implements ISetupManager {
}
// prevent recursion loop from when getting mounts from providers ends up setting up the filesystem
static $updatingProviders = false;
if ($updatingProviders) {
if ($this->updatingProviders) {
return;
}
$updatingProviders = true;
$this->updatingProviders = true;
$providers = $this->mountProviderCollection->getProviders();
$nonAuthoritativeProviders = array_filter(
@ -265,7 +266,7 @@ class SetupManager implements ISetupManager {
$this->userMountCache->registerMounts($user, $mount, $providerNames);
$this->usersMountsUpdated[$user->getUID()] = true;
$updatingProviders = false;
$this->updatingProviders = false;
}
#[Override]

View file

@ -74,6 +74,8 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage,
private ?LoggerInterface $logger = null;
private ?IFilenameValidator $filenameValidator = null;
private ?CacheDependencies $cacheDependencies = null;
public function __construct(array $parameters) {
}
@ -304,11 +306,10 @@ abstract class Common implements Storage, ILockingStorage, IWriteStreamStorage,
}
protected function getCacheDependencies(): CacheDependencies {
static $dependencies = null;
if (!$dependencies) {
$dependencies = Server::get(CacheDependencies::class);
if ($this->cacheDependencies === null) {
$this->cacheDependencies = Server::get(CacheDependencies::class);
}
return $dependencies;
return $this->cacheDependencies;
}
public function getCache(string $path = '', ?IStorage $storage = null): ICache {

View file

@ -11,7 +11,6 @@ use OCP\Server;
use Psr\Log\LoggerInterface;
class NaturalSort {
private static $instance;
private $collator;
private $cache = [];
@ -113,10 +112,7 @@ class NaturalSort {
* Returns a singleton
* @return NaturalSort instance
*/
public static function getInstance() {
if (!isset(self::$instance)) {
self::$instance = new NaturalSort();
}
return self::$instance;
public static function getInstance(): NaturalSort {
return \OCP\Server::get(NaturalSort::class);
}
}

View file

@ -60,7 +60,6 @@ use OC\Files\Config\UserMountCache;
use OC\Files\Config\UserMountCacheListener;
use OC\Files\Conversion\ConversionManager;
use OC\Files\FilenameValidator;
use OC\Files\Filesystem;
use OC\Files\Lock\LockManager;
use OC\Files\Mount\CacheMountProvider;
use OC\Files\Mount\LocalHomeMountProvider;
@ -440,12 +439,11 @@ class Server extends ServerContainer implements IServerContainer {
});
$this->registerAlias(IFileAccess::class, FileAccess::class);
$this->registerService('RootFolder', function (ContainerInterface $c) {
$manager = Filesystem::getMountManager();
$view = new View();
/** @var IUserSession $userSession */
$userSession = $c->get(IUserSession::class);
$root = new Root(
$manager,
$c->get(\OC\Files\Mount\Manager::class),
$view,
$userSession->getUser(),
$c->get(IUserMountCache::class),

View file

@ -72,7 +72,7 @@ class Setup {
$this->l10n = $l10nFactory->get('lib');
}
protected static array $dbSetupClasses = [
private const DB_SETUP_CLASSES = [
'mysql' => MySQL::class,
'pgsql' => PostgreSQL::class,
'oci' => OCI::class,
@ -334,13 +334,13 @@ class Setup {
$options['directory'] = \OC::$SERVERROOT . '/data';
}
if (!isset(self::$dbSetupClasses[$dbType])) {
if (!isset(self::DB_SETUP_CLASSES[$dbType])) {
$dbType = 'sqlite';
}
$dataDir = htmlspecialchars_decode($options['directory']);
$class = self::$dbSetupClasses[$dbType];
$class = self::DB_SETUP_CLASSES[$dbType];
/** @var AbstractDatabase $dbSetup */
$dbSetup = new $class($l, $this->config, $this->logger, $this->random);
$error = array_merge($error, $dbSetup->validate($options));

View file

@ -412,24 +412,13 @@ class Util {
return \OC_Hook::emit($signalclass, $signalname, $params);
}
/**
* Cached encrypted CSRF token. Some static unit-tests of ownCloud compare
* multiple Template elements which invoke `callRegister`. If the value
* would not be cached these unit-tests would fail.
* @var string
*/
private static $token = '';
/**
* Register an get/post call. This is important to prevent CSRF attacks
* @since 4.5.0
* @deprecated 32.0.0 directly use CsrfTokenManager instead
*/
public static function callRegister() {
if (self::$token === '') {
self::$token = \OCP\Server::get(CsrfTokenManager::class)->getToken()->getEncryptedValue();
}
return self::$token;
return \OCP\Server::get(CsrfTokenManager::class)->getToken()->getEncryptedValue();
}
/**