softproidea / php-helpers
Framework-agnostic PHP helpers: IDs and OTPs, dates and time ranges, geo and geofencing, tiered pricing, phone numbers and strings.
Requires
- php: ^8.1
- ext-mbstring: *
Requires (Dev)
- phpoffice/phpspreadsheet: ^5.12
- phpunit/phpunit: ^10.5
Suggests
- phpoffice/phpspreadsheet: Required to use Softproidea\PhpHelpers\Excel\SheetReader
Provides
None
Conflicts
None
Replaces
None
README
Framework-agnostic PHP 8.1+ helpers with no runtime dependencies besides ext-mbstring.
composer require softproidea/php-helpers
All classes are final with static methods, in the Softproidea\PhpHelpers namespace:
use Softproidea\PhpHelpers\{Ids, Dates, TimeRange, Geo, Pricing, Phone, Str};
| 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 |
Ids::uuid(); // "3f2b8c1e-9a47-4d6b-8e0f-2c5a7d9b1e43" Ids::compactUuid(); // "3f2b8c1e9a474d6b8e0f2c5a7d9b1e43" Ids::token(8); // "9f86d081884c7d65" Ids::otp(); // "048213" Ids::reference('inv'); // "48213INV" Ids::sequence(42); // "000042" Ids::millis(); // 1796211378663
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 |
Dates::isValid('2026-02-30'); // false Dates::format('2026-12-02', 'd M Y'); // "02 Dec 2026" Dates::utcToLocal('2026-12-02 06:00:00', 'Asia/Colombo'); // "2026-12-02 11:30:00" Dates::localToUtc('2026-12-02 11:30:00', 'Asia/Colombo'); // "2026-12-02 06:00:00" Dates::convertTimezone('2026-12-02 09:00:00', 'Europe/London', 'Asia/Tokyo'); // "2026-12-02 18:00:00" Dates::isWeekend('2026-12-05'); // true Dates::isWithinRange('2026-12-01', '2026-12-31', '2026-12-31'); // true Dates::datesBetween('2026-12-01', '2026-12-15', 'monday'); // ["2026-12-07", "2026-12-14"] Dates::shiftMonth(2026, 12, 1); // ['year' => 2027, 'month' => 1, 'monthName' => 'January'] Dates::startOfMonth('2026-12-02'); // "2026-12-01" Dates::endOfMonth('2026-12-02'); // "2026-12-31" Dates::age('1996-01-01', '2026-06-01'); // 30 Dates::monthLabel('2026-03-10'); // "March-2026" Dates::monthLabel('2026-03-10', 'Commission-From'); // "Commission-From-March-2026" Dates::nextWeekday(['Monday', 'Thursday'], '2026-12-02'); // "2026-12-03"
monthDays() returns one array per day, handy for date strips and calendars:
Dates::monthDays(2026, 12, '2026-12-03')[2]; // [ // 'date' => '2026-12-03', 'day' => 3, 'dayName' => 'Thu', 'dayLetter' => 'T', // 'isToday' => false, 'isSelected' => true, 'isWeekend' => false, // ]
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 |
TimeRange::slots('09:00', '12:00'); // [['start' => '09:00', 'end' => '10:00'], ['start' => '10:00', 'end' => '11:00'], ['start' => '11:00', 'end' => '12:00']] TimeRange::slots('09:00', '10:30', 30); // three 30-minute slots TimeRange::hourlyLabels(8, 9); // [['key' => '08:00 AM', 'value' => '08:00 AM'], ['key' => '09:00 AM', 'value' => '09:00 AM']] TimeRange::addHours('23:00', 2); // "01:00" TimeRange::addMinutes('23:50', 20); // "00:10" TimeRange::overlaps('10:00', '12:00', '11:00', '13:00'); // true TimeRange::overlaps('10:00', '12:00', '12:00', '13:00'); // false TimeRange::overlaps('22:00', '02:00', '01:00', '03:00'); // true (crosses midnight) TimeRange::contains('09:00', '17:00', '10:00', '12:00'); // true TimeRange::minutesBetween('22:00', '02:00'); // 240 TimeRange::isWithin('23:30', '22:00', '02:00'); // true TimeRange::to12Hour('00:00'); // "12:00 AM" TimeRange::to24Hour('02:30 PM'); // "14:30" TimeRange::toMinutes('01:15'); // 75
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.
Geo::isValidCoordinate('6.9', '79.8'); // true Geo::isValidCoordinate(91, 0); // false Geo::parse('6.9271, 79.8612'); // [6.9271, 79.8612] Geo::parse('hello'); // null Geo::distanceMetres(6.9271, 79.8612, 6.9344, 79.8428); // ~2187.2 Geo::distanceKm(0, 0, 1, 0); // ~111.19 Geo::isWithinRadius(6.9275, 79.8615, 6.9271, 79.8612, 100); // true $fence = [ ['lat' => 6.9, 'lng' => 79.8], ['lat' => 6.9, 'lng' => 79.9], ['lat' => 7.0, 'lng' => 79.9], ]; Geo::isInsidePolygon(6.95, 79.88, $fence); // true Geo::isInsidePolygon(6.95, 79.88, json_encode($fence)); // true Geo::bearing(0, 0, 0, 1); // 90.0 (due east) Geo::destination(0, 0, 90, 1000); // ['lat' => 0.0, 'lng' => ~0.00899] Geo::boundingBox($fence); // ['minLat' => 6.9, 'minLng' => 79.8, 'maxLat' => 7.0, 'maxLng' => 79.9] Geo::centroid($fence); // ['lat' => ~6.9333, 'lng' => ~79.8667] Geo::pathLengthMetres([[0, 0], [1, 0], [2, 0]]); // ~222390.0
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.
$slabs = [ ['from' => 5, 'to' => 10, 'rate' => 80], ['from' => 10, 'to' => 20, 'rate' => 60], ]; Pricing::tiered(3, 5, 500, $slabs, 50); // 500.0 (within base) Pricing::tiered(8, 5, 500, $slabs, 50); // 740.0 (500 + 3 x 80) Pricing::tiered(15, 5, 500, $slabs, 50); // 1200.0 (500 + 5 x 80 + 5 x 60) Pricing::tiered(25, 5, 500, $slabs, 50); // 1750.0 (... + 5 x 50 extra) Pricing::applyDiscount(1000, 15); // ['original' => 1000.0, 'discount' => 150.0, 'final' => 850.0] Pricing::addPercent(100, 8); // ['base' => 100.0, 'charge' => 8.0, 'total' => 108.0] Pricing::percentOf(200, 12.5); // 25.0 Pricing::split(1000, 20); // ['share' => 200.0, 'remainder' => 800.0] Pricing::divide(10.00, 3); // [3.34, 3.33, 3.33] Pricing::parse('1,234.50'); // 1234.5 Pricing::parse('abc'); // null Pricing::format(1234.5); // "1,234.50" Pricing::format(1234.5, 2, ',', '.'); // "1.234,50" Pricing::round(2.456); // 2.46
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.
Phone::toE164('077 123 4567', '94'); // "+94771234567" Phone::toE164('+94 77 123 4567'); // "+94771234567" Phone::toE164('0094771234567'); // "+94771234567" Phone::toE164('94771234567', '+94'); // "+94771234567" Phone::toE164('abc'); // null Phone::isValidE164('+94771234567'); // true Phone::stripPrefix('tel:94771234567'); // "94771234567" Phone::mask('+94771234567'); // "+9477****567"
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? |
Str::firstName(' Jane Q. Doe '); // "Jane" Str::slug('Hello, World!'); // "hello-world" Str::truncate('Hello world', 6); // "Hello…" Str::maskEmail('jane.doe@example.com'); // "j******e@example.com" Str::isJson('{"a":1}'); // true Str::parseList("['mon', 'wed']"); // ["mon", "wed"] Str::parseList('a,b'); // ["a", "b"] Str::parseList('[]'); // [] Str::inListIgnoreCase('Unnamed Road', ['unnamed road', 'un-named road']); // true Str::startsWithAny('tel:94', ['sip:', 'tel:']); // true
Excel
Helpers for reading messy spreadsheets. Excel\Text has no dependencies. Excel\SheetReader needs
phpoffice/phpspreadsheet: composer require phpoffice/phpspreadsheet.
use Softproidea\PhpHelpers\Excel\{Text, SheetReader}; use PhpOffice\PhpSpreadsheet\IOFactory;
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 |
Text::title('net_profit-x'); // "Net profit x" Text::formatAmount('1234567.500'); // "1,234,567.5" Text::parseNumber('1,234'); // 1234 Text::hasDatePlaceholder('As at <DD/MM>'); // true Text::isTicked('✓'); // true
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.
$sheet = IOFactory::load('report.xlsx')->getSheetByName('Balance Sheet'); $reader = new SheetReader($sheet, ['dateFormat' => 'Y-m-d', 'precision' => 5, 'strict' => false]);
| 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.
$col = $reader->findHeaderColumn('net profit'); // 1 $row = $reader->findSectionStart('Assets', 3); // 10 $reader->value($row + 1, $col); // "99" $reader->valueBelowLabel(10, 'Total', 4); // value under the "Total" label
Development
composer install
composer test