Webmozart\PathUtil\Path::getRoot PHP Method

getRoot() public static method

The result is a canonical path.
Since: 1.0 Added method.
Since: 2.0 Method now fails if $path is not a string.
public static getRoot ( string $path ) : string
$path string A path string.
return string The canonical root directory. Returns an empty string if the given path is relative or empty.
    public static function getRoot($path)
    {
        if ('' === $path) {
            return '';
        }
        Assert::string($path, 'The path must be a string. Got: %s');
        // Maintain scheme
        if (false !== ($pos = strpos($path, '://'))) {
            $scheme = substr($path, 0, $pos + 3);
            $path = substr($path, $pos + 3);
        } else {
            $scheme = '';
        }
        // UNIX root "/" or "\" (Windows style)
        if ('/' === $path[0] || '\\' === $path[0]) {
            return $scheme . '/';
        }
        $length = strlen($path);
        // Windows root
        if ($length > 1 && ctype_alpha($path[0]) && ':' === $path[1]) {
            // Special case: "C:"
            if (2 === $length) {
                return $scheme . $path . '/';
            }
            // Normal case: "C:/ or "C:\"
            if ('/' === $path[2] || '\\' === $path[2]) {
                return $scheme . $path[0] . $path[1] . '/';
            }
        }
        return '';
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * @expectedException \InvalidArgumentException
  * @expectedExceptionMessage The path must be a string. Got: array
  */
 public function testGetRootFailsIfInvalidPath()
 {
     Path::getRoot(array());
 }