Passed
Push — feature/909_Ampache_API_improv... ( 673c0e...814067 )
by Pauli
02:45
created

Util::arrayGroupBy()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

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