Passed
Push — master ( 4ba04f...598605 )
by Pauli
03:26 queued 13s
created

Util::stringCaseCompare()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php declare(strict_types=1);
2
3
/**
4
 * ownCloud - Music app
5
 *
6
 * This file is licensed under the Affero General Public License version 3 or
7
 * later. See the COPYING file.
8
 *
9
 * @author Pauli Järvinen <[email protected]>
10
 * @copyright Pauli Järvinen 2018 - 2021
11
 */
12
13
namespace OCA\Music\Utility;
14
15
use OCP\Files\Folder;
16
17
/**
18
 * Miscellaneous static utility functions
19
 */
20
class Util {
21
22
	/**
23
	 * Map the given array by calling a named member function for each of the array elements
24
	 */
25
	public static function arrayMapMethod(array $arr, string $methodName, array $methodArgs=[]) : array {
26
		$func = function ($obj) use ($methodName, $methodArgs) {
27
			return \call_user_func_array([$obj, $methodName], $methodArgs);
28
		};
29
		return \array_map($func, $arr);
30
	}
31
32
	/**
33
	 * Extract ID of each array element by calling getId and return
34
	 * the IDs as an array
35
	 */
36
	public static function extractIds(array $arr) : array {
37
		return self::arrayMapMethod($arr, 'getId');
38
	}
39
40
	/**
41
	 * Extract User ID of each array element by calling getUserId and return
42
	 * the IDs as an array
43
	 */
44
	public static function extractUserIds(array $arr) : array {
45
		return self::arrayMapMethod($arr, 'getUserId');
46
	}
47
48
	/**
49
	 * Create look-up table from given array of items which have a `getId` function.
50
	 * @return array where keys are the values returned by `getId` of each item
51
	 */
52
	public static function createIdLookupTable(array $array) : array {
53
		$lut = [];
54
		foreach ($array as $item) {
55
			$lut[$item->getId()] = $item;
56
		}
57
		return $lut;
58
	}
59
60
	/**
61
	 * Get difference of two arrays, i.e. elements belonging to $b but not $a.
62
	 * This function is faster than the built-in array_diff for large arrays but
63
	 * at the expense of higher RAM usage and can be used only for arrays of
64
	 * integers or strings.
65
	 * From https://stackoverflow.com/a/8827033
66
	 */
67
	public static function arrayDiff(array $b, array $a) : array {
68
		$at = \array_flip($a);
69
		$d = [];
70
		foreach ($b as $i) {
71
			if (!isset($at[$i])) {
72
				$d[] = $i;
73
			}
74
		}
75
		return $d;
76
	}
77
78
	/**
79
	 * Get multiple items from @a $array, as indicated by a second array @a $indices.
80
	 */
81
	public static function arrayMultiGet(array $array, array $indices) : array {
82
		$result = [];
83
		foreach ($indices as $index) {
84
			$result[] = $array[$index];
85
		}
86
		return $result;
87
	}
88
89
	/**
90
	 * Like the built-in function \array_filter but this one works recursively on nested arrays.
91
	 * Another difference is that this function always requires an explicit callback condition.
92
	 * Both inner nodes and leafs nodes are passed to the $condition.
93
	 */
94
	public static function arrayFilterRecursive(array  $array, callable $condition) : array {
95
		$result = [];
96
97
		foreach ($array as $key => $value) {
98
			if ($condition($value)) {
99
				if (\is_array($value)) {
100
					$result[$key] = self::arrayFilterRecursive($value, $condition);
101
				} else {
102
					$result[$key] = $value;
103
				}
104
			}
105
		}
106
107
		return $result;
108
	}
109
110
	/**
111
	 * Inverse operation of self::arrayFilterRecursive, keeping only those items where
112
	 * the $condition evaluates to *false*.
113
	 */
114
	public static function arrayRejectRecursive(array $array, callable $condition) : array {
115
		$invCond = function($item) use ($condition) {
116
			return !$condition($item);
117
		};
118
		return self::arrayFilterRecursive($array, $invCond);
119
	}
120
121
	/**
122
	 * Convert the given array $arr so that keys of the potentially multi-dimensional array
123
	 * are converted using the mapping given in $dictionary. Keys not found from $dictionary
124
	 * are not altered.
125
	 */
126
	public static function convertArrayKeys(array $arr, array $dictionary) : array {
127
		$newArr = [];
128
129
		foreach ($arr as $k => $v) {
130
			$key = $dictionary[$k] ?? $k;
131
			$newArr[$key] = \is_array($v) ? self::convertArrayKeys($v, $dictionary) : $v;
132
		}
133
134
		return $newArr;
135
	}
136
137
	/**
138
	 * Walk through the given, potentially multi-dimensional, array and cast all leaf nodes
139
	 * to integer type. The array is modified in-place.
140
	 */
141
	public static function intCastArrayValues(array $arr) : void {
142
		\array_walk_recursive($arr, function(&$value) {
143
			$value = \intval($value);
144
		});
145
	}
146
147
	/**
148
	 * Like the built-in \explode(...) function but this one can be safely called with
149
	 * null string, and no warning will be emitted. Also, this returns an empty array from
150
	 * null and '' inputs while the built-in alternative returns a 1-item array containing
151
	 * an empty string.
152
	 * @param string $delimiter
153
	 * @param string|null $string
154
	 * @return array
155
	 */
156
	public static function explode(string $delimiter, ?string $string) : array {
157
		if ($delimiter === '') {
158
			throw new \UnexpectedValueException();
159
		} elseif ($string === null || $string === '') {
160
			return [];
161
		} else {
162
			return \explode($delimiter, $string);
163
		}
164
	}
165
166
	/**
167
	 * Truncate the given string to maximum length, appendig ellipsis character
168
	 * if the truncation happened. Also null argument may be safely passed and
169
	 * it remains unaltered.
170
	 */
171
	public static function truncate(?string $string, int $maxLength) : ?string {
172
		if ($string === null) {
173
			return null;
174
		} else {
175
			return \mb_strimwidth($string, 0, $maxLength, "\u{2026}");
176
		}
177
	}
178
179
	/**
180
	 * Test if given string starts with another given string
181
	 */
182
	public static function startsWith(string $string, string $potentialStart, bool $ignoreCase=false) : bool {
183
		$actualStart = \substr($string, 0, \strlen($potentialStart));
184
		if ($ignoreCase) {
185
			$actualStart = \mb_strtolower($actualStart);
186
			$potentialStart = \mb_strtolower($potentialStart);
187
		}
188
		return $actualStart === $potentialStart;
189
	}
190
191
	/**
192
	 * Test if given string ends with another given string
193
	 */
194
	public static function endsWith(string $string, string $potentialEnd, bool $ignoreCase=false) : bool {
195
		$actualEnd = \substr($string, -\strlen($potentialEnd));
196
		if ($ignoreCase) {
197
			$actualEnd = \mb_strtolower($actualEnd);
198
			$potentialEnd = \mb_strtolower($potentialEnd);
199
		}
200
		return $actualEnd === $potentialEnd;
201
	}
202
203
	/**
204
	 * Multi-byte safe case-insensitive string comparison
205
	 * @return int negative value if $a is less than $b, positive value if $a is greater than $b, and 0 if they are equal.
206
	 */
207
	public static function stringCaseCompare(?string $a, ?string $b) : int {
208
		return \strcmp(\mb_strtolower($a ?? ''), \mb_strtolower($b ?? ''));
209
	}
210
211
	/**
212
	 * Test if $item is a string and not empty or only consisting of whitespace
213
	 */
214
	public static function isNonEmptyString(/*mixed*/ $item) : bool {
215
		return \is_string($item) && \trim($item) !== '';
216
	}
217
218
	/**
219
	 * Convert file size given in bytes to human-readable format
220
	 */
221
	public static function formatFileSize(?int $bytes, int $decimals = 1) : ?string {
222
		if ($bytes === null) {
223
			return null;
224
		} else {
225
			$units = 'BKMGTP';
226
			$factor = \floor((\strlen((string)$bytes) - 1) / 3);
227
			return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
228
		}
229
	}
230
231
	/**
232
	 * Convert time given as seconds to the HH:MM:SS format
233
	 */
234
	public static function formatTime(?int $seconds) : ?string {
235
		if ($seconds === null) {
236
			return null;
237
		} else {
238
			return \sprintf('%02d:%02d:%02d', ($seconds/3600), ($seconds/60%60), $seconds%60);
239
		}
240
	}
241
242
	/**
243
	 * Convert date and time given in the SQL format to the ISO UTC "Zulu format" e.g. "2021-08-19T19:33:15Z"
244
	 */
245
	public static function formatZuluDateTime(?string $dbDateString) : ?string {
246
		if ($dbDateString === null) {
247
			return null;
248
		} else {
249
			$dateTime = new \DateTime($dbDateString);
250
			return $dateTime->format('Y-m-d\TH:i:s.v\Z');
251
		}
252
	}
253
254
	/**
255
	 * Convert date and time given in the SQL format to the ISO UTC "offset format" e.g. "2021-08-19T19:33:15+00:00"
256
	 */
257
	public static function formatDateTimeUtcOffset(?string $dbDateString) : ?string {
258
		if ($dbDateString === null) {
259
			return null;
260
		} else {
261
			$dateTime = new \DateTime($dbDateString);
262
			return $dateTime->format('c');
263
		}
264
	}
265
266
	/**
267
	 * Get a Folder object using a parent Folder object and a relative path
268
	 */
269
	public static function getFolderFromRelativePath(Folder $parentFolder, string $relativePath) : Folder {
270
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
271
			$node = $parentFolder->get($relativePath);
272
			if ($node instanceof Folder) {
273
				return $node;
274
			} else {
275
				throw new \InvalidArgumentException('Path points to a file while folder expected');
276
			}
277
		} else {
278
			return $parentFolder;
279
		}
280
	}
281
282
	/**
283
	 * Create relative path from the given working dir (CWD) to the given target path
284
	 * @param string $cwdPath Absolute CWD path
285
	 * @param string $targetPath Absolute target path
286
	 */
287
	public static function relativePath(string $cwdPath, string $targetPath) : string {
288
		$cwdParts = \explode('/', $cwdPath);
289
		$targetParts = \explode('/', $targetPath);
290
291
		// remove the common prefix of the paths
292
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
293
			\array_shift($cwdParts);
294
			\array_shift($targetParts);
295
		}
296
297
		// prepend up-navigation from CWD to the closest common parent folder with the target
298
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
299
			\array_unshift($targetParts, '..');
300
		}
301
302
		return \implode('/', $targetParts);
303
	}
304
305
	/**
306
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
307
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
308
	 */
309
	public static function resolveRelativePath(string $cwdPath, string $relativePath) : string {
310
		$cwdParts = \explode('/', $cwdPath);
311
		$relativeParts = \explode('/', $relativePath);
312
313
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
314
		if ($cwdParts[\count($cwdParts)-1] === '') {
315
			\array_pop($cwdParts);
316
		}
317
318
		foreach ($relativeParts as $part) {
319
			if ($part === '..') {
320
				\array_pop($cwdParts);
321
			} else {
322
				\array_push($cwdParts, $part);
323
			}
324
		}
325
326
		return \implode('/', $cwdParts);
327
	}
328
329
	/**
330
	 * Encode a file path so that it can be used as part of a WebDAV URL
331
	 */
332
	public static function urlEncodePath(string $path) : string {
333
		// URL encode each part of the file path
334
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
335
	}
336
337
	/**
338
	 * Compose URL from parts as returned by the system function parse_url.
339
	 * From https://stackoverflow.com/a/35207936
340
	 */
341
	public static function buildUrl(array $parts) : string {
342
		return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') .
343
				((isset($parts['user']) || isset($parts['host'])) ? '//' : '') .
344
				(isset($parts['user']) ? "{$parts['user']}" : '') .
345
				(isset($parts['pass']) ? ":{$parts['pass']}" : '') .
346
				(isset($parts['user']) ? '@' : '') .
347
				(isset($parts['host']) ? "{$parts['host']}" : '') .
348
				(isset($parts['port']) ? ":{$parts['port']}" : '') .
349
				(isset($parts['path']) ? "{$parts['path']}" : '') .
350
				(isset($parts['query']) ? "?{$parts['query']}" : '') .
351
				(isset($parts['fragment']) ? "#{$parts['fragment']}" : '');
352
	}
353
354
	/**
355
	 * Swap values of two variables in place
356
	 * @param mixed $a
357
	 * @param mixed $b
358
	 */
359
	public static function swap(&$a, &$b) : void {
360
		$temp = $a;
361
		$a = $b;
362
		$b = $temp;
363
	}
364
}
365