1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace PHPStan\BetterReflection\Util;
6:
7: use function array_pop;
8: use function assert;
9: use function explode;
10: use function implode;
11: use function is_string;
12: use function preg_match;
13: use function str_replace;
14: use function strpos;
15: use function substr;
16: use function trim;
17:
18: use const DIRECTORY_SEPARATOR;
19:
20: class FileHelper
21: {
22: public static function normalizeWindowsPath(string $path): string
23: {
24: return str_replace('\\', '/', $path);
25: }
26:
27: public static function normalizePath(string $originalPath, string $directorySeparator = DIRECTORY_SEPARATOR): string
28: {
29: $isLocalPath = $originalPath !== '' && $originalPath[0] === '/';
30:
31: $matches = null;
32: if (! $isLocalPath) {
33: if (! preg_match('~^([a-z]+)\\:\\/\\/(.+)~', $originalPath, $matches)) {
34: $matches = null;
35: }
36: }
37:
38: if ($matches !== null) {
39: [, $scheme, $path] = $matches;
40: } else {
41: $scheme = null;
42: $path = $originalPath;
43: }
44:
45: $path = str_replace(['\\', '//', '///', '////'], '/', $path);
46:
47: $pathRoot = strpos($path, '/') === 0 ? $directorySeparator : '';
48: $pathParts = explode('/', trim($path, '/'));
49:
50: $normalizedPathParts = [];
51: foreach ($pathParts as $pathPart) {
52: if ($pathPart === '.') {
53: continue;
54: }
55:
56: if ($pathPart === '..') {
57: $removedPart = array_pop($normalizedPathParts);
58: assert(is_string($removedPart));
59: if ($scheme === 'phar' && substr($removedPart, -5) === '.phar') {
60: $scheme = null;
61: }
62: } else {
63: $normalizedPathParts[] = $pathPart;
64: }
65: }
66:
67: return ($scheme !== null ? $scheme . '://' : '') . $pathRoot . implode($directorySeparator, $normalizedPathParts);
68: }
69:
70: public static function normalizeSystemPath(string $originalPath): string
71: {
72: $path = self::normalizeWindowsPath($originalPath);
73: preg_match('~^([a-z]+)\\:\\/\\/(.+)~', $path, $matches);
74: $scheme = null;
75: if ($matches !== []) {
76: [, $scheme, $path] = $matches;
77: }
78:
79: if (DIRECTORY_SEPARATOR === '\\') {
80: // @infection-ignore-all UnwrapStrReplace Needed only on Windows
81: $path = str_replace('/', DIRECTORY_SEPARATOR, $path);
82: }
83:
84: return ($scheme !== null ? $scheme . '://' : '') . $path;
85: }
86: }
87: