Passed
Push — master ( b806b4...5b46ab )
by Pauli
02:42
created

Util::arrayRejectRecursive()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 3
c 1
b 0
f 0
dl 0
loc 5
rs 10
cc 1
nc 1
nop 2
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 ($string === null || $string === '') {
158
			return [];
159
		} else {
160
			return \explode($delimiter, $string);
161
		}
162
	}
163
164
	/**
165
	 * Truncate the given string to maximum length, appendig ellipsis character
166
	 * if the truncation happened. Also null argument may be safely passed and
167
	 * it remains unaltered.
168
	 */
169
	public static function truncate(?string $string, int $maxLength) : ?string {
170
		if ($string === null) {
171
			return null;
172
		} else {
173
			return \mb_strimwidth($string, 0, $maxLength, "\u{2026}");
174
		}
175
	}
176
177
	/**
178
	 * Test if given string starts with another given string
179
	 */
180
	public static function startsWith(string $string, string $potentialStart, bool $ignoreCase=false) : bool {
181
		$actualStart = \substr($string, 0, \strlen($potentialStart));
182
		if ($ignoreCase) {
183
			$actualStart = \mb_strtolower($actualStart);
184
			$potentialStart = \mb_strtolower($potentialStart);
185
		}
186
		return $actualStart === $potentialStart;
187
	}
188
189
	/**
190
	 * Test if given string ends with another given string
191
	 */
192
	public static function endsWith(string $string, string $potentialEnd, bool $ignoreCase=false) : bool {
193
		$actualEnd = \substr($string, -\strlen($potentialEnd));
194
		if ($ignoreCase) {
195
			$actualEnd = \mb_strtolower($actualEnd);
196
			$potentialEnd = \mb_strtolower($potentialEnd);
197
		}
198
		return $actualEnd === $potentialEnd;
199
	}
200
201
	/**
202
	 * Multi-byte safe case-insensitive string comparison
203
	 * @return int negative value if $a is less than $b, positive value if $a is greater than $b, and 0 if they are equal.
204
	 */
205
	public static function stringCaseCompare(?string $a, ?string $b) : int {
206
		return \strcmp(\mb_strtolower($a ?? ''), \mb_strtolower($b ?? ''));
207
	}
208
209
	/**
210
	 * Test if $item is a string and not empty or only consisting of whitespace
211
	 */
212
	public static function isNonEmptyString(/*mixed*/ $item) : bool {
213
		return \is_string($item) && \trim($item) !== '';
214
	}
215
216
	/**
217
	 * Convert file size given in bytes to human-readable format
218
	 */
219
	public static function formatFileSize(?int $bytes, int $decimals = 1) : ?string {
220
		if ($bytes === null) {
221
			return null;
222
		} else {
223
			$units = 'BKMGTP';
224
			$factor = \floor((\strlen((string)$bytes) - 1) / 3);
225
			return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
226
		}
227
	}
228
229
	/**
230
	 * Convert time given as seconds to the HH:MM:SS format
231
	 */
232
	public static function formatTime(?int $seconds) : ?string {
233
		if ($seconds === null) {
234
			return null;
235
		} else {
236
			return \sprintf('%02d:%02d:%02d', ($seconds/3600), ($seconds/60%60), $seconds%60);
237
		}
238
	}
239
240
	/**
241
	 * Convert date and time given in the SQL format to the ISO UTC "Zulu format" e.g. "2021-08-19T19:33:15Z"
242
	 */
243
	public static function formatZuluDateTime(?string $dbDateString) : ?string {
244
		if ($dbDateString === null) {
245
			return null;
246
		} else {
247
			$dateTime = new \DateTime($dbDateString);
248
			return $dateTime->format('Y-m-d\TH:i:s.v\Z');
249
		}
250
	}
251
252
	/**
253
	 * Convert date and time given in the SQL format to the ISO UTC "offset format" e.g. "2021-08-19T19:33:15+00:00"
254
	 */
255
	public static function formatDateTimeUtcOffset(?string $dbDateString) : ?string {
256
		if ($dbDateString === null) {
257
			return null;
258
		} else {
259
			$dateTime = new \DateTime($dbDateString);
260
			return $dateTime->format('c');
261
		}
262
	}
263
264
	/**
265
	 * Get a Folder object using a parent Folder object and a relative path
266
	 */
267
	public static function getFolderFromRelativePath(Folder $parentFolder, string $relativePath) : Folder {
268
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
269
			$node = $parentFolder->get($relativePath);
270
			if ($node instanceof Folder) {
271
				return $node;
272
			} else {
273
				throw new \InvalidArgumentException('Path points to a file while folder expected');
274
			}
275
		} else {
276
			return $parentFolder;
277
		}
278
	}
279
280
	/**
281
	 * Create relative path from the given working dir (CWD) to the given target path
282
	 * @param string $cwdPath Absolute CWD path
283
	 * @param string $targetPath Absolute target path
284
	 */
285
	public static function relativePath(string $cwdPath, string $targetPath) : string {
286
		$cwdParts = \explode('/', $cwdPath);
287
		$targetParts = \explode('/', $targetPath);
288
289
		// remove the common prefix of the paths
290
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
291
			\array_shift($cwdParts);
292
			\array_shift($targetParts);
293
		}
294
295
		// prepend up-navigation from CWD to the closest common parent folder with the target
296
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
297
			\array_unshift($targetParts, '..');
298
		}
299
300
		return \implode('/', $targetParts);
301
	}
302
303
	/**
304
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
305
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
306
	 */
307
	public static function resolveRelativePath(string $cwdPath, string $relativePath) : string {
308
		$cwdParts = \explode('/', $cwdPath);
309
		$relativeParts = \explode('/', $relativePath);
310
311
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
312
		if ($cwdParts[\count($cwdParts)-1] === '') {
313
			\array_pop($cwdParts);
314
		}
315
316
		foreach ($relativeParts as $part) {
317
			if ($part === '..') {
318
				\array_pop($cwdParts);
319
			} else {
320
				\array_push($cwdParts, $part);
321
			}
322
		}
323
324
		return \implode('/', $cwdParts);
325
	}
326
327
	/**
328
	 * Encode a file path so that it can be used as part of a WebDAV URL
329
	 */
330
	public static function urlEncodePath(string $path) : string {
331
		// URL encode each part of the file path
332
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
333
	}
334
335
	/**
336
	 * Swap values of two variables in place
337
	 * @param mixed $a
338
	 * @param mixed $b
339
	 */
340
	public static function swap(&$a, &$b) : void {
341
		$temp = $a;
342
		$a = $b;
343
		$b = $temp;
344
	}
345
}
346