Completed
Pull Request — master (#777)
by Pauli
13:02 queued 10:41
created

Util::resolveRelativePath()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 10
nc 6
nop 2
dl 0
loc 18
ccs 0
cts 10
cp 0
crap 20
rs 9.9332
c 1
b 0
f 0
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
	 * @return boolean
143
	 */
144
	public static function startsWith($string, $potentialStart) {
145
		return \substr($string, 0, \strlen($potentialStart)) === $potentialStart;
146
	}
147
148
	/**
149
	 * Test if given string ends with another given string
150
	 * @param string $string
151
	 * @param string $potentialEnd
152
	 * @param boolean $ignoreCase
153
	 * @return boolean
154
	 */
155
	public static function endsWith($string, $potentialEnd, $ignoreCase=false) {
156
		$actualEnd = \substr($string, -\strlen($potentialEnd));
157
		if ($ignoreCase) {
158
			$actualEnd = \mb_strtolower($actualEnd);
159
			$potentialEnd = \mb_strtolower($potentialEnd);
160
		}
161
		return $actualEnd === $potentialEnd;
162
	}
163
164
	/**
165
	 * Multi-byte safe case-insensitive string comparison
166
	 * @param string $a
167
	 * @param string $b
168
	 * @return int < 0 if $a is less than $b; > 0 if $a is greater than $b, and 0 if they are equal. 
169
	 */
170
	public static function stringCaseCompare($a, $b) {
171
		return \strcmp(\mb_strtolower($a), \mb_strtolower($b));
172
	}
173
174
	/**
175
	 * Convert file size given in bytes to human-readable format
176
	 * @param int $bytes
177
	 * @param int $decimals
178
	 * @return string
179
	 */
180
	public static function formatFileSize($bytes, $decimals = 1) {
181
		$units = 'BKMGTP';
182
		$factor = \floor((\strlen($bytes) - 1) / 3);
183
		return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor];
184
	}
185
186
	/**
187
	 * @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...
188
	 * @param string $relativePath
189
	 * @return Folder
190
	 */
191
	public static function getFolderFromRelativePath($parentFolder, $relativePath) {
192
		if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') {
193
			return $parentFolder->get($relativePath);
194
		} else {
195
			return $parentFolder;
196
		}
197
	}
198
199
	/**
200
	 * Create relative path from the given working dir (CWD) to the given target path
201
	 * @param string $cwdPath Absolute CWD path
202
	 * @param string $targetPath Absolute target path
203
	 * @return string
204
	 */
205
	public static function relativePath($cwdPath, $targetPath) {
206
		$cwdParts = \explode('/', $cwdPath);
207
		$targetParts = \explode('/', $targetPath);
208
209
		// remove the common prefix of the paths
210
		while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) {
211
			\array_shift($cwdParts);
212
			\array_shift($targetParts);
213
		}
214
215
		// prepend up-navigation from CWD to the closest common parent folder with the target
216
		for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) {
217
			\array_unshift($targetParts, '..');
218
		}
219
220
		return \implode('/', $targetParts);
221
	}
222
223
	/**
224
	 * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts),
225
	 * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath().
226
	 * @param string $cwdPath
227
	 * @param string $relativePath
228
	 * @return string
229
	 */
230
	public static function resolveRelativePath($cwdPath, $relativePath) {
231
		$cwdParts = \explode('/', $cwdPath);
232
		$relativeParts = \explode('/', $relativePath);
233
234
		// get rid of the trailing empty part of CWD which appears when CWD has a trailing '/'
235
		if ($cwdParts[\count($cwdParts)-1] === '') {
236
			\array_pop($cwdParts);
237
		}
238
239
		foreach ($relativeParts as $part) {
240
			if ($part === '..') {
241
				\array_pop($cwdParts);
242
			} else {
243
				\array_push($cwdParts, $part);
244
			}
245
		}
246
247
		return \implode('/', $cwdParts);
248
	}
249
250
	/**
251
	 * Swap values of two variables in place
252
	 * @param mixed $a
253
	 * @param mixed $b
254
	 */
255
	public static function swap(&$a, &$b) {
256
		$temp = $a;
257
		$a = $b;
258
		$b = $temp;
259
	}
260
}
261