Download the PHP package softproidea/php-helpers without Composer
On this page you can find all versions of the php package softproidea/php-helpers. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download softproidea/php-helpers
More information about softproidea/php-helpers
Files in softproidea/php-helpers
Package php-helpers
Short Description Framework-agnostic PHP helpers: IDs and OTPs, dates and time ranges, geo and geofencing, tiered pricing, phone numbers and strings.
License MIT
Informations about the package php-helpers
php-helpers
Framework-agnostic PHP 8.1+ helpers with no runtime dependencies besides ext-mbstring.
All classes are final with static methods, in the Softproidea\PhpHelpers namespace:
| Class | Purpose |
|---|---|
Ids |
UUIDs, tokens, OTPs, references |
Dates |
validation, timezones, ranges, month calendars |
TimeRange |
times of day, slots, overlap checks |
Geo |
distance, geofencing, bearings, bounding boxes |
Pricing |
tiered pricing, discounts, splits, formatting |
Phone |
E.164 normalisation and masking |
Str |
names, slugs, masking, list parsing |
Excel\Text |
clean and format spreadsheet text, amounts, ticks, date placeholders |
Excel\SheetReader |
find rows and columns, read typed cell values (needs PhpSpreadsheet) |
Invalid input throws \InvalidArgumentException unless a method says it returns null or false.
Ids
All random values come from a CSPRNG (random_bytes / random_int).
| Method | Returns | Description |
|---|---|---|
Ids::uuid() |
string |
RFC 4122 v4 UUID with dashes |
Ids::compactUuid() |
string |
UUID without dashes (32 hex chars) |
Ids::token(int $bytes = 16) |
string |
Random hex string, $bytes * 2 characters long |
Ids::otp(int $length = 6) |
string |
Numeric one-time code. Leading zeros are possible, so it is a string |
Ids::reference(string $suffix = '', int $digits = 5) |
string |
Random digits plus an upper-cased suffix. Not guaranteed unique |
Ids::sequence(int $number, int $width = 6) |
string |
Zero-padded number |
Ids::millis() |
int |
Current Unix time in milliseconds |
Dates
Built on native DateTimeImmutable, no Carbon needed. Any date argument accepts a string, a Unix timestamp (int) or a DateTimeInterface.
Constants: Dates::MONTHS (January to December) and Dates::WEEKDAYS (Monday to Sunday).
| Method | Returns | Description |
|---|---|---|
parse($value, string $timezone = 'UTC') |
DateTimeImmutable |
Parse a string, timestamp or date object. Throws if it can't be parsed |
now(string $timezone = 'UTC') |
DateTimeImmutable |
Current time in a zone |
today(string $timezone = 'UTC', string $format = 'Y-m-d') |
string |
Today's date in a zone |
isValid(mixed $value, string $format = 'Y-m-d') |
bool |
Strict check. 2026-02-30 is rejected, non-strings return false |
format($value, string $format = 'Y-m-d') |
string |
Format any date value |
convertTimezone($value, string $from, string $to, string $format = 'Y-m-d H:i:s') |
string |
Convert between zones. Plain strings are read in $from |
utcToLocal($value, string $timezone, string $format = ...) |
string |
Shortcut for UTC to a zone |
localToUtc($value, string $timezone, string $format = ...) |
string |
Shortcut for a zone to UTC |
secondsSince($from, ?DateTimeInterface $now = null) |
int |
Seconds elapsed. Negative if $from is in the future |
isWeekend($date) |
bool |
Saturday or Sunday |
isWithinRange($from, $to, $date = null, string $timezone = 'UTC') |
bool |
Inclusive range check. $date defaults to today |
datesBetween($start, $end, ?string $weekday = null) |
string[] |
Every Y-m-d from start to end inclusive, optionally one weekday (case-insensitive) |
monthDays(int $year, int $month, ?string $selectedDate = null, string $timezone = 'UTC') |
array |
One entry per day, see below |
shiftMonth(int $year, int $month, int $by = 0) |
array |
Move forwards or backwards by months, no day overflow |
startOfMonth($date) |
string |
First day of the month as Y-m-d |
endOfMonth($date) |
string |
Last day of the month as Y-m-d |
age($birthDate, $on = null) |
int |
Whole years, as of today or $on |
monthLabel($date, string $prefix = '', string $separator = '-') |
string |
Label such as March-2026 |
nextWeekday(array $weekdays, $from = null) |
?string |
Next date (today excluded) that falls on one of the weekday names |
monthDays() returns one array per day, handy for date strips and calendars:
TimeRange
Times of day in H:i (24 hour) or hh:mm AM/PM format. End times are exclusive. A range whose end is at or before its start crosses midnight, so 22:00 to 02:00 is four hours. Invalid times throw.
| Method | Returns | Description |
|---|---|---|
slots(string $start, string $end, int $stepMinutes = 60) |
array |
Split a range into ['start' => .., 'end' => ..] slots. A partial last slot is dropped |
hourlyLabels(int $firstHour = 8, int $lastHour = 18) |
array |
12-hour labels as ['key' => .., 'value' => ..] for a booking UI. $lastHour is inclusive |
addHours(string $time, float $hours) |
string |
Add or subtract hours, wrapping at midnight |
addMinutes(string $time, int $minutes) |
string |
Add or subtract minutes, wrapping at midnight |
overlaps(string $startA, string $endA, string $startB, string $endB) |
bool |
Do the ranges share any time? Touching ends do not count |
contains(string $outerStart, string $outerEnd, string $innerStart, string $innerEnd) |
bool |
Does the inner range fit completely inside the outer one? |
minutesBetween(string $start, string $end) |
int |
Length of a range in minutes |
isWithin(string $time, string $start, string $end) |
bool |
Is a time inside [start, end)? |
to12Hour(string $time) |
string |
"14:30" to "02:30 PM" |
to24Hour(string $time) |
string |
"02:30 PM" to "14:30" |
toMinutes(string $time) |
int |
Minutes since midnight. Accepts both formats |
Geo
Points can be ['lat' => .., 'lng' => ..], ['latitude' => .., 'longitude' => ..] (lon also works) or [lat, lng]. Distances use the haversine formula on a spherical Earth (radius Geo::EARTH_RADIUS_METRES, 6,371,000 m), which is accurate to roughly 0.5%.
| Method | Returns | Description |
|---|---|---|
isValidCoordinate(mixed $lat, mixed $lng) |
bool |
Numeric, finite and within ±90 / ±180 |
parse(mixed $value) |
?array |
"lat,lng" string or point array to [float $lat, float $lng], or null |
distanceMetres(float $lat1, float $lng1, float $lat2, float $lng2) |
float |
Great-circle distance in metres |
distanceKm(float $lat1, float $lng1, float $lat2, float $lng2) |
float |
Same, in kilometres |
isWithinRadius(float $lat, float $lng, float $centerLat, float $centerLng, float $radiusMetres) |
bool |
Is a point inside a circle? |
isInsidePolygon(float $lat, float $lng, array\|string $polygon) |
bool |
Geofence test. Polygon is a list of points or a JSON string. Open or closed rings work. Needs 3 or more valid points, otherwise false |
bearing(float $lat1, float $lng1, float $lat2, float $lng2) |
float |
Compass bearing from point 1 to 2 (0 to 360, 0 is north) |
destination(float $lat, float $lng, float $bearingDegrees, float $distanceMetres) |
array |
['lat' => .., 'lng' => ..] after travelling that far on that bearing |
boundingBox(array $points) |
?array |
['minLat', 'minLng', 'maxLat', 'maxLng'], or null if no valid points |
centroid(array $points) |
?array |
Average point ['lat' => .., 'lng' => ..], or null. Fine for city-sized areas |
pathLengthMetres(array $points) |
float |
Total length of a path through the points |
Invalid points inside a list are skipped. Points exactly on a polygon edge may count as inside or outside.
Pricing
Amounts are floats rounded to 2 decimals. For accounting-grade precision pass results into a money library.
| Method | Returns | Description |
|---|---|---|
tiered(float $distance, float $baseDistance, float $basePrice, array $slabs = [], float $extraRate = 0.0) |
float |
Distance-based price, see below |
applyDiscount(float $price, float $percent) |
array |
['original', 'discount', 'final']. Percent must be 0 to 100 |
addPercent(float $amount, float $percent) |
array |
['base', 'charge', 'total'], for tax or service charges |
percentOf(float $amount, float $percent) |
float |
A percentage of an amount |
split(float $amount, float $sharePercent) |
array |
['share', 'remainder'] that always add up to the amount |
divide(float $amount, int $parts) |
float[] |
Equal parts in cents. Leftover cents go to the first parts |
parse(string $value) |
?float |
"1,234.50" to 1234.5, or null if not a number |
format(float $amount, int $decimals = 2, string $decimalSeparator = '.', string $thousandsSeparator = ',') |
string |
Display format |
round(float $amount, int $decimals = 2) |
float |
Round half away from zero |
tiered() rules
- Up to
$baseDistancethe price is$basePrice. - Each slab (
['from' => .., 'to' => .., 'rate' => ..]) charges its rate for the part of the distance inside[from, to]. Bounds are absolute distances, not relative to the base. Slabs may be in any order. - Anything past the last slab is charged at
$extraRateper unit. - A negative distance throws.
Phone
Normalises format only. It does not know which numbers are assigned, so for full validation use giggsey/libphonenumber-for-php.
| Method | Returns | Description |
|---|---|---|
toE164(string $number, string $defaultCountryCode = '') |
?string |
Normalise to +<digits>. Returns null if the result isn't a plausible E.164 number |
isValidE164(string $number) |
bool |
+, then 7 to 15 digits, not starting with 0 |
stripPrefix(string $number, string $prefix = 'tel:') |
string |
Remove a prefix such as tel: if present |
mask(string $number, int $visibleStart = 5, int $visibleEnd = 3, string $maskChar = '*') |
string |
Hide the middle digits |
toE164() handles +94 77 123 4567, 0094771234567, national format with a leading 0 (uses the default country code), and numbers that already start with the country code.
Str
| Method | Returns | Description |
|---|---|---|
firstName(string $fullName) |
string |
First word of a name, or '' |
slug(string $text, string $separator = '-') |
string |
URL-friendly lowercase slug. Accents are transliterated when iconv supports it |
truncate(string $text, int $limit, string $suffix = '…') |
string |
Shorten to $limit characters including the suffix (multibyte-safe) |
maskEmail(string $email) |
string |
Hide the middle of the local part |
isJson(string $text) |
bool |
Is it valid JSON? Empty string is false |
parseList(string $value) |
string[] |
Parse a,b,c, ['a', 'b'] or ["a","b"]. Handy for env values |
inListIgnoreCase(string $value, array $list) |
bool |
Case-insensitive, trimmed membership test |
startsWithAny(string $text, array $prefixes) |
bool |
Does the text start with any non-empty prefix? |
Excel
Helpers for reading messy spreadsheets. Excel\Text has no dependencies. Excel\SheetReader needs
phpoffice/phpspreadsheet: composer require phpoffice/phpspreadsheet.
Excel\Text
| Method | Returns | Description |
|---|---|---|
Text::clean(?string $text) |
string |
Fix non-breaking spaces, line breaks, �, ’ and ❌, then trim |
Text::collapse(?string $text) |
string |
clean() plus runs of whitespace collapsed to one space |
Text::capitalizeFirst(?string $text) |
?string |
Trim and upper-case the first character. Blank input is returned unchanged |
Text::title(?string $title) |
?string |
_ and - become spaces, cleaned and capitalised. Text containing [A-B] is returned as is |
Text::isNumeric(?string $text) |
bool |
Is the text a number? ("1,000" is not) |
Text::toFloat(mixed $value) |
float |
Lenient float, 0.0 for anything that isn't a number. Commas are removed |
Text::parseNumber(?string $value) |
int\|float\|string |
"1,234.5" gives 1234.5. Empty or - gives "-". Other text is returned unchanged |
Text::formatAmount(string\|int\|float\|null $value) |
?string |
Thousands separators, up to 16 decimals, trailing zeros removed. Numeric strings stay exact |
Text::numberToString(float $number, int $precision = 5) |
string |
Plain string, never scientific notation, whole numbers lose decimals |
Text::isTicked(?string $value, string $pattern = ...) |
bool |
√ ✓ ✔ v a yes y true, case-insensitive. Pass your own regex to change what counts |
Text::hasDatePlaceholder(?string $title) |
bool |
true if a heading still has <DD/MM>, [YEAR], ....., M/Y, a trailing as at and so on |
Text::isAllowedSheetName(?string $name, array $allowed) |
bool |
Case-insensitive, trimmed |
Excel\SheetReader
Wrap one worksheet. Rows and columns are zero-based (row 0 is Excel row 1, column 0 is column A) and "not found" is -1 or null.
| Option | Default | Description |
|---|---|---|
dateFormat |
m/d/Y |
PHP date format for date cells |
precision |
5 |
Decimals kept when reading numbers |
strict |
false |
true throws \RuntimeException (with sheet, row and column) for unreadable cells instead of returning "ERROR" |
| Method | Returns | Description |
|---|---|---|
text(int $row, int $col) |
string |
Cell as Excel displays it (number formats applied), whitespace cleaned |
value(int $row, int $col) |
string |
Typed value as a clean string: dates formatted, numbers rounded, formulas calculated, booleans true/false, Excel errors become "ERROR" |
date(int $row, int $col) |
?DateTimeImmutable |
Date cell, or null if empty or not a date |
columnHeader(int $col, int $headerRow = 0) |
string |
"Net Profit" gives "NET_PROFIT", or COLUMN_<n> if empty |
isEmptyRow(int $row) |
bool |
No non-blank cell on the row |
firstValueInRow(int $row, int $startCol = 0) |
?string |
First non-empty value from $startCol |
findColumn(string $text, int $fromRow = 0, ?int $toRow = null, string $mode = CONTAINS) |
int |
Column of the first matching cell |
findHeaderColumn(string $text, int $headerRows = 5, string $mode = CONTAINS) |
int |
Same, limited to the first rows |
findRow(string $text, int $fromRow = 0, ?int $maxCol = null, string $mode = CONTAINS) |
int |
Row of the first matching cell |
findSectionStart(string $sectionName, int $maxCol) |
int |
Row where a named section starts |
findNextSectionRow(int $startRow, string $prefix, int $col = 0) |
int |
Next row whose cell starts with $prefix, or last row + 1 if none |
valueBelowLabel(int $startRow, string $label, int $col) |
?string |
Find a label within 10 rows, return the value directly under it |
lastRow() / lastColumn(int $row) |
int |
Index of the last row with data / last column on a row |
sheet() |
Worksheet |
The wrapped worksheet |
Match modes (constants on SheetReader): CONTAINS (default), STARTS_WITH, EXACT. All are case-insensitive and ignore surrounding spaces.
Development
All versions of php-helpers with dependencies
ext-mbstring Version *