Path-php

Path
in package

Represents a filesystem path.

Most of the methods rely on the php builtin methods, see each method's documentation for more.

Tags
see
https://github.com/olinox14/path-php#path-php

Table of Contents

Properties

$builtin  : BuiltinProxy
$handle  : mixed
$path  : string

Methods

__construct()  : mixed
__toString()  : string
absPath()  : self
Returns an absolute version of the current path.
append()  : self
Appends part(s) to the current path.
atime()  : int
Retrieves the last access time of a file or directory.
basename()  : string
Get the base name of the path.
cd()  : void
Changes the current working directory to this path.
chdir()  : void
> Alias for Path->cd($path)
chgrp()  : void
Changes the group ownership of a file or directory.
chmod()  : void
> Alias for Path->setPermissions() method
chown()  : void
Changes the owner of a file or directory.
chroot()  : void
Changes the root directory of the current process to the specified directory.
chunks()  : Generator
Retrieves chunks of data from the file.
copy()  : Path
Copy a file.
copyTree()  : self
Recursively copy a directory tree and return the destination directory.
ctime()  : int
Retrieves the creation time of a file or directory.
delete()  : void
Deletes a file or a directory (non-recursively).
dirname()  : self
> Alias for Path->parent() method
dirs()  : array<string|int, self>
Retrieves an array of this directory’s subdirectories.
eq()  : bool
Checks if the given path is equal to the current path.
exists()  : bool
Checks if a file or directory exists.
expand()  : self
Expands the path by performing three operations: expanding user, expanding variables, and normalizing the path.
expandUser()  : self
Expands the user directory in the file path.
expandVars()  : self
Expands variables in the path.
ext()  : string
Get the extension of the given path.
files()  : array<string|int, self>
Retrieves an array of files present in the directory.
fnmatch()  : bool
Performs a pattern matching using the `fnmatch()` function.
getContent()  : string
Retrieves the content of a file.
getHomeDir()  : self
Retrieves and returns the home directory of the current user.
getOwnerId()  : int
Retrieves the id of the owner of the file or directory.
getOwnerName()  : string
Retrieves the name of the owner of the file or directory.
getPermissions()  : int
Retrieves the permissions of a file or directory.
getRelativePath()  : self
Computes a version of this path that is relative to another path.
glob()  : array<string|int, self>
Retrieves a list of files and directories that match a specified pattern.
isAbs()  : bool
Check whether this path is absolute.
isDir()  : bool
Check if the given path is a directory.
isExecutable()  : bool
Determines if the file or directory is executable.
isFile()  : bool
Check if the path refers to a regular file.
isLink()  : bool
Checks if the file is a symbolic link.
isMount()  : bool
Checks if the path is a mount point.
isReadable()  : bool
Checks if the file or directory is readable.
isWritable()  : bool
Determines if the file or directory is writable.
join()  : self
Joins two or more parts of a path together.
lines()  : array<string|int, string>
Retrieves the content of a file as an array of lines.
link()  : Path
Create a hard link pointing to this path.
lstat()  : array<string, int|float>
Gives information about a file or symbolic link
mkdir()  : void
Creates a new directory.
move()  : Path
Recursively move a file or directory to another location.
mtime()  : int
Retrieves the last modified time of a file or directory.
name()  : string
Get the name of the file or path, without its extension.
normCase()  : self
Normalize the case of a pathname.
normPath()  : self
Normalizes the path of the file or directory.
open()  : resource|false
Opens a file in the specified mode.
parent()  : self
Retrieves the parent directory of a file or directory path.
parts()  : array<string|int, string>
Returns the individual parts of this path.
path()  : string
The current path as a string.
putContent()  : int
Writes contents to a file.
putLines()  : int
Writes an array of lines to a file.
readHash()  : string
Retrieves the hash of a file or directory using the specified algorithm.
readLink()  : self
Returns the target of a symbolic link.
readText()  : string
> Alias for getContent()
realpath()  : self
> Alias for absPath()
remove()  : void
Removes the file.
remove_p()  : void
Like remove(), but does not throw an exception if the file does not exist.
rename()  : self
> Alias for Path->move()
rmdir()  : void
Removes a directory.
sameFile()  : bool
Return True if both pathname arguments refer to the same file or directory.
setOwner()  : void
Changes ownership of the file.
setPermissions()  : void
Changes the permissions of a file or directory.
size()  : int
Size of the file, in bytes.
splitDrive()  : array<string|int, string>
Split the pathname path into a pair (drive, tail) where drive is either a mount point or the empty string.
symlink()  : self
Creates a symbolic link to the specified destination.
touch()  : void
Updates the access and modification time of a file, or creates a new empty file if it doesn't exist.
unlink()  : void
> Alias for Path->remove()
walkDirs()  : Iterator
Walks through the directories of a given directory and returns an iterator.
with()  : mixed
Calls a callback with a file handle opened with the specified mode and closes the handle afterward.
cast()  : self
Casts the input into a Path instance.

Properties

$builtin

protected BuiltinProxy $builtin

$handle

protected mixed $handle

$path

protected string $path

Methods

__construct()

public __construct(string|self $path) : mixed
Parameters
$path : string|self

__toString()

public __toString() : string
Return values
string

append()

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.

Tags
see
Path::join()
Return values
self

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.

Tags
see
https://www.php.net/manual/en/function.chgrp.php
throws
FileNotFoundException

If the file or directory does not exist.

throws
IOException

If there is an error changing the group ownership.

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
Tags
see
setPermissions()
throws
FileNotFoundException
throws
IOException

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.

Tags
see
https://www.php.net/manual/en/function.chown.php
throws
FileNotFoundException

If the file or directory does not exist.

throws
IOException

If an error occurs while changing the owner of the file or directory.

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.

Tags
throws
FileNotFoundException
throws
IOException
throws
Throwable
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 ]) : Path

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
Tags
see
https://www.php.net/manual/en/function.copy.php
see
https://www.php.net/manual/en/function.symlink.php
throws
FileExistsException
throws
FileNotFoundException

If the source file does not exist or is not a file.

throws
IOException
Return values
Path

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).

Tags
throws
FileExistsException

If the destination path or directory already exists.

throws
FileNotFoundException

If the source file or directory does not exist.

throws
IOException
Return values
self

The newly created file or directory as a Path

dirname()

> Alias for Path->parent() method

public dirname([int $levels = 1 ]) : self
Parameters
$levels : int = 1
Tags
see
parent()
Return values
self

dirs()

Retrieves an array of this directory’s subdirectories.

public dirs() : array<string|int, self>

This does not walk recursively into subdirectories (but @see walkDirs())

Tags
throws
FileNotFoundException
Return values
array<string|int, self>

eq()

Checks if the given path is equal to the current path.

public eq(string|Path $path) : bool

NB: This method does not perform any path resolution.

Parameters
$path : string|Path

The path to compare against.

Return values
bool

expandUser()

Expands the user directory in the file path.

public expandUser() : self
Tags
throws
IOException
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.

files()

Retrieves an array of files present in the directory.

public files([bool $includeSymlinks = true ]) : array<string|int, self>
Parameters
$includeSymlinks : bool = true
Tags
throws
FileNotFoundException

If the directory specified in the path does not exist.

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.

Tags
see
https://www.php.net/manual/en/function.fnmatch.php
Return values
bool

True if the path matches the pattern, false otherwise.

getHomeDir()

Retrieves and returns the home directory of the current user.

public getHomeDir() : self
Tags
throws
RuntimeException

When unable to determine the home directory. TODO: move to a utils class and test

Return values
self

The Path instance representing the home directory.

getRelativePath()

Computes a version of this path that is relative to another path.

public getRelativePath(string|Path $basePath) : self

This method relies on the php realpath method and then requires the path to refer to an existing file.

Parameters
$basePath : string|Path
Tags
throws
FileNotFoundException
throws
IOException
Return values
self

isAbs()

Check whether this path is absolute.

public isAbs() : bool
Return values
bool

isExecutable()

Determines if the file or directory is executable.

public isExecutable() : bool
Tags
throws
FileNotFoundException

If the file or directory does not exist.

Return values
bool

isMount()

Checks if the path is a mount point.

public isMount() : bool
Return values
bool

isWritable()

Determines if the file or directory is writable.

public isWritable() : bool
Tags
throws
FileNotFoundException

If the file or directory does not exist.

Return values
bool

join()

Joins two or more parts of a path together.

public static join(string|Path $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|Path

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>
Tags
throws
FileNotFoundException
throws
IOException
Return values
array<string|int, string>

move()

Recursively move a file or directory to another location.

public move(string|Path $destination) : Path

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|Path

The new location where the file or directory should be moved to.

Tags
see
https://www.php.net/manual/en/function.rename.php
throws
IOException
throws
FileNotFoundException
throws
FileExistsException
Return values
Path

normCase()

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
self

normPath()

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'.

Tags
see
https://www.php.net/manual/en/function.fopen.php
throws
FileNotFoundException

If the path does not refer to a file.

throws
IOException

If the file fails to open.

Return values
resource|false

Returns a file pointer resource on success, or false on failure.

parts()

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
string

putContent()

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

Tags
see
https://www.php.net/manual/en/function.file-put-contents.php
throws
FileNotFoundException
throws
IOException
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

Tags
throws
FileNotFoundException
throws
IOException
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.

Tags
see
https://www.php.net/manual/en/function.hash-file.php
throws
IOException

If there is an error computing the hash.

Return values
string

The computed hash of the file or directory.

realpath()

> Alias for absPath()

public realpath() : self
Tags
see
absPath()
throws
IOException
Return values
self

rmdir()

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
Tags
throws
FileNotFoundException
throws
IOException

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
Tags
throws
IOException
Return values
bool

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

Tags
see
https://www.php.net/manual/en/function.chmod.php
throws
FileNotFoundException
throws
IOException

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.

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.

Tags
see
https://www.php.net/manual/en/function.symlink.php
throws
FileNotFoundException

If the file or directory does not exist.

throws
FileExistsException

If the symbolic link already exists.

throws
IOException

If there was an error while creating the symbolic link.

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.

Tags
see
https://www.php.net/manual/en/function.touch.php
throws
IOException

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.

Tags
see
https://www.php.net/manual/en/class.recursiveiteratoriterator.php
see
https://www.php.net/manual/en/class.iterator.php
throws
FileNotFoundException

If the directory does not exist

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'.

Tags
throws
Throwable

If an exception is thrown within the callback function.

cast()

Casts the input into a Path instance.

protected cast(string|self $path) : self
Parameters
$path : string|self

The input path to be cast.

Return values
self

        
On this page

Search results