Passed
Push — master ( 2447d4...95d3a4 )
by Pauli
02:17
created

Util::arrayGetOrDefault()   A

Complexity

Conditions 5
Paths 7

Size

Total Lines 16
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 5.583

Importance

Changes 4
Bugs 1 Features 0
Metric Value
cc 5
eloc 11
c 4
b 1
f 0
nc 7
nop 3
dl 0
loc 16
ccs 5
cts 7
cp 0.7143
crap 5.583
rs 9.6111
1
<?php
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
	 * Extract ID of each array element by calling getId and return
24
	 * the IDs as an array
25
	 * @param array $arr
26
	 * @return array
27 4
	 */
28 4
	public static function extractIds(array $arr) {
29 4
		return \array_map(function ($i) {
30
			return $i->getId();
31
		}, $arr);
32
	}
33
34
	/**
35
	 * Extract User ID of each array element by calling getUserId and return
36
	 * the IDs as an array
37
	 * @param array $arr
38
	 * @return array
39
	 */
40
	public static function extractUserIds(array $arr) {
41
		return \array_map(function ($i) {
42
			return $i->getUserId();
43
		}, $arr);
44
	}
45
46
	/**
47
	 * Create look-up table from given array of items which have a `getId` function.
48
	 * @param array $array
49
	 * @return array where keys are the values returned by `getId` of each item
50
	 */
51
	public static function createIdLookupTable(array $array) {
52
		$lut = [];
53
		foreach ($array as $item) {
54
			$lut[$item->getId()] = $item;
55
		}
56
		return $lut;
57
	}
58
59
	/**
60
	 * Get difference of two arrays, i.e. elements belonging to $b but not $a.
61
	 * This function is faster than the built-in array_diff for large arrays but
62
	 * at the expense of higher RAM usage and can be used only for arrays of
63
	 * integers or strings.
64
	 * From https://stackoverflow.com/a/8827033
65
	 * @param array $b
66
	 * @param array $a
67
	 * @return array
68
	 */
69
	public static function arrayDiff(array $b, array $a) {
70
		$at = \array_flip($a);
71
		$d = [];
72
		foreach ($b as $i) {
73
			if (!isset($at[$i])) {
74
				$d[] = $i;
75
			}
76
		}
77
		return $d;
78
	}
79
80
	/**
81
	 * Get multiple items from @a $array, as indicated by a second array @a $indices.
82
	 * @param array $array
83
	 * @param array $indices
84
	 * @return array
85
	 */
86
	public static function arrayMultiGet(array $array, array $indices) {
87
		$result = [];
88
		foreach ($indices as $index) {
89
			$result[] = $array[$index];
90
		}
91
		return $result;
92
	}
93
94
	/**
95
	 * Convert the given array $arr so that keys of the potentially multi-dimensional array
96
	 * are converted using the mapping given in $dictionary. Keys not found from $dictionary
97
	 * are not altered. 
98
	 * @param array $arr
99
	 * @param array $dictionary
100
	 * @return array
101
	 */
102
	public static function convertArrayKeys(array $arr, array $dictionary) {
103
		$newArr = [];
104
105
		foreach ($arr as $k => $v) {
106
			$key = $dictionary[$k] ?? $k;
107
			$newArr[$key] = is_array($v) ? self::convertArrayKeys($v, $dictionary) : $v;
108
		}
109
110
		return $newArr;
111
	}
112
113
	/**
114
	 * Like the built-in \explode(...) function but this one can be safely called with
115
	 * null string, and no warning will be emitted. Also, this returns an empty array from
116
	 * null and '' inputs while the built-in alternative returns a 1-item array containing
117
	 * an empty string.
118
	 * @param string $delimiter
119
	 * @param string|null $string
120
	 * @return array
121
	 */
122
	public static function explode($delimiter, $string) {
123 3
		if ($string === null || $string === '') {
124 3
			return [];
125 3
		} else {
126
			return \explode($delimiter, $string);
127
		}
128 3
	}
129 3
130 3
	/**
131
	 * Truncate the given string to maximum length, appendig ellipsis character
132
	 * if the truncation happened. Also null argument may be safely passed and
133 3
	 * it remains unaltered.
134
	 * @param string|null $string
135
	 * @param int $maxLength
136
	 * @return string|null
137
	 */
138
	public static function truncate($string, $maxLength) {
139
		if ($string === null) {
140
			return null;
141
		} else {
142
			return \mb_strimwidth($string, 0, $maxLength, "\u{2026}");
143
		}
144
	}
145
146
	/**
147
	 * Test if given string starts with another given string
148
	 * @param string $string
149
	 * @param string $potentialStart
150
	 * @param boolean $ignoreCase
151
	 * @return boolean
152
	 */
153
	public static function startsWith($string, $potentialStart, $ignoreCase=false) {
154
		$actualStart = \substr($string, 0, \strlen($potentialStart));
155
		if ($ignoreCase) {
156
			$actualStart= \mb_strtolower($actualStart);
157
			$potentialStart= \mb_strtolower($potentialStart);
158
		}
159
		return $actualStart === $potentialStart;
160
	}
161
162
	/**
163
	 * Test if given string ends with another given string
164 3
	 * @param string $string
165 3
	 * @param string $potentialEnd
166 1
	 * @param boolean $ignoreCase
167
	 * @return boolean
168 2
	 */
169
	public static function endsWith($string, $potentialEnd, $ignoreCase=false) {
170
		$actualEnd = \substr($string, -\strlen($potentialEnd));
171
		if ($ignoreCase) {
172
			$actualEnd = \mb_strtolower($actualEnd);
173
			$potentialEnd = \mb_strtolower($potentialEnd);
174
		}
175
		return $actualEnd === $potentialEnd;
176
	}
177
178
	/**
179
	 * Multi-byte safe case-insensitive string comparison
180
	 * @param string $a
181
	 * @param string $b
182
	 * @return int < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 
183
	 */
184
	public static function stringCaseCompare($a, $b) {
185
		return \strcmp(\mb_strtolower($a), \mb_strtolower($b));
186
	}
187
188
	/**
189
	 * Convert file size given in bytes to human-readable format
190
	 * @param int $bytes
191
	 * @param int $decimals
192
	 * @return string
193
	 */
194
	public static function formatFileSize($bytes, $decimals = 1) {
195
		$units = 'BKMGTP';
196
		$factor = \floor((\strlen($bytes) - 1) / 3);
197
		return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
198
	}
199
200
	/**
201
	 * @param Folder $parentFolder
202
	 * @param string $relativePath
203
	 * @return Folder
204
	 */
205
	public static function getFolderFromRelativePath(Folder $parentFolder, $relativePath) {
206
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
207
			return $parentFolder->get($relativePath);
208
		} else {
209
			return $parentFolder;
210
		}
211
	}
212
213
	/**
214
	 * Create relative path from the given working dir (CWD) to the given target path
215
	 * @param string $cwdPath Absolute CWD path
216
	 * @param string $targetPath Absolute target path
217
	 * @return string
218
	 */
219
	public static function relativePath($cwdPath, $targetPath) {
220
		$cwdParts = \explode('/', $cwdPath);
221
		$targetParts = \explode('/', $targetPath);
222
223
		// remove the common prefix of the paths
224
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
225
			\array_shift($cwdParts);
226
			\array_shift($targetParts);
227
		}
228
229
		// prepend up-navigation from CWD to the closest common parent folder with the target
230
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
231
			\array_unshift($targetParts, '..');
232
		}
233
234
		return \implode('/', $targetParts);
235
	}
236
237
	/**
238
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
239
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
240
	 * @param string $cwdPath
241
	 * @param string $relativePath
242
	 * @return string
243
	 */
244
	public static function resolveRelativePath($cwdPath, $relativePath) {
245
		$cwdParts = \explode('/', $cwdPath);
246
		$relativeParts = \explode('/', $relativePath);
247
248
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
249
		if ($cwdParts[\count($cwdParts)-1] === '') {
250
			\array_pop($cwdParts);
251
		}
252
253
		foreach ($relativeParts as $part) {
254
			if ($part === '..') {
255
				\array_pop($cwdParts);
256
			} else {
257
				\array_push($cwdParts, $part);
258
			}
259
		}
260
261
		return \implode('/', $cwdParts);
262
	}
263
264
	/**
265
	 * Encode a file path so that it can be used as part of a WebDAV URL
266
	 * @param string $path
267
	 * @return string
268
	 */
269
	public static function urlEncodePath($path) {
270
		// URL encode each part of the file path
271
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
272
	}
273
274
	/**
275
	 * Swap values of two variables in place
276
	 * @param mixed $a
277
	 * @param mixed $b
278
	 */
279
	public static function swap(&$a, &$b) {
280
		$temp = $a;
281
		$a = $b;
282
		$b = $temp;
283
	}
284
}
285