Passed
Push — master ( 49e88e...27428c )
by Pauli
02:49 queued 10s
created

Util::arrayMapMethod()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
c 0
b 0
f 0
nc 1
nop 2
dl 0
loc 5
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 - 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
		$units = 'BKMGTP';
189
		$factor = \floor((\strlen($bytes) - 1) / 3);
190
		return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
191
	}
192
193
	/**
194
	 * Get a Folder object using a parent Folder object and a relative path
195
	 */
196
	public static function getFolderFromRelativePath(Folder $parentFolder, string $relativePath) : Folder {
197
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
198
			$node = $parentFolder->get($relativePath);
199
			if ($node instanceof Folder) {
200
				return $node;
201
			} else {
202
				throw new \InvalidArgumentException('Path points to a file while folder expected');
203
			}
204
		} else {
205
			return $parentFolder;
206
		}
207
	}
208
209
	/**
210
	 * Create relative path from the given working dir (CWD) to the given target path
211
	 * @param string $cwdPath Absolute CWD path
212
	 * @param string $targetPath Absolute target path
213
	 */
214
	public static function relativePath(string $cwdPath, string $targetPath) : string {
215
		$cwdParts = \explode('/', $cwdPath);
216
		$targetParts = \explode('/', $targetPath);
217
218
		// remove the common prefix of the paths
219
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
220
			\array_shift($cwdParts);
221
			\array_shift($targetParts);
222
		}
223
224
		// prepend up-navigation from CWD to the closest common parent folder with the target
225
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
226
			\array_unshift($targetParts, '..');
227
		}
228
229
		return \implode('/', $targetParts);
230
	}
231
232
	/**
233
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
234
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
235
	 */
236
	public static function resolveRelativePath(string $cwdPath, string $relativePath) : string {
237
		$cwdParts = \explode('/', $cwdPath);
238
		$relativeParts = \explode('/', $relativePath);
239
240
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
241
		if ($cwdParts[\count($cwdParts)-1] === '') {
242
			\array_pop($cwdParts);
243
		}
244
245
		foreach ($relativeParts as $part) {
246
			if ($part === '..') {
247
				\array_pop($cwdParts);
248
			} else {
249
				\array_push($cwdParts, $part);
250
			}
251
		}
252
253
		return \implode('/', $cwdParts);
254
	}
255
256
	/**
257
	 * Encode a file path so that it can be used as part of a WebDAV URL
258
	 */
259
	public static function urlEncodePath(string $path) : string {
260
		// URL encode each part of the file path
261
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
262
	}
263
264
	/**
265
	 * Swap values of two variables in place
266
	 * @param mixed $a
267
	 * @param mixed $b
268
	 */
269
	public static function swap(&$a, &$b) : void {
270
		$temp = $a;
271
		$a = $b;
272
		$b = $temp;
273
	}
274
}
275