Search by

Library of utilities

Package info

gitlab.com/zdenekgebauer/utils

pkg:composer/zdenekgebauer/utils

Statistics

Installs: 13

Dependents: 1

Suggesters: 0

Stars: 0

1.0.4 2026-11-29 11:23 UTC

This package is auto-updated.

Last update: 2026-11-29 10:25:11 UTC


README

PHP 8.4+ utility library. Static helper classes organized by domain — no instantiation needed.

Requirements

  • PHP >= 8.4
  • ext-fileinfo
  • ext-filter
  • ext-mbstring
  • optional ext-intl: internationalized domains in EmailValidator, transliteration in FileName::normalize()

Installation

composer require zdenekgebauer/utils

Namespaces

NamespaceClasses
ZdenekGebauer\Utils\Email\EmailValidator
ZdenekGebauer\Utils\Filesystem\Dir, FileName, Log
ZdenekGebauer\Utils\Html\Html, Url
ZdenekGebauer\Utils\Tree\Tree, NodeInterface
ZdenekGebauer\Utils\Vars\StringUtils, NumberUtils, PhoneUtils, Country, DateUtils, DateTimeUtc, DateTimeImmutableUtc, JsonUtils, Currency, Money, MoneyUtils

Email

EmailValidator

use ZdenekGebauer\Utils\Email\EmailValidator;

EmailValidator::isEmail('user@example.com');        // true
EmailValidator::isEmail('user@háčky.com');          // true (internationalized domain)
EmailValidator::isEmail('user@somewhere.香港');     // true
EmailValidator::isEmail('root@localhost');          // true (host without a dot)
EmailValidator::isEmail('.user@example.com');       // false
EmailValidator::isEmail('user@example.');           // false
EmailValidator::isEmail('ádresa@example.com');      // false
EmailValidator::isEmail('ádresa@example.com', allowUnicodeLocalPart: true); // true (needs SMTPUTF8 to deliver)

// Extract all valid emails from a string
EmailValidator::parseValidEmails('Send to foo@bar.com, baz@bar.com and invalid');
// => ['foo@bar.com', 'baz@bar.com']

// Domain in punycode, for servers without SMTPUTF8; needs ext-intl for an internationalized domain
EmailValidator::toAscii('user@háčky.com');          // 'user@xn--hky-ela4t.com'

With ext-intl an internationalized domain is checked against the IDNA rules; without it only its structure (letters, digits and inner hyphens in each label) is checked.

Filesystem

Dir

use ZdenekGebauer\Utils\Filesystem\Dir;

Dir::mkdir('/path/to/dir');                         // creates recursively if not exists
Dir::emptyRecursive('/path/to/dir');                // delete all contents
Dir::emptyRecursive('/path/to/dir', selfDelete: true); // also delete the directory itself

Both methods throw \RuntimeException when the operation fails.

FileName

Validates against the Windows rules, a superset of POSIX, so an accepted name works on either system.

use ZdenekGebauer\Utils\Filesystem\FileName;

FileName::isValid('žluťoučký.txt');                // true
FileName::isValid('a:b.txt');                      // false (forbidden character)
FileName::isValid('con.txt');                      // false (reserved device name)
FileName::isValid('file.');                        // false (Windows strips trailing dot and space)

FileName::normalize('Žluťoučký kůň?.JPG');         // 'Zlutoucky-kun.JPG'
FileName::normalize('Report–2026.pdf');            // 'Report-2026.pdf' (Unicode separators become a hyphen)
FileName::normalize('отчёт.pdf');                  // 'otcet.pdf' (needs ext-intl)
FileName::normalize('🎉.png');                     // \InvalidArgumentException: unreadable file name
FileName::normalize('CON.txt');                    // \InvalidArgumentException: reserved file name

normalize() returns an ASCII name of at most 255 bytes that passes isValid(). With ext-intl it transliterates any script (Any-Latin; Latin-ASCII); without it only Latin accents are replaced and other scripts are dropped.

Log

use ZdenekGebauer\Utils\Filesystem\Log;

// Rotate log: copy with timestamp suffix, truncate original, keep last 5 versions
Log::logrotate('/var/log/app.log', history: 5);

Html

Html

use ZdenekGebauer\Utils\Html\Html;

Html::escape('<script>');                           // '&lt;script&gt;'
Html::checked(true);                               // ' checked'
Html::checked(true, xhtml: true);                  // ' checked="checked"'
Html::disabled(false);                             // ''
Html::selected(true);                              // ' selected'
Html::hidden(true);                                // ' hidden'

Html::options(['a' => 'Apple', 'b' => 'Banana'], selectedKey: 'a');
// => '<option value="a" selected>Apple</option><option value="b">Banana</option>'
Html::options([0 => 'No', 1 => 'Yes'], selectedKey: '1');   // keys compared as strings, 1 matches '1'
Html::options([0 => 'No', 1 => 'Yes']);                     // nothing selected, key 0 does not match null

Html::shrinkHtml('<p>  hello  </p>');              // removes extra whitespace between tags
Html::stripHtml('<b>Hello</b> <script>bad()</script>'); // 'Hello'
Html::stripInvisibleTags('<p>a</p><script>x()</script>'); // '<p>a</p> ' (head, style, script, object, noscript…)
Html::addLineBreaks('<p>a</p><div>b</div>');       // line break before and after each block tag
Html::html2Text($htmlString);                      // converts HTML to plain text, preserving table structure
Html::textToHtml("a < b\nc");                      // "a &lt; b<br />\nc"

Url

use ZdenekGebauer\Utils\Html\Url;

Url::queryUrl('https://example.com', ['page' => 2, 'q' => 'foo']);
// => 'https://example.com?page=2&q=foo'

Url::toDataUri('/path/to/image.png');              // 'data:image/png;base64,...'

Url::urlToAbs('<img src="img/logo.png">', 'https://example.com/');
// => '<img src="https://example.com/img/logo.png">'

Url::removeAbsUrl($html, 'https://example.com');  // strips base URL from src/href

Tree

Requires nodes implementing NodeInterface (getId(): int, getParentId(): int). Root nodes have getParentId() === 0.

use ZdenekGebauer\Utils\Tree\Tree;
use ZdenekGebauer\Utils\Tree\NodeInterface;

$tree = new Tree($nodes);

$tree->children(parentId: 5);                     // direct children of node 5
$tree->getAllChildren(nodeId: 5);                  // all descendants recursively
$tree->getNodeById(id: 5);                        // ?NodeInterface
$tree->getParents(nodeId: 5);                     // ancestor nodes up to root
$tree->getNodes();                                 // all nodes

Vars

StringUtils

use ZdenekGebauer\Utils\Vars\StringUtils;

StringUtils::maxLength('hello world', 5);          // 'hello'
StringUtils::strlen('příliš');                     // 6 (multibyte-aware)
StringUtils::substr('příliš žluťoučký', 6, 4);    // ' žlu'
StringUtils::removeAccents('Příliš Žluťoučký');    // 'Prilis Zlutoucky'
StringUtils::slugify('Příliš žluťoučký kůň');      // 'prilis-zlutoucky-kun'
StringUtils::keywords('the quick brown fox', minLength: 4); // ['quick', 'brown']
StringUtils::perex('Long text here...', length: 10, suffix: '…');
StringUtils::randomString(length: 16);             // random alphanumeric string
StringUtils::strPadCut('abc', 5, '0');             // 'abc00'

NumberUtils

use ZdenekGebauer\Utils\Vars\NumberUtils;

NumberUtils::floatval('1 234,56');                 // 1234.56 (handles comma, space, nbsp, &#8239;)
NumberUtils::floatvalPositive(-5.0);               // 0.0
NumberUtils::intval('1,234');                      // 1234
NumberUtils::intvalPositive(-3);                   // 0
NumberUtils::filterIntPositive([-1, 0, 2, 5]);     // [2, 5]
NumberUtils::formatIso(1234567.89, decimals: 2);   // '1 234 567.89'
NumberUtils::humanFilesize(1_048_576);             // '1.00 MiB'
NumberUtils::humanFilesize(1_000_000, decimalSuffix: true); // '1.00 MB'
NumberUtils::bytesFromSuffix('8M');                // 8388608
NumberUtils::bytesFromSuffix('8MB');               // 0 (unparseable)
NumberUtils::iniBytes('upload_max_filesize');      // php.ini value in bytes

PhoneUtils

Supported countries: AT, CZ, DE, HU, PL, SK.

Intentionally simple: it checks the digit count only, not number ranges or types, and knows no other countries. For full parsing, validation and formatting of any number worldwide use giggsey/libphonenumber-for-php, a port of Google's libphonenumber.

use ZdenekGebauer\Utils\Vars\PhoneUtils;

PhoneUtils::isValid('+420 777 123 456', 'CZ', needCountryCode: true);  // true
PhoneUtils::getCountryPrefix('CZ');                // '420'
PhoneUtils::toCondensed('+420 777 123 456');       // '420777123456'
PhoneUtils::toE164Format('777 123 456', 'CZ');     // '+420777123456'
PhoneUtils::toE164Format('030 1234567', 'DE');     // '+49301234567' (national trunk prefix removed)
PhoneUtils::toE164Format('00420 777 123 456', 'SK'); // '+420777123456' (already international)
PhoneUtils::toE164Format('612345678', 'FR');       // \InvalidArgumentException: unsupported country
PhoneUtils::toLocalFormat('420777123456');          // '420 777 123 456' (digits in triplets)
PhoneUtils::toLocalFormat('+420777123456', 'CZ');   // '777 123 456'
PhoneUtils::toLocalFormat('+421905123456', 'SK');   // '0905 123 456'
PhoneUtils::toLocalFormat('+36301234567', 'HU');    // '06 30 123 4567'
PhoneUtils::toLocalFormat('+49301234567', 'DE');    // '0301234567' (area code length unknown, not split)
PhoneUtils::toLocalFormat('+49301234567', 'CZ');    // '+49301234567' (foreign number stays in E.164)

A number starting with + or 00 is international and keeps its own country prefix; otherwise it is treated as national for the given country.

Country

Backed enum of European ISO 3166-1 alpha-2 codes, the case name equals its value.

use ZdenekGebauer\Utils\Vars\Country;

Country::from('CZ');                               // Country::CZ
Country::tryFrom('cz');                            // null, codes are upper case

Currency / Money / MoneyUtils

Currency is a backed enum (string) with cases: BTC, CHF, CZK, DKK, EUR, GBP, HUF, NOK, PLN, SEK, UAH, USD.

Money is an immutable value object holding an integer amount in subunits (e.g. cents) and a Currency.

use ZdenekGebauer\Utils\Vars\Currency;
use ZdenekGebauer\Utils\Vars\Money;
use ZdenekGebauer\Utils\Vars\MoneyUtils;

$currency = Currency::EUR;
$currency->symbol();                               // '€'
$currency->symbolBefore();                         // true
$currency->defaultDecimals();                      // 2
$currency->subunitCoefficient();                   // 100

// Amount is always stored in subunits (cents, satoshi, etc.)
$price = new Money(amount: 1999, currency: Currency::CZK); // 19.99 Kč

MoneyUtils::normalizeAmount('19,99', Currency::CZK);       // 1999 (float → subunits)
MoneyUtils::formatAmount($price);                          // '19.99'
MoneyUtils::formatAmount($price, forceDecimals: 0);        // '20'
MoneyUtils::formatAmount($price, decimalSeparator: ',', thousandsSeparator: ' '); // '19,99'
MoneyUtils::formatCurrency($price);                        // '19.99 Kč'
MoneyUtils::formatCurrency(new Money(500, Currency::EUR)); // '€5.00'

MoneyUtils::formatCurrencyTemplate($price);
// => '<span data-amount>19.99</span> <span data-currency>Kč</span>'
MoneyUtils::formatCurrencyTemplate($price, template: '{amount} {symbol}'); // '19.99 Kč'

DateUtils

use ZdenekGebauer\Utils\Vars\DateUtils;

DateUtils::format($dateTime, 'Y-m-d');             // '' if null, formatted string otherwise
DateUtils::toDateTime('15.3.2025');                // DateTimeImmutable|null
DateUtils::isTimeValid('13:45');                   // true
DateUtils::minutesToFormat(90);                    // '01:30'
DateUtils::minutesToFormat(90, 'h:n');             // '1:30'
DateUtils::timeToArray('13:45:30');                // [13, 45, 30]
DateUtils::withTime($date, 12, 0, 0);              // DateTimeImmutable with time set
DateUtils::withTimezone($dateTime, 'Europe/Prague'); // DateTimeImmutable|null
DateUtils::withTimezoneUtc($dateTime);             // DateTimeImmutable|null
DateUtils::getDateImmutable($mutableDate);         // DateTimeImmutable|null
DateUtils::getDateMutable($immutableDate);         // DateTime|null

DateTimeUtc / DateTimeImmutableUtc

Drop-in replacements for DateTime / DateTimeImmutable that always use UTC timezone.

use ZdenekGebauer\Utils\Vars\DateTimeUtc;
use ZdenekGebauer\Utils\Vars\DateTimeImmutableUtc;

$now = new DateTimeUtc();                          // mutable, UTC
$now = new DateTimeImmutableUtc();                 // immutable, UTC
$specific = new DateTimeImmutableUtc('2025-01-15 10:00:00');

JsonUtils

use ZdenekGebauer\Utils\Vars\JsonUtils;

$obj = JsonUtils::decodeObject('{"key":"value"}');         // stdClass, empty stdClass on error
$obj = JsonUtils::decodeObject('[1,2]');                   // stdClass with keys "0", "1"
$obj = JsonUtils::decodeObject('123');                     // empty stdClass, JSON is not an object
$obj = JsonUtils::decodeObject('invalid', throwOnError: true); // throws JsonException

$json = JsonUtils::encodeObject($stdClass);                // string, '' on error
$json = JsonUtils::encodeObject($stdClass, throwOnError: true); // throws JsonException

Changelog

See CHANGELOG.md. Version 1.0.2 breaks the API of 1.0.1, check it before upgrading.

License

MIT, see LICENSE.