pinkava / utils
Comprehensive PHP utility library providing type conversion, validation, formatting, and helper functions
Requires
- php: >=8.3
- nette/utils: ^4.0
Requires (Dev)
- ergebnis/composer-normalize: ^2.52
- nette/phpstan-rules: ^1.0
- nette/tester: ^2.5
- phpstan/extension-installer: ^1.4
- phpstan/phpstan-deprecation-rules: ^2.0
- phpstan/phpstan-nette: ^2.0
- phpstan/phpstan-strict-rules: ^2.0
- roave/security-advisories: dev-latest
- shipmonk/phpstan-rules: ^4.4
- spaze/phpstan-disallowed-calls: ^4.6
- spaze/phpstan-disallowed-calls-nette: ^3.0
- tomasvotruba/type-coverage: ^2.3
Suggests
- ext-intl: Converter\Scalar::processImportValueAs*() normalizes cells to NFC only with it, decomposed characters stay as they are without it
- tracy/tracy: Required for Sanitizer class to sanitize sensitive data
Provides
None
Conflicts
None
Replaces
None
README
A comprehensive PHP utility library providing type conversion, validation, formatting, and helper functions for modern PHP applications.
Requirements
- PHP 8.3 or higher
- nette/utils ^4.0
Installation
Install via Composer:
composer require pinkava/utils
Features
- Type Converters: Safe type conversions with strict typing
- Array Converters: Batch array transformations with type safety
- Date/Time Utilities: Date conversion and formatting
- Image Utilities: Data URI conversion for images
- Color Utilities: Color conversion and brightness adjustment
- Byte Converters: Human-readable file size conversions
- HTML Utilities: HTML attribute manipulation and tag conversion
- Text Validators: String validation helpers
- URL Validators: URL pattern matching and validation
- Localization: Simple static translator implementation
API Documentation
Converter\Scalar
Type conversion utilities for scalar values with strict type checking.
use Pinkava\Utils\Converter\Scalar;
// String conversions
Scalar::toString(123); // "123"
Scalar::toStringOrNull(""); // null
Scalar::toStringOrNull("hello"); // "hello"
// Integer conversions
Scalar::toInt("42"); // 42
Scalar::toInt(" 1.0 "); // 1
Scalar::toInt(""); // 0
Scalar::toInt("12abc"); // throws UnexpectedValueException (not a silent 12)
Scalar::toIntOrNull(""); // null
Scalar::toIntOrNull("42"); // 42
Scalar::toIntOrNull("abc"); // null (not a silent 0)
Scalar::toIntOrNull("1.5"); // null
Scalar::toIntOrNull("99999999999999999999"); // null (outside the int range)
// Boolean conversions
Scalar::toBool(1); // true
Scalar::toBool("false"); // false
Scalar::toBool(""); // false
Scalar::toBool("abc"); // throws UnexpectedValueException (not a silent true)
Scalar::toBoolOrNull(""); // null
Scalar::toBoolOrNull("1.0"); // true (a numeric string like the number)
Scalar::toBoolOrNull(" "); // null (whitespace only)
Scalar::toBoolOrNull("yes"); // true
Scalar::toBoolOrNull("abc"); // null (not a silent true)
// Float conversions
Scalar::toFloat("3.14"); // 3.14
Scalar::toFloat("1" . str_repeat("0", 400)); // throws UnexpectedValueException (out of the float range)
Scalar::toFloat("abc"); // throws UnexpectedValueException (not a silent 0.0)
Scalar::toFloatOrNull(""); // null
Scalar::toFloatOrNull("1,5"); // 1.5 (single decimal comma)
Scalar::toFloatOrNull("abc"); // null (not a silent 0.0)
Scalar::toFloatOrNull("1" . str_repeat("0", 400)); // null (not INF)
// Mixed conversions
Scalar::toStringOrInt("123"); // 123 (as int)
Scalar::toStringOrInt("abc"); // "abc" (as string)
Scalar::toStringOrIntOrNull(""); // null
// Import value processing (useful for CSV/Excel imports)
Scalar::processImportValueAsString(" text "); // "text"
Scalar::processImportValueAsInt(" 123 "); // 123
Scalar::processImportValueAsInt("1 234 567"); // 1234567
Scalar::processImportValueAsFloat("1.234,56"); // 1234.56 (Czech notation)
Scalar::processImportValueAsFloat("1,234.56"); // 1234.56 (English notation)
Scalar::processImportValueAsFloat("1.000"); // 1.0 (a single comma or dot is the decimal separator)
Scalar::processImportValueAsInt("12.03.2024"); // null (thousands groups must have 3 digits)
Scalar::processImportValueAsFloat("1,"); // null (trailing separator)
Converter\Arrays
Batch array transformations with type safety. Supports both single-level and multi-level arrays.
Only the values are converted, keys are kept as they are (PHP itself stores a numeric string key
such as "1" as int). The ...Multi methods convert nested arrays at any depth; the single-level
ones throw UnexpectedValueException on a nested array.
use Pinkava\Utils\Converter\Arrays;
// String conversions
$data = [1 => 123, 2 => 456];
Arrays::toString($data); // [1 => "123", 2 => "456"]
Arrays::toStringOrNull([1, ""]); // [0 => "1", 1 => null]
// Multi-level conversions (any depth)
$nested = ["key" => ["subkey" => ["deep" => 123]]];
Arrays::toStringMulti($nested); // ["key" => ["subkey" => ["deep" => "123"]]]
// Integer conversions
Arrays::toInt(["1", "2", "3"]); // [1, 2, 3]
Arrays::toInt(["a" => "1", "b" => "2"]); // ["a" => 1, "b" => 2] (keys kept)
Arrays::toIntList(["a" => "1", "b" => "2"]); // [1, 2] (list)
// Integer keys - a key that is not an integer, or that would collide ("007" and 7), throws
Arrays::toStringOrIntOrNullKeyInt(["1" => "5", "+2" => ""]); // [1 => 5, 2 => null]
Arrays::toStringOrIntOrNullKeyInt(["a" => 1]); // throws UnexpectedValueException
// Mixed conversions
Arrays::toStringOrInt(["123", "abc"]); // [123, "abc"]
Arrays::toStringOrIntOrNull(["123", ""]); // [123, null]
Arrays::toStringOrIntOrNullMulti([["1", ""], [2]]); // [[1, null], [2]]
Converter\Date
Date and time conversion utilities with type safety.
use Pinkava\Utils\Converter\Date;
// Convert to DateTimeImmutable
Date::toDateTimeImmutable("2024-03-01"); // DateTimeImmutable object
Date::toDateTimeImmutable(new DateTimeImmutable); // Returns same object
Date::toDateTimeImmutable(new DateTime); // Immutable copy
Date::toDateTimeImmutable("@1709251200"); // Unix timestamp
Date::toDateTimeImmutable(1709251200); // throws UnexpectedValueException (an int is ambiguous)
Date::toDateTimeImmutable("invalid"); // throws UnexpectedValueException
Date::toDateTimeImmutable("2023-02-29"); // throws UnexpectedValueException (no such date)
// Nullable conversions
Date::toDateTimeImmutableOrNull("2024-03-01"); // DateTimeImmutable object
Date::toDateTimeImmutableOrNull(null); // null
Date::toDateTimeImmutableOrNull(""); // null (not the current time)
Date::toDateTimeImmutableOrNull("invalid"); // null (graceful handling)
Date::toDateTimeImmutableOrNull("2023-02-29"); // null (not 2023-03-01)
Converter\Byte
Convert between human-readable file sizes and bytes. All units are binary (1024).
use Pinkava\Utils\Converter\Byte;
// Human to bytes - units k, M, G, T, P, E, optionally with "i" and/or "B", case-insensitive
Byte::human2byte("10k"); // 10240
Byte::human2byte("10K"); // 10240
Byte::human2byte("10kb"); // 10240
Byte::human2byte("10 KiB"); // 10240
Byte::human2byte("1,5MB"); // 1572864 (decimal comma or dot)
Byte::human2byte("1G"); // 1073741824
Byte::human2byte("10PB"); // 11258999068426240
Byte::human2byte("abc"); // throws InvalidArgumentException (also negative, overflowing)
Byte::human2byteOrNull("abc"); // null
// Bytes to human-readable
Byte::byte2human(1023); // "1023B"
Byte::byte2human(10240); // "10.00kB"
Byte::byte2human(10240, 0); // "10kB"
Byte::byte2human(1048576); // "1.00MB"
Byte::byte2human(1073741824, 1); // "1.0GB"
Byte::byte2human(-1536); // "-1.50kB"
Converter\Image
Convert base64 data URI strings to Nette Image objects.
use Pinkava\Utils\Converter\Image;
// Convert data URI to Image
$dataUri = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==";
$image = Image::fromDataUri($dataUri);
// Also accepted: upper-case "DATA:"/"BASE64", extra parameters and line-wrapped (MIME) base64
Image::fromDataUri("data:image/png;name=pixel.png;base64,iVBORw0KGgo...");
// Now you can use Nette\Utils\Image methods
$image->resize(100, 100);
$image->save("output.png");
Converter\Color
Color conversion and manipulation utilities with strict type safety.
use Pinkava\Utils\Converter\Color;
// Adjust brightness
Color::adjustBrightness('#808080', 0.5); // "#c0c0c0" (50% lighter)
Color::adjustBrightness('#808080', -0.5); // "#404040" (50% darker)
Color::adjustBrightness('#888', 1.0); // "#ffffff" (full brightness)
// Hex to RGB string
Color::hexToRgb('#ffffff'); // "255, 255, 255"
Color::hexToRgb('#ff5733'); // "255, 87, 51"
Color::hexToRgb('fff'); // "255, 255, 255" (without #)
// Hex to RGB array
Color::hexToRgbArray('#ff5733'); // ["r" => 255, "g" => 87, "b" => 51]
Color::hexToRgbArray('#888'); // ["r" => 136, "g" => 136, "b" => 136]
// RGB to Hex
Color::rgbToHex(255, 87, 51); // "#ff5733"
Color::rgbToHex(0, 0, 0); // "#000000"
// Validation
Color::isValidHex('#ffffff'); // true
Color::isValidHex('#fff'); // true
Color::isValidHex('invalid'); // false
Color::isValidHex('##fff'); // false (at most one '#')
Color::isValidHex("fff\n"); // false
// Get contrasting text color - black or white, whichever has the higher WCAG contrast ratio
Color::getContrastColor('#ffffff'); // "#000000" (black text on white)
Color::getContrastColor('#000000'); // "#ffffff" (white text on black)
Color::getContrastColor('#1DA1F2'); // "#000000" (black text on Twitter blue, 7.4:1 vs 2.8:1)
Color::getContrastColor('#3b5998'); // "#ffffff" (white text on Facebook blue)
Color::getContrastColor('#FFFC00'); // "#000000" (black text on yellow)
Formatter\Date
Format date ranges with smart year handling.
use Pinkava\Utils\Formatter\Date;
use DateTimeImmutable;
// Same day, different times - the year only when it is not the current year
$from = new DateTimeImmutable("2024-03-01 14:00");
$to = new DateTimeImmutable("2024-03-01 16:00");
Date::formatDateRange($from, $to); // "1. 3. 2024 14:00 - 16:00" ("1. 3. 14:00 - 16:00" in 2024)
// Different days, same year
$from = new DateTimeImmutable("2024-03-01 14:00");
$to = new DateTimeImmutable("2024-03-15 16:00");
Date::formatDateRange($from, $to); // "1. 3. 14:00 - 15. 3. 2024 16:00"
// Different years
$from = new DateTimeImmutable("2024-12-31 14:00");
$to = new DateTimeImmutable("2025-01-01 16:00");
Date::formatDateRange($from, $to); // "31. 12. 2024 14:00 - 1. 1. 2025 16:00"
// Only one date
Date::formatDateRange($from, null); // "31. 12. 2024 14:00"
Date::formatDateRange(null, null); // ""
$to is converted to the timezone of $from; an end earlier than the start throws InvalidArgumentException.
Checker\Text
Simple text validation helpers.
use Pinkava\Utils\Checker\Text;
// Check if string is filled (not null and not empty)
Text::isFilledString("hello"); // true
Text::isFilledString(""); // false
Text::isFilledString(null); // false
Html\Converter
Convert HTML tags to plain text representations.
use Pinkava\Utils\Html\Converter;
// Convert <br> tags to newlines, existing newlines are kept, entities are decoded afterwards
Converter::br2nl("Hello<br>World<br/>Test"); // "Hello\nWorld\nTest"
Converter::br2nl("A & B<br>\nC"); // "A & B\nC"
// Convert <p> tags to newlines
Converter::p2nl("<p>Paragraph 1</p><p>Paragraph 2</p>");
// "Paragraph 1\nParagraph 2"
The result of br2nl() is plain text (<script> becomes <script>) - escape it before printing it into HTML.
Html\Attribute
Extract and manipulate HTML attributes.
use Pinkava\Utils\Html\Attribute;
// Extract attribute value from HTML tag - whole names only, HTML entities decoded
$html = '<a data-href="x" href="https://example.com?a=1&b=2" class="link">Click</a>';
Attribute::getValue('href', $html); // "https://example.com?a=1&b=2"
Attribute::getValue('class', $html); // "link"
Attribute::getValue('id', $html); // null
// Insert attributes into HTML tags
$html = '<img src="photo.jpg"><img src="photo2.jpg">';
Attribute::insertToHtmlTag($html, 'img', 'class', 'responsive');
// '<img src="photo.jpg" class="responsive"><img src="photo2.jpg" class="responsive">'
// Add to existing attributes - whole tokens are compared, the rest of the HTML is kept as it is
$html = '<img src="photo.jpg" class="thumb">';
Attribute::insertToHtmlTag($html, 'img', 'class', 'responsive');
// '<img src="photo.jpg" class="responsive thumb">'
Attribute::insertToHtmlTag('<a class="btn-primary">', 'a', 'class', 'btn');
// '<a class="btn btn-primary">'
Html\Text
Blank checks and one-line text for HTML from a WYSIWYG editor.
use Pinkava\Utils\Html\Text;
Text::isBlank('<p><br></p>'); // true - what the editor leaves after deleting
Text::isBlank('<img src="a.jpg">'); // false - an image, video, svg, table or iframe is content
Text::isBlank('<!-- <img src="a.jpg"> -->'); // true - comments, scripts and styles are not content
Text::isInvisible("\u{A0}\u{200B}"); // true - spaces and zero-width characters only
Text::toLine('<p>First</p><p>Second</p>'); // 'First Second', null when nothing visible is left
Text::toHtml('Fish & chips'); // 'Fish & chips'
Text::stripInvisible("a\u{200B}b"); // 'ab'
Validator\Url
Regular expression patterns for URL validation. They contain no delimiters or anchors and only
syntax shared by PCRE and JavaScript, so they work in a Nette form Form::Pattern rule as well.
FacebookUrlPattern- optional protocol, optionalwww./m./mobile.subdomain and either a username (letters, digits and dots, at least 5 characters, not only dots) orprofile.php?id=<digits>InstagramNamePattern- 1-30 letters, digits, underscores and dots; dots neither at the start or end nor consecutive
use Pinkava\Utils\Validator\Url;
// Anchor the pattern yourself, \z so that a trailing newline does not match
if (preg_match('~^' . Url::FacebookUrlPattern . '\z~', $url) === 1) {
// Valid Facebook URL
}
// Nette Forms anchors the pattern on its own (server and client side)
$form->addText('instagram')
->addRule($form::Pattern, 'Invalid username', Url::InstagramNamePattern);
Validator\BirthNumber
Validation of Czech birth numbers (RRMMDD/CCCC; 9 digits before 1954, 10 digits from 1954).
use Pinkava\Utils\Validator\BirthNumber;
BirthNumber::isValid('780101/0008'); // true
BirthNumber::isValid('7801010020'); // true - check digit 0 for remainder 10 (up to 1985)
BirthNumber::isValid('800101/123'); // false - 9 digits are not issued from 1954
BirthNumber::isFemale('785101/0002'); // true (month + 50 or + 70)
BirthNumber::isExtendedSeries('0421010007'); // true (month + 20 or + 70, since 2004)
Validator\BankAccount
Validation of Czech bank account numbers ([prefix-]base/bankCode) with the bank list of the Czech National Bank.
use Pinkava\Utils\Validator\BankAccount;
BankAccount::isValid('19-2000145399/0800'); // true
BankAccount::isValid('19-2000145398/0800'); // false (checksum)
BankAccount::isValid('00/0800'); // false (base needs at least two nonzero digits)
BankAccount::isValid("19/0800\n"); // false (no whitespace, use Normalizer\BankAccount)
BankAccount::getBankName('19-2000145399/0800'); // "Česká spořitelna, a.s."
BankAccount::getBankName('2010'); // "Fio banka, a.s."
BankAccount::getBicCode('0800'); // "GIBACZPX"
BankAccount::getBankCode('19-2000145399/0800'); // "0800"
BankAccount::getPrefix('19-2000145399/0800'); // "19"
BankAccount::getBaseNumber('19-2000145399/0800'); // "2000145399"
BankAccount::getBanksList(); // ["0100" => "0100 - Komerční banka, a.s.", ...]
// The data itself, keyed by bank code
BankAccount::Banks['0800']; // "Česká spořitelna, a.s."
BankAccount::BicCodes['0800']; // "GIBACZPX"
Bank codes without a leading zero (2010) are int keys, PHP converts numeric string keys.
Localization\StaticTranslator
Simple static translator implementing Nette's Translator interface.
use Pinkava\Utils\Localization\StaticTranslator;
// Create translator with messages
$messages = [
'en' => [
'hello' => 'Hello',
'goodbye' => 'Goodbye',
],
'cs' => [
'hello' => 'Ahoj',
'goodbye' => 'Nashledanou',
],
];
$translator = new StaticTranslator('cs', $messages);
$translator->translate('hello'); // "Ahoj"
$translator->translate('goodbye'); // "Nashledanou"
$translator->translate('unknown'); // "unknown" (fallback)
$translator->getLocale(); // "cs"
// An HtmlStringable message gets an HtmlStringable translation (printed unescaped by Latte)
$translator->translate(Html::el()->setHtml('hello')); // Html object with "Ahoj"
Development
Running Tests
composer tester
Code Quality
# PHPStan static analysis
composer phpstan
# Generate PHPStan baseline
composer phpstan:generate-baseline
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
License
This is a proprietary library for private use.
Author
Marek Pinkava - pinkavam@gmail.com