Skip to main content
Drupal API
User account menu
  • Log in

Breadcrumb

  1. Drupal Core 11.1.x
  2. Path.php

function Path::getDirectory

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 value

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.

File

vendor/symfony/filesystem/Path.php, line 142

Class

Path
Contains utility methods for handling path strings.

Namespace

Symfony\Component\Filesystem

Code

public static function getDirectory(string $path) : string {
    if ('' === $path) {
        return '';
    }
    $path = self::canonicalize($path);
    // Maintain scheme
    if (false !== ($schemeSeparatorPosition = strpos($path, '://'))) {
        $scheme = substr($path, 0, $schemeSeparatorPosition + 3);
        $path = 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 . substr($path, 0, 3);
    }
    return $scheme . substr($path, 0, $dirSeparatorPosition);
}

API Navigation

  • Drupal Core 11.1.x
  • Topics
  • Classes
  • Functions
  • Constants
  • Globals
  • Files
  • Namespaces
  • Deprecated
  • Services
RSS feed
Powered by Drupal