Toolkit Reference
Static utility classes to use instead of raw PHP functions.
All Toolkit classes live in Phlat\Toolkit\ and are static-only. Import with use Phlat\Toolkit\Str; and call Str::slug(...). Prefer them to raw PHP functions: if a utility is missing, it belongs here.
Method lists show parameters only where they aren't obvious.
Arr: arrays
- Inspect:
isEmpty,count,has($a, $value, $strict),hasKey,first,last - Extract:
keys,values,take($a, $n),slice($a, $offset, $length),chunk($a, $size),pluck($a, $key) - Transform:
map,filter(re-indexed),partition(returns[matches, rest]),reduce($a, $fn, $initial),unique,reverse,flip,flatten(one level) - Search:
find($a, $fn)(first match or null),findKey($a, $fn) - Sort:
sort($a, $flags),sortBy($a, $fn) - Combine:
keyBy($a, $fn),merge(...$arrays)(later wins),mergeRecursive,prepend,append,only($a, $keys),except($a, $keys)
Str: strings
Unicode-aware via mb_*.
- Inspect:
length,isEmpty,startsWith($s, $prefix, $ci),endsWith,contains(case-insensitive by default) - Extract:
before($s, $needle),after,between($s, $start, $end),substr($s, $start, $length) - Case and shape:
lower,upper,title,camel,snake,slug($s, $sep) - Truncate:
truncate($s, $len, $suffix)(the suffix counts toward the limit),words($s, $count, $suffix) - Trim:
trim($s, $chars),trimStart,trimEnd,removeStart($s, $prefix),removeEnd - Replace:
replace,replaceFirst,replaceLast,translate($s, $map)([search => replace]) - Split:
split($s, $delimiter, $limit),join($parts, $glue),lines(on\nor\r\n),match($pattern, $subject, &$matches)
F: files
- Inspect:
exists,isReadable,isWritable,size(bytes),modified(Unix timestamp) - Path:
name(with extension),stem,extension(no dot),directory,resolve(...$paths)(first path that resolves to a real file, or null) - Read and write:
read,write($path, $contents),append. All throw on failure. - Operate:
copy($source, $dest),move,delete,symlink($target, $link),isLink,mime
Dir: directories
- Inspect:
exists,isEmpty,isReadable,isWritable - Path:
name,parent($path, $levels),resolve(follows symlinks; null if not found) - Contents:
list(entry names),files(full paths of files directly inside),directories(full paths of subdirectories directly inside) - Operate:
make($path, $permissions)(recursive, idempotent),delete(empty directory),deleteRecursive,move
Dt: dates and times
Returns DateTimeImmutable.
- Create:
now($timezone),parse($value, $tz),fromTimestamp - Format:
format($dt, $format),ago($dt)("3 minutes ago"),timestamp - Compare:
diff($a, $b)(aDateInterval),isBefore,isAfter
Hash: hashing and tokens
| Method | Description |
|---|---|
password($value) / verify($value, $hash) |
Bcrypt hash / check |
random($bytes) |
Secure random hex string |
uuid() |
Random UUID v4 |
equals($a, $b) |
Timing-safe comparison |
md5($value) / sha256($value) |
Hex digest |
Json
All throw \JsonException on failure, except valid.
encode($data, $pretty), decode (to an associative array), valid, decodeArray($json, $default) (the default for invalid JSON or a non-array result).
Num: numbers
- Format:
format($n, $decimals, $point, $thousands),currency($amount, $symbol, $decimals)($1,234.56),percent($value, $decimals)(12.5%),bytes(1.2 MiB) - Math:
round($value, $precision),floor,ceil,abs,clamp($value, $min, $max),min,max,random($min, $max)(secure)
Res: HTTP responses
| Method | Description |
|---|---|
code(int $code) |
Set the response code |
header($name, $value) / hasHeader($name) |
Set a header / check one was set |
redirect($url, $code = 302) |
Redirect and exit |
html($body, $code = 200) |
Send an HTML body and exit |
json($data, $code = 200) |
Send JSON and exit |
text($body, $code = 200) |
Send text/plain and exit |
redirect, html, json and text exit immediately, so nothing after them runs. HTMX headers are on Hx.
Hx: HTMX responses
Sets HTMX response headers. In Latte, hx is a global alias: {do hx::retarget(...)}.
| Method | Header | Notes |
|---|---|---|
navigate($url) |
HX-Redirect |
Full-page navigation. Exits |
location($url) |
HX-Location |
Client-side redirect, no full reload. Exits |
refresh() |
HX-Refresh |
Full page refresh. Exits |
pushUrl($url) |
HX-Push-Url |
|
replaceUrl($url) |
HX-Replace-Url |
|
trigger(array $events, ?$target) |
HX-Trigger |
Pass $target (a CSS selector) when the requesting element may be gone by the time the event fires |
retarget($selector) |
HX-Retarget |
|
reswap($strategy) |
HX-Reswap |
|
reselect($selector) |
HX-Reselect |
San: sanitization
- Strings:
text(trim and strip tags),html(escape for output),filename - Scalars:
intandfloat(null if not numeric),bool(accepts true/1/yes/on) - Network:
email(lowercased; null if invalid),url(null if invalid)
Ses: raw sessions
A wrapper over $_SESSION that starts the session lazily. It knows nothing of login, flash semantics or CSRF; those are on the Session service below.
- Lifecycle:
start,isActive,close(writes and releases the lock),destroy,regenerate(call after login),id - Data:
get,set,ensure($key, $value)(get, setting a default first if missing),has,delete,all(non-internal data) - Flash:
setFlash,getFlash(doesn't remove it),deleteFlash
Session: the request-scoped service
$app->session (Phlat\Session, an instance rather than a static class) is the API most code should use: get, set, has, delete, flash/pop, csrf/verifyCsrf/requireCsrf, login/logout/isLoggedIn/requireLogin/user, can/requirePermission, and isThrottled/throttle. See the CSRF example in Latte Templates and the guard example in Routing.
Url
- Parse and build:
parse($url, $component)(aPHP_URL_*constant),query($params),join(...$parts)(collapses duplicate slashes),withQuery($url, $params),isAbsolute - Encode:
encode/decode(urlencode, spaces as+),rawEncode/rawDecode(rawurlencode, spaces as%20),base64Encode/base64Decode(URL-safe)
V: validation
All return bool.
- Presence:
required(not null,''or[]),blank - Format:
email,url,numeric,integer,alpha,alphanumeric(Unicode-aware),date,match($value, $pattern) - Length and range:
minLength,maxLength,min,max,between($value, $min, $max) - Comparison:
in($value, $options)(strict),same($a, $b)(===, for password confirm),accepted(true/1/yes/on)
V::check() collects errors across fields. It returns a [field => message] array of failing fields only, stopping at the first failure per field:
$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);
}
Other classes
No reference lists yet:
| Class | Covers |
|---|---|
Cli |
Terminal output and input for commands: messages, tables, progress, prompts |
Color |
Hex to rgb/hsl, lighten, darken, readable text contrast |
Db |
PDO connections and SQL execution, used by the registry |
Git / GitResult |
Runs git commands against a repository |
Http / HttpResponse |
Outbound HTTP requests and their responses |
Invoke |
Calls a callable, matching available values to its parameters by name |
Ser |
PHP serialize and unserialize |
Srv |
Read-only server and environment values: host, scheme, ip, headers |