Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

chore(php): Refactor empty array check in core and lib #38191

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion core/BackgroundJobs/CheckForUserCertificates.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public function run($arguments): void {
\OC_Util::tearDownFS();
});

if (empty($uploadList)) {
if ($uploadList === []) {
$this->config->deleteAppValue('files_external', 'user_certificate_scan');
} else {
$this->config->setAppValue('files_external', 'user_certificate_scan', json_encode($uploadList));
Expand Down
2 changes: 1 addition & 1 deletion core/Command/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ protected function writeTableInOutputFormat(InputInterface $input, OutputInterfa
default:
$table = new Table($output);
$table->setRows($items);
if (!empty($items) && is_string(array_key_first(reset($items)))) {
if ($items !== [] && is_string(array_key_first(reset($items)))) {
$table->setHeaders(array_keys(reset($items)));
}
$table->render();
Expand Down
6 changes: 3 additions & 3 deletions core/Command/Config/Import.php
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ protected function getArrayFromFile($importFile) {
*/
protected function validateFileContent($content) {
$decodedContent = json_decode($content, true);
if (!is_array($decodedContent) || empty($decodedContent)) {
if (!is_array($decodedContent) || $decodedContent === []) {
throw new \UnexpectedValueException('The file must contain a valid json array');
}

Expand All @@ -138,10 +138,10 @@ protected function validateArray($array) {
$arrayKeys = array_keys($array);
$additionalKeys = array_diff($arrayKeys, $this->validRootKeys);
$commonKeys = array_intersect($arrayKeys, $this->validRootKeys);
if (!empty($additionalKeys)) {
if ($additionalKeys !== []) {
throw new \UnexpectedValueException('Found invalid entries in root: ' . implode(', ', $additionalKeys));
}
if (empty($commonKeys)) {
if ($commonKeys === []) {
throw new \UnexpectedValueException('At least one key of the following is expected: ' . implode(', ', $this->validRootKeys));
}

Expand Down
4 changes: 2 additions & 2 deletions core/Command/Config/System/Base.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ public function __construct(SystemConfig $systemConfig) {
public function completeArgumentValues($argumentName, CompletionContext $context) {
if ($argumentName === 'name') {
$words = $this->getPreviousNames($context, $context->getWordIndex());
if (empty($words)) {
if ($words === []) {
$completions = $this->systemConfig->getKeys();
} else {
$key = array_shift($words);
$value = $this->systemConfig->getValue($key);
$completions = array_keys($value);

while (!empty($words) && is_array($value)) {
while ($words !== [] && is_array($value)) {
$key = array_shift($words);
if (!isset($value[$key]) || !is_array($value[$key])) {
break;
Expand Down
2 changes: 1 addition & 1 deletion core/Command/Config/System/DeleteConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ protected function removeSubValue($keys, $currentValue, $throwError) {

if (is_array($currentValue)) {
if (isset($currentValue[$nextKey])) {
if (empty($keys)) {
if ($keys === []) {
unset($currentValue[$nextKey]);
} else {
$currentValue[$nextKey] = $this->removeSubValue($keys, $currentValue[$nextKey], $throwError);
Expand Down
2 changes: 1 addition & 1 deletion core/Command/Config/System/GetConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$configValue = $defaultValue;
} else {
$configValue = $this->systemConfig->getValue($configName);
if (!empty($configNames)) {
if ($configNames !== []) {
foreach ($configNames as $configName) {
if (isset($configValue[$configName])) {
$configValue = $configValue[$configName];
Expand Down
2 changes: 1 addition & 1 deletion core/Command/Config/System/SetConfig.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ protected function mergeArrayValue(array $configNames, $existingValues, $value,
if (!is_array($existingValues)) {
$existingValues = [];
}
if (!empty($configNames)) {
if ($configNames !== []) {
if (isset($existingValues[$configName])) {
$existingValue = $existingValues[$configName];
} else {
Expand Down
2 changes: 1 addition & 1 deletion core/Command/Db/ConvertFilecacheBigInt.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
}
}

if (empty($updates)) {
if ($updates === []) {
$output->writeln('<info>All tables already up to date!</info>');
return 0;
}
Expand Down
2 changes: 1 addition & 1 deletion core/Command/Db/ConvertType.php
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int

// warn/fail if there are more tables in 'from' database
$extraFromTables = array_diff($fromTables, $toTables);
if (!empty($extraFromTables)) {
if ($extraFromTables !== []) {
$output->writeln('<comment>The following tables will not be converted:</comment>');
$output->writeln($extraFromTables);
if (!$input->getOption('all-apps')) {
Expand Down
2 changes: 1 addition & 1 deletion core/Command/TwoFactorAuth/State.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ private function filterEnabledDisabledUnknownProviders(array $providerStates): a

private function printProviders(string $title, array $providers,
OutputInterface $output) {
if (empty($providers)) {
if ($providers === []) {
// Ignore and don't print anything
return;
}
Expand Down
2 changes: 1 addition & 1 deletion core/Command/User/Report.php
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int
$table->setHeaders(['User Report', '']);
$userCountArray = $this->countUsers();
$total = 0;
if (!empty($userCountArray)) {
if ($userCountArray !== []) {
$rows = [];
foreach ($userCountArray as $classname => $users) {
$total += $users;
Expand Down
2 changes: 1 addition & 1 deletion core/ajax/update.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ function (MigratorExecuteSqlEvent $event) use ($eventSource, $l): void {
$disabledApps[$app] = $l->t('%s (incompatible)', [$app]);
}

if (!empty($disabledApps)) {
if ($disabledApps !== []) {
$eventSource->send('notice', $l->t('The following apps have been disabled: %s', [implode(', ', $disabledApps)]));
}
} else {
Expand Down
6 changes: 3 additions & 3 deletions lib/base.php
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,7 @@ public static function initPaths(): void {
OC::$APPSROOTS[] = ['path' => OC::$SERVERROOT . '/apps', 'url' => '/apps', 'writable' => true];
}

if (empty(OC::$APPSROOTS)) {
if (OC::$APPSROOTS === []) {
throw new \RuntimeException('apps directory not found! Please put the Nextcloud apps folder in the Nextcloud folder'
. '. You can also configure the location in the config.php file.');
}
Expand Down Expand Up @@ -392,7 +392,7 @@ private static function printUpgradePage(\OC\SystemConfig $systemConfig): void {
}
}

if (!empty($incompatibleShippedApps)) {
if ($incompatibleShippedApps !== []) {
$l = Server::get(\OCP\L10N\IFactory::class)->get('core');
$hint = $l->t('Application %1$s is not present or has a non-compatible version with this server. Please check the apps directory.', [implode(', ', $incompatibleShippedApps)]);
throw new \OCP\HintException('Application ' . implode(', ', $incompatibleShippedApps) . ' is not present or has a non-compatible version with this server. Please check the apps directory.', $hint);
Expand Down Expand Up @@ -919,7 +919,7 @@ private static function registerAppRestrictionsHooks(): void {
$key = array_search($group->getGID(), $restrictions);
unset($restrictions[$key]);
$restrictions = array_values($restrictions);
if (empty($restrictions)) {
if ($restrictions === []) {
$appManager->disableApp($appId);
} else {
$appManager->enableAppForGroups($appId, $restrictions);
Expand Down
2 changes: 1 addition & 1 deletion lib/composer/composer/ClassLoader.php
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ public function __construct($vendorDir = null)
*/
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
if ($this->prefixesPsr0 !== []) {
return call_user_func_array('array_merge', array_values($this->prefixesPsr0));
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/Accounts/AccountManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -354,7 +354,7 @@ protected function getUser(IUser $user, bool $insertIfNotExists = true): array {
$accountData = $result->fetchAll();
$result->closeCursor();

if (empty($accountData)) {
if ($accountData === []) {
$userData = $this->buildDefaultUserRecord($user);
if ($insertIfNotExists) {
$this->insertNewUser($user, $userData);
Expand Down
2 changes: 1 addition & 1 deletion lib/private/App/AppManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ public function hasProtectedAppType($types) {
}

$protectedTypes = array_intersect($this->protectedAppTypes, $types);
return !empty($protectedTypes);
return $protectedTypes !== [];
}

/**
Expand Down
4 changes: 2 additions & 2 deletions lib/private/App/AppStore/Fetcher/AppFetcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ protected function fetch($ETag, $content, $allowUnstable = false) {
/** @var mixed[] $response */
$response = parent::fetch($ETag, $content);

if (empty($response)) {
if ($response === []) {
return [];
}

Expand Down Expand Up @@ -139,7 +139,7 @@ protected function fetch($ETag, $content, $allowUnstable = false) {
}
}

if (empty($releases)) {
if ($releases === []) {
// Remove apps that don't have a matching release
$response['data'][$dataKey] = [];
continue;
Expand Down
2 changes: 1 addition & 1 deletion lib/private/App/AppStore/Fetcher/Fetcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ public function get($allowUnstable = false) {
try {
$responseJson = $this->fetch($ETag, $content, $allowUnstable);

if (empty($responseJson)) {
if ($responseJson === []) {
return [];
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/AppFramework/Http/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ public function dispatch(Controller $controller, string $methodName): array {

$response = $this->executeController($controller, $methodName);

if (!empty($databaseStatsBefore)) {
if ($databaseStatsBefore !== []) {
$databaseStatsAfter = $this->connection->getInner()->getStats();
$numBuilt = $databaseStatsAfter['built'] - $databaseStatsBefore['built'];
$numExecuted = $databaseStatsAfter['executed'] - $databaseStatsBefore['executed'];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ public function beforeController($controller, $methodName) {
$reflectionMethod = new ReflectionMethod($controller, $methodName);
$attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);

if (!empty($attributes)) {
if ($attributes !== []) {
$remoteAddress = $this->request->getRemoteAddress();

foreach ($attributes as $attribute) {
Expand All @@ -99,7 +99,7 @@ public function afterController($controller, $methodName, Response $response) {
$reflectionMethod = new ReflectionMethod($controller, $methodName);
$attributes = $reflectionMethod->getAttributes(BruteForceProtection::class);

if (!empty($attributes)) {
if ($attributes !== []) {
$ip = $this->request->getRemoteAddress();
$metaData = $response->getThrottleMetadata();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ protected function getAuthorizedAdminSettingClasses(ReflectionMethod $reflection
}

$attributes = $reflectionMethod->getAttributes(AuthorizedAdminSetting::class);
if (!empty($attributes)) {
if ($attributes !== []) {
foreach ($attributes as $attribute) {
/** @var AuthorizedAdminSetting $setting */
$setting = $attribute->newInstance();
Expand Down
4 changes: 2 additions & 2 deletions lib/private/Authentication/Login/TwoFactorCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ public function process(LoginData $loginData): LoginResult {
$providerSet = $this->twoFactorManager->getProviderSet($loginData->getUser());
$loginProviders = $this->twoFactorManager->getLoginSetupProviders($loginData->getUser());
$providers = $providerSet->getPrimaryProviders();
if (empty($providers)
if ($providers === []
&& !$providerSet->isProviderMissing()
&& !empty($loginProviders)
&& $loginProviders !== []
&& $this->mandatoryTwoFactor->isEnforcedFor($loginData->getUser())) {
// No providers set up, but 2FA is enforced and setup providers are available
$url = 'core.TwoFactorChallenge.setupProviders';
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Authentication/Token/RemoteWipe.php
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ public function markAllTokensForWipe(IUser $user): bool {
return $token instanceof IWipeableToken;
});

if (empty($wipeable)) {
if ($wipeable === []) {
return false;
}

Expand Down
4 changes: 2 additions & 2 deletions lib/private/Authentication/TwoFactorAuth/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ public function isTwoFactorAuthenticated(IUser $user): bool {
$providerIds = array_keys($enabled);
$providerIdsWithoutBackupCodes = array_diff($providerIds, [self::BACKUP_CODES_PROVIDER_ID]);

$this->userIsTwoFactorAuthenticated[$user->getUID()] = !empty($providerIdsWithoutBackupCodes);
$this->userIsTwoFactorAuthenticated[$user->getUID()] = $providerIdsWithoutBackupCodes !== [];
return $this->userIsTwoFactorAuthenticated[$user->getUID()];
}

Expand Down Expand Up @@ -222,7 +222,7 @@ private function isProviderMissing(array $states, array $providers): bool {
}
}

if (!empty($missing)) {
if ($missing !== []) {
// There was at least one provider missing
$this->logger->alert(count($missing) . " two-factor auth providers failed to load", ['app' => 'core']);

Expand Down
8 changes: 4 additions & 4 deletions lib/private/Calendar/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public function handleIMipReply(string $principalUri, string $sender, string $re
}

$calendars = $this->getCalendarsForPrincipal($principalUri);
if (empty($calendars)) {
if ($calendars === []) {
$this->logger->warning('Could not find any calendars for principal ' . $principalUri);
return false;
}
Expand All @@ -283,7 +283,7 @@ public function handleIMipReply(string $principalUri, string $sender, string $re
// We should not search in writable calendars
if ($calendar instanceof IHandleImipMessage) {
$o = $calendar->search($sender, ['ATTENDEE'], ['uid' => $vEvent->{'UID'}->getValue()]);
if (!empty($o)) {
if ($o !== []) {
$found = $calendar;
$name = $o[0]['uri'];
break;
Expand Down Expand Up @@ -347,7 +347,7 @@ public function handleIMipCancel(string $principalUri, string $sender, ?string $

// Check if we have a calendar to work with
$calendars = $this->getCalendarsForPrincipal($principalUri);
if (empty($calendars)) {
if ($calendars === []) {
$this->logger->warning('Could not find any calendars for principal ' . $principalUri);
return false;
}
Expand All @@ -361,7 +361,7 @@ public function handleIMipCancel(string $principalUri, string $sender, ?string $
// We should not search in writable calendars
if ($calendar instanceof IHandleImipMessage) {
$o = $calendar->search($recipient, ['ATTENDEE'], ['uid' => $vEvent->{'UID'}->getValue()]);
if (!empty($o)) {
if ($o !== []) {
$found = $calendar;
$name = $o[0]['uri'];
break;
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Collaboration/Collaborators/GroupPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ public function search($search, $limit, $offset, ISearchResult $searchResult) {
}

$userGroups = [];
if (!empty($groups) && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) {
if ($groups !== [] && ($this->shareWithGroupOnly || $this->shareeEnumerationInGroupOnly)) {
// Intersect all the groups that match with the groups this user is a member of
$userGroups = $this->groupManager->getUserGroups($this->userSession->getUser());
$userGroups = array_map(function (IGroup $group) {
Expand Down
6 changes: 3 additions & 3 deletions lib/private/Collaboration/Collaborators/UserPlugin.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public function search($search, $limit, $offset, ISearchResult $searchResult) {

if (!$this->shareWithGroupOnly && $this->shareeEnumerationPhone) {
$usersTmp = $this->userManager->searchKnownUsersByDisplayName($currentUserId, $search, $limit, $offset);
if (!empty($usersTmp)) {
if ($usersTmp !== []) {
foreach ($usersTmp as $user) {
if ($user->isEnabled()) { // Don't keep deactivated users
$users[$user->getUID()] = $user;
Expand Down Expand Up @@ -217,7 +217,7 @@ public function search($search, $limit, $offset, ISearchResult $searchResult) {

if (!$addToWideResults && $this->shareeEnumerationInGroupOnly) {
$commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
if (!empty($commonGroups)) {
if ($commonGroups !== []) {
$addToWideResults = true;
}
}
Expand Down Expand Up @@ -248,7 +248,7 @@ public function search($search, $limit, $offset, ISearchResult $searchResult) {
if ($this->shareWithGroupOnly) {
// Only add, if we have a common group
$commonGroups = array_intersect($currentUserGroups, $this->groupManager->getUserGroupIds($user));
$addUser = !empty($commonGroups);
$addUser = $commonGroups !== [];
}

if ($addUser) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ private function fetchReference(Reference $reference): void {
$userFolder = $this->rootFolder->getUserFolder($this->userId);
$files = $userFolder->getById($fileId);

if (empty($files)) {
if ($files === []) {
throw new NotFoundException();
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/Collaboration/Reference/ReferenceManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ public function touchProvider(string $userId, string $providerId, ?int $timestam
$matchingProviders = array_filter($providers, static function (IDiscoverableReferenceProvider $provider) use ($providerId) {
return $provider->getId() === $providerId;
});
if (!empty($matchingProviders)) {
if ($matchingProviders !== []) {
if ($timestamp === null) {
$timestamp = time();
}
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Collaboration/Resources/Manager.php
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ public function searchCollections(IUser $user, string $filter, int $limit = 50,
}
$result->closeCursor();

if (empty($collections) && $foundResults === $limit) {
if ($collections === [] && $foundResults === $limit) {
return $this->searchCollections($user, $filter, $limit, $start + $limit);
}

Expand Down
Loading