Skip to content

Commit

Permalink
Merge pull request #38261 from fsamapoor/replace_strpos_calls_in_lib_…
Browse files Browse the repository at this point in the history
…private

Refactors "strpos" calls in  lib/private to improve code readability.
  • Loading branch information
icewind1991 authored Jun 1, 2023
2 parents e81fdfe + fa31c70 commit 9f1d497
Show file tree
Hide file tree
Showing 65 changed files with 108 additions and 112 deletions.
2 changes: 1 addition & 1 deletion lib/private/Accounts/AccountManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ protected function parsePhoneNumber(string $input): string {

if ($defaultRegion === '') {
// When no default region is set, only +49… numbers are valid
if (strpos($input, '+') !== 0) {
if (!str_starts_with($input, '+')) {
throw new InvalidArgumentException(self::PROPERTY_PHONE);
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/Accounts/AccountProperty.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ public function getScope(): string {
}

public static function mapScopeToV2(string $scope): string {
if (strpos($scope, 'v2-') === 0) {
if (str_starts_with($scope, 'v2-')) {
return $scope;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/App/AppStore/Fetcher/AppFetcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ protected function fetch($ETag, $content, $allowUnstable = false) {
foreach ($app['releases'] as $release) {
// Exclude all nightly and pre-releases if required
if (($allowNightly || $release['isNightly'] === false)
&& ($allowPreReleases || strpos($release['version'], '-') === false)) {
&& ($allowPreReleases || !str_contains($release['version'], '-'))) {
// Exclude all versions not compatible with the current version
try {
$versionParser = new VersionParser();
Expand Down
2 changes: 1 addition & 1 deletion lib/private/App/AppStore/Version/VersionParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public function getVersion($versionSpec) {
if (!$this->isValidVersionString($firstVersionNumber)) {
break;
}
if (strpos($firstVersion, '>') === 0) {
if (str_starts_with($firstVersion, '>')) {
return new Version($firstVersionNumber, '');
}
return new Version('', $firstVersionNumber);
Expand Down
2 changes: 1 addition & 1 deletion lib/private/App/DependencyAnalyzer.php
Original file line number Diff line number Diff line change
Expand Up @@ -383,7 +383,7 @@ protected function toVisibleVersion($version) {
case '9.1':
return '10';
default:
if (strpos($version, '9.1.') === 0) {
if (str_starts_with($version, '9.1.')) {
$version = '10.0.' . substr($version, 4);
}
return $version;
Expand Down
6 changes: 3 additions & 3 deletions lib/private/AppFramework/App.php
Original file line number Diff line number Diff line change
Expand Up @@ -92,12 +92,12 @@ public static function buildAppNamespace(string $appId, string $topNamespace = '
}

public static function getAppIdForClass(string $className, string $topNamespace = 'OCA\\'): ?string {
if (strpos($className, $topNamespace) !== 0) {
if (!str_starts_with($className, $topNamespace)) {
return null;
}

foreach (self::$nameSpaceCache as $appId => $namespace) {
if (strpos($className, $topNamespace . $namespace . '\\') === 0) {
if (str_starts_with($className, $topNamespace . $namespace . '\\')) {
return $appId;
}
}
Expand Down Expand Up @@ -148,7 +148,7 @@ public static function main(string $controllerName, string $methodName, DIContai
try {
$controller = $container->get($controllerName);
} catch (QueryException $e) {
if (strpos($controllerName, '\\Controller\\') !== false) {
if (str_contains($controllerName, '\\Controller\\')) {
// This is from a global registered app route that is not enabled.
[/*OC(A)*/, $app, /* Controller/Name*/] = explode('\\', $controllerName, 3);
throw new HintException('App ' . strtolower($app) . ' is not enabled');
Expand Down
4 changes: 2 additions & 2 deletions lib/private/AppFramework/Http/Dispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ private function executeController(Controller $controller, string $methodName):
$value === 'false' &&
(
$this->request->method === 'GET' ||
strpos($this->request->getHeader('Content-Type'),
'application/x-www-form-urlencoded') !== false
str_contains($this->request->getHeader('Content-Type'),
'application/x-www-form-urlencoded')
)
) {
$value = false;
Expand Down
18 changes: 9 additions & 9 deletions lib/private/AppFramework/Http/Request.php
Original file line number Diff line number Diff line change
Expand Up @@ -413,8 +413,8 @@ private function isPutStreamContent(): bool {
return $this->method === 'PUT'
&& $this->getHeader('Content-Length') !== '0'
&& $this->getHeader('Content-Length') !== ''
&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') === false
&& strpos($this->getHeader('Content-Type'), 'application/json') === false;
&& !str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')
&& !str_contains($this->getHeader('Content-Type'), 'application/json');
}

/**
Expand All @@ -439,7 +439,7 @@ protected function decodeContent() {
// or post correctly
} elseif ($this->method !== 'GET'
&& $this->method !== 'POST'
&& strpos($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded') !== false) {
&& str_contains($this->getHeader('Content-Type'), 'application/x-www-form-urlencoded')) {
parse_str(file_get_contents($this->inputStream), $params);
if (\is_array($params)) {
$this->items['params'] = $params;
Expand Down Expand Up @@ -603,7 +603,7 @@ public function getRemoteAddress(): string {
$IP = trim($IP);

// remove brackets from IPv6 addresses
if (strpos($IP, '[') === 0 && substr($IP, -1) === ']') {
if (str_starts_with($IP, '[') && str_ends_with($IP, ']')) {
$IP = substr($IP, 1, -1);
}

Expand Down Expand Up @@ -642,7 +642,7 @@ public function getServerProtocol(): string {
}

if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_PROTO'])) {
if (strpos($this->server['HTTP_X_FORWARDED_PROTO'], ',') !== false) {
if (str_contains($this->server['HTTP_X_FORWARDED_PROTO'], ',')) {
$parts = explode(',', $this->server['HTTP_X_FORWARDED_PROTO']);
$proto = strtolower(trim($parts[0]));
} else {
Expand Down Expand Up @@ -724,7 +724,7 @@ public function getRawPathInfo(): string {
// FIXME: Sabre does not really belong here
[$path, $name] = \Sabre\Uri\split($scriptName);
if (!empty($path)) {
if ($path === $pathInfo || strpos($pathInfo, $path.'/') === 0) {
if ($path === $pathInfo || str_starts_with($pathInfo, $path . '/')) {
$pathInfo = substr($pathInfo, \strlen($path));
} else {
throw new \Exception("The requested uri($requestUri) cannot be processed by the script '$scriptName')");
Expand All @@ -734,10 +734,10 @@ public function getRawPathInfo(): string {
$name = '';
}

if (strpos($pathInfo, '/'.$name) === 0) {
if (str_starts_with($pathInfo, '/' . $name)) {
$pathInfo = substr($pathInfo, \strlen($name) + 1);
}
if ($name !== '' && strpos($pathInfo, $name) === 0) {
if ($name !== '' && str_starts_with($pathInfo, $name)) {
$pathInfo = substr($pathInfo, \strlen($name));
}
if ($pathInfo === false || $pathInfo === '/') {
Expand Down Expand Up @@ -803,7 +803,7 @@ public function getInsecureServerHost(): string {

$host = 'localhost';
if ($this->fromTrustedProxy() && isset($this->server['HTTP_X_FORWARDED_HOST'])) {
if (strpos($this->server['HTTP_X_FORWARDED_HOST'], ',') !== false) {
if (str_contains($this->server['HTTP_X_FORWARDED_HOST'], ',')) {
$parts = explode(',', $this->server['HTTP_X_FORWARDED_HOST']);
$host = trim(current($parts));
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public function afterController($controller, $methodName, Response $response) {

// Check if we are even asked for gzip
$header = $this->request->getHeader('Accept-Encoding');
if (strpos($header, 'gzip') === false) {
if (!str_contains($header, 'gzip')) {
return $response;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ public function beforeController($controller, $methodName) {
if (!$this->request->passesCSRFCheck() && !(
$controller instanceof OCSController && (
$this->request->getHeader('OCS-APIREQUEST') === 'true' ||
strpos($this->request->getHeader('Authorization'), 'Bearer ') === 0
str_starts_with($this->request->getHeader('Authorization'), 'Bearer ')
)
)) {
throw new CrossSiteRequestForgeryException();
Expand Down
2 changes: 1 addition & 1 deletion lib/private/AppFramework/OCS/BaseResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ protected function toXML(array $array, \XMLWriter $writer): void {
continue;
}

if (\is_string($k) && strpos($k, '@') === 0) {
if (\is_string($k) && str_starts_with($k, '@')) {
$writer->writeAttribute(substr($k, 1), $v);
continue;
}
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Cache/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ public function clear($prefix = '') {
$dh = $storage->opendir('/');
if (is_resource($dh)) {
while (($file = readdir($dh)) !== false) {
if ($file != '.' and $file != '..' and ($prefix === '' || strpos($file, $prefix) === 0)) {
if ($file != '.' and $file != '..' and ($prefix === '' || str_starts_with($file, $prefix))) {
$storage->unlink('/' . $file);
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Collaboration/Collaborators/Search.php
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ public function search($search, array $shareTypes, $lookup, $limit, $offset) {
// if we have an exact local user match with an email-a-like query,
// there is no need to show the remote and email matches.
$userType = new SearchResultType('users');
if (strpos($search, '@') !== false && $searchResult->hasExactIdMatch($userType)) {
if (str_contains($search, '@') && $searchResult->hasExactIdMatch($userType)) {
$searchResult->unsetResult($remoteType);
$searchResult->unsetResult($emailType);
}
Expand Down
4 changes: 2 additions & 2 deletions lib/private/Comments/Comment.php
Original file line number Diff line number Diff line change
Expand Up @@ -240,9 +240,9 @@ public function getMentions() {
$result = [];
foreach ($mentionIds as $mentionId) {
$cleanId = trim(substr($mentionId, 1), '"');
if (strpos($cleanId, 'guest/') === 0) {
if (str_starts_with($cleanId, 'guest/')) {
$result[] = ['type' => 'guest', 'id' => $cleanId];
} elseif (strpos($cleanId, 'group/') === 0) {
} elseif (str_starts_with($cleanId, 'group/')) {
$result[] = ['type' => 'group', 'id' => substr($cleanId, 6)];
} else {
$result[] = ['type' => 'user', 'id' => $cleanId];
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Contacts/ContactsMenu/ContactsStore.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ private function contactArrayToEntry(array $contact): Entry {
}

$avatarPrefix = "VALUE=uri:";
if (isset($contact['PHOTO']) && strpos($contact['PHOTO'], $avatarPrefix) === 0) {
if (isset($contact['PHOTO']) && str_starts_with($contact['PHOTO'], $avatarPrefix)) {
$entry->setAvatar(substr($contact['PHOTO'], strlen($avatarPrefix)));
}

Expand Down
4 changes: 2 additions & 2 deletions lib/private/DB/MySqlTools.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ protected function isMariaDBWithLargePrefix(IDBConnection $connection) {
return false;
}

return strpos($row, 'maria') && version_compare($row, '10.3', '>=') ||
strpos($row, 'maria') === false && version_compare($row, '8.0', '>=');
return str_contains($row, 'maria') && version_compare($row, '10.3', '>=') ||
!str_contains($row, 'maria') && version_compare($row, '8.0', '>=');
}
}
2 changes: 1 addition & 1 deletion lib/private/DB/QueryBuilder/QueryBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -1321,7 +1321,7 @@ public function getTableName($table) {
* @return string
*/
protected function prefixTableName($table) {
if ($this->automaticTablePrefix === false || strpos($table, '*PREFIX*') === 0) {
if ($this->automaticTablePrefix === false || str_starts_with($table, '*PREFIX*')) {
return $table;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/DB/SchemaWrapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ public function performDropTableCalls() {
public function getTableNamesWithoutPrefix() {
$tableNames = $this->schema->getTableNames();
return array_map(function ($tableName) {
if (strpos($tableName, $this->connection->getPrefix()) === 0) {
if (str_starts_with($tableName, $this->connection->getPrefix())) {
return substr($tableName, strlen($this->connection->getPrefix()));
}

Expand Down
5 changes: 1 addition & 4 deletions lib/private/Encryption/Util.php
Original file line number Diff line number Diff line change
Expand Up @@ -311,10 +311,7 @@ public function isExcluded($path) {
// detect alternative key storage root
$rootDir = $this->getKeyStorageRoot();
if ($rootDir !== '' &&
0 === strpos(
Filesystem::normalizePath($path),
Filesystem::normalizePath($rootDir)
)
str_starts_with(Filesystem::normalizePath($path), Filesystem::normalizePath($rootDir))
) {
return true;
}
Expand Down
8 changes: 4 additions & 4 deletions lib/private/Federation/CloudIdManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public function handleCardEvent(Event $event): void {
if ($event instanceof CardUpdatedEvent) {
$data = $event->getCardData()['carddata'];
foreach (explode("\r\n", $data) as $line) {
if (strpos($line, "CLOUD;") === 0) {
if (str_starts_with($line, "CLOUD;")) {
$parts = explode(':', $line, 2);
if (isset($parts[1])) {
$key = $parts[1];
Expand Down Expand Up @@ -210,9 +210,9 @@ public function getCloudId(string $user, ?string $remote): ICloudId {
* @return string
*/
private function removeProtocolFromUrl($url) {
if (strpos($url, 'https://') === 0) {
if (str_starts_with($url, 'https://')) {
return substr($url, strlen('https://'));
} elseif (strpos($url, 'http://') === 0) {
} elseif (str_starts_with($url, 'http://')) {
return substr($url, strlen('http://'));
}

Expand Down Expand Up @@ -246,6 +246,6 @@ protected function fixRemoteURL(string $remote): string {
* @return bool
*/
public function isValidCloudId(string $cloudId): bool {
return strpos($cloudId, '@') !== false;
return str_contains($cloudId, '@');
}
}
2 changes: 1 addition & 1 deletion lib/private/Files/Cache/Cache.php
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,7 @@ public function search($pattern) {
* @return ICacheEntry[] an array of cache entries where the mimetype matches the search
*/
public function searchByMime($mimetype) {
if (strpos($mimetype, '/') === false) {
if (!str_contains($mimetype, '/')) {
$operator = new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%');
} else {
$operator = new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype);
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Cache/LocalRootScanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,6 @@ public function scan($path, $recursive = self::SCAN_RECURSIVE, $reuse = -1, $loc

private function shouldScanPath(string $path): bool {
$path = trim($path, '/');
return $path === '' || strpos($path, 'appdata_') === 0 || strpos($path, '__groupfolders') === 0;
return $path === '' || str_starts_with($path, 'appdata_') || str_starts_with($path, '__groupfolders');
}
}
2 changes: 1 addition & 1 deletion lib/private/Files/Cache/Propagator.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ public function __construct(\OC\Files\Storage\Storage $storage, IDBConnection $c
public function propagateChange($internalPath, $time, $sizeDifference = 0) {
// Do not propagate changes in ignored paths
foreach ($this->ignore as $ignore) {
if (strpos($internalPath, $ignore) === 0) {
if (str_starts_with($internalPath, $ignore)) {
return;
}
}
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Cache/Scanner.php
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ public static function isPartialFile($file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'part') {
return true;
}
if (strpos($file, '.part/') !== false) {
if (str_contains($file, '.part/')) {
return true;
}

Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Cache/SearchBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ private function getOperatorFieldAndValue(ISearchComparison $operator) {
$field = 'mimepart';
$value = (int)$this->mimetypeLoader->getId($matches[1]);
$type = ISearchComparison::COMPARE_EQUAL;
} elseif (strpos($value, '%') !== false) {
} elseif (str_contains($value, '%')) {
throw new \InvalidArgumentException('Unsupported query value for mimetype: ' . $value . ', only values in the format "mime/type" or "mime/%" are supported');
} else {
$field = 'mimetype';
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Cache/Wrapper/CacheJail.php
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ protected function addJailFilterQuery(ISearchOperator $filter): ISearchOperator
}

public function getCacheEntryFromSearchResult(ICacheEntry $rawEntry): ?ICacheEntry {
if ($this->getGetUnjailedRoot() === '' || strpos($rawEntry->getPath(), $this->getGetUnjailedRoot()) === 0) {
if ($this->getGetUnjailedRoot() === '' || str_starts_with($rawEntry->getPath(), $this->getGetUnjailedRoot())) {
$rawEntry = $this->getCache()->getCacheEntryFromSearchResult($rawEntry);
if ($rawEntry) {
$jailedPath = $this->getJailedPath($rawEntry->getPath());
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Config/UserMountCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ public function getMountsInPath(IUser $user, string $path): array {
$path = rtrim($path, '/') . '/';
$mounts = $this->getMountsForUser($user);
return array_filter($mounts, function (ICachedMountInfo $mount) use ($path) {
return $mount->getMountPoint() !== $path && strpos($mount->getMountPoint(), $path) === 0;
return $mount->getMountPoint() !== $path && str_starts_with($mount->getMountPoint(), $path);
});
}
}
2 changes: 1 addition & 1 deletion lib/private/Files/Filesystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -451,7 +451,7 @@ public static function isValidPath($path) {
if (!$path || $path[0] !== '/') {
$path = '/' . $path;
}
if (strpos($path, '/../') !== false || strrchr($path, '/') === '/..') {
if (str_contains($path, '/../') || strrchr($path, '/') === '/..') {
return false;
}
return true;
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Mount/MountPoint.php
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ public function __construct(
$this->storage = $this->loader->wrap($this, $storage);
} else {
// Update old classes to new namespace
if (strpos($storage, 'OC_Filestorage_') !== false) {
if (str_contains($storage, 'OC_Filestorage_')) {
$storage = '\OC\Files\Storage\\' . substr($storage, 15);
}
$this->class = $storage;
Expand Down
2 changes: 1 addition & 1 deletion lib/private/Files/Mount/RootMountProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ private function validateObjectStoreConfig(array &$config) {

// instantiate object store implementation
$name = $config['class'];
if (strpos($name, 'OCA\\') === 0 && substr_count($name, '\\') >= 2) {
if (str_starts_with($name, 'OCA\\') && substr_count($name, '\\') >= 2) {
$segments = explode('\\', $name);
OC_App::loadApp(strtolower($segments[1]));
}
Expand Down
6 changes: 3 additions & 3 deletions lib/private/Files/Node/Folder.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ public function getRelativePath($path) {
* @return bool
*/
public function isSubNode($node) {
return strpos($node->getPath(), $this->path . '/') === 0;
return str_starts_with($node->getPath(), $this->path . '/');
}

/**
Expand Down Expand Up @@ -284,7 +284,7 @@ private function cacheEntryToFileInfo(IMountPoint $mount, string $appendRoot, IC
* @return Node[]
*/
public function searchByMime($mimetype) {
if (strpos($mimetype, '/') === false) {
if (!str_contains($mimetype, '/')) {
$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_LIKE, 'mimetype', $mimetype . '/%'));
} else {
$query = $this->queryFromOperator(new SearchComparison(ISearchComparison::COMPARE_EQUAL, 'mimetype', $mimetype));
Expand Down Expand Up @@ -339,7 +339,7 @@ protected function getByIdInRootMount(int $id): array {
$absolutePath = '/' . ltrim($cacheEntry->getPath(), '/');
$currentPath = rtrim($this->path, '/') . '/';

if (strpos($absolutePath, $currentPath) !== 0) {
if (!str_starts_with($absolutePath, $currentPath)) {
return [];
}

Expand Down
Loading

0 comments on commit 9f1d497

Please sign in to comment.