| Total Complexity | 76 |
| Total Lines | 397 |
| Duplicated Lines | 0 % |
| Changes | 5 | ||
| Bugs | 0 | Features | 0 |
Complex classes like Util often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Util, and based on these observations, apply Extract Interface, too.
| 1 | <?php declare(strict_types=1); |
||
| 20 | class Util { |
||
| 21 | |||
| 22 | const UINT32_MAX = 0xFFFFFFFF; |
||
| 23 | const SINT32_MAX = 0x7FFFFFFF; |
||
| 24 | const SINT32_MIN = -self::SINT32_MAX - 1; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * Map the given array by calling a named member function for each of the array elements |
||
| 28 | */ |
||
| 29 | public static function arrayMapMethod(array $arr, string $methodName, array $methodArgs=[]) : array { |
||
| 30 | $func = function ($obj) use ($methodName, $methodArgs) { |
||
| 31 | return \call_user_func_array([$obj, $methodName], $methodArgs); |
||
| 32 | }; |
||
| 33 | return \array_map($func, $arr); |
||
| 34 | } |
||
| 35 | |||
| 36 | /** |
||
| 37 | * Extract ID of each array element by calling getId and return |
||
| 38 | * the IDs as an array |
||
| 39 | */ |
||
| 40 | public static function extractIds(array $arr) : array { |
||
| 42 | } |
||
| 43 | |||
| 44 | /** |
||
| 45 | * Extract User ID of each array element by calling getUserId and return |
||
| 46 | * the IDs as an array |
||
| 47 | */ |
||
| 48 | public static function extractUserIds(array $arr) : array { |
||
| 50 | } |
||
| 51 | |||
| 52 | /** |
||
| 53 | * Create a look-up table from given array of items which have a `getId` function. |
||
| 54 | * @return array where keys are the values returned by `getId` of each item |
||
| 55 | */ |
||
| 56 | public static function createIdLookupTable(array $array) : array { |
||
| 62 | } |
||
| 63 | |||
| 64 | /** |
||
| 65 | * Create a look-up table from given array so that keys of the table are obtained by calling |
||
| 66 | * the given method on each array entry and the values are arrays of entries having the same |
||
| 67 | * value returned by that method. |
||
| 68 | * @param string $getKeyMethod Name of a method found on $array entries which returns a string or an int |
||
| 69 | * @return array [int|string => array] |
||
| 70 | */ |
||
| 71 | public static function arrayGroupBy(array $array, string $getKeyMethod) : array { |
||
| 72 | $lut = []; |
||
| 73 | foreach ($array as $item) { |
||
| 74 | $lut[$item->$getKeyMethod()][] = $item; |
||
| 75 | } |
||
| 76 | return $lut; |
||
| 77 | } |
||
| 78 | |||
| 79 | /** |
||
| 80 | * Get difference of two arrays, i.e. elements belonging to $b but not $a. |
||
| 81 | * This function is faster than the built-in array_diff for large arrays but |
||
| 82 | * at the expense of higher RAM usage and can be used only for arrays of |
||
| 83 | * integers or strings. |
||
| 84 | * From https://stackoverflow.com/a/8827033 |
||
| 85 | */ |
||
| 86 | public static function arrayDiff(array $b, array $a) : array { |
||
| 87 | $at = \array_flip($a); |
||
| 88 | $d = []; |
||
| 89 | foreach ($b as $i) { |
||
| 90 | if (!isset($at[$i])) { |
||
| 91 | $d[] = $i; |
||
| 92 | } |
||
| 93 | } |
||
| 94 | return $d; |
||
| 95 | } |
||
| 96 | |||
| 97 | /** |
||
| 98 | * Get multiple items from @a $array, as indicated by a second array @a $indices. |
||
| 99 | */ |
||
| 100 | public static function arrayMultiGet(array $array, array $indices) : array { |
||
| 101 | $result = []; |
||
| 102 | foreach ($indices as $index) { |
||
| 103 | $result[] = $array[$index]; |
||
| 104 | } |
||
| 105 | return $result; |
||
| 106 | } |
||
| 107 | |||
| 108 | /** |
||
| 109 | * Like the built-in function \array_filter but this one works recursively on nested arrays. |
||
| 110 | * Another difference is that this function always requires an explicit callback condition. |
||
| 111 | * Both inner nodes and leafs nodes are passed to the $condition. |
||
| 112 | */ |
||
| 113 | public static function arrayFilterRecursive(array $array, callable $condition) : array { |
||
| 114 | $result = []; |
||
| 115 | |||
| 116 | foreach ($array as $key => $value) { |
||
| 117 | if ($condition($value)) { |
||
| 118 | if (\is_array($value)) { |
||
| 119 | $result[$key] = self::arrayFilterRecursive($value, $condition); |
||
| 120 | } else { |
||
| 121 | $result[$key] = $value; |
||
| 122 | } |
||
| 123 | } |
||
| 124 | } |
||
| 125 | |||
| 126 | return $result; |
||
| 127 | } |
||
| 128 | |||
| 129 | /** |
||
| 130 | * Inverse operation of self::arrayFilterRecursive, keeping only those items where |
||
| 131 | * the $condition evaluates to *false*. |
||
| 132 | */ |
||
| 133 | public static function arrayRejectRecursive(array $array, callable $condition) : array { |
||
| 134 | $invCond = function($item) use ($condition) { |
||
| 135 | return !$condition($item); |
||
| 136 | }; |
||
| 137 | return self::arrayFilterRecursive($array, $invCond); |
||
| 138 | } |
||
| 139 | |||
| 140 | /** |
||
| 141 | * Convert the given array $arr so that keys of the potentially multi-dimensional array |
||
| 142 | * are converted using the mapping given in $dictionary. Keys not found from $dictionary |
||
| 143 | * are not altered. |
||
| 144 | */ |
||
| 145 | public static function convertArrayKeys(array $arr, array $dictionary) : array { |
||
| 146 | $newArr = []; |
||
| 147 | |||
| 148 | foreach ($arr as $k => $v) { |
||
| 149 | $key = $dictionary[$k] ?? $k; |
||
| 150 | $newArr[$key] = \is_array($v) ? self::convertArrayKeys($v, $dictionary) : $v; |
||
| 151 | } |
||
| 152 | |||
| 153 | return $newArr; |
||
| 154 | } |
||
| 155 | |||
| 156 | /** |
||
| 157 | * Walk through the given, potentially multi-dimensional, array and cast all leaf nodes |
||
| 158 | * to integer type. The array is modified in-place. Optionally, apply the conversion only |
||
| 159 | * on the leaf nodes matching the given predicate. |
||
| 160 | */ |
||
| 161 | public static function intCastArrayValues(array &$arr, ?callable $predicate=null) : void { |
||
| 162 | \array_walk_recursive($arr, function(&$value) use($predicate) { |
||
| 163 | if ($predicate === null || $predicate($value)) { |
||
| 164 | $value = (int)$value; |
||
| 165 | } |
||
| 166 | }); |
||
| 167 | } |
||
| 168 | |||
| 169 | /** |
||
| 170 | * Given a two-dimensional array, sort the outer dimension according to values in the |
||
| 171 | * specified column of the inner dimension. |
||
| 172 | */ |
||
| 173 | public static function arraySortByColumn(array &$arr, string $column) : void { |
||
| 174 | \usort($arr, function ($a, $b) use ($column) { |
||
| 175 | return self::stringCaseCompare($a[$column], $b[$column]); |
||
| 176 | }); |
||
| 177 | } |
||
| 178 | |||
| 179 | /** |
||
| 180 | * Like the built-in \explode(...) function but this one can be safely called with |
||
| 181 | * null string, and no warning will be emitted. Also, this returns an empty array from |
||
| 182 | * null and '' inputs while the built-in alternative returns a 1-item array containing |
||
| 183 | * an empty string. |
||
| 184 | * @param string $delimiter |
||
| 185 | * @param string|null $string |
||
| 186 | * @return array |
||
| 187 | */ |
||
| 188 | public static function explode(string $delimiter, ?string $string) : array { |
||
| 189 | if ($delimiter === '') { |
||
| 190 | throw new \UnexpectedValueException(); |
||
| 191 | } elseif ($string === null || $string === '') { |
||
| 192 | return []; |
||
| 193 | } else { |
||
| 194 | return \explode($delimiter, $string); |
||
| 195 | } |
||
| 196 | } |
||
| 197 | |||
| 198 | /** |
||
| 199 | * Truncate the given string to maximum length, appendig ellipsis character |
||
| 200 | * if the truncation happened. Also null argument may be safely passed and |
||
| 201 | * it remains unaltered. |
||
| 202 | */ |
||
| 203 | public static function truncate(?string $string, int $maxLength) : ?string { |
||
| 204 | if ($string === null) { |
||
| 205 | return null; |
||
| 206 | } else { |
||
| 207 | return \mb_strimwidth($string, 0, $maxLength, "\u{2026}"); |
||
| 208 | } |
||
| 209 | } |
||
| 210 | |||
| 211 | /** |
||
| 212 | * Test if given string starts with another given string |
||
| 213 | */ |
||
| 214 | public static function startsWith(string $string, string $potentialStart, bool $ignoreCase=false) : bool { |
||
| 215 | $actualStart = \substr($string, 0, \strlen($potentialStart)); |
||
| 216 | if ($ignoreCase) { |
||
| 217 | $actualStart = \mb_strtolower($actualStart); |
||
| 218 | $potentialStart = \mb_strtolower($potentialStart); |
||
| 219 | } |
||
| 220 | return $actualStart === $potentialStart; |
||
| 221 | } |
||
| 222 | |||
| 223 | /** |
||
| 224 | * Test if given string ends with another given string |
||
| 225 | */ |
||
| 226 | public static function endsWith(string $string, string $potentialEnd, bool $ignoreCase=false) : bool { |
||
| 227 | $actualEnd = \substr($string, -\strlen($potentialEnd)); |
||
| 228 | if ($ignoreCase) { |
||
| 229 | $actualEnd = \mb_strtolower($actualEnd); |
||
| 230 | $potentialEnd = \mb_strtolower($potentialEnd); |
||
| 231 | } |
||
| 232 | return $actualEnd === $potentialEnd; |
||
| 233 | } |
||
| 234 | |||
| 235 | /** |
||
| 236 | * Multi-byte safe case-insensitive string comparison |
||
| 237 | * @return int negative value if $a is less than $b, positive value if $a is greater than $b, and 0 if they are equal. |
||
| 238 | */ |
||
| 239 | public static function stringCaseCompare(?string $a, ?string $b) : int { |
||
| 241 | } |
||
| 242 | |||
| 243 | /** |
||
| 244 | * Convert snake case string (like_this) to camel case (likeThis). |
||
| 245 | */ |
||
| 246 | public static function snakeToCamelCase(string $input): string { |
||
| 247 | return \lcfirst(\str_replace('_', '', \ucwords($input, '_'))); |
||
| 248 | } |
||
| 249 | |||
| 250 | /** |
||
| 251 | * Test if $item is a string and not empty or only consisting of whitespace |
||
| 252 | */ |
||
| 253 | public static function isNonEmptyString(/*mixed*/ $item) : bool { |
||
| 254 | return \is_string($item) && \trim($item) !== ''; |
||
| 255 | } |
||
| 256 | |||
| 257 | /** |
||
| 258 | * Convert file size given in bytes to human-readable format |
||
| 259 | */ |
||
| 260 | public static function formatFileSize(?int $bytes, int $decimals = 1) : ?string { |
||
| 261 | if ($bytes === null) { |
||
| 262 | return null; |
||
| 263 | } else { |
||
| 264 | $units = 'BKMGTP'; |
||
| 265 | $factor = \floor((\strlen((string)$bytes) - 1) / 3); |
||
| 266 | return \sprintf("%.{$decimals}f", $bytes / \pow(1024, $factor)) . @$units[(int)$factor]; |
||
| 267 | } |
||
| 268 | } |
||
| 269 | |||
| 270 | /** |
||
| 271 | * Convert time given as seconds to the HH:MM:SS format |
||
| 272 | */ |
||
| 273 | public static function formatTime(?int $seconds) : ?string { |
||
| 274 | if ($seconds === null) { |
||
| 275 | return null; |
||
| 276 | } else { |
||
| 277 | return \sprintf('%02d:%02d:%02d', ($seconds/3600), ($seconds/60%60), $seconds%60); |
||
| 278 | } |
||
| 279 | } |
||
| 280 | |||
| 281 | /** |
||
| 282 | * Convert date and time given in the SQL format to the ISO UTC "Zulu format" e.g. "2021-08-19T19:33:15Z" |
||
| 283 | */ |
||
| 284 | public static function formatZuluDateTime(?string $dbDateString) : ?string { |
||
| 285 | if ($dbDateString === null) { |
||
| 286 | return null; |
||
| 287 | } else { |
||
| 288 | $dateTime = new \DateTime($dbDateString); |
||
| 289 | return $dateTime->format('Y-m-d\TH:i:s.v\Z'); |
||
| 290 | } |
||
| 291 | } |
||
| 292 | |||
| 293 | /** |
||
| 294 | * Convert date and time given in the SQL format to the ISO UTC "offset format" e.g. "2021-08-19T19:33:15+00:00" |
||
| 295 | */ |
||
| 296 | public static function formatDateTimeUtcOffset(?string $dbDateString) : ?string { |
||
| 297 | if ($dbDateString === null) { |
||
| 298 | return null; |
||
| 299 | } else { |
||
| 300 | $dateTime = new \DateTime($dbDateString); |
||
| 301 | return $dateTime->format('c'); |
||
| 302 | } |
||
| 303 | } |
||
| 304 | |||
| 305 | /** |
||
| 306 | * Get a Folder object using a parent Folder object and a relative path |
||
| 307 | */ |
||
| 308 | public static function getFolderFromRelativePath(Folder $parentFolder, string $relativePath) : Folder { |
||
| 309 | if ($relativePath !== null && $relativePath !== '/' && $relativePath !== '') { |
||
| 310 | $node = $parentFolder->get($relativePath); |
||
| 311 | if ($node instanceof Folder) { |
||
| 312 | return $node; |
||
| 313 | } else { |
||
| 314 | throw new \InvalidArgumentException('Path points to a file while folder expected'); |
||
| 315 | } |
||
| 316 | } else { |
||
| 317 | return $parentFolder; |
||
| 318 | } |
||
| 319 | } |
||
| 320 | |||
| 321 | /** |
||
| 322 | * Create relative path from the given working dir (CWD) to the given target path |
||
| 323 | * @param string $cwdPath Absolute CWD path |
||
| 324 | * @param string $targetPath Absolute target path |
||
| 325 | */ |
||
| 326 | public static function relativePath(string $cwdPath, string $targetPath) : string { |
||
| 327 | $cwdParts = \explode('/', $cwdPath); |
||
| 328 | $targetParts = \explode('/', $targetPath); |
||
| 329 | |||
| 330 | // remove the common prefix of the paths |
||
| 331 | while (\count($cwdParts) > 0 && \count($targetParts) > 0 && $cwdParts[0] === $targetParts[0]) { |
||
| 332 | \array_shift($cwdParts); |
||
| 333 | \array_shift($targetParts); |
||
| 334 | } |
||
| 335 | |||
| 336 | // prepend up-navigation from CWD to the closest common parent folder with the target |
||
| 337 | for ($i = 0, $count = \count($cwdParts); $i < $count; ++$i) { |
||
| 338 | \array_unshift($targetParts, '..'); |
||
| 339 | } |
||
| 340 | |||
| 341 | return \implode('/', $targetParts); |
||
| 342 | } |
||
| 343 | |||
| 344 | /** |
||
| 345 | * Given a current working directory path (CWD) and a relative path (possibly containing '..' parts), |
||
| 346 | * form an absolute path matching the relative path. This is a reverse operation for Util::relativePath(). |
||
| 347 | */ |
||
| 348 | public static function resolveRelativePath(string $cwdPath, string $relativePath) : string { |
||
| 349 | $cwdParts = \explode('/', $cwdPath); |
||
| 350 | $relativeParts = \explode('/', $relativePath); |
||
| 351 | |||
| 352 | // get rid of the trailing empty part of CWD which appears when CWD has a trailing '/' |
||
| 353 | if ($cwdParts[\count($cwdParts)-1] === '') { |
||
| 354 | \array_pop($cwdParts); |
||
| 355 | } |
||
| 356 | |||
| 357 | foreach ($relativeParts as $part) { |
||
| 358 | if ($part === '..') { |
||
| 359 | \array_pop($cwdParts); |
||
| 360 | } else { |
||
| 361 | \array_push($cwdParts, $part); |
||
| 362 | } |
||
| 363 | } |
||
| 364 | |||
| 365 | return \implode('/', $cwdParts); |
||
| 366 | } |
||
| 367 | |||
| 368 | /** |
||
| 369 | * Encode a file path so that it can be used as part of a WebDAV URL |
||
| 370 | */ |
||
| 371 | public static function urlEncodePath(string $path) : string { |
||
| 372 | // URL encode each part of the file path |
||
| 373 | return \join('/', \array_map('rawurlencode', \explode('/', $path))); |
||
| 374 | } |
||
| 375 | |||
| 376 | /** |
||
| 377 | * Compose URL from parts as returned by the system function parse_url. |
||
| 378 | * From https://stackoverflow.com/a/35207936 |
||
| 379 | */ |
||
| 380 | public static function buildUrl(array $parts) : string { |
||
| 381 | return (isset($parts['scheme']) ? "{$parts['scheme']}:" : '') . |
||
| 382 | ((isset($parts['user']) || isset($parts['host'])) ? '//' : '') . |
||
| 383 | (isset($parts['user']) ? "{$parts['user']}" : '') . |
||
| 384 | (isset($parts['pass']) ? ":{$parts['pass']}" : '') . |
||
| 385 | (isset($parts['user']) ? '@' : '') . |
||
| 386 | (isset($parts['host']) ? "{$parts['host']}" : '') . |
||
| 387 | (isset($parts['port']) ? ":{$parts['port']}" : '') . |
||
| 388 | (isset($parts['path']) ? "{$parts['path']}" : '') . |
||
| 389 | (isset($parts['query']) ? "?{$parts['query']}" : '') . |
||
| 390 | (isset($parts['fragment']) ? "#{$parts['fragment']}" : ''); |
||
| 391 | } |
||
| 392 | |||
| 393 | /** |
||
| 394 | * Swap values of two variables in place |
||
| 395 | * @param mixed $a |
||
| 396 | * @param mixed $b |
||
| 397 | */ |
||
| 398 | public static function swap(&$a, &$b) : void { |
||
| 402 | } |
||
| 403 | |||
| 404 | /** |
||
| 405 | * Limit an integer value between the specified minimum and maximum. |
||
| 406 | * A null value is a valid input and will produce a null output. |
||
| 407 | * @param int|float|null $input |
||
| 408 | * @param int|float $min |
||
| 409 | * @param int|float $max |
||
| 410 | * @return int|float|null |
||
| 411 | */ |
||
| 412 | public static function limit($input, $min, $max) { |
||
| 417 | } |
||
| 418 | } |
||
| 419 | } |
||
| 420 |