Passed
Push — master ( 124be7...f358a5 )
by Pauli
03:35 queued 16s
created

Util::relativePath()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 16
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 8
nc 4
nop 2
dl 0
loc 16
rs 9.6111
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 - 2025
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
	const UINT32_MAX = 0xFFFFFFFF;
23
	const SINT32_MAX = 0x7FFFFFFF;
24
	const SINT32_MIN = -self::SINT32_MAX - 1;
25
26
	/**
27
	 * Extract ID of each array element by calling getId and return
28
	 * the IDs as an array
29
	 */
30
	public static function extractIds(array $arr) : array {
31
		return \array_map(fn($i) => $i->getId(), $arr);
32
	}
33
34
	/**
35
	 * Extract User ID of each array element by calling getUserId and return
36
	 * the IDs as an array
37
	 */
38
	public static function extractUserIds(array $arr) : array {
39
		return \array_map(fn($i) => $i->getUserId(), $arr);
40
	}
41
42
	/**
43
	 * Create a look-up table from given array of items which have a `getId` function.
44
	 * @return array where keys are the values returned by `getId` of each item
45
	 */
46
	public static function createIdLookupTable(array $array) : array {
47
		$lut = [];
48
		foreach ($array as $item) {
49
			$lut[$item->getId()] = $item;
50
		}
51
		return $lut;
52
	}
53
54
	/**
55
	 * Create a look-up table from given array so that keys of the table are obtained by calling
56
	 * the given method on each array entry and the values are arrays of entries having the same
57
	 * value returned by that method.
58
	 * @param string $getKeyMethod Name of a method found on $array entries which returns a string or an int
59
	 * @return array [int|string => array]
60
	 */
61
	public static function arrayGroupBy(array $array, string $getKeyMethod) : array {
62
		$lut = [];
63
		foreach ($array as $item) {
64
			$lut[$item->$getKeyMethod()][] = $item;
65
		}
66
		return $lut;
67
	}
68
69
	/**
70
	 * Get difference of two arrays, i.e. elements belonging to $b but not $a.
71
	 * This function is faster than the built-in array_diff for large arrays but
72
	 * at the expense of higher RAM usage and can be used only for arrays of
73
	 * integers or strings.
74
	 * From https://stackoverflow.com/a/8827033
75
	 */
76
	public static function arrayDiff(array $b, array $a) : array {
77
		$at = \array_flip($a);
78
		$d = [];
79
		foreach ($b as $i) {
80
			if (!isset($at[$i])) {
81
				$d[] = $i;
82
			}
83
		}
84
		return $d;
85
	}
86
87
	/**
88
	 * Get multiple items from @a $array, as indicated by a second array @a $keys.
89
	 * If @a $preserveKeys is given as true, the result will have the original keys, otherwise
90
	 * the result is re-indexed with keys 0, 1, 2, ...
91
	 */
92
	public static function arrayMultiGet(array $array, array $keys, bool $preserveKeys=false) : array {
93
		$result = [];
94
		foreach ($keys as $key) {
95
			if ($preserveKeys) {
96
				$result[$key] = $array[$key];
97
			} else {
98
				$result[] = $array[$key];
99
			}
100
		}
101
		return $result;
102
	}
103
104
	/**
105
	 * Get multiple columns from the multidimensional @a $array. This is similar to the built-in
106
	 * function \array_column except that this can return multiple columns and not just one.
107
	 * @param int|string|null $indexColumn
108
	 */
109
	public static function arrayColumns(array $array, array $columns, $indexColumn=null) : array {
110
		if ($indexColumn !== null) {
111
			$array = \array_column($array, null, $indexColumn);
112
		}
113
114
		return \array_map(fn($row) => self::arrayMultiGet($row, $columns, true), $array);
115
	}
116
117
	/**
118
	 * Like the built-in function \array_filter but this one works recursively on nested arrays.
119
	 * Another difference is that this function always requires an explicit callback condition.
120
	 * Both inner nodes and leafs nodes are passed to the $condition.
121
	 */
122
	public static function arrayFilterRecursive(array $array, callable $condition) : array {
123
		$result = [];
124
125
		foreach ($array as $key => $value) {
126
			if ($condition($value)) {
127
				if (\is_array($value)) {
128
					$result[$key] = self::arrayFilterRecursive($value, $condition);
129
				} else {
130
					$result[$key] = $value;
131
				}
132
			}
133
		}
134
135
		return $result;
136
	}
137
138
	/**
139
	 * Inverse operation of self::arrayFilterRecursive, keeping only those items where
140
	 * the $condition evaluates to *false*.
141
	 */
142
	public static function arrayRejectRecursive(array $array, callable $condition) : array {
143
		$invCond = fn($item) => !$condition($item);
144
		return self::arrayFilterRecursive($array, $invCond);
145
	}
146
147
	/**
148
	 * Convert the given array $arr so that keys of the potentially multi-dimensional array
149
	 * are converted using the mapping given in $dictionary. Keys not found from $dictionary
150
	 * are not altered.
151
	 */
152
	public static function convertArrayKeys(array $arr, array $dictionary) : array {
153
		$newArr = [];
154
155
		foreach ($arr as $k => $v) {
156
			$key = $dictionary[$k] ?? $k;
157
			$newArr[$key] = \is_array($v) ? self::convertArrayKeys($v, $dictionary) : $v;
158
		}
159
160
		return $newArr;
161
	}
162
163
	/**
164
	 * Walk through the given, potentially multi-dimensional, array and cast all leaf nodes
165
	 * to integer type. The array is modified in-place. Optionally, apply the conversion only
166
	 * on the leaf nodes matching the given predicate.
167
	 */
168
	public static function intCastArrayValues(array &$arr, ?callable $predicate=null) : void {
169
		\array_walk_recursive($arr, function(&$value) use($predicate) {
170
			if ($predicate === null || $predicate($value)) {
171
				$value = (int)$value;
172
			}
173
		});
174
	}
175
176
	/**
177
	 * Given a two-dimensional array, sort the outer dimension according to values in the
178
	 * specified column of the inner dimension.
179
	 */
180
	public static function arraySortByColumn(array &$arr, string $column) : void {
181
		\usort($arr, fn($a, $b) => self::stringCaseCompare($a[$column], $b[$column]));
182
	}
183
184
	/**
185
	 * Like the built-in \explode(...) function but this one can be safely called with
186
	 * null string, and no warning will be emitted. Also, this returns an empty array from
187
	 * null and '' inputs while the built-in alternative returns a 1-item array containing
188
	 * an empty string.
189
	 * @param string $delimiter
190
	 * @param string|null $string
191
	 * @return array
192
	 */
193
	public static function explode(string $delimiter, ?string $string) : array {
194
		if ($delimiter === '') {
195
			throw new \UnexpectedValueException();
196
		} elseif ($string === null || $string === '') {
197
			return [];
198
		} else {
199
			return \explode($delimiter, $string);
200
		}
201
	}
202
203
	/**
204
	 * Truncate the given string to maximum number of bytes, appending ellipsis character
205
	 * (or other given marker) if the truncation happened. Note that for multi-byte encoding (like utf8),
206
	 * the number of bytes may not be the same as the number of characters.
207
	 * Also null argument may be safely passed and it remains unaltered.
208
	 */
209
	public static function truncate(?string $string, int $maxBytes, string $trimMarker="\u{2026}") : ?string {
210
		if ($string === null) {
211
			return null;
212
		} else if (\strlen($string) > $maxBytes) {
213
			$string = \mb_strcut($string, 0, $maxBytes - \strlen($trimMarker));
214
			return $string . $trimMarker;
215
		} else {
216
			return $string;
217
		}
218
	}
219
220
	/**
221
	 * Test if given string starts with another given string
222
	 */
223
	public static function startsWith(string $string, string $potentialStart, bool $ignoreCase=false) : bool {
224
		$actualStart = \substr($string, 0, \strlen($potentialStart));
225
		if ($ignoreCase) {
226
			$actualStart = \mb_strtolower($actualStart);
227
			$potentialStart = \mb_strtolower($potentialStart);
228
		}
229
		return $actualStart === $potentialStart;
230
	}
231
232
	/**
233
	 * Test if given string ends with another given string
234
	 */
235
	public static function endsWith(string $string, string $potentialEnd, bool $ignoreCase=false) : bool {
236
		$actualEnd = \substr($string, -\strlen($potentialEnd));
237
		if ($ignoreCase) {
238
			$actualEnd = \mb_strtolower($actualEnd);
239
			$potentialEnd = \mb_strtolower($potentialEnd);
240
		}
241
		return $actualEnd === $potentialEnd;
242
	}
243
244
	/**
245
	 * Multi-byte safe case-insensitive string comparison
246
	 * @return int negative value if $a is less than $b, positive value if $a is greater than $b, and 0 if they are equal.
247
	 */
248
	public static function stringCaseCompare(?string $a, ?string $b) : int {
249
		return \strcmp(\mb_strtolower($a ?? ''), \mb_strtolower($b ?? ''));
250
	}
251
252
	/** 
253
	 * Convert snake case string (like_this) to camel case (likeThis).
254
	 */
255
	public static function snakeToCamelCase(string $input): string {
256
		return \lcfirst(\str_replace('_', '', \ucwords($input, '_')));
257
	}
258
259
	/**
260
	 * Test if $item is a string and not empty or only consisting of whitespace
261
	 */
262
	public static function isNonEmptyString(/*mixed*/ $item) : bool {
263
		return \is_string($item) && \trim($item) !== '';
264
	}
265
266
	/**
267
	 * Split given string to a prefix and a basename (=the remaining part after the prefix), considering the possible
268
	 * prefixes given as an array. If none of the prefixes match, the returned basename will be the original string
269
	 * and the prefix will be null.
270
	 * @param string[] $potentialPrefixes
271
	 */
272
	public static function splitPrefixAndBasename(?string $name, array $potentialPrefixes) : array {
273
		$parts = ['prefix' => null, 'basename' => $name];
274
275
		if ($name !== null) {
276
			foreach ($potentialPrefixes as $prefix) {
277
				if (Util::startsWith($name, $prefix . ' ', /*ignoreCase=*/true)) {
278
					$parts['prefix'] = $prefix;
279
					$parts['basename'] = \substr($name, \strlen($prefix) + 1);
280
					break;
281
				}
282
			}
283
		}
284
285
		return $parts;
286
	}
287
288
	/**
289
	 * Convert file size given in bytes to human-readable format
290
	 */
291
	public static function formatFileSize(?int $bytes, int $decimals = 1) : ?string {
292
		if ($bytes === null) {
293
			return null;
294
		} else {
295
			$units = 'BKMGTP';
296
			$factor = \floor((\strlen((string)$bytes) - 1) / 3);
297
			return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
298
		}
299
	}
300
301
	/**
302
	 * Convert time given as seconds to the HH:MM:SS format
303
	 */
304
	public static function formatTime(?int $seconds) : ?string {
305
		if ($seconds === null) {
306
			return null;
307
		} else {
308
			return \sprintf('%02d:%02d:%02d', ($seconds/3600), ($seconds/60%60), $seconds%60);
309
		}
310
	}
311
312
	/**
313
	 * Convert date and time given in the SQL format to the ISO UTC "Zulu format" e.g. "2021-08-19T19:33:15Z"
314
	 */
315
	public static function formatZuluDateTime(?string $dbDateString) : ?string {
316
		if ($dbDateString === null) {
317
			return null;
318
		} else {
319
			$dateTime = new \DateTime($dbDateString);
320
			return $dateTime->format('Y-m-d\TH:i:s.v\Z');
321
		}
322
	}
323
324
	/**
325
	 * Convert date and time given in the SQL format to the ISO UTC "offset format" e.g. "2021-08-19T19:33:15+00:00"
326
	 */
327
	public static function formatDateTimeUtcOffset(?string $dbDateString) : ?string {
328
		if ($dbDateString === null) {
329
			return null;
330
		} else {
331
			$dateTime = new \DateTime($dbDateString);
332
			return $dateTime->format('c');
333
		}
334
	}
335
336
	/**
337
	 * Encode a file path so that it can be used as part of a WebDAV URL
338
	 */
339
	public static function urlEncodePath(string $path) : string {
340
		// URL encode each part of the file path
341
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
342
	}
343
344
	/**
345
	 * Compose URL from parts as returned by the system function parse_url.
346
	 * From https://stackoverflow.com/a/35207936
347
	 */
348
	public static function buildUrl(array $parts) : string {
349
		return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') .
350
				((isset($parts['user']) || isset($parts['host'])) ? '//' : '') .
351
				(isset($parts['user']) ? "{$parts['user']}" : '') .
352
				(isset($parts['pass']) ? ":{$parts['pass']}" : '') .
353
				(isset($parts['user']) ? '@' : '') .
354
				(isset($parts['host']) ? "{$parts['host']}" : '') .
355
				(isset($parts['port']) ? ":{$parts['port']}" : '') .
356
				(isset($parts['path']) ? "{$parts['path']}" : '') .
357
				(isset($parts['query']) ? "?{$parts['query']}" : '') .
358
				(isset($parts['fragment']) ? "#{$parts['fragment']}" : '');
359
	}
360
361
	/**
362
	 * Swap values of two variables in place
363
	 * @param mixed $a
364
	 * @param mixed $b
365
	 */
366
	public static function swap(&$a, &$b) : void {
367
		$temp = $a;
368
		$a = $b;
369
		$b = $temp;
370
	}
371
372
	/**
373
	 * Limit an integer value between the specified minimum and maximum.
374
	 * A null value is a valid input and will produce a null output.
375
	 * @param int|float|null $input
376
	 * @param int|float $min
377
	 * @param int|float $max
378
	 * @return int|float|null
379
	 */
380
	public static function limit($input, $min, $max) {
381
		if ($input === null) {
382
			return null;
383
		} else {
384
			return \max($min, \min($input, $max));
385
		}
386
	}
387
}
388