Path
Represents a filesystem path.
Most of the methods rely on the php builtin methods, see each method's documentation for more.
Methods
__construct()
public
__construct(string|self $path) : mixed
Parameters
- $path : string|self
__toString()
public
__toString() : string
Return values
stringabsPath()
Returns an absolute version of the current path.
public
absPath() : self
As this method relies on the php realpath
method, it will fail if the path refers to a
non-existing file.
Return values
selfappend()
Appends part(s) to the current path.
public
append(string ...$parts) : self
Parameters
- $parts : string
-
The part(s) to be appended to the current path.
Return values
selfatime()
Retrieves the last access time of a file or directory.
public
atime() : int
Return values
int —The last access time of the file or directory as a timestamp.
basename()
Get the base name of the path.
public
basename() : string
Example :
Path('path/to/file.ext').basename()
>>> 'file.ext'
.
Return values
stringcd()
Changes the current working directory to this path.
public
cd() : void
chdir()
Alias for Path->cd($path)
public
chdir() : void
chgrp()
Changes the group ownership of a file or directory.
public
chgrp(int|string $group[, bool $clearStatCache = false ]) : void
Parameters
- $group : int|string
-
The group name or ID. If a string is provided, it must be a valid group name. If an integer is provided, it must be a valid group ID.
- $clearStatCache : bool = false
-
Whether to clear the stat cache before changing the group ownership. Defaults to false.
chmod()
> Alias for Path->setPermissions() method
public
chmod(int $mode[, bool $asOctal = false ][, bool $clearStatCache = false ]) : void
Parameters
- $mode : int
-
The new permissions (octal).
- $asOctal : bool = false
- $clearStatCache : bool = false
chown()
Changes the owner of a file or directory.
public
chown(int|string $user[, bool $clearStatCache = false ]) : void
Parameters
- $user : int|string
-
The new owner of the file or directory. Accepts either the user's numeric ID or username.
- $clearStatCache : bool = false
-
Optional. Whether to clear the stat cache before changing the owner. Default is false.
chroot()
Changes the root directory of the current process to the specified directory.
public
chroot() : void
chunks()
Retrieves chunks of data from the file.
public
chunks([int $chunk_size = 8192 ]) : Generator
Parameters
- $chunk_size : int = 8192
-
The size of each chunk in bytes. Defaults to 8192.
Return values
Generator —Returns a generator that yields each chunk of data read from the file.
copy()
Copy a file.
public
copy(string|self $destination[, bool $follow_symlinks = false ][, bool $erase = true ]) :
Copy data and mode bits (“cp src dst”). The destination may be a directory. Return the file’s destination as a Path. If follow_symlinks is false, symlinks won’t be followed. This resembles GNU’s “cp -P src dst”. This method does not conserve permissions. If $follow_symlinks is true and if $destination is a directory, the newly created file will have the filename of the symlink, and not the one of its target.
Parameters
- $destination : string|self
-
The destination path or object to copy the file to.
- $follow_symlinks : bool = false
- $erase : bool = true
Return values
copyTree()
Recursively copy a directory tree and return the destination directory.
public
copyTree(string|self $destination[, bool $followSymlinks = false ]) : self
If $follow_symlinks is false, symbolic links in the source tree result in symbolic links in the destination tree; if it is true, the contents of the files pointed to by symbolic links are copied.
Parameters
- $destination : string|self
-
The destination path or directory to copy the content to.
- $followSymlinks : bool = false
-
Whether to follow symbolic links (default is false).
Return values
self —The newly created file or directory as a Path
ctime()
Retrieves the creation time of a file or directory.
public
ctime() : int
Return values
int —The creation time of the file or directory as a timestamp.
delete()
Deletes a file or a directory (non-recursively).
public
delete() : void
dirname()
Alias for Path->parent() method
public
dirname([int $levels = 1 ]) : self
Parameters
- $levels : int = 1
Return values
selfdirs()
Retrieves an array of this directory’s subdirectories.
public
dirs() : array<string|int, self>
This does not walk recursively into subdirectories (but @see walkDirs())
Return values
array<string|int, self>eq()
Checks if the given path is equal to the current path.
public
eq(string| $path) : bool
NB: This method does not perform any path resolution.
Parameters
- $path : string|
-
The path to compare against.
Return values
boolexists()
Checks if a file or directory exists.
public
exists() : bool
Return values
boolexpand()
Expands the path by performing three operations: expanding user, expanding variables, and normalizing the path.
public
expand() : self
Return values
self —The expanded path.
expandUser()
Expands the user directory in the file path.
public
expandUser() : self
Return values
self —The modified instance with the expanded user path.
expandVars()
Expands variables in the path.
public
expandVars() : self
Searches for variable placeholders in the path and replaces them with their corresponding values from the environment variables.
Return values
self —The path with expanded variables.
ext()
Get the extension of the given path.
public
ext() : string
Return values
string —Returns the extension of the path as a string if it exists, or an empty string otherwise.
files()
Retrieves an array of files present in the directory.
public
files([bool $includeSymlinks = true ]) : array<string|int, self>
Parameters
- $includeSymlinks : bool = true
Return values
array<string|int, self> —An array of files present in the directory.
fnmatch()
Performs a pattern matching using the `fnmatch()` function.
public
fnmatch(string $pattern) : bool
Parameters
- $pattern : string
-
A filename pattern with wildcards.
Return values
bool —True if the path matches the pattern, false otherwise.
getContent()
Retrieves the content of a file.
public
getContent() : string
Return values
string —The content of the file as a string.
getHomeDir()
Retrieves and returns the home directory of the current user.
public
getHomeDir() : self
Return values
self —The Path instance representing the home directory.
getOwnerId()
Retrieves the id of the owner of the file or directory.
public
getOwnerId() : int
Return values
int —The owner identifier of the file or directory
getOwnerName()
Retrieves the name of the owner of the file or directory.
public
getOwnerName() : string
Return values
string —The name of the owner
getPermissions()
Retrieves the permissions of a file or directory.
public
getPermissions([bool $asOctal = true ]) : int
Parameters
- $asOctal : bool = true
Return values
int —The permissions of the file or directory
getRelativePath()
Computes a version of this path that is relative to another path.
public
getRelativePath(string| $basePath) : self
This method relies on the php realpath
method and then requires the path to refer to
an existing file.
Parameters
- $basePath : string|
Return values
selfglob()
Retrieves a list of files and directories that match a specified pattern.
public
glob(string $pattern) : array<string|int, self>
Parameters
- $pattern : string
-
The pattern to search for.
Return values
array<string|int, self> —A list of files and directories that match the pattern.
isAbs()
Check whether this path is absolute.
public
isAbs() : bool
Return values
boolisDir()
Check if the given path is a directory.
public
isDir() : bool
Return values
boolisExecutable()
Determines if the file or directory is executable.
public
isExecutable() : bool
Return values
boolisFile()
Check if the path refers to a regular file.
public
isFile() : bool
Return values
boolisLink()
Checks if the file is a symbolic link.
public
isLink() : bool
Return values
boolisMount()
Checks if the path is a mount point.
public
isMount() : bool
Return values
boolisReadable()
Checks if the file or directory is readable.
public
isReadable() : bool
Return values
boolisWritable()
Determines if the file or directory is writable.
public
isWritable() : bool
Return values
booljoin()
Joins two or more parts of a path together.
public
static join(string| $path, string ...$parts) : self
Joins two or more parts of a path together, inserting '/' as needed. If any component is an absolute path, all previous path components will be discarded. An empty last part will result in a path that ends with a separator.
Example :
Path::join('/home', 'user')
>>> '/home/user'
Parameters
- $path : string|
-
The base path
- $parts : string
-
The parts of the path to be joined.
Return values
self —The resulting path after joining the parts using the directory separator.
lines()
Retrieves the content of a file as an array of lines.
public
lines() : array<string|int, string>
Return values
array<string|int, string>link()
Create a hard link pointing to this path.
public
link(string| $newLink) :
Parameters
- $newLink : string|
Return values
lstat()
Gives information about a file or symbolic link
public
lstat() : array<string, int|float>
Return values
array<string, int|float>mkdir()
Creates a new directory.
public
mkdir([int $mode = 0777 ][, bool $recursive = false ]) : void
Parameters
- $mode : int = 0777
-
The permissions for the new directory. Default is 0777.
- $recursive : bool = false
-
Indicates whether to create parent directories if they do not exist. Default is false.
move()
Recursively move a file or directory to another location.
public
move(string| $destination) :
Moves a file or directory to a new location. Existing files or dirs will be overwritten. Returns the path of the newly created file or directory. If the destination is a directory or a symlink to a directory, the source is moved inside the directory. The destination path must not already exist.
Parameters
- $destination : string|
-
The new location where the file or directory should be moved to.
Return values
mtime()
Retrieves the last modified time of a file or directory.
public
mtime() : int
Return values
int —The last modified time of the file or directory as a timestamp.
name()
Get the name of the file or path, without its extension.
public
name() : string
Example:
Path('path/to/file.ext').name()
>>> 'file'
.
Return values
stringnormCase()
Normalize the case of a pathname.
public
normCase() : self
Convert all characters in the pathname to lowercase, and also convert forward slashes and backslashes to the current directory separator.
Return values
selfnormPath()
Normalizes the path of the file or directory.
public
normPath() : self
Normalize a pathname by collapsing redundant separators and up-level references so that A//B, A/B/, A/./B and A/foo/../B all become A/B. This string manipulation may change the meaning of a path that contains symbolic links. On Windows, it converts forward slashes to backward slashes. To normalize case, use normcase().
Return values
self —A new instance of the class with the normalized path.
open()
Opens a file in the specified mode.
public
open([string $mode = 'r' ]) : resource|false
Parameters
- $mode : string = 'r'
-
The mode in which to open the file. Defaults to 'r'.
Return values
resource|false —Returns a file pointer resource on success, or false on failure.
parent()
Retrieves the parent directory of a file or directory path.
public
parent([int $levels = 1 ]) : self
Parameters
- $levels : int = 1
Return values
selfparts()
Returns the individual parts of this path.
public
parts() : array<string|int, string>
The eventual leading directory separator is kept.
Example :
Path('/foo/bar/baz').parts()
>>> '/', 'foo', 'bar', 'baz'
Return values
array<string|int, string>path()
The current path as a string.
public
path() : string
Return values
stringputContent()
Writes contents to a file.
public
putContent(string $content[, bool $append = false ][, bool $create = true ]) : int
Parameters
- $content : string
-
The contents to be written to the file.
- $append : bool = false
-
Append the content to the file's content instead of replacing it
- $create : bool = true
-
Creates the file if it does not already exist
Return values
int —The number of bytes that were written to the file
putLines()
Writes an array of lines to a file.
public
putLines(array<string|int, string> $lines[, bool $append = false ][, bool $create = true ]) : int
Parameters
- $lines : array<string|int, string>
-
An array of lines to be written to the file.
- $append : bool = false
-
Append the content to the file's content instead of replacing it
- $create : bool = true
-
Creates the file if it does not already exist
Return values
int —The number of bytes written to the file.
readHash()
Retrieves the hash of a file or directory using the specified algorithm.
public
readHash(string $algo[, bool $binary = false ]) : string
Parameters
- $algo : string
-
The hashing algorithm to use. Supported algorithms can be found at the PHP documentation.
- $binary : bool = false
-
(optional) Determines whether the hash should be returned as binary or hexadecimal. Default is false.
Return values
string —The computed hash of the file or directory.
readLink()
Returns the target of a symbolic link.
public
readLink() : self
Return values
self —The target of the symbolic link as a new instance of the current class.
readText()
> Alias for getContent()
public
readText() : string
Return values
stringrealpath()
> Alias for absPath()
public
realpath() : self
Return values
selfremove()
Removes the file.
public
remove() : void
remove_p()
Like remove(), but does not throw an exception if the file does not exist.
public
remove_p() : void
It will still raise a FileExistsException
if the target is an existing directory.
rename()
> Alias for Path->move()
public
rename(string|self $newPath) : self
Parameters
- $newPath : string|self
Return values
selfrmdir()
Removes a directory.
public
rmdir([bool $recursive = false ][, bool $permissive = false ]) : void
If $recursive is true, the directory will be removed with its content. Else, an IOException will be raised. If the target directory does not exist, a FileNotFoundException will be raised, except if $permissive is set to true. If the target is an existing file, a FileNotFoundException will be raised even if $permissive is true.
Parameters
- $recursive : bool = false
- $permissive : bool = false
sameFile()
Return True if both pathname arguments refer to the same file or directory.
public
sameFile(string|self $other) : bool
As this method relies on the realpath
method, this will throw an exception if any of the two files does
not exist.
Parameters
- $other : string|self
Return values
boolsetOwner()
Changes ownership of the file.
public
setOwner(string $user, string $group[, bool $clearStatCache = false ]) : void
Parameters
- $user : string
-
The new owner username.
- $group : string
-
The new owner group name.
- $clearStatCache : bool = false
setPermissions()
Changes the permissions of a file or directory.
public
setPermissions(int $permissions[, bool $asOctal = false ][, bool $clearStatCache = false ]) : void
Parameters
- $permissions : int
-
The new permissions to set.
- $asOctal : bool = false
-
Set to true if permissions are given as octal
- $clearStatCache : bool = false
-
Force a clear cache of the php stat cache
size()
Size of the file, in bytes.
public
size() : int
Return values
int —The size of the file in bytes.
splitDrive()
Split the pathname path into a pair (drive, tail) where drive is either a mount point or the empty string.
public
static splitDrive(string|self $path) : array<string|int, string>
If the path contains a drive letter, drive will contain everything up to and including the colon:
Path::splitDrive("c:/dir")
>>> ["c:", "/dir"]
If the path contains a UNC path, drive will contain the host name and share:
Path::splitDrive("//host/computer/dir")
>>> ["//host/computer", "/dir"]
Parameters
- $path : string|self
Return values
array<string|int, string> —An 2-members array containing the drive and the path.
symlink()
Creates a symbolic link to the specified destination.
public
symlink(string|self $newLink) : self
Parameters
- $newLink : string|self
-
The path or the instance of the symbolic link to create.
Return values
self —The instance of the symbolic link that was created.
touch()
Updates the access and modification time of a file, or creates a new empty file if it doesn't exist.
public
touch([int|DateTime|null $time = null ][, int|DateTime|null $atime = null ]) : void
Parameters
- $time : int|DateTime|null = null
-
(optional) The access and modification time to set. Default is the current time.
- $atime : int|DateTime|null = null
-
(optional) The access time to set. Default is the value of $time.
unlink()
> Alias for Path->remove()
public
unlink() : void
walkDirs()
Walks through the directories of a given directory and returns an iterator.
public
walkDirs() : Iterator
This method uses the built-in RecursiveIteratorIterator
and RecursiveDirectoryIterator
classes to
traverse through all the files and directories within the given directory.
Return values
Iterator —An iterator that yields each file or directory within the given directory
with()
Calls a callback with a file handle opened with the specified mode and closes the handle afterward.
public
with(callable $callback[, string $mode = 'r' ]) : mixed
Parameters
- $callback : callable
-
The callback function to be called with the file handle.
- $mode : string = 'r'
-
The mode in which to open the file. Defaults to 'r'.
cast()
Casts the input into a Path instance.
protected
cast(string|self $path) : self
Parameters
- $path : string|self
-
The input path to be cast.