Webmozart\PathUtil\Path::getDirectory PHP Method

getDirectory() public static method

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:/webmozart") returns "C:", not "C:/" - dirname("C:/") returns ".", not "C:/" - dirname("C:") returns ".", not "C:/" - dirname("webmozart") returns ".", not "" - dirname() does not canonicalize the result This method fixes these shortcomings and behaves like dirname() otherwise. 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 getDirectory ( string $path ) : string
$path string A path string.
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($path)
    {
        if ('' === $path) {
            return '';
        }
        $path = static::canonicalize($path);
        // Maintain scheme
        if (false !== ($pos = strpos($path, '://'))) {
            $scheme = substr($path, 0, $pos + 3);
            $path = substr($path, $pos + 3);
        } else {
            $scheme = '';
        }
        if (false !== ($pos = strrpos($path, '/'))) {
            // Directory equals root directory "/"
            if (0 === $pos) {
                return $scheme . '/';
            }
            // Directory equals Windows root "C:/"
            if (2 === $pos && ctype_alpha($path[0]) && ':' === $path[1]) {
                return $scheme . substr($path, 0, 3);
            }
            return $scheme . substr($path, 0, $pos);
        }
        return '';
    }

Usage Example

Ejemplo n.º 1
0
 /**
  * {@inheritdoc}
  */
 public function write($path, $contents)
 {
     Assert::notEmpty($path, 'Cannot write to an empty path.');
     if (is_dir($path)) {
         throw new StorageException(sprintf('Cannot write %s: Is a directory.', $path));
     }
     if (!is_dir($dir = Path::getDirectory($path))) {
         $filesystem = new Filesystem();
         $filesystem->mkdir($dir);
     }
     if (false === ($numBytes = @file_put_contents($path, $contents))) {
         $error = error_get_last();
         throw new StorageException(sprintf('Could not write %s: %s.', $path, $error['message']));
     }
     return $numBytes;
 }
All Usage Examples Of Webmozart\PathUtil\Path::getDirectory