Passed
Push — master ( 543ba8...434da3 )
by Pauli
01:50
created

Util::arrayMultiGet()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

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
ccs 0
cts 5
cp 0
crap 6
rs 10
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
/**
16
 * Miscellaneous static utility functions
17
 */
18
class Util {
19
20
	/**
21
	 * Extract ID of each array element by calling getId and return
22
	 * the IDs as an array
23
	 * @param array $arr
24
	 * @return array
25
	 */
26 4
	public static function extractIds(array $arr) {
27
		return \array_map(function ($i) {
28 4
			return $i->getId();
29 4
		}, $arr);
30
	}
31
32
	/**
33
	 * Extract User ID of each array element by calling getUserId and return
34
	 * the IDs as an array
35
	 * @param array $arr
36
	 * @return array
37
	 */
38
	public static function extractUserIds(array $arr) {
39
		return \array_map(function ($i) {
40
			return $i->getUserId();
41
		}, $arr);
42
	}
43
44
	/**
45
	 * Create look-up table from given array of items which have a `getId` function.
46
	 * @param array $array
47
	 * @return array where keys are the values returned by `getId` of each item
48
	 */
49
	public static function createIdLookupTable(array $array) {
50
		$lut = [];
51
		foreach ($array as $item) {
52
			$lut[$item->getId()] = $item;
53
		}
54
		return $lut;
55
	}
56
57
	/**
58
	 * Get difference of two arrays, i.e. elements belonging to $b but not $a.
59
	 * This function is faster than the built-in array_diff for large arrays but
60
	 * at the expense of higher RAM usage and can be used only for arrays of
61
	 * integers or strings.
62
	 * From https://stackoverflow.com/a/8827033
63
	 * @param array $b
64
	 * @param array $a
65
	 * @return array
66
	 */
67
	public static function arrayDiff(array $b, array $a) {
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
	 * @param array $array
81
	 * @param array $indices
82
	 * @return array
83
	 */
84
	public static function arrayMultiGet(array $array, array $indices) {
85
		$result = [];
86
		foreach ($indices as $index) {
87
			$result[] = $array[$index];
88
		}
89
		return $result;
90
	}
91
92
	/**
93
	 * Convert the given array $arr so that keys of the potentially multi-dimensional array
94
	 * are converted using the mapping given in $dictionary. Keys not found from $dictionary
95
	 * are not altered. 
96
	 * @param array $arr
97
	 * @param array $dictionary
98
	 * @return array
99
	 */
100
	public static function convertArrayKeys(array $arr, array $dictionary) {
101
		$newArr = [];
102
103
		foreach ($arr as $k => $v) {
104
			$key = self::arrayGetOrDefault($dictionary, $k, $k);
105
			$newArr[$key] = is_array($v) ? self::convertArrayKeys($v, $dictionary) : $v;
106
		}
107
108
		return $newArr;
109
	}
110
111
	/**
112
	 * Get array value if exists, otherwise return a default value or null.
113
	 * The function supports getting value from a nested array by giving an array-type $key.
114
	 * In that case, the first value of the $key is used on the outer-most array, second value
115
	 * from $key on the next level, and so on. That is, arrayGetOrDefault($arr, ['a', 'b', 'c'])
116
	 * will return $arr['a']['b']['c'] is all the keys along the path are found.
117
	 *
118
	 * @param array $array
119
	 * @param int|string|array $key
120
	 * @param mixed|null $default
121
	 * @return mixed|null
122
	 */
123 3
	public static function arrayGetOrDefault(array $array, $key, $default=null) {
124 3
		if (!\is_array($key)) {
125 3
			$key = [$key];
126
		}
127
128 3
		$temp = $array;
129 3
		foreach ($key as $k) {
130 3
			if (isset($temp[$k])) {
131
				$temp = $temp[$k];
132
			} else {
133 3
				return $default;
134
			}
135
		}
136
		return $temp;
137
	}
138
139
	/**
140
	 * Truncate the given string to maximum length, appendig ellipsis character
141
	 * if the truncation happened. Also null argument may be safely passed and
142
	 * it remains unaltered.
143
	 * @param string|null $string
144
	 * @param int $maxLength
145
	 * @return string|null
146
	 */
147 3
	public static function truncate($string, $maxLength) {
148 3
		if ($string === null) {
149 1
			return null;
150
		} else {
151 2
			return \mb_strimwidth($string, 0, $maxLength, "\u{2026}");
152
		}
153
	}
154
155
	/**
156
	 * Test if given string starts with another given string
157
	 * @param string $string
158
	 * @param string $potentialStart
159
	 * @param boolean $ignoreCase
160
	 * @return boolean
161
	 */
162
	public static function startsWith($string, $potentialStart, $ignoreCase=false) {
163
		$actualStart = \substr($string, 0, \strlen($potentialStart));
164
		if ($ignoreCase) {
165
			$actualStart= \mb_strtolower($actualStart);
166
			$potentialStart= \mb_strtolower($potentialStart);
167
		}
168
		return $actualStart === $potentialStart;
169
	}
170
171
	/**
172
	 * Test if given string ends with another given string
173
	 * @param string $string
174
	 * @param string $potentialEnd
175
	 * @param boolean $ignoreCase
176
	 * @return boolean
177
	 */
178
	public static function endsWith($string, $potentialEnd, $ignoreCase=false) {
179
		$actualEnd = \substr($string, -\strlen($potentialEnd));
180
		if ($ignoreCase) {
181
			$actualEnd = \mb_strtolower($actualEnd);
182
			$potentialEnd = \mb_strtolower($potentialEnd);
183
		}
184
		return $actualEnd === $potentialEnd;
185
	}
186
187
	/**
188
	 * Multi-byte safe case-insensitive string comparison
189
	 * @param string $a
190
	 * @param string $b
191
	 * @return int < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 
192
	 */
193
	public static function stringCaseCompare($a, $b) {
194
		return \strcmp(\mb_strtolower($a), \mb_strtolower($b));
195
	}
196
197
	/**
198
	 * Convert file size given in bytes to human-readable format
199
	 * @param int $bytes
200
	 * @param int $decimals
201
	 * @return string
202
	 */
203
	public static function formatFileSize($bytes, $decimals = 1) {
204
		$units = 'BKMGTP';
205
		$factor = \floor((\strlen($bytes) - 1) / 3);
206
		return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
207
	}
208
209
	/**
210
	 * @param Folder $parentFolder
0 ignored issues
show
Bug introduced by
The type OCA\Music\Utility\Folder was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
211
	 * @param string $relativePath
212
	 * @return Folder
213
	 */
214
	public static function getFolderFromRelativePath($parentFolder, $relativePath) {
215
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
216
			return $parentFolder->get($relativePath);
217
		} else {
218
			return $parentFolder;
219
		}
220
	}
221
222
	/**
223
	 * Create relative path from the given working dir (CWD) to the given target path
224
	 * @param string $cwdPath Absolute CWD path
225
	 * @param string $targetPath Absolute target path
226
	 * @return string
227
	 */
228
	public static function relativePath($cwdPath, $targetPath) {
229
		$cwdParts = \explode('/', $cwdPath);
230
		$targetParts = \explode('/', $targetPath);
231
232
		// remove the common prefix of the paths
233
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
234
			\array_shift($cwdParts);
235
			\array_shift($targetParts);
236
		}
237
238
		// prepend up-navigation from CWD to the closest common parent folder with the target
239
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
240
			\array_unshift($targetParts, '..');
241
		}
242
243
		return \implode('/', $targetParts);
244
	}
245
246
	/**
247
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
248
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
249
	 * @param string $cwdPath
250
	 * @param string $relativePath
251
	 * @return string
252
	 */
253
	public static function resolveRelativePath($cwdPath, $relativePath) {
254
		$cwdParts = \explode('/', $cwdPath);
255
		$relativeParts = \explode('/', $relativePath);
256
257
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
258
		if ($cwdParts[\count($cwdParts)-1] === '') {
259
			\array_pop($cwdParts);
260
		}
261
262
		foreach ($relativeParts as $part) {
263
			if ($part === '..') {
264
				\array_pop($cwdParts);
265
			} else {
266
				\array_push($cwdParts, $part);
267
			}
268
		}
269
270
		return \implode('/', $cwdParts);
271
	}
272
273
	/**
274
	 * Encode a file path so that it can be used as part of a WebDAV URL
275
	 * @param string $path
276
	 * @return string
277
	 */
278
	public static function urlEncodePath($path) {
279
		// URL encode each part of the file path
280
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
281
	}
282
283
	/**
284
	 * Swap values of two variables in place
285
	 * @param mixed $a
286
	 * @param mixed $b
287
	 */
288
	public static function swap(&$a, &$b) {
289
		$temp = $a;
290
		$a = $b;
291
		$b = $temp;
292
	}
293
}
294