Toolkit Reference

Static utility classes covering strings, arrays, files, directories, HTTP, sessions, hashing, dates, numbers, URLs, sanitization, and validation. Always prefer Toolkit methods over raw PHP functions.

All Toolkit classes live in Phlat\Toolkit\ and are static-only. Import with use Phlat\Toolkit\{Class}; and call as ClassName::method(...).


Arr — Arrays

Inspection

Method Returns Description
Arr::isEmpty(array $a) bool True if the array is empty
Arr::count(array $a) int Number of elements
Arr::has($a, $value, $strict) bool True if value is present (by value)
Arr::hasKey($a, $key) bool True if key exists
Arr::first(array $a) mixed First element, or null
Arr::last(array $a) mixed Last element, or null

Extraction

Method Returns Description
Arr::keys(array $a) array All keys
Arr::values(array $a) array All values, re-indexed
Arr::take($a, int $n) array First N elements
Arr::slice($a, $offset, $length) array Subset by offset/length
Arr::chunk($a, int $size) array Split into chunks
Arr::pluck($a, string $key) array Extract one key from each nested array

Transformation

Method Returns Description
Arr::map($a, callable $fn) array Apply callback to each element
Arr::filter($a, callable $fn) array Filter by callback, re-indexed
Arr::partition($a, callable $fn) array Split into [matches, non-matches]
Arr::reduce($a, callable $fn, $initial) mixed Reduce to a single value
Arr::unique(array $a) array Deduplicate values, re-indexed
Arr::reverse(array $a) array Reverse order
Arr::flip(array $a) array Swap keys and values
Arr::flatten(array $a) array Flatten one level of nesting

Searching

Method Returns Description
Arr::find($a, callable $fn) mixed First matching element, or null
Arr::findKey($a, callable $fn) int|string|null Key of first match, or null

Sorting

Method Returns Description
Arr::sort($a, $flags) array Sorted copy, re-indexed
Arr::sortBy($a, callable $fn) array Sorted by comparison callback

Combination

Method Returns Description
Arr::keyBy($a, callable $fn) array Rekey by function result
Arr::merge(array ...$arrays) array Merge; later arrays override earlier
Arr::mergeRecursive(array ...$arrays) array Deep merge
Arr::prepend($a, ...$values) array Prepend values
Arr::append($a, ...$values) array Append values
Arr::only($a, array $keys) array Keep only listed keys
Arr::except($a, array $keys) array Remove listed keys

Str — Strings

All operations are Unicode-aware (via mb_* functions).

Inspection

Method Returns Description
Str::length(string $s) int Character count
Str::isEmpty(string $s) bool True if ''
Str::startsWith($s, $prefix, $ci) bool Prefix check (case-insensitive by default)
Str::endsWith($s, $suffix, $ci) bool Suffix check
Str::contains($s, $needle, $ci) bool Substring check

Extraction

Method Returns Description
Str::before($s, $needle) string Everything before the first needle
Str::after($s, $needle) string Everything after the first needle
Str::between($s, $start, $end) string Substring between two delimiters
Str::substr($s, $start, $length) string Unicode substring

Transformation

Method Returns Description
Str::lower(string $s) string Lowercase
Str::upper(string $s) string Uppercase
Str::title(string $s) string Title case
Str::slug($s, $sep) string URL slug: lowercase, non-alphanumeric → separator
Str::camel(string $s) string camelCase from hyphen/underscore/space
Str::snake(string $s) string snake_case from camelCase
Str::truncate($s, $len, $suffix) string Truncate to length; suffix counts toward limit
Str::words($s, $count, $suffix) string Truncate to word count

Removal

Method Returns Description
Str::trim($s, $chars) string Trim both ends
Str::trimStart($s, $chars) string Trim left
Str::trimEnd($s, $chars) string Trim right
Str::removeStart($s, $prefix) string Remove exact prefix if present
Str::removeEnd($s, $suffix) string Remove exact suffix if present

Replacement

Method Returns Description
Str::replace($s, $search, $replace) string Replace all occurrences
Str::replaceFirst($s, $search, $replace) string Replace first occurrence only
Str::replaceLast($s, $search, $replace) string Replace last occurrence only
Str::translate($s, array $map) string Replace via [search => replace] map

Splitting

Method Returns Description
Str::split($s, $delimiter, $limit) array Explode on delimiter
Str::join($parts, $glue) string Implode with glue
Str::lines(string $s) array Split on \n or \r\n
Str::match($pattern, $subject, &$matches) bool Regex match

F — Files

Inspection

Method Returns Description
F::exists(string $path) bool True if a file exists
F::isReadable(string $path) bool True if readable
F::isWritable(string $path) bool True if writable
F::size(string $path) int Size in bytes
F::modified(string $path) int Last-modified Unix timestamp

Path

Method Returns Description
F::name(string $path) string Filename with extension
F::stem(string $path) string Filename without extension
F::extension(string $path) string Extension without dot
F::directory(string $path) string Parent directory path
F::resolve(string ...$paths) string|null First path that resolves to a real file, or null

Read / Write

Method Returns Description
F::read(string $path) string Read file contents (throws on failure)
F::write(string $path, string $contents) void Write file (throws on failure)
F::append(string $path, string $contents) void Append to file (throws on failure)

Operations

Method Returns Description
F::copy($source, $dest) bool Copy a file
F::move($source, $dest) bool Move or rename a file
F::delete(string $path) bool Delete a file

Dir — Directories

Inspection

Method Returns Description
Dir::exists(string $path) bool True if directory exists
Dir::isEmpty(string $path) bool True if no entries
Dir::isReadable(string $path) bool True if readable
Dir::isWritable(string $path) bool True if writable

Path

Method Returns Description
Dir::name(string $path) string Final path segment
Dir::parent($path, $levels) string Parent directory
Dir::resolve(string $path) string|null Resolve symlinks; null if not found
Dir::join(string ...$parts) string Join path segments, collapse duplicate slashes

Contents

Method Returns Description
Dir::list(string $path) array All entry names (excluding . and ..)
Dir::files(string $path) array Full paths of files directly inside $path
Dir::directories(string $path) array Full paths of subdirectories directly inside $path

Operations

Method Returns Description
Dir::make($path, $permissions) bool Create recursively, idempotent
Dir::delete(string $path) bool Delete empty directory
Dir::deleteRecursive(string $path) bool Delete directory and all contents
Dir::move($source, $dest) bool Move or rename a directory

Dt — Dates & Times

Returns DateTimeImmutable objects. Format with $dt->format('Y-m-d').

Creation

Method Returns Description
Dt::now(?string $timezone) DateTimeImmutable Current date and time
Dt::parse(string $value, ?string $tz) DateTimeImmutable Parse a date/time string
Dt::fromTimestamp(int $ts) DateTimeImmutable From Unix timestamp

Formatting

Method Returns Description
Dt::format($dt, string $format) string Format with PHP date format
Dt::ago($dt) string Human relative time: "3 minutes ago"
Dt::timestamp($dt) int Unix timestamp

Comparison

Method Returns Description
Dt::diff($a, $b) DateInterval Difference between two datetimes
Dt::isBefore($a, $b) bool True if $a is before $b
Dt::isAfter($a, $b) bool True if $a is after $b

Hash — Hashing & Tokens

Method Returns Description
Hash::password(string $value) string Bcrypt hash
Hash::verify($value, $hash) bool Verify password against hash
Hash::random(int $bytes) string Cryptographically secure random hex string
Hash::uuid() string Random UUID v4
Hash::equals(string $a, string $b) bool Timing-safe string comparison
Hash::md5(string $value) string MD5 hex digest
Hash::sha256(string $value) string SHA-256 hex digest

Json — JSON

All methods throw \JsonException on failure.

Method Returns Description
Json::encode($data, bool $pretty) string Encode to JSON
Json::decode(string $json) mixed Decode to associative array
Json::valid(string $json) bool True if the string is valid JSON

Num — Numbers

Formatting

Method Returns Description
Num::format($n, $decimals, $point, $thousands) string Grouped number format
Num::currency($amount, $symbol, $decimals) string Currency, e.g. $1,234.56
Num::percent($value, $decimals) string Percentage string, e.g. 12.5%
Num::bytes(int $bytes) string Human-readable size, e.g. 1.2 MiB

Math

Method Returns Description
Num::round($value, $precision) int|float Round to precision
Num::floor($value) int|float Floor
Num::ceil($value) int|float Ceiling
Num::abs($value) int|float Absolute value
Num::clamp($value, $min, $max) int|float Clamp between min and max
Num::min(int|float ...$values) int|float Minimum
Num::max(int|float ...$values) int|float Maximum
Num::random($min, $max) int Cryptographically secure random integer

Res — HTTP Responses

Status

Method Returns Description
Res::code(int $code) void Set HTTP response code
Res::header(string $name, string $value) void Set a response header

Redirect

Method Returns Description
Res::redirect(string $url, int $code) never Redirect and exit (default 302)
Res::navigate(string $url) never Set HX-Redirect and exit (HTMX full-page navigation)

Hypermedia signals

Method Returns Description
Res::trigger(string ...$events) void Set HX-Trigger to signal events to the client

Output

Method Returns Description
Res::json($data, int $code) string Set JSON Content-Type and return encoded body
Res::text(string $body, int $code) string Set text/plain Content-Type and return body

San — Sanitization

Strings

Method Returns Description
San::text(string $value) string Trim and strip all HTML tags
San::html(string $value) string HTML-escape for safe output
San::pageName(string $value) string Lowercase slug: letters, numbers, hyphens only
San::filename(string $value) string Strip characters unsafe in filenames

Scalars

Method Returns Description
San::int(mixed $value) int|null Returns null if not numeric
San::float(mixed $value) float|null Returns null if not numeric
San::bool(mixed $value) bool Coerces to bool (accepts true/1/yes/on)

Network

Method Returns Description
San::email(string $value) string|null Validate and lowercase; null if invalid
San::url(string $value) string|null Validate URL; null if invalid

Ses — Sessions

Sessions start lazily — no need to call session_start().

Lifecycle

Method Returns Description
Ses::destroy() void Destroy the session
Ses::regenerate() bool Regenerate session ID (call after login)
Ses::id() string Current session ID

Data

Method Returns Description
Ses::get(string $key, $default) mixed Get session value
Ses::set(string $key, $value) void Set session value
Ses::has(string $key) bool True if key exists
Ses::delete(string $key) void Delete a session key
Ses::all() array All non-internal session data

Flash

Method Returns Description
Ses::flash(string $key, $value) void Store a one-time value
Ses::pop(string $key, $default) mixed Read and remove a flash value

CSRF

Method Returns Description
Ses::csrf() string Get (or generate) CSRF token
Ses::verifyCsrf(string $token) bool Verify a submitted CSRF token

Url — URLs

Method Returns Description
Url::parse(string $url, int $component) string|null Extract URL component (PHP_URL_* constants)
Url::query(array $params) string Build a query string
Url::join(string ...$parts) string Join URL segments, collapse duplicate slashes
Url::withQuery(string $url, array $params) string Append query string to URL
Url::isAbsolute(string $url) bool True if URL has a scheme
Url::encode(string $s) string urlencode (spaces → +)
Url::decode(string $s) string urldecode
Url::rawEncode(string $s) string rawurlencode (spaces → %20, RFC 3986)
Url::rawDecode(string $s) string rawurldecode
Url::base64Encode(string $data) string URL-safe base64 encode
Url::base64Decode(string $data) string URL-safe base64 decode

V — Validation

All methods return bool. Use V::check() to collect errors across multiple fields.

Presence

Method Description
V::required($value) True if non-empty (not null, not '', not [])
V::blank($value) True if empty — opposite of required

Format

Method Description
V::email(string $value) Valid email address
V::url(string $value) Valid URL
V::numeric($value) Numeric value
V::integer($value) Valid integer
V::alpha(string $value) Letters only (Unicode-aware)
V::alphanumeric(string $value) Letters and numbers only
V::date(string $value) Parseable date string
V::match(string $value, string $pattern) Matches regex

Length & Range

Method Description
V::minLength($value, int $min) String at least N characters
V::maxLength($value, int $max) String at most N characters
V::min($value, $min) Number >= min
V::max($value, $max) Number <= max
V::between($value, $min, $max) Number within range

Comparison

Method Description
V::in($value, array $options) Strict match against allowed values
V::same($a, $b) Identical values (===) — for password confirm
V::accepted($value) Truthy toggle (true/1/yes/on)

Collecting errors

$errors = V::check([
    'email' => [
        [V::required($email), 'Email is required'],
        [V::email($email),    'Invalid email address'],
    ],
    'name' => [
        [V::required($name),     'Name is required'],
        [V::minLength($name, 2), 'Name too short'],
    ],
]);

if ($errors) {
    throw new \Phlat\Exceptions\ValidationException($errors);
}

V::check() returns a [field => message] array of failing fields only. Evaluation stops at the first failure per field.