4 * This file is part of the webmozart/path-util package.
6 * (c) Bernhard Schussek <bschussek@gmail.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Webmozart\PathUtil;
14 use InvalidArgumentException;
16 use Webmozart\Assert\Assert;
19 * Contains utility methods for handling path strings.
21 * The methods in this class are able to deal with both UNIX and Windows paths
22 * with both forward and backward slashes. All methods return normalized parts
23 * containing only forward slashes and no excess "." and ".." segments.
27 * @author Bernhard Schussek <bschussek@gmail.com>
28 * @author Thomas Schulz <mail@king2500.net>
33 * The number of buffer entries that triggers a cleanup operation.
35 const CLEANUP_THRESHOLD = 1250;
38 * The buffer size after the cleanup operation.
40 const CLEANUP_SIZE = 1000;
43 * Buffers input/output of {@link canonicalize()}.
47 private static $buffer = array();
50 * The size of the buffer.
54 private static $bufferSize = 0;
57 * Canonicalizes the given path.
59 * During normalization, all slashes are replaced by forward slashes ("/").
60 * Furthermore, all "." and ".." segments are removed as far as possible.
61 * ".." segments at the beginning of relative paths are not removed.
64 * echo Path::canonicalize("\webmozart\puli\..\css\style.css");
65 * // => /webmozart/css/style.css
67 * echo Path::canonicalize("../css/./style.css");
68 * // => ../css/style.css
71 * This method is able to deal with both UNIX and Windows paths.
73 * @param string $path A path string.
75 * @return string The canonical path.
77 * @since 1.0 Added method.
78 * @since 2.0 Method now fails if $path is not a string.
79 * @since 2.1 Added support for `~`.
81 public static function canonicalize($path)
87 Assert::string($path, 'The path must be a string. Got: %s');
89 // This method is called by many other methods in this class. Buffer
90 // the canonicalized paths to make up for the severe performance
92 if (isset(self::$buffer[$path])) {
93 return self::$buffer[$path];
96 // Replace "~" with user's home directory.
97 if ('~' === $path[0]) {
98 $path = static::getHomeDirectory().substr($path, 1);
101 $path = str_replace('\\', '/', $path);
103 list($root, $pathWithoutRoot) = self::split($path);
105 $parts = explode('/', $pathWithoutRoot);
106 $canonicalParts = array();
108 // Collapse "." and "..", if possible
109 foreach ($parts as $part) {
110 if ('.' === $part || '' === $part) {
114 // Collapse ".." with the previous part, if one exists
115 // Don't collapse ".." if the previous part is also ".."
116 if ('..' === $part && count($canonicalParts) > 0
117 && '..' !== $canonicalParts[count($canonicalParts) - 1]) {
118 array_pop($canonicalParts);
123 // Only add ".." prefixes for relative paths
124 if ('..' !== $part || '' === $root) {
125 $canonicalParts[] = $part;
129 // Add the root directory again
130 self::$buffer[$path] = $canonicalPath = $root.implode('/', $canonicalParts);
133 // Clean up regularly to prevent memory leaks
134 if (self::$bufferSize > self::CLEANUP_THRESHOLD) {
135 self::$buffer = array_slice(self::$buffer, -self::CLEANUP_SIZE, null, true);
136 self::$bufferSize = self::CLEANUP_SIZE;
139 return $canonicalPath;
143 * Normalizes the given path.
145 * During normalization, all slashes are replaced by forward slashes ("/").
146 * Contrary to {@link canonicalize()}, this method does not remove invalid
147 * or dot path segments. Consequently, it is much more efficient and should
148 * be used whenever the given path is known to be a valid, absolute system
151 * This method is able to deal with both UNIX and Windows paths.
153 * @param string $path A path string.
155 * @return string The normalized path.
157 * @since 2.2 Added method.
159 public static function normalize($path)
161 Assert::string($path, 'The path must be a string. Got: %s');
163 return str_replace('\\', '/', $path);
167 * Returns the directory part of the path.
169 * This method is similar to PHP's dirname(), but handles various cases
170 * where dirname() returns a weird result:
172 * - dirname() does not accept backslashes on UNIX
173 * - dirname("C:/webmozart") returns "C:", not "C:/"
174 * - dirname("C:/") returns ".", not "C:/"
175 * - dirname("C:") returns ".", not "C:/"
176 * - dirname("webmozart") returns ".", not ""
177 * - dirname() does not canonicalize the result
179 * This method fixes these shortcomings and behaves like dirname()
182 * The result is a canonical path.
184 * @param string $path A path string.
186 * @return string The canonical directory part. Returns the root directory
187 * if the root directory is passed. Returns an empty string
188 * if a relative path is passed that contains no slashes.
189 * Returns an empty string if an empty string is passed.
191 * @since 1.0 Added method.
192 * @since 2.0 Method now fails if $path is not a string.
194 public static function getDirectory($path)
200 $path = static::canonicalize($path);
203 if (false !== ($pos = strpos($path, '://'))) {
204 $scheme = substr($path, 0, $pos + 3);
205 $path = substr($path, $pos + 3);
210 if (false !== ($pos = strrpos($path, '/'))) {
211 // Directory equals root directory "/"
216 // Directory equals Windows root "C:/"
217 if (2 === $pos && ctype_alpha($path[0]) && ':' === $path[1]) {
218 return $scheme.substr($path, 0, 3);
221 return $scheme.substr($path, 0, $pos);
228 * Returns canonical path of the user's home directory.
230 * Supported operating systems:
233 * - Windows8 and upper
235 * If your operation system or environment isn't supported, an exception is thrown.
237 * The result is a canonical path.
239 * @return string The canonical home directory
241 * @throws RuntimeException If your operation system or environment isn't supported
243 * @since 2.1 Added method.
245 public static function getHomeDirectory()
248 if (getenv('HOME')) {
249 return static::canonicalize(getenv('HOME'));
252 // For >= Windows8 support
253 if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) {
254 return static::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH'));
257 throw new RuntimeException("Your environment or operation system isn't supported");
261 * Returns the root directory of a path.
263 * The result is a canonical path.
265 * @param string $path A path string.
267 * @return string The canonical root directory. Returns an empty string if
268 * the given path is relative or empty.
270 * @since 1.0 Added method.
271 * @since 2.0 Method now fails if $path is not a string.
273 public static function getRoot($path)
279 Assert::string($path, 'The path must be a string. Got: %s');
282 if (false !== ($pos = strpos($path, '://'))) {
283 $scheme = substr($path, 0, $pos + 3);
284 $path = substr($path, $pos + 3);
289 // UNIX root "/" or "\" (Windows style)
290 if ('/' === $path[0] || '\\' === $path[0]) {
294 $length = strlen($path);
297 if ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) {
298 // Special case: "C:"
300 return $scheme.$path.'/';
303 // Normal case: "C:/ or "C:\"
304 if ('/' === $path[2] || '\\' === $path[2]) {
305 return $scheme.$path[0].$path[1].'/';
313 * Returns the file name from a file path.
315 * @param string $path The path string.
317 * @return string The file name.
319 * @since 1.1 Added method.
320 * @since 2.0 Method now fails if $path is not a string.
322 public static function getFilename($path)
328 Assert::string($path, 'The path must be a string. Got: %s');
330 return basename($path);
334 * Returns the file name without the extension from a file path.
336 * @param string $path The path string.
337 * @param string|null $extension If specified, only that extension is cut
338 * off (may contain leading dot).
340 * @return string The file name without extension.
342 * @since 1.1 Added method.
343 * @since 2.0 Method now fails if $path or $extension have invalid types.
345 public static function getFilenameWithoutExtension($path, $extension = null)
351 Assert::string($path, 'The path must be a string. Got: %s');
352 Assert::nullOrString($extension, 'The extension must be a string or null. Got: %s');
354 if (null !== $extension) {
355 // remove extension and trailing dot
356 return rtrim(basename($path, $extension), '.');
359 return pathinfo($path, PATHINFO_FILENAME);
363 * Returns the extension from a file path.
365 * @param string $path The path string.
366 * @param bool $forceLowerCase Forces the extension to be lower-case
367 * (requires mbstring extension for correct
368 * multi-byte character handling in extension).
370 * @return string The extension of the file path (without leading dot).
372 * @since 1.1 Added method.
373 * @since 2.0 Method now fails if $path is not a string.
375 public static function getExtension($path, $forceLowerCase = false)
381 Assert::string($path, 'The path must be a string. Got: %s');
383 $extension = pathinfo($path, PATHINFO_EXTENSION);
385 if ($forceLowerCase) {
386 $extension = self::toLower($extension);
393 * Returns whether the path has an extension.
395 * @param string $path The path string.
396 * @param string|array|null $extensions If null or not provided, checks if
397 * an extension exists, otherwise
398 * checks for the specified extension
399 * or array of extensions (with or
400 * without leading dot).
401 * @param bool $ignoreCase Whether to ignore case-sensitivity
402 * (requires mbstring extension for
403 * correct multi-byte character
404 * handling in the extension).
406 * @return bool Returns `true` if the path has an (or the specified)
407 * extension and `false` otherwise.
409 * @since 1.1 Added method.
410 * @since 2.0 Method now fails if $path or $extensions have invalid types.
412 public static function hasExtension($path, $extensions = null, $ignoreCase = false)
418 $extensions = is_object($extensions) ? array($extensions) : (array) $extensions;
420 Assert::allString($extensions, 'The extensions must be strings. Got: %s');
422 $actualExtension = self::getExtension($path, $ignoreCase);
424 // Only check if path has any extension
425 if (empty($extensions)) {
426 return '' !== $actualExtension;
429 foreach ($extensions as $key => $extension) {
431 $extension = self::toLower($extension);
434 // remove leading '.' in extensions array
435 $extensions[$key] = ltrim($extension, '.');
438 return in_array($actualExtension, $extensions);
442 * Changes the extension of a path string.
444 * @param string $path The path string with filename.ext to change.
445 * @param string $extension New extension (with or without leading dot).
447 * @return string The path string with new file extension.
449 * @since 1.1 Added method.
450 * @since 2.0 Method now fails if $path or $extension is not a string.
452 public static function changeExtension($path, $extension)
458 Assert::string($extension, 'The extension must be a string. Got: %s');
460 $actualExtension = self::getExtension($path);
461 $extension = ltrim($extension, '.');
463 // No extension for paths
464 if ('/' === substr($path, -1)) {
468 // No actual extension in path
469 if (empty($actualExtension)) {
470 return $path.('.' === substr($path, -1) ? '' : '.').$extension;
473 return substr($path, 0, -strlen($actualExtension)).$extension;
477 * Returns whether a path is absolute.
479 * @param string $path A path string.
481 * @return bool Returns true if the path is absolute, false if it is
484 * @since 1.0 Added method.
485 * @since 2.0 Method now fails if $path is not a string.
487 public static function isAbsolute($path)
493 Assert::string($path, 'The path must be a string. Got: %s');
496 if (false !== ($pos = strpos($path, '://'))) {
497 $path = substr($path, $pos + 3);
500 // UNIX root "/" or "\" (Windows style)
501 if ('/' === $path[0] || '\\' === $path[0]) {
506 if (strlen($path) > 1 && ctype_alpha($path[0]) && ':' === $path[1]) {
507 // Special case: "C:"
508 if (2 === strlen($path)) {
512 // Normal case: "C:/ or "C:\"
513 if ('/' === $path[2] || '\\' === $path[2]) {
522 * Returns whether a path is relative.
524 * @param string $path A path string.
526 * @return bool Returns true if the path is relative or empty, false if
529 * @since 1.0 Added method.
530 * @since 2.0 Method now fails if $path is not a string.
532 public static function isRelative($path)
534 return !static::isAbsolute($path);
538 * Turns a relative path into an absolute path.
540 * Usually, the relative path is appended to the given base path. Dot
541 * segments ("." and "..") are removed/collapsed and all slashes turned
542 * into forward slashes.
545 * echo Path::makeAbsolute("../style.css", "/webmozart/puli/css");
546 * // => /webmozart/puli/style.css
549 * If an absolute path is passed, that path is returned unless its root
550 * directory is different than the one of the base path. In that case, an
551 * exception is thrown.
554 * Path::makeAbsolute("/style.css", "/webmozart/puli/css");
557 * Path::makeAbsolute("C:/style.css", "C:/webmozart/puli/css");
560 * Path::makeAbsolute("C:/style.css", "/webmozart/puli/css");
561 * // InvalidArgumentException
564 * If the base path is not an absolute path, an exception is thrown.
566 * The result is a canonical path.
568 * @param string $path A path to make absolute.
569 * @param string $basePath An absolute base path.
571 * @return string An absolute path in canonical form.
573 * @throws InvalidArgumentException If the base path is not absolute or if
574 * the given path is an absolute path with
575 * a different root than the base path.
577 * @since 1.0 Added method.
578 * @since 2.0 Method now fails if $path or $basePath is not a string.
579 * @since 2.2.2 Method does not fail anymore of $path and $basePath are
580 * absolute, but on different partitions.
582 public static function makeAbsolute($path, $basePath)
584 Assert::stringNotEmpty($basePath, 'The base path must be a non-empty string. Got: %s');
586 if (!static::isAbsolute($basePath)) {
587 throw new InvalidArgumentException(sprintf(
588 'The base path "%s" is not an absolute path.',
593 if (static::isAbsolute($path)) {
594 return static::canonicalize($path);
597 if (false !== ($pos = strpos($basePath, '://'))) {
598 $scheme = substr($basePath, 0, $pos + 3);
599 $basePath = substr($basePath, $pos + 3);
604 return $scheme.self::canonicalize(rtrim($basePath, '/\\').'/'.$path);
608 * Turns a path into a relative path.
610 * The relative path is created relative to the given base path:
613 * echo Path::makeRelative("/webmozart/style.css", "/webmozart/puli");
617 * If a relative path is passed and the base path is absolute, the relative
618 * path is returned unchanged:
621 * Path::makeRelative("style.css", "/webmozart/puli/css");
625 * If both paths are relative, the relative path is created with the
626 * assumption that both paths are relative to the same directory:
629 * Path::makeRelative("style.css", "webmozart/puli/css");
630 * // => ../../../style.css
633 * If both paths are absolute, their root directory must be the same,
634 * otherwise an exception is thrown:
637 * Path::makeRelative("C:/webmozart/style.css", "/webmozart/puli");
638 * // InvalidArgumentException
641 * If the passed path is absolute, but the base path is not, an exception
645 * Path::makeRelative("/webmozart/style.css", "webmozart/puli");
646 * // InvalidArgumentException
649 * If the base path is not an absolute path, an exception is thrown.
651 * The result is a canonical path.
653 * @param string $path A path to make relative.
654 * @param string $basePath A base path.
656 * @return string A relative path in canonical form.
658 * @throws InvalidArgumentException If the base path is not absolute or if
659 * the given path has a different root
660 * than the base path.
662 * @since 1.0 Added method.
663 * @since 2.0 Method now fails if $path or $basePath is not a string.
665 public static function makeRelative($path, $basePath)
667 Assert::string($basePath, 'The base path must be a string. Got: %s');
669 $path = static::canonicalize($path);
670 $basePath = static::canonicalize($basePath);
672 list($root, $relativePath) = self::split($path);
673 list($baseRoot, $relativeBasePath) = self::split($basePath);
675 // If the base path is given as absolute path and the path is already
676 // relative, consider it to be relative to the given absolute path
678 if ('' === $root && '' !== $baseRoot) {
679 // If base path is already in its root
680 if ('' === $relativeBasePath) {
681 $relativePath = ltrim($relativePath, './\\');
684 return $relativePath;
687 // If the passed path is absolute, but the base path is not, we
688 // cannot generate a relative path
689 if ('' !== $root && '' === $baseRoot) {
690 throw new InvalidArgumentException(sprintf(
691 'The absolute path "%s" cannot be made relative to the '.
692 'relative path "%s". You should provide an absolute base '.
699 // Fail if the roots of the two paths are different
700 if ($baseRoot && $root !== $baseRoot) {
701 throw new InvalidArgumentException(sprintf(
702 'The path "%s" cannot be made relative to "%s", because they '.
703 'have different roots ("%s" and "%s").',
711 if ('' === $relativeBasePath) {
712 return $relativePath;
715 // Build a "../../" prefix with as many "../" parts as necessary
716 $parts = explode('/', $relativePath);
717 $baseParts = explode('/', $relativeBasePath);
720 // Once we found a non-matching part in the prefix, we need to add
721 // "../" parts for all remaining parts
724 foreach ($baseParts as $i => $basePart) {
725 if ($match && isset($parts[$i]) && $basePart === $parts[$i]) {
732 $dotDotPrefix .= '../';
735 return rtrim($dotDotPrefix.implode('/', $parts), '/');
739 * Returns whether the given path is on the local filesystem.
741 * @param string $path A path string.
743 * @return bool Returns true if the path is local, false for a URL.
745 * @since 1.0 Added method.
746 * @since 2.0 Method now fails if $path is not a string.
748 public static function isLocal($path)
750 Assert::string($path, 'The path must be a string. Got: %s');
752 return '' !== $path && false === strpos($path, '://');
756 * Returns the longest common base path of a set of paths.
758 * Dot segments ("." and "..") are removed/collapsed and all slashes turned
759 * into forward slashes.
762 * $basePath = Path::getLongestCommonBasePath(array(
763 * '/webmozart/css/style.css',
764 * '/webmozart/css/..'
769 * The root is returned if no common base path can be found:
772 * $basePath = Path::getLongestCommonBasePath(array(
773 * '/webmozart/css/style.css',
779 * If the paths are located on different Windows partitions, `null` is
783 * $basePath = Path::getLongestCommonBasePath(array(
784 * 'C:/webmozart/css/style.css',
785 * 'D:/webmozart/css/..'
790 * @param array $paths A list of paths.
792 * @return string|null The longest common base path in canonical form or
793 * `null` if the paths are on different Windows
796 * @since 1.0 Added method.
797 * @since 2.0 Method now fails if $paths are not strings.
799 public static function getLongestCommonBasePath(array $paths)
801 Assert::allString($paths, 'The paths must be strings. Got: %s');
803 list($bpRoot, $basePath) = self::split(self::canonicalize(reset($paths)));
805 for (next($paths); null !== key($paths) && '' !== $basePath; next($paths)) {
806 list($root, $path) = self::split(self::canonicalize(current($paths)));
808 // If we deal with different roots (e.g. C:/ vs. D:/), it's time
810 if ($root !== $bpRoot) {
814 // Make the base path shorter until it fits into path
816 if ('.' === $basePath) {
817 // No more base paths
824 // Prevent false positives for common prefixes
826 if (0 === strpos($path.'/', $basePath.'/')) {
831 $basePath = dirname($basePath);
835 return $bpRoot.$basePath;
839 * Joins two or more path strings.
841 * The result is a canonical path.
843 * @param string[]|string $paths Path parts as parameters or array.
845 * @return string The joint path.
847 * @since 2.0 Added method.
849 public static function join($paths)
851 if (!is_array($paths)) {
852 $paths = func_get_args();
855 Assert::allString($paths, 'The paths must be strings. Got: %s');
860 foreach ($paths as $path) {
861 $path = (string) $path;
867 if (null === $finalPath) {
868 // For first part we keep slashes, like '/top', 'C:\' or 'phar://'
870 $wasScheme = (strpos($path, '://') !== false);
874 // Only add slash if previous part didn't end with '/' or '\'
875 if (!in_array(substr($finalPath, -1), array('/', '\\'))) {
879 // If first part included a scheme like 'phar://' we allow current part to start with '/', otherwise trim
880 $finalPath .= $wasScheme ? $path : ltrim($path, '/');
884 if (null === $finalPath) {
888 return self::canonicalize($finalPath);
892 * Returns whether a path is a base path of another path.
894 * Dot segments ("." and "..") are removed/collapsed and all slashes turned
895 * into forward slashes.
898 * Path::isBasePath('/webmozart', '/webmozart/css');
901 * Path::isBasePath('/webmozart', '/webmozart');
904 * Path::isBasePath('/webmozart', '/webmozart/..');
907 * Path::isBasePath('/webmozart', '/puli');
911 * @param string $basePath The base path to test.
912 * @param string $ofPath The other path.
914 * @return bool Whether the base path is a base path of the other path.
916 * @since 1.0 Added method.
917 * @since 2.0 Method now fails if $basePath or $ofPath is not a string.
919 public static function isBasePath($basePath, $ofPath)
921 Assert::string($basePath, 'The base path must be a string. Got: %s');
923 $basePath = self::canonicalize($basePath);
924 $ofPath = self::canonicalize($ofPath);
926 // Append slashes to prevent false positives when two paths have
927 // a common prefix, for example /base/foo and /base/foobar.
928 // Don't append a slash for the root "/", because then that root
929 // won't be discovered as common prefix ("//" is not a prefix of
931 return 0 === strpos($ofPath.'/', rtrim($basePath, '/').'/');
935 * Splits a part into its root directory and the remainder.
937 * If the path has no root directory, an empty root directory will be
940 * If the root directory is a Windows style partition, the resulting root
941 * will always contain a trailing slash.
943 * list ($root, $path) = Path::split("C:/webmozart")
944 * // => array("C:/", "webmozart")
946 * list ($root, $path) = Path::split("C:")
947 * // => array("C:/", "")
949 * @param string $path The canonical path to split.
951 * @return string[] An array with the root directory and the remaining
954 private static function split($path)
957 return array('', '');
960 // Remember scheme as part of the root, if any
961 if (false !== ($pos = strpos($path, '://'))) {
962 $root = substr($path, 0, $pos + 3);
963 $path = substr($path, $pos + 3);
968 $length = strlen($path);
970 // Remove and remember root directory
971 if ('/' === $path[0]) {
973 $path = $length > 1 ? substr($path, 1) : '';
974 } elseif ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) {
976 // Windows special case: "C:"
979 } elseif ('/' === $path[2]) {
980 // Windows normal case: "C:/"..
981 $root .= substr($path, 0, 3);
982 $path = $length > 3 ? substr($path, 3) : '';
986 return array($root, $path);
990 * Converts string to lower-case (multi-byte safe if mbstring is installed).
992 * @param string $str The string
994 * @return string Lower case string
996 private static function toLower($str)
998 if (function_exists('mb_strtolower')) {
999 return mb_strtolower($str, mb_detect_encoding($str));
1002 return strtolower($str);
1005 private function __construct()