Chris@0: Chris@0: * Chris@0: * For the full copyright and license information, please view the LICENSE Chris@0: * file that was distributed with this source code. Chris@0: */ Chris@0: Chris@0: namespace Webmozart\PathUtil; Chris@0: Chris@0: use InvalidArgumentException; Chris@0: use RuntimeException; Chris@0: use Webmozart\Assert\Assert; Chris@0: Chris@0: /** Chris@0: * Contains utility methods for handling path strings. Chris@0: * Chris@0: * The methods in this class are able to deal with both UNIX and Windows paths Chris@0: * with both forward and backward slashes. All methods return normalized parts Chris@0: * containing only forward slashes and no excess "." and ".." segments. Chris@0: * Chris@0: * @since 1.0 Chris@0: * Chris@0: * @author Bernhard Schussek Chris@0: * @author Thomas Schulz Chris@0: */ Chris@0: final class Path Chris@0: { Chris@0: /** Chris@0: * The number of buffer entries that triggers a cleanup operation. Chris@0: */ Chris@0: const CLEANUP_THRESHOLD = 1250; Chris@0: Chris@0: /** Chris@0: * The buffer size after the cleanup operation. Chris@0: */ Chris@0: const CLEANUP_SIZE = 1000; Chris@0: Chris@0: /** Chris@0: * Buffers input/output of {@link canonicalize()}. Chris@0: * Chris@0: * @var array Chris@0: */ Chris@0: private static $buffer = array(); Chris@0: Chris@0: /** Chris@0: * The size of the buffer. Chris@0: * Chris@0: * @var int Chris@0: */ Chris@0: private static $bufferSize = 0; Chris@0: Chris@0: /** Chris@0: * Canonicalizes the given path. Chris@0: * Chris@0: * During normalization, all slashes are replaced by forward slashes ("/"). Chris@0: * Furthermore, all "." and ".." segments are removed as far as possible. Chris@0: * ".." segments at the beginning of relative paths are not removed. Chris@0: * Chris@0: * ```php Chris@0: * echo Path::canonicalize("\webmozart\puli\..\css\style.css"); Chris@0: * // => /webmozart/css/style.css Chris@0: * Chris@0: * echo Path::canonicalize("../css/./style.css"); Chris@0: * // => ../css/style.css Chris@0: * ``` Chris@0: * Chris@0: * This method is able to deal with both UNIX and Windows paths. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return string The canonical path. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: * @since 2.1 Added support for `~`. Chris@0: */ Chris@0: public static function canonicalize($path) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: // This method is called by many other methods in this class. Buffer Chris@0: // the canonicalized paths to make up for the severe performance Chris@0: // decrease. Chris@0: if (isset(self::$buffer[$path])) { Chris@0: return self::$buffer[$path]; Chris@0: } Chris@0: Chris@0: // Replace "~" with user's home directory. Chris@0: if ('~' === $path[0]) { Chris@0: $path = static::getHomeDirectory().substr($path, 1); Chris@0: } Chris@0: Chris@0: $path = str_replace('\\', '/', $path); Chris@0: Chris@0: list($root, $pathWithoutRoot) = self::split($path); Chris@0: Chris@0: $parts = explode('/', $pathWithoutRoot); Chris@0: $canonicalParts = array(); Chris@0: Chris@0: // Collapse "." and "..", if possible Chris@0: foreach ($parts as $part) { Chris@0: if ('.' === $part || '' === $part) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: // Collapse ".." with the previous part, if one exists Chris@0: // Don't collapse ".." if the previous part is also ".." Chris@0: if ('..' === $part && count($canonicalParts) > 0 Chris@0: && '..' !== $canonicalParts[count($canonicalParts) - 1]) { Chris@0: array_pop($canonicalParts); Chris@0: Chris@0: continue; Chris@0: } Chris@0: Chris@0: // Only add ".." prefixes for relative paths Chris@0: if ('..' !== $part || '' === $root) { Chris@0: $canonicalParts[] = $part; Chris@0: } Chris@0: } Chris@0: Chris@0: // Add the root directory again Chris@0: self::$buffer[$path] = $canonicalPath = $root.implode('/', $canonicalParts); Chris@0: ++self::$bufferSize; Chris@0: Chris@0: // Clean up regularly to prevent memory leaks Chris@0: if (self::$bufferSize > self::CLEANUP_THRESHOLD) { Chris@0: self::$buffer = array_slice(self::$buffer, -self::CLEANUP_SIZE, null, true); Chris@0: self::$bufferSize = self::CLEANUP_SIZE; Chris@0: } Chris@0: Chris@0: return $canonicalPath; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Normalizes the given path. Chris@0: * Chris@0: * During normalization, all slashes are replaced by forward slashes ("/"). Chris@0: * Contrary to {@link canonicalize()}, this method does not remove invalid Chris@0: * or dot path segments. Consequently, it is much more efficient and should Chris@0: * be used whenever the given path is known to be a valid, absolute system Chris@0: * path. Chris@0: * Chris@0: * This method is able to deal with both UNIX and Windows paths. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return string The normalized path. Chris@0: * Chris@0: * @since 2.2 Added method. Chris@0: */ Chris@0: public static function normalize($path) Chris@0: { Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: return str_replace('\\', '/', $path); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the directory part of the path. Chris@0: * Chris@0: * This method is similar to PHP's dirname(), but handles various cases Chris@0: * where dirname() returns a weird result: Chris@0: * Chris@0: * - dirname() does not accept backslashes on UNIX Chris@0: * - dirname("C:/webmozart") returns "C:", not "C:/" Chris@0: * - dirname("C:/") returns ".", not "C:/" Chris@0: * - dirname("C:") returns ".", not "C:/" Chris@0: * - dirname("webmozart") returns ".", not "" Chris@0: * - dirname() does not canonicalize the result Chris@0: * Chris@0: * This method fixes these shortcomings and behaves like dirname() Chris@0: * otherwise. Chris@0: * Chris@0: * The result is a canonical path. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return string The canonical directory part. Returns the root directory Chris@0: * if the root directory is passed. Returns an empty string Chris@0: * if a relative path is passed that contains no slashes. Chris@0: * Returns an empty string if an empty string is passed. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function getDirectory($path) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: $path = static::canonicalize($path); Chris@0: Chris@0: // Maintain scheme Chris@0: if (false !== ($pos = strpos($path, '://'))) { Chris@0: $scheme = substr($path, 0, $pos + 3); Chris@0: $path = substr($path, $pos + 3); Chris@0: } else { Chris@0: $scheme = ''; Chris@0: } Chris@0: Chris@0: if (false !== ($pos = strrpos($path, '/'))) { Chris@0: // Directory equals root directory "/" Chris@0: if (0 === $pos) { Chris@0: return $scheme.'/'; Chris@0: } Chris@0: Chris@0: // Directory equals Windows root "C:/" Chris@0: if (2 === $pos && ctype_alpha($path[0]) && ':' === $path[1]) { Chris@0: return $scheme.substr($path, 0, 3); Chris@0: } Chris@0: Chris@0: return $scheme.substr($path, 0, $pos); Chris@0: } Chris@0: Chris@0: return ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns canonical path of the user's home directory. Chris@0: * Chris@0: * Supported operating systems: Chris@0: * Chris@0: * - UNIX Chris@0: * - Windows8 and upper Chris@0: * Chris@0: * If your operation system or environment isn't supported, an exception is thrown. Chris@0: * Chris@0: * The result is a canonical path. Chris@0: * Chris@0: * @return string The canonical home directory Chris@0: * Chris@0: * @throws RuntimeException If your operation system or environment isn't supported Chris@0: * Chris@0: * @since 2.1 Added method. Chris@0: */ Chris@0: public static function getHomeDirectory() Chris@0: { Chris@0: // For UNIX support Chris@0: if (getenv('HOME')) { Chris@0: return static::canonicalize(getenv('HOME')); Chris@0: } Chris@0: Chris@0: // For >= Windows8 support Chris@0: if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) { Chris@0: return static::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH')); Chris@0: } Chris@0: Chris@0: throw new RuntimeException("Your environment or operation system isn't supported"); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the root directory of a path. Chris@0: * Chris@0: * The result is a canonical path. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return string The canonical root directory. Returns an empty string if Chris@0: * the given path is relative or empty. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function getRoot($path) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: // Maintain scheme Chris@0: if (false !== ($pos = strpos($path, '://'))) { Chris@0: $scheme = substr($path, 0, $pos + 3); Chris@0: $path = substr($path, $pos + 3); Chris@0: } else { Chris@0: $scheme = ''; Chris@0: } Chris@0: Chris@0: // UNIX root "/" or "\" (Windows style) Chris@0: if ('/' === $path[0] || '\\' === $path[0]) { Chris@0: return $scheme.'/'; Chris@0: } Chris@0: Chris@0: $length = strlen($path); Chris@0: Chris@0: // Windows root Chris@0: if ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) { Chris@0: // Special case: "C:" Chris@0: if (2 === $length) { Chris@0: return $scheme.$path.'/'; Chris@0: } Chris@0: Chris@0: // Normal case: "C:/ or "C:\" Chris@0: if ('/' === $path[2] || '\\' === $path[2]) { Chris@0: return $scheme.$path[0].$path[1].'/'; Chris@0: } Chris@0: } Chris@0: Chris@0: return ''; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the file name from a file path. Chris@0: * Chris@0: * @param string $path The path string. Chris@0: * Chris@0: * @return string The file name. Chris@0: * Chris@0: * @since 1.1 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function getFilename($path) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: return basename($path); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the file name without the extension from a file path. Chris@0: * Chris@0: * @param string $path The path string. Chris@0: * @param string|null $extension If specified, only that extension is cut Chris@0: * off (may contain leading dot). Chris@0: * Chris@0: * @return string The file name without extension. Chris@0: * Chris@0: * @since 1.1 Added method. Chris@0: * @since 2.0 Method now fails if $path or $extension have invalid types. Chris@0: */ Chris@0: public static function getFilenameWithoutExtension($path, $extension = null) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Assert::nullOrString($extension, 'The extension must be a string or null. Got: %s'); Chris@0: Chris@0: if (null !== $extension) { Chris@0: // remove extension and trailing dot Chris@0: return rtrim(basename($path, $extension), '.'); Chris@0: } Chris@0: Chris@0: return pathinfo($path, PATHINFO_FILENAME); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the extension from a file path. Chris@0: * Chris@0: * @param string $path The path string. Chris@0: * @param bool $forceLowerCase Forces the extension to be lower-case Chris@0: * (requires mbstring extension for correct Chris@0: * multi-byte character handling in extension). Chris@0: * Chris@0: * @return string The extension of the file path (without leading dot). Chris@0: * Chris@0: * @since 1.1 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function getExtension($path, $forceLowerCase = false) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: $extension = pathinfo($path, PATHINFO_EXTENSION); Chris@0: Chris@0: if ($forceLowerCase) { Chris@0: $extension = self::toLower($extension); Chris@0: } Chris@0: Chris@0: return $extension; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns whether the path has an extension. Chris@0: * Chris@0: * @param string $path The path string. Chris@0: * @param string|array|null $extensions If null or not provided, checks if Chris@0: * an extension exists, otherwise Chris@0: * checks for the specified extension Chris@0: * or array of extensions (with or Chris@0: * without leading dot). Chris@0: * @param bool $ignoreCase Whether to ignore case-sensitivity Chris@0: * (requires mbstring extension for Chris@0: * correct multi-byte character Chris@0: * handling in the extension). Chris@0: * Chris@0: * @return bool Returns `true` if the path has an (or the specified) Chris@0: * extension and `false` otherwise. Chris@0: * Chris@0: * @since 1.1 Added method. Chris@0: * @since 2.0 Method now fails if $path or $extensions have invalid types. Chris@0: */ Chris@0: public static function hasExtension($path, $extensions = null, $ignoreCase = false) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: $extensions = is_object($extensions) ? array($extensions) : (array) $extensions; Chris@0: Chris@0: Assert::allString($extensions, 'The extensions must be strings. Got: %s'); Chris@0: Chris@0: $actualExtension = self::getExtension($path, $ignoreCase); Chris@0: Chris@0: // Only check if path has any extension Chris@0: if (empty($extensions)) { Chris@0: return '' !== $actualExtension; Chris@0: } Chris@0: Chris@0: foreach ($extensions as $key => $extension) { Chris@0: if ($ignoreCase) { Chris@0: $extension = self::toLower($extension); Chris@0: } Chris@0: Chris@0: // remove leading '.' in extensions array Chris@0: $extensions[$key] = ltrim($extension, '.'); Chris@0: } Chris@0: Chris@0: return in_array($actualExtension, $extensions); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Changes the extension of a path string. Chris@0: * Chris@0: * @param string $path The path string with filename.ext to change. Chris@0: * @param string $extension New extension (with or without leading dot). Chris@0: * Chris@0: * @return string The path string with new file extension. Chris@0: * Chris@0: * @since 1.1 Added method. Chris@0: * @since 2.0 Method now fails if $path or $extension is not a string. Chris@0: */ Chris@0: public static function changeExtension($path, $extension) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: Assert::string($extension, 'The extension must be a string. Got: %s'); Chris@0: Chris@0: $actualExtension = self::getExtension($path); Chris@0: $extension = ltrim($extension, '.'); Chris@0: Chris@0: // No extension for paths Chris@0: if ('/' === substr($path, -1)) { Chris@0: return $path; Chris@0: } Chris@0: Chris@0: // No actual extension in path Chris@0: if (empty($actualExtension)) { Chris@0: return $path.('.' === substr($path, -1) ? '' : '.').$extension; Chris@0: } Chris@0: Chris@0: return substr($path, 0, -strlen($actualExtension)).$extension; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns whether a path is absolute. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return bool Returns true if the path is absolute, false if it is Chris@0: * relative or empty. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function isAbsolute($path) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return false; Chris@0: } Chris@0: Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: // Strip scheme Chris@0: if (false !== ($pos = strpos($path, '://'))) { Chris@0: $path = substr($path, $pos + 3); Chris@0: } Chris@0: Chris@0: // UNIX root "/" or "\" (Windows style) Chris@0: if ('/' === $path[0] || '\\' === $path[0]) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: // Windows root Chris@0: if (strlen($path) > 1 && ctype_alpha($path[0]) && ':' === $path[1]) { Chris@0: // Special case: "C:" Chris@0: if (2 === strlen($path)) { Chris@0: return true; Chris@0: } Chris@0: Chris@0: // Normal case: "C:/ or "C:\" Chris@0: if ('/' === $path[2] || '\\' === $path[2]) { Chris@0: return true; Chris@0: } Chris@0: } Chris@0: Chris@0: return false; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns whether a path is relative. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return bool Returns true if the path is relative or empty, false if Chris@0: * it is absolute. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function isRelative($path) Chris@0: { Chris@0: return !static::isAbsolute($path); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Turns a relative path into an absolute path. Chris@0: * Chris@0: * Usually, the relative path is appended to the given base path. Dot Chris@0: * segments ("." and "..") are removed/collapsed and all slashes turned Chris@0: * into forward slashes. Chris@0: * Chris@0: * ```php Chris@0: * echo Path::makeAbsolute("../style.css", "/webmozart/puli/css"); Chris@0: * // => /webmozart/puli/style.css Chris@0: * ``` Chris@0: * Chris@0: * If an absolute path is passed, that path is returned unless its root Chris@0: * directory is different than the one of the base path. In that case, an Chris@0: * exception is thrown. Chris@0: * Chris@0: * ```php Chris@0: * Path::makeAbsolute("/style.css", "/webmozart/puli/css"); Chris@0: * // => /style.css Chris@0: * Chris@0: * Path::makeAbsolute("C:/style.css", "C:/webmozart/puli/css"); Chris@0: * // => C:/style.css Chris@0: * Chris@0: * Path::makeAbsolute("C:/style.css", "/webmozart/puli/css"); Chris@0: * // InvalidArgumentException Chris@0: * ``` Chris@0: * Chris@0: * If the base path is not an absolute path, an exception is thrown. Chris@0: * Chris@0: * The result is a canonical path. Chris@0: * Chris@0: * @param string $path A path to make absolute. Chris@0: * @param string $basePath An absolute base path. Chris@0: * Chris@0: * @return string An absolute path in canonical form. Chris@0: * Chris@0: * @throws InvalidArgumentException If the base path is not absolute or if Chris@0: * the given path is an absolute path with Chris@0: * a different root than the base path. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path or $basePath is not a string. Chris@0: * @since 2.2.2 Method does not fail anymore of $path and $basePath are Chris@0: * absolute, but on different partitions. Chris@0: */ Chris@0: public static function makeAbsolute($path, $basePath) Chris@0: { Chris@0: Assert::stringNotEmpty($basePath, 'The base path must be a non-empty string. Got: %s'); Chris@0: Chris@0: if (!static::isAbsolute($basePath)) { Chris@0: throw new InvalidArgumentException(sprintf( Chris@0: 'The base path "%s" is not an absolute path.', Chris@0: $basePath Chris@0: )); Chris@0: } Chris@0: Chris@0: if (static::isAbsolute($path)) { Chris@0: return static::canonicalize($path); Chris@0: } Chris@0: Chris@0: if (false !== ($pos = strpos($basePath, '://'))) { Chris@0: $scheme = substr($basePath, 0, $pos + 3); Chris@0: $basePath = substr($basePath, $pos + 3); Chris@0: } else { Chris@0: $scheme = ''; Chris@0: } Chris@0: Chris@0: return $scheme.self::canonicalize(rtrim($basePath, '/\\').'/'.$path); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Turns a path into a relative path. Chris@0: * Chris@0: * The relative path is created relative to the given base path: Chris@0: * Chris@0: * ```php Chris@0: * echo Path::makeRelative("/webmozart/style.css", "/webmozart/puli"); Chris@0: * // => ../style.css Chris@0: * ``` Chris@0: * Chris@0: * If a relative path is passed and the base path is absolute, the relative Chris@0: * path is returned unchanged: Chris@0: * Chris@0: * ```php Chris@0: * Path::makeRelative("style.css", "/webmozart/puli/css"); Chris@0: * // => style.css Chris@0: * ``` Chris@0: * Chris@0: * If both paths are relative, the relative path is created with the Chris@0: * assumption that both paths are relative to the same directory: Chris@0: * Chris@0: * ```php Chris@0: * Path::makeRelative("style.css", "webmozart/puli/css"); Chris@0: * // => ../../../style.css Chris@0: * ``` Chris@0: * Chris@0: * If both paths are absolute, their root directory must be the same, Chris@0: * otherwise an exception is thrown: Chris@0: * Chris@0: * ```php Chris@0: * Path::makeRelative("C:/webmozart/style.css", "/webmozart/puli"); Chris@0: * // InvalidArgumentException Chris@0: * ``` Chris@0: * Chris@0: * If the passed path is absolute, but the base path is not, an exception Chris@0: * is thrown as well: Chris@0: * Chris@0: * ```php Chris@0: * Path::makeRelative("/webmozart/style.css", "webmozart/puli"); Chris@0: * // InvalidArgumentException Chris@0: * ``` Chris@0: * Chris@0: * If the base path is not an absolute path, an exception is thrown. Chris@0: * Chris@0: * The result is a canonical path. Chris@0: * Chris@0: * @param string $path A path to make relative. Chris@0: * @param string $basePath A base path. Chris@0: * Chris@0: * @return string A relative path in canonical form. Chris@0: * Chris@0: * @throws InvalidArgumentException If the base path is not absolute or if Chris@0: * the given path has a different root Chris@0: * than the base path. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path or $basePath is not a string. Chris@0: */ Chris@0: public static function makeRelative($path, $basePath) Chris@0: { Chris@0: Assert::string($basePath, 'The base path must be a string. Got: %s'); Chris@0: Chris@0: $path = static::canonicalize($path); Chris@0: $basePath = static::canonicalize($basePath); Chris@0: Chris@0: list($root, $relativePath) = self::split($path); Chris@0: list($baseRoot, $relativeBasePath) = self::split($basePath); Chris@0: Chris@0: // If the base path is given as absolute path and the path is already Chris@0: // relative, consider it to be relative to the given absolute path Chris@0: // already Chris@0: if ('' === $root && '' !== $baseRoot) { Chris@0: // If base path is already in its root Chris@0: if ('' === $relativeBasePath) { Chris@0: $relativePath = ltrim($relativePath, './\\'); Chris@0: } Chris@0: Chris@0: return $relativePath; Chris@0: } Chris@0: Chris@0: // If the passed path is absolute, but the base path is not, we Chris@0: // cannot generate a relative path Chris@0: if ('' !== $root && '' === $baseRoot) { Chris@0: throw new InvalidArgumentException(sprintf( Chris@0: 'The absolute path "%s" cannot be made relative to the '. Chris@0: 'relative path "%s". You should provide an absolute base '. Chris@0: 'path instead.', Chris@0: $path, Chris@0: $basePath Chris@0: )); Chris@0: } Chris@0: Chris@0: // Fail if the roots of the two paths are different Chris@0: if ($baseRoot && $root !== $baseRoot) { Chris@0: throw new InvalidArgumentException(sprintf( Chris@0: 'The path "%s" cannot be made relative to "%s", because they '. Chris@0: 'have different roots ("%s" and "%s").', Chris@0: $path, Chris@0: $basePath, Chris@0: $root, Chris@0: $baseRoot Chris@0: )); Chris@0: } Chris@0: Chris@0: if ('' === $relativeBasePath) { Chris@0: return $relativePath; Chris@0: } Chris@0: Chris@0: // Build a "../../" prefix with as many "../" parts as necessary Chris@0: $parts = explode('/', $relativePath); Chris@0: $baseParts = explode('/', $relativeBasePath); Chris@0: $dotDotPrefix = ''; Chris@0: Chris@0: // Once we found a non-matching part in the prefix, we need to add Chris@0: // "../" parts for all remaining parts Chris@0: $match = true; Chris@0: Chris@0: foreach ($baseParts as $i => $basePart) { Chris@0: if ($match && isset($parts[$i]) && $basePart === $parts[$i]) { Chris@0: unset($parts[$i]); Chris@0: Chris@0: continue; Chris@0: } Chris@0: Chris@0: $match = false; Chris@0: $dotDotPrefix .= '../'; Chris@0: } Chris@0: Chris@0: return rtrim($dotDotPrefix.implode('/', $parts), '/'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns whether the given path is on the local filesystem. Chris@0: * Chris@0: * @param string $path A path string. Chris@0: * Chris@0: * @return bool Returns true if the path is local, false for a URL. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $path is not a string. Chris@0: */ Chris@0: public static function isLocal($path) Chris@0: { Chris@0: Assert::string($path, 'The path must be a string. Got: %s'); Chris@0: Chris@0: return '' !== $path && false === strpos($path, '://'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns the longest common base path of a set of paths. Chris@0: * Chris@0: * Dot segments ("." and "..") are removed/collapsed and all slashes turned Chris@0: * into forward slashes. Chris@0: * Chris@0: * ```php Chris@0: * $basePath = Path::getLongestCommonBasePath(array( Chris@0: * '/webmozart/css/style.css', Chris@0: * '/webmozart/css/..' Chris@0: * )); Chris@0: * // => /webmozart Chris@0: * ``` Chris@0: * Chris@0: * The root is returned if no common base path can be found: Chris@0: * Chris@0: * ```php Chris@0: * $basePath = Path::getLongestCommonBasePath(array( Chris@0: * '/webmozart/css/style.css', Chris@0: * '/puli/css/..' Chris@0: * )); Chris@0: * // => / Chris@0: * ``` Chris@0: * Chris@0: * If the paths are located on different Windows partitions, `null` is Chris@0: * returned. Chris@0: * Chris@0: * ```php Chris@0: * $basePath = Path::getLongestCommonBasePath(array( Chris@0: * 'C:/webmozart/css/style.css', Chris@0: * 'D:/webmozart/css/..' Chris@0: * )); Chris@0: * // => null Chris@0: * ``` Chris@0: * Chris@0: * @param array $paths A list of paths. Chris@0: * Chris@0: * @return string|null The longest common base path in canonical form or Chris@0: * `null` if the paths are on different Windows Chris@0: * partitions. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $paths are not strings. Chris@0: */ Chris@0: public static function getLongestCommonBasePath(array $paths) Chris@0: { Chris@0: Assert::allString($paths, 'The paths must be strings. Got: %s'); Chris@0: Chris@0: list($bpRoot, $basePath) = self::split(self::canonicalize(reset($paths))); Chris@0: Chris@0: for (next($paths); null !== key($paths) && '' !== $basePath; next($paths)) { Chris@0: list($root, $path) = self::split(self::canonicalize(current($paths))); Chris@0: Chris@0: // If we deal with different roots (e.g. C:/ vs. D:/), it's time Chris@0: // to quit Chris@0: if ($root !== $bpRoot) { Chris@0: return null; Chris@0: } Chris@0: Chris@0: // Make the base path shorter until it fits into path Chris@0: while (true) { Chris@0: if ('.' === $basePath) { Chris@0: // No more base paths Chris@0: $basePath = ''; Chris@0: Chris@0: // Next path Chris@0: continue 2; Chris@0: } Chris@0: Chris@0: // Prevent false positives for common prefixes Chris@0: // see isBasePath() Chris@0: if (0 === strpos($path.'/', $basePath.'/')) { Chris@0: // Next path Chris@0: continue 2; Chris@0: } Chris@0: Chris@0: $basePath = dirname($basePath); Chris@0: } Chris@0: } Chris@0: Chris@0: return $bpRoot.$basePath; Chris@0: } Chris@0: Chris@0: /** Chris@0: * Joins two or more path strings. Chris@0: * Chris@0: * The result is a canonical path. Chris@0: * Chris@0: * @param string[]|string $paths Path parts as parameters or array. Chris@0: * Chris@0: * @return string The joint path. Chris@0: * Chris@0: * @since 2.0 Added method. Chris@0: */ Chris@0: public static function join($paths) Chris@0: { Chris@0: if (!is_array($paths)) { Chris@0: $paths = func_get_args(); Chris@0: } Chris@0: Chris@0: Assert::allString($paths, 'The paths must be strings. Got: %s'); Chris@0: Chris@0: $finalPath = null; Chris@0: $wasScheme = false; Chris@0: Chris@0: foreach ($paths as $path) { Chris@0: $path = (string) $path; Chris@0: Chris@0: if ('' === $path) { Chris@0: continue; Chris@0: } Chris@0: Chris@0: if (null === $finalPath) { Chris@0: // For first part we keep slashes, like '/top', 'C:\' or 'phar://' Chris@0: $finalPath = $path; Chris@0: $wasScheme = (strpos($path, '://') !== false); Chris@0: continue; Chris@0: } Chris@0: Chris@0: // Only add slash if previous part didn't end with '/' or '\' Chris@0: if (!in_array(substr($finalPath, -1), array('/', '\\'))) { Chris@0: $finalPath .= '/'; Chris@0: } Chris@0: Chris@0: // If first part included a scheme like 'phar://' we allow current part to start with '/', otherwise trim Chris@0: $finalPath .= $wasScheme ? $path : ltrim($path, '/'); Chris@0: $wasScheme = false; Chris@0: } Chris@0: Chris@0: if (null === $finalPath) { Chris@0: return ''; Chris@0: } Chris@0: Chris@0: return self::canonicalize($finalPath); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Returns whether a path is a base path of another path. Chris@0: * Chris@0: * Dot segments ("." and "..") are removed/collapsed and all slashes turned Chris@0: * into forward slashes. Chris@0: * Chris@0: * ```php Chris@0: * Path::isBasePath('/webmozart', '/webmozart/css'); Chris@0: * // => true Chris@0: * Chris@0: * Path::isBasePath('/webmozart', '/webmozart'); Chris@0: * // => true Chris@0: * Chris@0: * Path::isBasePath('/webmozart', '/webmozart/..'); Chris@0: * // => false Chris@0: * Chris@0: * Path::isBasePath('/webmozart', '/puli'); Chris@0: * // => false Chris@0: * ``` Chris@0: * Chris@0: * @param string $basePath The base path to test. Chris@0: * @param string $ofPath The other path. Chris@0: * Chris@0: * @return bool Whether the base path is a base path of the other path. Chris@0: * Chris@0: * @since 1.0 Added method. Chris@0: * @since 2.0 Method now fails if $basePath or $ofPath is not a string. Chris@0: */ Chris@0: public static function isBasePath($basePath, $ofPath) Chris@0: { Chris@0: Assert::string($basePath, 'The base path must be a string. Got: %s'); Chris@0: Chris@0: $basePath = self::canonicalize($basePath); Chris@0: $ofPath = self::canonicalize($ofPath); Chris@0: Chris@0: // Append slashes to prevent false positives when two paths have Chris@0: // a common prefix, for example /base/foo and /base/foobar. Chris@0: // Don't append a slash for the root "/", because then that root Chris@0: // won't be discovered as common prefix ("//" is not a prefix of Chris@0: // "/foobar/"). Chris@0: return 0 === strpos($ofPath.'/', rtrim($basePath, '/').'/'); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Splits a part into its root directory and the remainder. Chris@0: * Chris@0: * If the path has no root directory, an empty root directory will be Chris@0: * returned. Chris@0: * Chris@0: * If the root directory is a Windows style partition, the resulting root Chris@0: * will always contain a trailing slash. Chris@0: * Chris@0: * list ($root, $path) = Path::split("C:/webmozart") Chris@0: * // => array("C:/", "webmozart") Chris@0: * Chris@0: * list ($root, $path) = Path::split("C:") Chris@0: * // => array("C:/", "") Chris@0: * Chris@0: * @param string $path The canonical path to split. Chris@0: * Chris@0: * @return string[] An array with the root directory and the remaining Chris@0: * relative path. Chris@0: */ Chris@0: private static function split($path) Chris@0: { Chris@0: if ('' === $path) { Chris@0: return array('', ''); Chris@0: } Chris@0: Chris@0: // Remember scheme as part of the root, if any Chris@0: if (false !== ($pos = strpos($path, '://'))) { Chris@0: $root = substr($path, 0, $pos + 3); Chris@0: $path = substr($path, $pos + 3); Chris@0: } else { Chris@0: $root = ''; Chris@0: } Chris@0: Chris@0: $length = strlen($path); Chris@0: Chris@0: // Remove and remember root directory Chris@0: if ('/' === $path[0]) { Chris@0: $root .= '/'; Chris@0: $path = $length > 1 ? substr($path, 1) : ''; Chris@0: } elseif ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) { Chris@0: if (2 === $length) { Chris@0: // Windows special case: "C:" Chris@0: $root .= $path.'/'; Chris@0: $path = ''; Chris@0: } elseif ('/' === $path[2]) { Chris@0: // Windows normal case: "C:/".. Chris@0: $root .= substr($path, 0, 3); Chris@0: $path = $length > 3 ? substr($path, 3) : ''; Chris@0: } Chris@0: } Chris@0: Chris@0: return array($root, $path); Chris@0: } Chris@0: Chris@0: /** Chris@0: * Converts string to lower-case (multi-byte safe if mbstring is installed). Chris@0: * Chris@0: * @param string $str The string Chris@0: * Chris@0: * @return string Lower case string Chris@0: */ Chris@0: private static function toLower($str) Chris@0: { Chris@0: if (function_exists('mb_strtolower')) { Chris@0: return mb_strtolower($str, mb_detect_encoding($str)); Chris@0: } Chris@0: Chris@0: return strtolower($str); Chris@0: } Chris@0: Chris@0: private function __construct() Chris@0: { Chris@0: } Chris@0: }