Passed
Push — feature/786_podcasts ( 2abc0b...a609d5 )
by Pauli
02:17
created

Util::createIdLookupTable()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 1
dl 0
loc 6
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 - 2020
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 {
26
		$func = function ($obj) use ($methodName) {
27
			return $obj->$methodName();
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
	 * Convert the given array $arr so that keys of the potentially multi-dimensional array
91
	 * are converted using the mapping given in $dictionary. Keys not found from $dictionary
92
	 * are not altered.
93
	 */
94
	public static function convertArrayKeys(array $arr, array $dictionary) : array {
95
		$newArr = [];
96
97
		foreach ($arr as $k => $v) {
98
			$key = $dictionary[$k] ?? $k;
99
			$newArr[$key] = \is_array($v) ? self::convertArrayKeys($v, $dictionary) : $v;
100
		}
101
102
		return $newArr;
103
	}
104
105
	/**
106
	 * Walk through the given, potentially multi-dimensional, array and cast all leaf nodes
107
	 * to integer type. The array is modified in-place.
108
	 */
109
	public static function intCastArrayValues(array $arr) : void {
110
		\array_walk_recursive($arr, function(&$value) {
111
			$value = \intval($value);
112
		});
113
	}
114
115
	/**
116
	 * Like the built-in \explode(...) function but this one can be safely called with
117
	 * null string, and no warning will be emitted. Also, this returns an empty array from
118
	 * null and '' inputs while the built-in alternative returns a 1-item array containing
119
	 * an empty string.
120
	 * @param string $delimiter
121
	 * @param string|null $string
122
	 * @return array
123
	 */
124
	public static function explode(string $delimiter, ?string $string) : array {
125
		if ($string === null || $string === '') {
126
			return [];
127
		} else {
128
			return \explode($delimiter, $string);
129
		}
130
	}
131
132
	/**
133
	 * Truncate the given string to maximum length, appendig ellipsis character
134
	 * if the truncation happened. Also null argument may be safely passed and
135
	 * it remains unaltered.
136
	 */
137
	public static function truncate(?string $string, int $maxLength) : ?string {
138
		if ($string === null) {
139
			return null;
140
		} else {
141
			return \mb_strimwidth($string, 0, $maxLength, "\u{2026}");
142
		}
143
	}
144
145
	/**
146
	 * Test if given string starts with another given string
147
	 */
148
	public static function startsWith(string $string, string $potentialStart, bool $ignoreCase=false) : bool {
149
		$actualStart = \substr($string, 0, \strlen($potentialStart));
150
		if ($ignoreCase) {
151
			$actualStart= \mb_strtolower($actualStart);
152
			$potentialStart= \mb_strtolower($potentialStart);
153
		}
154
		return $actualStart === $potentialStart;
155
	}
156
157
	/**
158
	 * Test if given string ends with another given string
159
	 */
160
	public static function endsWith(string $string, string $potentialEnd, bool $ignoreCase=false) : bool {
161
		$actualEnd = \substr($string, -\strlen($potentialEnd));
162
		if ($ignoreCase) {
163
			$actualEnd = \mb_strtolower($actualEnd);
164
			$potentialEnd = \mb_strtolower($potentialEnd);
165
		}
166
		return $actualEnd === $potentialEnd;
167
	}
168
169
	/**
170
	 * Multi-byte safe case-insensitive string comparison
171
	 * @return int < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal.
172
	 */
173
	public static function stringCaseCompare(?string $a, ?string $b) : int {
174
		return \strcmp(\mb_strtolower($a ?? ''), \mb_strtolower($b ?? ''));
175
	}
176
177
	/**
178
	 * Test if $item is a string and not empty or only consisting of whitespace
179
	 */
180
	public static function isNonEmptyString(/*mixed*/ $item) : bool {
181
		return \is_string($item) && \trim($item) !== '';
182
	}
183
184
	/**
185
	 * Convert file size given in bytes to human-readable format
186
	 */
187
	public static function formatFileSize(?int $bytes, int $decimals = 1) : ?string {
188
		if ($bytes === null) {
189
			return null;
190
		} else {
191
			$units = 'BKMGTP';
192
			$factor = \floor((\strlen((string)$bytes) - 1) / 3);
193
			return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
194
		}
195
	}
196
197
	/**
198
	 * Convert time given as seconds to the HH:MM:SS format
199
	 */
200
	public static function formatTime(?int $seconds) : ?string {
201
		if ($seconds === null) {
202
			return null;
203
		} else {
204
			return \sprintf('%02d:%02d:%02d', ($seconds/3600), ($seconds/60%60), $seconds%60);
205
		}
206
	}
207
208
	/**
209
	 * Convert date and time given in the SQL format to the ISO UTC "Zulu format" e.g. "2021-08-19T19:33:15Z"
210
	 */
211
	public static function formatZuluDateTime(?string $dbDateString) : ?string {
212
		if ($dbDateString === null) {
213
			return null;
214
		} else {
215
			$dateTime = new \DateTime($dbDateString);
216
			return $dateTime->format('Y-m-d\TH:i:s.v\Z');
217
		}
218
	}
219
220
	/**
221
	 * Convert date and time given in the SQL format to the ISO UTC "offset format" e.g. "2021-08-19T19:33:15+00:00"
222
	 */
223
	public static function formatDateTimeUtcOffset(?string $dbDateString) : ?string {
224
		if ($dbDateString === null) {
225
			return null;
226
		} else {
227
			$dateTime = new \DateTime($dbDateString);
228
			return $dateTime->format('c');
229
		}
230
	}
231
232
	/**
233
	 * Get a Folder object using a parent Folder object and a relative path
234
	 */
235
	public static function getFolderFromRelativePath(Folder $parentFolder, string $relativePath) : Folder {
236
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
237
			$node = $parentFolder->get($relativePath);
238
			if ($node instanceof Folder) {
239
				return $node;
240
			} else {
241
				throw new \InvalidArgumentException('Path points to a file while folder expected');
242
			}
243
		} else {
244
			return $parentFolder;
245
		}
246
	}
247
248
	/**
249
	 * Create relative path from the given working dir (CWD) to the given target path
250
	 * @param string $cwdPath Absolute CWD path
251
	 * @param string $targetPath Absolute target path
252
	 */
253
	public static function relativePath(string $cwdPath, string $targetPath) : string {
254
		$cwdParts = \explode('/', $cwdPath);
255
		$targetParts = \explode('/', $targetPath);
256
257
		// remove the common prefix of the paths
258
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
259
			\array_shift($cwdParts);
260
			\array_shift($targetParts);
261
		}
262
263
		// prepend up-navigation from CWD to the closest common parent folder with the target
264
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
265
			\array_unshift($targetParts, '..');
266
		}
267
268
		return \implode('/', $targetParts);
269
	}
270
271
	/**
272
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
273
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
274
	 */
275
	public static function resolveRelativePath(string $cwdPath, string $relativePath) : string {
276
		$cwdParts = \explode('/', $cwdPath);
277
		$relativeParts = \explode('/', $relativePath);
278
279
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
280
		if ($cwdParts[\count($cwdParts)-1] === '') {
281
			\array_pop($cwdParts);
282
		}
283
284
		foreach ($relativeParts as $part) {
285
			if ($part === '..') {
286
				\array_pop($cwdParts);
287
			} else {
288
				\array_push($cwdParts, $part);
289
			}
290
		}
291
292
		return \implode('/', $cwdParts);
293
	}
294
295
	/**
296
	 * Encode a file path so that it can be used as part of a WebDAV URL
297
	 */
298
	public static function urlEncodePath(string $path) : string {
299
		// URL encode each part of the file path
300
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
301
	}
302
303
	/**
304
	 * Swap values of two variables in place
305
	 * @param mixed $a
306
	 * @param mixed $b
307
	 */
308
	public static function swap(&$a, &$b) : void {
309
		$temp = $a;
310
		$a = $b;
311
		$b = $temp;
312
	}
313
}
314