From a6a25bb31b541acc0e7e92906ff5d9457ef60db5 Mon Sep 17 00:00:00 2001 From: dantleech Date: Sat, 15 Oct 2022 11:07:22 +0200 Subject: [PATCH] Webmozart/path vendoring (#1009) * Vendored webmozart/path * Add note * Fix CS --- CHANGELOG.md | 1 + composer.json | 3 +- .../lib/Command/Handler/OutputDirHandler.php | 2 +- .../xdebug/lib/Executor/ProfileExecutor.php | 2 +- lib/Benchmark/BenchmarkFinder.php | 2 +- lib/Config/Processor/IncludeGlobProcessor.php | 2 +- lib/Config/Processor/IncludeProcessor.php | 2 +- lib/Extension/RunnerExtension.php | 2 +- lib/Extension/StorageExtension.php | 2 +- lib/Path/Path.php | 824 ++++++++++++++++++ lib/PhpBench.php | 2 +- lib/Report/Renderer/HtmlRenderer.php | 2 +- lib/Util/PathNormalizer.php | 4 +- tests/Util/Workspace.php | 2 +- 14 files changed, 838 insertions(+), 14 deletions(-) create mode 100644 lib/Path/Path.php diff --git a/CHANGELOG.md b/CHANGELOG.md index 56eb6acd0..a46f73c6e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ master Improvements: +- Remove dependency on `webmozaty/path` (copied the class into PHPBench) - Update PHPStan to 1.0 and fix new errors #1006 - Use `webmozart/glob` instead of `glob` for benchmark paths and config include paths #1005 diff --git a/composer.json b/composer.json index 83f300b42..ca2700d4c 100644 --- a/composer.json +++ b/composer.json @@ -28,8 +28,7 @@ "symfony/finder": "^4.2 || ^5.0 || ^6.0", "symfony/options-resolver": "^4.2 || ^5.0 || ^6.0", "symfony/process": "^4.2 || ^5.0 || ^6.0", - "webmozart/glob": "^4.6", - "webmozart/path-util": "^2.3" + "webmozart/glob": "^4.6" }, "require-dev": { "dantleech/invoke": "^2.0", diff --git a/extensions/xdebug/lib/Command/Handler/OutputDirHandler.php b/extensions/xdebug/lib/Command/Handler/OutputDirHandler.php index 3fbfe63ac..22f81aca9 100644 --- a/extensions/xdebug/lib/Command/Handler/OutputDirHandler.php +++ b/extensions/xdebug/lib/Command/Handler/OutputDirHandler.php @@ -12,12 +12,12 @@ namespace PhpBench\Extensions\XDebug\Command\Handler; +use PhpBench\Path\Path; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Filesystem\Filesystem; -use Webmozart\PathUtil\Path; class OutputDirHandler { diff --git a/extensions/xdebug/lib/Executor/ProfileExecutor.php b/extensions/xdebug/lib/Executor/ProfileExecutor.php index cad3f8a82..16e666865 100644 --- a/extensions/xdebug/lib/Executor/ProfileExecutor.php +++ b/extensions/xdebug/lib/Executor/ProfileExecutor.php @@ -17,10 +17,10 @@ use PhpBench\Executor\ExecutionContext; use PhpBench\Executor\ExecutionResults; use PhpBench\Extensions\XDebug\XDebugUtil; +use PhpBench\Path\Path; use PhpBench\Registry\Config; use RuntimeException; use Symfony\Component\OptionsResolver\OptionsResolver; -use Webmozart\PathUtil\Path; class ProfileExecutor implements BenchmarkExecutorInterface { diff --git a/lib/Benchmark/BenchmarkFinder.php b/lib/Benchmark/BenchmarkFinder.php index 4adcd14b6..b01b0cb77 100644 --- a/lib/Benchmark/BenchmarkFinder.php +++ b/lib/Benchmark/BenchmarkFinder.php @@ -15,10 +15,10 @@ use Generator; use PhpBench\Benchmark\Metadata\BenchmarkMetadata; use PhpBench\Benchmark\Metadata\MetadataFactory; +use PhpBench\Path\Path; use Psr\Log\LoggerInterface; use SplFileInfo; use Symfony\Component\Finder\Finder; -use Webmozart\PathUtil\Path; /** * This class finds a benchmark (or benchmarks depending on the path), loads diff --git a/lib/Config/Processor/IncludeGlobProcessor.php b/lib/Config/Processor/IncludeGlobProcessor.php index e7a8fb6fa..be18611d6 100644 --- a/lib/Config/Processor/IncludeGlobProcessor.php +++ b/lib/Config/Processor/IncludeGlobProcessor.php @@ -4,8 +4,8 @@ use PhpBench\Config\ConfigLoader; use PhpBench\Config\ConfigProcessor; +use PhpBench\Path\Path; use Webmozart\Glob\Glob; -use Webmozart\PathUtil\Path; class IncludeGlobProcessor implements ConfigProcessor { diff --git a/lib/Config/Processor/IncludeProcessor.php b/lib/Config/Processor/IncludeProcessor.php index 1d7fb05eb..0680925ba 100644 --- a/lib/Config/Processor/IncludeProcessor.php +++ b/lib/Config/Processor/IncludeProcessor.php @@ -4,7 +4,7 @@ use PhpBench\Config\ConfigLoader; use PhpBench\Config\ConfigProcessor; -use Webmozart\PathUtil\Path; +use PhpBench\Path\Path; class IncludeProcessor implements ConfigProcessor { diff --git a/lib/Extension/RunnerExtension.php b/lib/Extension/RunnerExtension.php index 16a0f4346..05e30b1e4 100644 --- a/lib/Extension/RunnerExtension.php +++ b/lib/Extension/RunnerExtension.php @@ -37,6 +37,7 @@ use PhpBench\Expression\Printer; use PhpBench\Expression\Printer\EvaluatingPrinter; use PhpBench\Json\JsonDecoder; +use PhpBench\Path\Path; use PhpBench\Progress\Logger\BlinkenLogger; use PhpBench\Progress\Logger\DotsLogger; use PhpBench\Progress\Logger\HistogramLogger; @@ -58,7 +59,6 @@ use Symfony\Component\Finder\Finder; use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\Process\ExecutableFinder; -use Webmozart\PathUtil\Path; class RunnerExtension implements ExtensionInterface { diff --git a/lib/Extension/StorageExtension.php b/lib/Extension/StorageExtension.php index 84977c7f4..4e74b4797 100644 --- a/lib/Extension/StorageExtension.php +++ b/lib/Extension/StorageExtension.php @@ -19,6 +19,7 @@ use PhpBench\Console\Command\LogCommand; use PhpBench\DependencyInjection\Container; use PhpBench\DependencyInjection\ExtensionInterface; +use PhpBench\Path\Path; use PhpBench\Serializer\XmlDecoder; use PhpBench\Serializer\XmlEncoder; use PhpBench\Storage\Driver\Xml\XmlDriver; @@ -29,7 +30,6 @@ use PhpBench\Storage\UuidResolver\TagResolver; use PhpBench\Util\TimeUnit; use Symfony\Component\OptionsResolver\OptionsResolver; -use Webmozart\PathUtil\Path; class StorageExtension implements ExtensionInterface { diff --git a/lib/Path/Path.php b/lib/Path/Path.php new file mode 100644 index 000000000..e9c51ae89 --- /dev/null +++ b/lib/Path/Path.php @@ -0,0 +1,824 @@ + + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ + +namespace PhpBench\Path; + +use Symfony\Component\Filesystem\Exception\InvalidArgumentException; +use Symfony\Component\Filesystem\Exception\RuntimeException; + +/** + * NOTE: This class is copied as the class was "moved" from a dedicated package + * to be part of the symfony/filesystem package which is not available in the + * current version constraints. + * + * Contains utility methods for handling path strings. + * + * The methods in this class are able to deal with both UNIX and Windows paths + * with both forward and backward slashes. All methods return normalized parts + * containing only forward slashes and no excess "." and ".." segments. + * + * @author Bernhard Schussek + * @author Thomas Schulz + * @author Théo Fidry + */ +final class Path +{ + /** + * The number of buffer entries that triggers a cleanup operation. + */ + private const CLEANUP_THRESHOLD = 1250; + + /** + * The buffer size after the cleanup operation. + */ + private const CLEANUP_SIZE = 1000; + + /** + * Buffers input/output of {@link canonicalize()}. + * + * @var array + */ + private static $buffer = []; + + /** + * @var int + */ + private static $bufferSize = 0; + + /** + * Canonicalizes the given path. + * + * During normalization, all slashes are replaced by forward slashes ("/"). + * Furthermore, all "." and ".." segments are removed as far as possible. + * ".." segments at the beginning of relative paths are not removed. + * + * ```php + * echo Path::canonicalize("\symfony\puli\..\css\style.css"); + * // => /symfony/css/style.css + * + * echo Path::canonicalize("../css/./style.css"); + * // => ../css/style.css + * ``` + * + * This method is able to deal with both UNIX and Windows paths. + */ + public static function canonicalize(string $path): string + { + if ('' === $path) { + return ''; + } + + // This method is called by many other methods in this class. Buffer + // the canonicalized paths to make up for the severe performance + // decrease. + if (isset(self::$buffer[$path])) { + return self::$buffer[$path]; + } + + // Replace "~" with user's home directory. + if ('~' === $path[0]) { + $path = self::getHomeDirectory().mb_substr($path, 1); + } + + $path = self::normalize($path); + + [$root, $pathWithoutRoot] = self::split($path); + + $canonicalParts = self::findCanonicalParts($root, $pathWithoutRoot); + + // Add the root directory again + self::$buffer[$path] = $canonicalPath = $root.implode('/', $canonicalParts); + ++self::$bufferSize; + + // Clean up regularly to prevent memory leaks + if (self::$bufferSize > self::CLEANUP_THRESHOLD) { + self::$buffer = \array_slice(self::$buffer, -self::CLEANUP_SIZE, null, true); + self::$bufferSize = self::CLEANUP_SIZE; + } + + return $canonicalPath; + } + + /** + * Normalizes the given path. + * + * During normalization, all slashes are replaced by forward slashes ("/"). + * Contrary to {@link canonicalize()}, this method does not remove invalid + * or dot path segments. Consequently, it is much more efficient and should + * be used whenever the given path is known to be a valid, absolute system + * path. + * + * This method is able to deal with both UNIX and Windows paths. + */ + public static function normalize(string $path): string + { + return str_replace('\\', '/', $path); + } + + /** + * Returns the directory part of the path. + * + * This method is similar to PHP's dirname(), but handles various cases + * where dirname() returns a weird result: + * + * - dirname() does not accept backslashes on UNIX + * - dirname("C:/symfony") returns "C:", not "C:/" + * - dirname("C:/") returns ".", not "C:/" + * - dirname("C:") returns ".", not "C:/" + * - dirname("symfony") returns ".", not "" + * - dirname() does not canonicalize the result + * + * This method fixes these shortcomings and behaves like dirname() + * otherwise. + * + * The result is a canonical path. + * + * @return string The canonical directory part. Returns the root directory + * if the root directory is passed. Returns an empty string + * if a relative path is passed that contains no slashes. + * Returns an empty string if an empty string is passed. + */ + public static function getDirectory(string $path): string + { + if ('' === $path) { + return ''; + } + + $path = self::canonicalize($path); + + // Maintain scheme + if (false !== ($schemeSeparatorPosition = mb_strpos($path, '://'))) { + $scheme = mb_substr($path, 0, $schemeSeparatorPosition + 3); + $path = mb_substr($path, $schemeSeparatorPosition + 3); + } else { + $scheme = ''; + } + + if (false === ($dirSeparatorPosition = strrpos($path, '/'))) { + return ''; + } + + // Directory equals root directory "/" + if (0 === $dirSeparatorPosition) { + return $scheme.'/'; + } + + // Directory equals Windows root "C:/" + if (2 === $dirSeparatorPosition && ctype_alpha($path[0]) && ':' === $path[1]) { + return $scheme.mb_substr($path, 0, 3); + } + + return $scheme.mb_substr($path, 0, $dirSeparatorPosition); + } + + /** + * Returns canonical path of the user's home directory. + * + * Supported operating systems: + * + * - UNIX + * - Windows8 and upper + * + * If your operating system or environment isn't supported, an exception is thrown. + * + * The result is a canonical path. + * + * @throws RuntimeException If your operating system or environment isn't supported + */ + public static function getHomeDirectory(): string + { + // For UNIX support + if (getenv('HOME')) { + return self::canonicalize(getenv('HOME')); + } + + // For >= Windows8 support + if (getenv('HOMEDRIVE') && getenv('HOMEPATH')) { + return self::canonicalize(getenv('HOMEDRIVE').getenv('HOMEPATH')); + } + + throw new RuntimeException("Cannot find the home directory path: Your environment or operating system isn't supported."); + } + + /** + * Returns the root directory of a path. + * + * The result is a canonical path. + * + * @return string The canonical root directory. Returns an empty string if + * the given path is relative or empty. + */ + public static function getRoot(string $path): string + { + if ('' === $path) { + return ''; + } + + // Maintain scheme + if (false !== ($schemeSeparatorPosition = strpos($path, '://'))) { + $scheme = substr($path, 0, $schemeSeparatorPosition + 3); + $path = substr($path, $schemeSeparatorPosition + 3); + } else { + $scheme = ''; + } + + $firstCharacter = $path[0]; + + // UNIX root "/" or "\" (Windows style) + if ('/' === $firstCharacter || '\\' === $firstCharacter) { + return $scheme.'/'; + } + + $length = mb_strlen($path); + + // Windows root + if ($length > 1 && ':' === $path[1] && ctype_alpha($firstCharacter)) { + // Special case: "C:" + if (2 === $length) { + return $scheme.$path.'/'; + } + + // Normal case: "C:/ or "C:\" + if ('/' === $path[2] || '\\' === $path[2]) { + return $scheme.$firstCharacter.$path[1].'/'; + } + } + + return ''; + } + + /** + * Returns the file name without the extension from a file path. + * + * @param string|null $extension if specified, only that extension is cut + * off (may contain leading dot) + */ + public static function getFilenameWithoutExtension(string $path, string $extension = null) + { + if ('' === $path) { + return ''; + } + + if (null !== $extension) { + // remove extension and trailing dot + return rtrim(basename($path, $extension), '.'); + } + + return pathinfo($path, \PATHINFO_FILENAME); + } + + /** + * Returns the extension from a file path (without leading dot). + * + * @param bool $forceLowerCase forces the extension to be lower-case + */ + public static function getExtension(string $path, bool $forceLowerCase = false): string + { + if ('' === $path) { + return ''; + } + + $extension = pathinfo($path, \PATHINFO_EXTENSION); + + if ($forceLowerCase) { + $extension = self::toLower($extension); + } + + return $extension; + } + + /** + * Returns whether the path has an (or the specified) extension. + * + * @param string $path the path string + * @param string|string[]|null $extensions if null or not provided, checks if + * an extension exists, otherwise + * checks for the specified extension + * or array of extensions (with or + * without leading dot) + * @param bool $ignoreCase whether to ignore case-sensitivity + */ + public static function hasExtension(string $path, $extensions = null, bool $ignoreCase = false): bool + { + if ('' === $path) { + return false; + } + + $actualExtension = self::getExtension($path, $ignoreCase); + + // Only check if path has any extension + if ([] === $extensions || null === $extensions) { + return '' !== $actualExtension; + } + + if (\is_string($extensions)) { + $extensions = [$extensions]; + } + + foreach ($extensions as $key => $extension) { + if ($ignoreCase) { + $extension = self::toLower($extension); + } + + // remove leading '.' in extensions array + $extensions[$key] = ltrim($extension, '.'); + } + + return \in_array($actualExtension, $extensions, true); + } + + /** + * Changes the extension of a path string. + * + * @param string $path The path string with filename.ext to change. + * @param string $extension new extension (with or without leading dot) + * + * @return string the path string with new file extension + */ + public static function changeExtension(string $path, string $extension): string + { + if ('' === $path) { + return ''; + } + + $actualExtension = self::getExtension($path); + $extension = ltrim($extension, '.'); + + // No extension for paths + if ('/' === mb_substr($path, -1)) { + return $path; + } + + // No actual extension in path + if (empty($actualExtension)) { + return $path.('.' === mb_substr($path, -1) ? '' : '.').$extension; + } + + return mb_substr($path, 0, -mb_strlen($actualExtension)).$extension; + } + + public static function isAbsolute(string $path): bool + { + if ('' === $path) { + return false; + } + + // Strip scheme + if (false !== ($schemeSeparatorPosition = mb_strpos($path, '://'))) { + $path = mb_substr($path, $schemeSeparatorPosition + 3); + } + + $firstCharacter = $path[0]; + + // UNIX root "/" or "\" (Windows style) + if ('/' === $firstCharacter || '\\' === $firstCharacter) { + return true; + } + + // Windows root + if (mb_strlen($path) > 1 && ctype_alpha($firstCharacter) && ':' === $path[1]) { + // Special case: "C:" + if (2 === mb_strlen($path)) { + return true; + } + + // Normal case: "C:/ or "C:\" + if ('/' === $path[2] || '\\' === $path[2]) { + return true; + } + } + + return false; + } + + public static function isRelative(string $path): bool + { + return !self::isAbsolute($path); + } + + /** + * Turns a relative path into an absolute path in canonical form. + * + * Usually, the relative path is appended to the given base path. Dot + * segments ("." and "..") are removed/collapsed and all slashes turned + * into forward slashes. + * + * ```php + * echo Path::makeAbsolute("../style.css", "/symfony/puli/css"); + * // => /symfony/puli/style.css + * ``` + * + * If an absolute path is passed, that path is returned unless its root + * directory is different than the one of the base path. In that case, an + * exception is thrown. + * + * ```php + * Path::makeAbsolute("/style.css", "/symfony/puli/css"); + * // => /style.css + * + * Path::makeAbsolute("C:/style.css", "C:/symfony/puli/css"); + * // => C:/style.css + * + * Path::makeAbsolute("C:/style.css", "/symfony/puli/css"); + * // InvalidArgumentException + * ``` + * + * If the base path is not an absolute path, an exception is thrown. + * + * The result is a canonical path. + * + * @param string $basePath an absolute base path + * + * @throws InvalidArgumentException if the base path is not absolute or if + * the given path is an absolute path with + * a different root than the base path + */ + public static function makeAbsolute(string $path, string $basePath): string + { + if ('' === $basePath) { + throw new InvalidArgumentException(sprintf('The base path must be a non-empty string. Got: "%s".', $basePath)); + } + + if (!self::isAbsolute($basePath)) { + throw new InvalidArgumentException(sprintf('The base path "%s" is not an absolute path.', $basePath)); + } + + if (self::isAbsolute($path)) { + return self::canonicalize($path); + } + + if (false !== ($schemeSeparatorPosition = mb_strpos($basePath, '://'))) { + $scheme = mb_substr($basePath, 0, $schemeSeparatorPosition + 3); + $basePath = mb_substr($basePath, $schemeSeparatorPosition + 3); + } else { + $scheme = ''; + } + + return $scheme.self::canonicalize(rtrim($basePath, '/\\').'/'.$path); + } + + /** + * Turns a path into a relative path. + * + * The relative path is created relative to the given base path: + * + * ```php + * echo Path::makeRelative("/symfony/style.css", "/symfony/puli"); + * // => ../style.css + * ``` + * + * If a relative path is passed and the base path is absolute, the relative + * path is returned unchanged: + * + * ```php + * Path::makeRelative("style.css", "/symfony/puli/css"); + * // => style.css + * ``` + * + * If both paths are relative, the relative path is created with the + * assumption that both paths are relative to the same directory: + * + * ```php + * Path::makeRelative("style.css", "symfony/puli/css"); + * // => ../../../style.css + * ``` + * + * If both paths are absolute, their root directory must be the same, + * otherwise an exception is thrown: + * + * ```php + * Path::makeRelative("C:/symfony/style.css", "/symfony/puli"); + * // InvalidArgumentException + * ``` + * + * If the passed path is absolute, but the base path is not, an exception + * is thrown as well: + * + * ```php + * Path::makeRelative("/symfony/style.css", "symfony/puli"); + * // InvalidArgumentException + * ``` + * + * If the base path is not an absolute path, an exception is thrown. + * + * The result is a canonical path. + * + * @throws InvalidArgumentException if the base path is not absolute or if + * the given path has a different root + * than the base path + */ + public static function makeRelative(string $path, string $basePath): string + { + $path = self::canonicalize($path); + $basePath = self::canonicalize($basePath); + + [$root, $relativePath] = self::split($path); + [$baseRoot, $relativeBasePath] = self::split($basePath); + + // If the base path is given as absolute path and the path is already + // relative, consider it to be relative to the given absolute path + // already + if ('' === $root && '' !== $baseRoot) { + // If base path is already in its root + if ('' === $relativeBasePath) { + $relativePath = ltrim($relativePath, './\\'); + } + + return $relativePath; + } + + // If the passed path is absolute, but the base path is not, we + // cannot generate a relative path + if ('' !== $root && '' === $baseRoot) { + 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)); + } + + // Fail if the roots of the two paths are different + if ($baseRoot && $root !== $baseRoot) { + 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)); + } + + if ('' === $relativeBasePath) { + return $relativePath; + } + + // Build a "../../" prefix with as many "../" parts as necessary + $parts = explode('/', $relativePath); + $baseParts = explode('/', $relativeBasePath); + $dotDotPrefix = ''; + + // Once we found a non-matching part in the prefix, we need to add + // "../" parts for all remaining parts + $match = true; + + foreach ($baseParts as $index => $basePart) { + if ($match && isset($parts[$index]) && $basePart === $parts[$index]) { + unset($parts[$index]); + + continue; + } + + $match = false; + $dotDotPrefix .= '../'; + } + + return rtrim($dotDotPrefix.implode('/', $parts), '/'); + } + + /** + * Returns whether the given path is on the local filesystem. + */ + public static function isLocal(string $path): bool + { + return '' !== $path && false === mb_strpos($path, '://'); + } + + /** + * Returns the longest common base path in canonical form of a set of paths or + * `null` if the paths are on different Windows partitions. + * + * Dot segments ("." and "..") are removed/collapsed and all slashes turned + * into forward slashes. + * + * ```php + * $basePath = Path::getLongestCommonBasePath( + * '/symfony/css/style.css', + * '/symfony/css/..' + * ); + * // => /symfony + * ``` + * + * The root is returned if no common base path can be found: + * + * ```php + * $basePath = Path::getLongestCommonBasePath( + * '/symfony/css/style.css', + * '/puli/css/..' + * ); + * // => / + * ``` + * + * If the paths are located on different Windows partitions, `null` is + * returned. + * + * ```php + * $basePath = Path::getLongestCommonBasePath( + * 'C:/symfony/css/style.css', + * 'D:/symfony/css/..' + * ); + * // => null + * ``` + */ + public static function getLongestCommonBasePath(string ...$paths): ?string + { + [$bpRoot, $basePath] = self::split(self::canonicalize(reset($paths))); + + for (next($paths); null !== key($paths) && '' !== $basePath; next($paths)) { + [$root, $path] = self::split(self::canonicalize(current($paths))); + + // If we deal with different roots (e.g. C:/ vs. D:/), it's time + // to quit + if ($root !== $bpRoot) { + return null; + } + + // Make the base path shorter until it fits into path + while (true) { + if ('.' === $basePath) { + // No more base paths + $basePath = ''; + + // next path + continue 2; + } + + // Prevent false positives for common prefixes + // see isBasePath() + if (0 === mb_strpos($path.'/', $basePath.'/')) { + // next path + continue 2; + } + + $basePath = \dirname($basePath); + } + } + + return $bpRoot.$basePath; + } + + /** + * Joins two or more path strings into a canonical path. + */ + public static function join(string ...$paths): string + { + $finalPath = null; + $wasScheme = false; + + foreach ($paths as $path) { + if ('' === $path) { + continue; + } + + if (null === $finalPath) { + // For first part we keep slashes, like '/top', 'C:\' or 'phar://' + $finalPath = $path; + $wasScheme = (false !== mb_strpos($path, '://')); + + continue; + } + + // Only add slash if previous part didn't end with '/' or '\' + if (!\in_array(mb_substr($finalPath, -1), ['/', '\\'])) { + $finalPath .= '/'; + } + + // If first part included a scheme like 'phar://' we allow \current part to start with '/', otherwise trim + $finalPath .= $wasScheme ? $path : ltrim($path, '/'); + $wasScheme = false; + } + + if (null === $finalPath) { + return ''; + } + + return self::canonicalize($finalPath); + } + + /** + * Returns whether a path is a base path of another path. + * + * Dot segments ("." and "..") are removed/collapsed and all slashes turned + * into forward slashes. + * + * ```php + * Path::isBasePath('/symfony', '/symfony/css'); + * // => true + * + * Path::isBasePath('/symfony', '/symfony'); + * // => true + * + * Path::isBasePath('/symfony', '/symfony/..'); + * // => false + * + * Path::isBasePath('/symfony', '/puli'); + * // => false + * ``` + */ + public static function isBasePath(string $basePath, string $ofPath): bool + { + $basePath = self::canonicalize($basePath); + $ofPath = self::canonicalize($ofPath); + + // Append slashes to prevent false positives when two paths have + // a common prefix, for example /base/foo and /base/foobar. + // Don't append a slash for the root "/", because then that root + // won't be discovered as common prefix ("//" is not a prefix of + // "/foobar/"). + return 0 === mb_strpos($ofPath.'/', rtrim($basePath, '/').'/'); + } + + /** + * @return non-empty-string[] + */ + private static function findCanonicalParts(string $root, string $pathWithoutRoot): array + { + $parts = explode('/', $pathWithoutRoot); + + $canonicalParts = []; + + // Collapse "." and "..", if possible + foreach ($parts as $part) { + if ('.' === $part || '' === $part) { + continue; + } + + // Collapse ".." with the previous part, if one exists + // Don't collapse ".." if the previous part is also ".." + if ('..' === $part && \count($canonicalParts) > 0 && '..' !== $canonicalParts[\count($canonicalParts) - 1]) { + array_pop($canonicalParts); + + continue; + } + + // Only add ".." prefixes for relative paths + if ('..' !== $part || '' === $root) { + $canonicalParts[] = $part; + } + } + + return $canonicalParts; + } + + /** + * Splits a canonical path into its root directory and the remainder. + * + * If the path has no root directory, an empty root directory will be + * returned. + * + * If the root directory is a Windows style partition, the resulting root + * will always contain a trailing slash. + * + * list ($root, $path) = Path::split("C:/symfony") + * // => ["C:/", "symfony"] + * + * list ($root, $path) = Path::split("C:") + * // => ["C:/", ""] + * + * @return array{string, string} an array with the root directory and the remaining relative path + */ + private static function split(string $path): array + { + if ('' === $path) { + return ['', '']; + } + + // Remember scheme as part of the root, if any + if (false !== ($schemeSeparatorPosition = mb_strpos($path, '://'))) { + $root = mb_substr($path, 0, $schemeSeparatorPosition + 3); + $path = mb_substr($path, $schemeSeparatorPosition + 3); + } else { + $root = ''; + } + + $length = mb_strlen($path); + + // Remove and remember root directory + if (0 === mb_strpos($path, '/')) { + $root .= '/'; + $path = $length > 1 ? mb_substr($path, 1) : ''; + } elseif ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) { + if (2 === $length) { + // Windows special case: "C:" + $root .= $path.'/'; + $path = ''; + } elseif ('/' === $path[2]) { + // Windows normal case: "C:/".. + $root .= mb_substr($path, 0, 3); + $path = $length > 3 ? mb_substr($path, 3) : ''; + } + } + + return [$root, $path]; + } + + private static function toLower(string $string): string + { + if (false !== $encoding = mb_detect_encoding($string)) { + return mb_strtolower($string, $encoding); + } + + return strtolower($string); + } + + private function __construct() + { + } +} diff --git a/lib/PhpBench.php b/lib/PhpBench.php index 4243a6c73..e0c8a775f 100644 --- a/lib/PhpBench.php +++ b/lib/PhpBench.php @@ -25,13 +25,13 @@ use PhpBench\Extension\StorageExtension; use PhpBench\Extensions\XDebug\XDebugExtension; use PhpBench\Json\JsonDecoder; +use PhpBench\Path\Path; use Symfony\Component\Console\Input\ArgvInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\ConsoleOutput; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Throwable; -use Webmozart\PathUtil\Path; use function set_error_handler; diff --git a/lib/Report/Renderer/HtmlRenderer.php b/lib/Report/Renderer/HtmlRenderer.php index 76b6418c7..8ea7404c6 100644 --- a/lib/Report/Renderer/HtmlRenderer.php +++ b/lib/Report/Renderer/HtmlRenderer.php @@ -3,6 +3,7 @@ namespace PhpBench\Report\Renderer; use PhpBench\Compat\SymfonyOptionsResolverCompat; +use PhpBench\Path\Path; use PhpBench\Registry\Config; use PhpBench\Report\Model\HtmlDocument; use PhpBench\Report\Model\Reports; @@ -11,7 +12,6 @@ use RuntimeException; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\OptionsResolver\OptionsResolver; -use Webmozart\PathUtil\Path; class HtmlRenderer implements RendererInterface { diff --git a/lib/Util/PathNormalizer.php b/lib/Util/PathNormalizer.php index 154c18efc..ccd22b980 100644 --- a/lib/Util/PathNormalizer.php +++ b/lib/Util/PathNormalizer.php @@ -2,8 +2,8 @@ namespace PhpBench\Util; +use PhpBench\Path\Path; use Webmozart\Glob\Glob; -use Webmozart\PathUtil\Path; class PathNormalizer { @@ -15,7 +15,7 @@ class PathNormalizer public static function normalizePaths(string $baseDir, array $paths): array { return array_merge(...array_map(static function (string $path) use ($baseDir) { - $path = Path::isAbsolute($path) ? $path : Path::join([$baseDir, $path]); + $path = Path::isAbsolute($path) ? $path : Path::join(...[$baseDir, $path]); if (self::isGlob($path)) { $globPaths = Glob::glob($path); diff --git a/tests/Util/Workspace.php b/tests/Util/Workspace.php index 3cc26ebc6..0b8fa8844 100644 --- a/tests/Util/Workspace.php +++ b/tests/Util/Workspace.php @@ -3,11 +3,11 @@ namespace PhpBench\Tests\Util; use InvalidArgumentException; +use PhpBench\Path\Path; use RecursiveDirectoryIterator; use RecursiveIteratorIterator; use RuntimeException; use SplFileInfo; -use Webmozart\PathUtil\Path; class Workspace {