Passed
Push — feature/playlist_improvements ( 417478...9b747b )
by Pauli
14:15
created

Util::urlEncodePath()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
eloc 1
c 1
b 0
f 0
nc 1
nop 1
dl 0
loc 3
rs 10
ccs 0
cts 0
cp 0
crap 2
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
	 * @param array $array
114
	 * @param int|string $key
115
	 * @param mixed|null $default
116
	 * @return mixed|null
117
	 */
118 3
	public static function arrayGetOrDefault(array $array, $key, $default=null) {
119 3
		return isset($array[$key]) ? $array[$key] : $default;
120
	}
121
122
	/**
123
	 * Truncate the given string to maximum length, appendig ellipsis character
124
	 * if the truncation happened. Also null argument may be safely passed and
125
	 * it remains unaltered.
126
	 * @param string|null $string
127
	 * @param int $maxLength
128
	 * @return string|null
129
	 */
130 3
	public static function truncate($string, $maxLength) {
131 3
		if ($string === null) {
132 1
			return null;
133
		} else {
134 2
			return \mb_strimwidth($string, 0, $maxLength, "\u{2026}");
135
		}
136
	}
137
138
	/**
139
	 * Test if given string starts with another given string
140
	 * @param string $string
141
	 * @param string $potentialStart
142
	 * @param boolean $ignoreCase
143
	 * @return boolean
144
	 */
145
	public static function startsWith($string, $potentialStart, $ignoreCase=false) {
146
		$actualStart = \substr($string, 0, \strlen($potentialStart));
147
		if ($ignoreCase) {
148
			$actualStart= \mb_strtolower($actualStart);
149
			$potentialStart= \mb_strtolower($potentialStart);
150
		}
151
		return $actualStart === $potentialStart;
152
	}
153
154
	/**
155
	 * Test if given string ends with another given string
156
	 * @param string $string
157
	 * @param string $potentialEnd
158
	 * @param boolean $ignoreCase
159
	 * @return boolean
160
	 */
161
	public static function endsWith($string, $potentialEnd, $ignoreCase=false) {
162
		$actualEnd = \substr($string, -\strlen($potentialEnd));
163
		if ($ignoreCase) {
164
			$actualEnd = \mb_strtolower($actualEnd);
165
			$potentialEnd = \mb_strtolower($potentialEnd);
166
		}
167
		return $actualEnd === $potentialEnd;
168
	}
169
170
	/**
171
	 * Multi-byte safe case-insensitive string comparison
172
	 * @param string $a
173
	 * @param string $b
174
	 * @return int < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 
175
	 */
176
	public static function stringCaseCompare($a, $b) {
177
		return \strcmp(\mb_strtolower($a), \mb_strtolower($b));
178
	}
179
180
	/**
181
	 * Convert file size given in bytes to human-readable format
182
	 * @param int $bytes
183
	 * @param int $decimals
184
	 * @return string
185
	 */
186
	public static function formatFileSize($bytes, $decimals = 1) {
187
		$units = 'BKMGTP';
188
		$factor = \floor((\strlen($bytes) - 1) / 3);
189
		return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
190
	}
191
192
	/**
193
	 * @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...
194
	 * @param string $relativePath
195
	 * @return Folder
196
	 */
197
	public static function getFolderFromRelativePath($parentFolder, $relativePath) {
198
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
199
			return $parentFolder->get($relativePath);
200
		} else {
201
			return $parentFolder;
202
		}
203
	}
204
205
	/**
206
	 * Create relative path from the given working dir (CWD) to the given target path
207
	 * @param string $cwdPath Absolute CWD path
208
	 * @param string $targetPath Absolute target path
209
	 * @return string
210
	 */
211
	public static function relativePath($cwdPath, $targetPath) {
212
		$cwdParts = \explode('/', $cwdPath);
213
		$targetParts = \explode('/', $targetPath);
214
215
		// remove the common prefix of the paths
216
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
217
			\array_shift($cwdParts);
218
			\array_shift($targetParts);
219
		}
220
221
		// prepend up-navigation from CWD to the closest common parent folder with the target
222
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
223
			\array_unshift($targetParts, '..');
224
		}
225
226
		return \implode('/', $targetParts);
227
	}
228
229
	/**
230
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
231
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
232
	 * @param string $cwdPath
233
	 * @param string $relativePath
234
	 * @return string
235
	 */
236
	public static function resolveRelativePath($cwdPath, $relativePath) {
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
	 * @param string $path
259
	 * @return string
260
	 */
261
	public static function urlEncodePath($path) {
262
		// URL encode each part of the file path
263
		return \join('/', \array_map('rawurlencode', \explode('/', $path)));
264
	}
265
266
	/**
267
	 * Swap values of two variables in place
268
	 * @param mixed $a
269
	 * @param mixed $b
270
	 */
271
	public static function swap(&$a, &$b) {
272
		$temp = $a;
273
		$a = $b;
274
		$b = $temp;
275
	}
276
}
277