Debian Codegraph @

lib/3rdParty/composer/symfony/filesystem/Path.php

raw symbols SCIP
1 <?php
2
3 /*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <[email protected]>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12 namespace Symfony\Component\Filesystem;
13
14 use Symfony\Component\Filesystem\Exception\InvalidArgumentException;
15 use Symfony\Component\Filesystem\Exception\RuntimeException;
16
17 /**
18 * Contains utility methods for handling path strings.
19 *
20 * The methods in this class are able to deal with both UNIX and Windows paths.
21 * On Windows, backward slashes are normalized to forward slashes. On UNIX,
22 * backward slashes are treated as valid filename characters and are not replaced.
23 * All methods return normalized parts with no excess "." and ".." segments.
24 *
25 * @author Bernhard Schussek <[email protected]>
26 * @author Thomas Schulz <[email protected]>
27 * @author Théo Fidry <[email protected]>
28 */
29 final class Path
30 {
31 /**
32 * The number of buffer entries that triggers a cleanup operation.
33 */
34 private const CLEANUP_THRESHOLD = 1250;
35
36 /**
37 * The buffer size after the cleanup operation.
38 */
39 private const CLEANUP_SIZE = 1000;
40
41 /**
42 * Buffers input/output of {@link canonicalize()}.
43 *
44 * @var array<string, string>
45 */
46 private static array $buffer = [];
47
48 private static int $bufferSize = 0;
49
50 /**
51 * Canonicalizes the given path.
52 *
53 * During normalization, all "." and ".." segments are removed as far as
54 * possible. ".." segments at the beginning of relative paths are not removed.
55 * On Windows, backward slashes are replaced by forward slashes ("/").
56 *
57 * ```php
58 * echo Path::canonicalize("../css/./style.css");
59 * // => ../css/style.css
60 * ```
61 *
62 * This method is able to deal with both UNIX and Windows paths.
63 */
64 public static function canonicalize(string $path): string
65 {
66 if ('' === $path) {
67 return '';
68 }
69
70 // This method is called by many other methods in this class. Buffer
71 // the canonicalized paths to make up for the severe performance
72 // decrease.
73 if (isset(self::$buffer[$path])) {
74 return self::$buffer[$path];
75 }
76
77 // Replace "~" with user's home directory.
78 if ('~' === $path[0]) {
79 $path = self::getHomeDirectory().substr($path, 1);
80 }
81
82 $path = self::normalize($path);
83
84 [$root, $pathWithoutRoot] = self::split($path);
85
86 $canonicalParts = self::findCanonicalParts($root, $pathWithoutRoot);
87
88 // Add the root directory again
89 self::$buffer[$path] = $canonicalPath = $root.implode('/', $canonicalParts);
90 ++self::$bufferSize;
91
92 // Clean up regularly to prevent memory leaks
93 if (self::$bufferSize > self::CLEANUP_THRESHOLD) {
94 self::$buffer = \array_slice(self::$buffer, -self::CLEANUP_SIZE, null, true);
95 self::$bufferSize = self::CLEANUP_SIZE;
96 }
97
98 return $canonicalPath;
99 }
100
101 /**
102 * Normalizes the given path.
103 *
104 * On Windows, backward slashes are replaced by forward slashes ("/").
105 * On UNIX, backward slashes are preserved as they are valid filename characters.
106 * Contrary to {@link canonicalize()}, this method does not remove invalid
107 * or dot path segments. Consequently, it is much more efficient and should
108 * be used whenever the given path is known to be a valid, absolute system
109 * path.
110 */
111 public static function normalize(string $path): string
112 {
113 return '\\' === \DIRECTORY_SEPARATOR ? str_replace('\\', '/', $path) : $path;
114 }
115
116 /**
117 * Returns the directory part of the path.
118 *
119 * This method is similar to PHP's dirname(), but handles various cases
120 * where dirname() returns a weird result:
121 *
122 * - dirname() does not accept backslashes on UNIX
123 * - dirname("C:/symfony") returns "C:", not "C:/"
124 * - dirname("C:/") returns ".", not "C:/"
125 * - dirname("C:") returns ".", not "C:/"
126 * - dirname("symfony") returns ".", not ""
127 * - dirname() does not canonicalize the result
128 *
129 * This method fixes these shortcomings and behaves like dirname()
130 * otherwise.
131 *
132 * The result is a canonical path.
133 *
134 * @return string The canonical directory part. Returns the root directory
135 * if the root directory is passed. Returns an empty string
136 * if a relative path is passed that contains no slashes.
137 * Returns an empty string if an empty string is passed.
138 */
139 public static function getDirectory(string $path): string
140 {
141 if ('' === $path) {
142 return '';
143 }
144
145 $path = self::canonicalize($path);
146
147 // Maintain scheme
148 if (false !== $schemeSeparatorPosition = strpos($path, '://')) {
149 $scheme = substr($path, 0, $schemeSeparatorPosition + 3);
150 $path = substr($path, $schemeSeparatorPosition + 3);
151 } else {
152 $scheme = '';
153 }
154
155 if (false === $dirSeparatorPosition = strrpos($path, '/')) {
156 return '';
157 }
158
159 // Directory equals root directory "/"
160 if (0 === $dirSeparatorPosition) {
161 return $scheme.'/';
162 }
163
164 // Directory equals Windows root "C:/"
165 if (2 === $dirSeparatorPosition && ctype_alpha($path[0]) && ':' === $path[1]) {
166 return $scheme.substr($path, 0, 3);
167 }
168
169 return $scheme.substr($path, 0, $dirSeparatorPosition);
170 }
171
172 /**
173 * Returns canonical path of the user's home directory.
174 *
175 * Supported operating systems:
176 *
177 * - UNIX
178 * - Windows8 and upper
179 *
180 * If your operating system or environment isn't supported, an exception is thrown.
181 *
182 * The result is a canonical path.
183 *
184 * @throws RuntimeException If your operating system or environment isn't supported
185 */
186 public static function getHomeDirectory(): string
187 {
188 // For UNIX support
189 if (getenv('HOME')) {
190 return self::canonicalize(getenv('HOME'));
191 }
192
193 // For >= Windows8 support
194 if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) {
195 return self::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH'));
196 }
197
198 throw new RuntimeException("Cannot find the home directory path: Your environment or operating system isn't supported.");
199 }
200
201 /**
202 * Returns the root directory of a path.
203 *
204 * The result is a canonical path.
205 *
206 * @return string The canonical root directory. Returns an empty string if
207 * the given path is relative or empty.
208 */
209 public static function getRoot(string $path): string
210 {
211 if ('' === $path) {
212 return '';
213 }
214
215 // Maintain scheme
216 if (false !== $schemeSeparatorPosition = strpos($path, '://')) {
217 $scheme = substr($path, 0, $schemeSeparatorPosition + 3);
218 $path = substr($path, $schemeSeparatorPosition + 3);
219 } else {
220 $scheme = '';
221 }
222
223 $firstCharacter = $path[0];
224
225 if ('/' === $firstCharacter) {
226 return $scheme.'/';
227 }
228
229 if ('\\' !== \DIRECTORY_SEPARATOR) {
230 return '';
231 }
232
233 if ('\\' === $firstCharacter) {
234 return $scheme.'/';
235 }
236
237 $length = \strlen($path);
238
239 // Windows root
240 if ($length > 1 && ':' === $path[1] && ctype_alpha($firstCharacter)) {
241 // Special case: "C:"
242 if (2 === $length) {
243 return $scheme.$path.'/';
244 }
245
246 // Normal case: "C:/" or "C:\"
247 if ('/' === $path[2] || '\\' === $path[2]) {
248 return $scheme.$firstCharacter.$path[1].'/';
249 }
250 }
251
252 return '';
253 }
254
255 /**
256 * Returns the file name without the extension from a file path.
257 *
258 * @param string|null $extension if specified, only that extension is cut
259 * off (may contain leading dot)
260 */
261 public static function getFilenameWithoutExtension(string $path, ?string $extension = null): string
262 {
263 if ('' === $path) {
264 return '';
265 }
266
267 if (null !== $extension) {
268 // remove extension and trailing dot
269 return rtrim(basename($path, $extension), '.');
270 }
271
272 return pathinfo($path, \PATHINFO_FILENAME);
273 }
274
275 /**
276 * Returns the extension from a file path (without leading dot).
277 *
278 * @param bool $forceLowerCase forces the extension to be lower-case
279 */
280 public static function getExtension(string $path, bool $forceLowerCase = false): string
281 {
282 if ('' === $path) {
283 return '';
284 }
285
286 $extension = pathinfo($path, \PATHINFO_EXTENSION);
287
288 if ($forceLowerCase) {
289 $extension = self::toLower($extension);
290 }
291
292 return $extension;
293 }
294
295 /**
296 * Returns whether the path has an (or the specified) extension.
297 *
298 * @param string $path the path string
299 * @param string|string[]|null $extensions if null or not provided, checks if
300 * an extension exists, otherwise
301 * checks for the specified extension
302 * or array of extensions (with or
303 * without leading dot)
304 * @param bool $ignoreCase whether to ignore case-sensitivity
305 */
306 public static function hasExtension(string $path, $extensions = null, bool $ignoreCase = false): bool
307 {
308 if ('' === $path) {
309 return false;
310 }
311
312 $actualExtension = self::getExtension($path, $ignoreCase);
313
314 // Only check if path has any extension
315 if ([] === $extensions || null === $extensions) {
316 return '' !== $actualExtension;
317 }
318
319 if (\is_string($extensions)) {
320 $extensions = [$extensions];
321 }
322
323 foreach ($extensions as $key => $extension) {
324 if ($ignoreCase) {
325 $extension = self::toLower($extension);
326 }
327
328 // remove leading '.' in extensions array
329 $extensions[$key] = ltrim($extension, '.');
330 }
331
332 return \in_array($actualExtension, $extensions, true);
333 }
334
335 /**
336 * Changes the extension of a path string.
337 *
338 * @param string $path The path string with filename.ext to change.
339 * @param string $extension new extension (with or without leading dot)
340 *
341 * @return string the path string with new file extension
342 */
343 public static function changeExtension(string $path, string $extension): string
344 {
345 if ('' === $path) {
346 return '';
347 }
348
349 $actualExtension = self::getExtension($path);
350 $extension = ltrim($extension, '.');
351
352 // No extension for paths
353 if (str_ends_with($path, '/')) {
354 return $path;
355 }
356
357 // No actual extension in path
358 if (!$actualExtension) {
359 return $path.(str_ends_with($path, '.') ? '' : '.').$extension;
360 }
361
362 return substr($path, 0, -\strlen($actualExtension)).$extension;
363 }
364
365 /**
366 * Returns whether the given path is absolute.
367 */
368 public static function isAbsolute(string $path): bool
369 {
370 if ('' === $path) {
371 return false;
372 }
373
374 // URLs and stream wrappers are considered absolute
375 if (str_contains($path, '://') && null !== parse_url($path, \PHP_URL_SCHEME)) {
376 return true;
377 }
378
379 if ('/' === $path[0]) {
380 return true;
381 }
382
383 if ('\\' !== \DIRECTORY_SEPARATOR) {
384 return false;
385 }
386
387 if ('\\' === $path[0]) {
388 return true;
389 }
390
391 // Windows root
392 if (\strlen($path) > 1 && ctype_alpha($path[0]) && ':' === $path[1]) {
393 // Special case: "C:"
394 if (2 === \strlen($path)) {
395 return true;
396 }
397
398 // Normal case: "C:/" or "C:\"
399 if ('/' === $path[2] || '\\' === $path[2]) {
400 return true;
401 }
402 }
403
404 return false;
405 }
406
407 public static function isRelative(string $path): bool
408 {
409 return !self::isAbsolute($path);
410 }
411
412 /**
413 * Turns a relative path into an absolute path in canonical form.
414 *
415 * Usually, the relative path is appended to the given base path. Dot
416 * segments ("." and "..") are removed/collapsed and all slashes turned
417 * into forward slashes.
418 *
419 * ```php
420 * echo Path::makeAbsolute("../style.css", "/symfony/puli/css");
421 * // => /symfony/puli/style.css
422 * ```
423 *
424 * If an absolute path is passed, that path is returned unless its root
425 * directory is different than the one of the base path. In that case, an
426 * exception is thrown.
427 *
428 * ```php
429 * Path::makeAbsolute("/style.css", "/symfony/puli/css");
430 * // => /style.css
431 *
432 * Path::makeAbsolute("C:/style.css", "C:/symfony/puli/css");
433 * // => C:/style.css
434 *
435 * Path::makeAbsolute("C:/style.css", "/symfony/puli/css");
436 * // InvalidArgumentException
437 * ```
438 *
439 * If the base path is not an absolute path, an exception is thrown.
440 *
441 * The result is a canonical path.
442 *
443 * @param string $basePath an absolute base path
444 *
445 * @throws InvalidArgumentException if the base path is not absolute or if
446 * the given path is an absolute path with
447 * a different root than the base path
448 */
449 public static function makeAbsolute(string $path, string $basePath): string
450 {
451 if ('' === $basePath) {
452 throw new InvalidArgumentException(\sprintf('The base path must be a non-empty string. Got: "%s".', $basePath));
453 }
454
455 if (!self::isAbsolute($basePath)) {
456 throw new InvalidArgumentException(\sprintf('The base path "%s" is not an absolute path.', $basePath));
457 }
458
459 if (self::isAbsolute($path)) {
460 return self::canonicalize($path);
461 }
462
463 if (false !== $schemeSeparatorPosition = strpos($basePath, '://')) {
464 $scheme = substr($basePath, 0, $schemeSeparatorPosition + 3);
465 $basePath = substr($basePath, $schemeSeparatorPosition + 3);
466 } else {
467 $scheme = '';
468 }
469
470 return $scheme.self::canonicalize(rtrim($basePath, '/'.\DIRECTORY_SEPARATOR).'/'.$path);
471 }
472
473 /**
474 * Turns a path into a relative path.
475 *
476 * The relative path is created relative to the given base path:
477 *
478 * ```php
479 * echo Path::makeRelative("/symfony/style.css", "/symfony/puli");
480 * // => ../style.css
481 * ```
482 *
483 * If a relative path is passed and the base path is absolute, the relative
484 * path is returned unchanged:
485 *
486 * ```php
487 * Path::makeRelative("style.css", "/symfony/puli/css");
488 * // => style.css
489 * ```
490 *
491 * If both paths are relative, the relative path is created with the
492 * assumption that both paths are relative to the same directory:
493 *
494 * ```php
495 * Path::makeRelative("style.css", "symfony/puli/css");
496 * // => ../../../style.css
497 * ```
498 *
499 * If both paths are absolute, their root directory must be the same,
500 * otherwise an exception is thrown:
501 *
502 * ```php
503 * Path::makeRelative("C:/symfony/style.css", "/symfony/puli");
504 * // InvalidArgumentException
505 * ```
506 *
507 * If the passed path is absolute, but the base path is not, an exception
508 * is thrown as well:
509 *
510 * ```php
511 * Path::makeRelative("/symfony/style.css", "symfony/puli");
512 * // InvalidArgumentException
513 * ```
514 *
515 * If the base path is not an absolute path, an exception is thrown.
516 *
517 * The result is a canonical path.
518 *
519 * @throws InvalidArgumentException if the base path is not absolute or if
520 * the given path has a different root
521 * than the base path
522 */
523 public static function makeRelative(string $path, string $basePath): string
524 {
525 $path = self::canonicalize($path);
526 $basePath = self::canonicalize($basePath);
527
528 [$root, $relativePath] = self::split($path);
529 [$baseRoot, $relativeBasePath] = self::split($basePath);
530
531 // If the base path is given as absolute path and the path is already
532 // relative, consider it to be relative to the given absolute path
533 // already
534 if ('' === $root && '' !== $baseRoot) {
535 // If base path is already in its root
536 if ('' === $relativeBasePath) {
537 $relativePath = ltrim($relativePath, './'.\DIRECTORY_SEPARATOR);
538 }
539
540 return $relativePath;
541 }
542
543 // If the passed path is absolute, but the base path is not, we
544 // cannot generate a relative path
545 if ('' !== $root && '' === $baseRoot) {
546 throw new InvalidArgumentException(\sprintf('The absolute path "%s" cannot be made relative to the relative path "%s". You should provide an absolute base path instead.', $path, $basePath));
547 }
548
549 // Fail if the roots of the two paths are different
550 if ($baseRoot && $root !== $baseRoot) {
551 throw new InvalidArgumentException(\sprintf('The path "%s" cannot be made relative to "%s", because they have different roots ("%s" and "%s").', $path, $basePath, $root, $baseRoot));
552 }
553
554 if ('' === $relativeBasePath) {
555 return $relativePath;
556 }
557
558 // Build a "../../" prefix with as many "../" parts as necessary
559 $parts = explode('/', $relativePath);
560 $baseParts = explode('/', $relativeBasePath);
561 $dotDotPrefix = '';
562
563 // Once we found a non-matching part in the prefix, we need to add
564 // "../" parts for all remaining parts
565 $match = true;
566
567 foreach ($baseParts as $index => $basePart) {
568 if ($match && isset($parts[$index]) && $basePart === $parts[$index]) {
569 unset($parts[$index]);
570
571 continue;
572 }
573
574 $match = false;
575 $dotDotPrefix .= '../';
576 }
577
578 return rtrim($dotDotPrefix.implode('/', $parts), '/');
579 }
580
581 /**
582 * Returns whether the given path is on the local filesystem.
583 */
584 public static function isLocal(string $path): bool
585 {
586 return '' !== $path && !str_contains($path, '://');
587 }
588
589 /**
590 * Returns the longest common base path in canonical form of a set of paths or
591 * `null` if the paths are on different Windows partitions.
592 *
593 * Dot segments ("." and "..") are removed/collapsed and all slashes turned
594 * into forward slashes.
595 *
596 * ```php
597 * $basePath = Path::getLongestCommonBasePath(
598 * '/symfony/css/style.css',
599 * '/symfony/css/..'
600 * );
601 * // => /symfony
602 * ```
603 *
604 * The root is returned if no common base path can be found:
605 *
606 * ```php
607 * $basePath = Path::getLongestCommonBasePath(
608 * '/symfony/css/style.css',
609 * '/puli/css/..'
610 * );
611 * // => /
612 * ```
613 *
614 * If the paths are located on different Windows partitions, `null` is
615 * returned.
616 *
617 * ```php
618 * $basePath = Path::getLongestCommonBasePath(
619 * 'C:/symfony/css/style.css',
620 * 'D:/symfony/css/..'
621 * );
622 * // => null
623 * ```
624 */
625 public static function getLongestCommonBasePath(string ...$paths): ?string
626 {
627 [$bpRoot, $basePath] = self::split(self::canonicalize(reset($paths)));
628
629 for (next($paths); null !== key($paths) && '' !== $basePath; next($paths)) {
630 [$root, $path] = self::split(self::canonicalize(current($paths)));
631
632 // If we deal with different roots (e.g. C:/ vs. D:/), it's time
633 // to quit
634 if ($root !== $bpRoot) {
635 return null;
636 }
637
638 // Make the base path shorter until it fits into path
639 while (true) {
640 if ('.' === $basePath) {
641 // No more base paths
642 $basePath = '';
643
644 // next path
645 continue 2;
646 }
647
648 // Prevent false positives for common prefixes
649 // see isBasePath()
650 if (str_starts_with($path.'/', $basePath.'/')) {
651 // next path
652 continue 2;
653 }
654
655 $basePath = \dirname($basePath);
656 }
657 }
658
659 return $bpRoot.$basePath;
660 }
661
662 /**
663 * Joins two or more path strings into a canonical path.
664 */
665 public static function join(string ...$paths): string
666 {
667 $finalPath = null;
668 $wasScheme = false;
669
670 foreach ($paths as $path) {
671 if ('' === $path) {
672 continue;
673 }
674
675 if (null === $finalPath) {
676 // For first part we keep slashes, like '/top', 'C:\' or 'phar://'
677 $finalPath = $path;
678 $wasScheme = str_contains($path, '://');
679 continue;
680 }
681
682 // Only add slash if previous part didn't end with '/' or '\' (Windows)
683 if ('/' !== substr($finalPath, -1) && \DIRECTORY_SEPARATOR !== substr($finalPath, -1)) {
684 $finalPath .= '/';
685 }
686
687 // If first part included a scheme like 'phar://' we allow \current part to start with '/', otherwise trim
688 $finalPath .= $wasScheme ? $path : ltrim($path, '/');
689 $wasScheme = false;
690 }
691
692 if (null === $finalPath) {
693 return '';
694 }
695
696 return self::canonicalize($finalPath);
697 }
698
699 /**
700 * Returns whether a path is a base path of another path.
701 *
702 * Dot segments ("." and "..") are removed/collapsed and all slashes turned
703 * into forward slashes.
704 *
705 * ```php
706 * Path::isBasePath('/symfony', '/symfony/css');
707 * // => true
708 *
709 * Path::isBasePath('/symfony', '/symfony');
710 * // => true
711 *
712 * Path::isBasePath('/symfony', '/symfony/..');
713 * // => false
714 *
715 * Path::isBasePath('/symfony', '/puli');
716 * // => false
717 * ```
718 */
719 public static function isBasePath(string $basePath, string $ofPath): bool
720 {
721 $basePath = self::canonicalize($basePath);
722 $ofPath = self::canonicalize($ofPath);
723
724 // Append slashes to prevent false positives when two paths have
725 // a common prefix, for example /base/foo and /base/foobar.
726 // Don't append a slash for the root "/", because then that root
727 // won't be discovered as common prefix ("//" is not a prefix of
728 // "/foobar/").
729 return str_starts_with($ofPath.'/', rtrim($basePath, '/').'/');
730 }
731
732 /**
733 * @return string[]
734 */
735 private static function findCanonicalParts(string $root, string $pathWithoutRoot): array
736 {
737 $parts = explode('/', $pathWithoutRoot);
738
739 $canonicalParts = [];
740
741 // Collapse "." and "..", if possible
742 foreach ($parts as $part) {
743 if ('.' === $part || '' === $part) {
744 continue;
745 }
746
747 // Collapse ".." with the previous part, if one exists
748 // Don't collapse ".." if the previous part is also ".."
749 if ('..' === $part && \count($canonicalParts) > 0 && '..' !== $canonicalParts[\count($canonicalParts) - 1]) {
750 array_pop($canonicalParts);
751
752 continue;
753 }
754
755 // Only add ".." prefixes for relative paths
756 if ('..' !== $part || '' === $root) {
757 $canonicalParts[] = $part;
758 }
759 }
760
761 return $canonicalParts;
762 }
763
764 /**
765 * Splits a canonical path into its root directory and the remainder.
766 *
767 * If the path has no root directory, an empty root directory will be
768 * returned.
769 *
770 * If the root directory is a Windows style partition, the resulting root
771 * will always contain a trailing slash.
772 *
773 * list ($root, $path) = Path::split("C:/symfony")
774 * // => ["C:/", "symfony"]
775 *
776 * list ($root, $path) = Path::split("C:")
777 * // => ["C:/", ""]
778 *
779 * @return array{string, string} an array with the root directory and the remaining relative path
780 */
781 private static function split(string $path): array
782 {
783 if ('' === $path) {
784 return ['', ''];
785 }
786
787 // Remember scheme as part of the root, if any
788 if (false !== $schemeSeparatorPosition = strpos($path, '://')) {
789 $root = substr($path, 0, $schemeSeparatorPosition + 3);
790 $path = substr($path, $schemeSeparatorPosition + 3);
791 } else {
792 $root = '';
793 }
794
795 $length = \strlen($path);
796
797 // Remove and remember root directory
798 if (str_starts_with($path, '/')) {
799 $root .= '/';
800 $path = $length > 1 ? substr($path, 1) : '';
801 } elseif ('\\' === \DIRECTORY_SEPARATOR && $length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) {
802 if (2 === $length) {
803 // Windows special case: "C:"
804 $root .= $path.'/';
805 $path = '';
806 } elseif ('/' === $path[2]) {
807 // Windows normal case: "C:/"..
808 $root .= substr($path, 0, 3);
809 $path = $length > 3 ? substr($path, 3) : '';
810 }
811 }
812
813 return [$root, $path];
814 }
815
816 private static function toLower(string $string): string
817 {
818 if (false !== $encoding = mb_detect_encoding($string, null, true)) {
819 return mb_strtolower($string, $encoding);
820 }
821
822 return strtolower($string);
823 }
824
825 private function __construct()
826 {
827 }
828 }