A comprehensive collection of PHP helper functions and classes to simplify common programming tasks.
- PHP ^8.2|^8.3
- ext-mbstring
- ext-json
composer require andreas-glaser/php-helpersA powerful utility class for array manipulation and operations.
ArrayHelper::get(array $array, $key, $default = null): Get value by key with default fallbackArrayHelper::getKeyByValue(array $array, $value, $default = null, $strict = true): Get first key with matching valueArrayHelper::getByPath(array $array, $path, $throwException = false, $default = null): Get value using dot notation pathArrayHelper::setByPath(array $array, $path, $value): Set value using dot notation pathArrayHelper::unsetByPath(array $array, string $path): Remove value using dot notation pathArrayHelper::existsByPath(array $array, $path): Check if path existsArrayHelper::issetByPath(array $array, $path): Check if path is setArrayHelper::prepend(array $array, $value, $key = false): Add element at array startArrayHelper::append(array $array, $value, $key = false): Add element at array endArrayHelper::insertBefore(array &$array, $position, array $values): Insert values before positionArrayHelper::insertAfter(array &$array, $position, array $values): Insert values after positionArrayHelper::getFirstValue(array $array, $default = null): Get first array valueArrayHelper::getLastValue(array $array, $default = null): Get last array valueArrayHelper::getRandomValue(array $array): Get random array valueArrayHelper::removeFirstElement(array $array): Remove first elementArrayHelper::removeLastElement(array $array): Remove last elementArrayHelper::removeByValue(array $array, $value, $strict = true): Remove element by valueArrayHelper::keysCamelToUnderscore(array $array): Convert camelCase keys to snake_caseArrayHelper::unsetEmptyValues(array $array, $recursive = false): Remove empty valuesArrayHelper::implodeIgnoreEmpty($glue, array $pieces): Join array elements ignoring empty valuesArrayHelper::implodeKeys(string $glue, array $array): Join array keys with delimiterArrayHelper::explodeIgnoreEmpty(string $delimiter, string $string): Split string ignoring empty valuesArrayHelper::valueToUpper(array $array, $recursive = true): Convert values to uppercaseArrayHelper::isAssoc(array $array): Check if array is associativeArrayHelper::assocIndexesExist(array $arrayToCheck, array $arrayToCompareWith, $throwException = true): Check if indexes existArrayHelper::replaceValue(array $array, $value, $replacement, $recursively = true, $caseSensitive = true): Replace values in arrayArrayHelper::merge(array $array1, array $array2): Merge arrays with proper handling of numeric keysArrayHelper::getFirstIndex($array, $default = null): Get first array indexArrayHelper::unshiftAssoc($array, $key, $val): Add element at start with keyArrayHelper::removeFirstIndex(array $array): Remove first array index
Comprehensive string manipulation and comparison utilities.
StringHelper::is($string, $stringToMatch, $caseSensitive = true): Compare strings with case sensitivity optionStringHelper::isOneOf($string, array $stringsToCompare, $caseSensitive = true): Check if string matches any in arrayStringHelper::contains($haystack, $needle, $caseSensitive = true, $encoding = 'UTF-8'): Check if string contains substringStringHelper::startsWith($haystack, $needle, $caseSensitive = true, $encoding = 'UTF-8'): Check if string starts with prefixStringHelper::endsWith($haystack, $needle, $caseSensitive = true, $encoding = 'UTF-8'): Check if string ends with suffixStringHelper::trimMulti($string, array $chars): Remove multiple characters from both endsStringHelper::lTrimMulti($string, array $chars): Remove multiple characters from left endStringHelper::rTrimMulti($string, array $chars): Remove multiple characters from right endStringHelper::camelToUnderscore($string): Convert camelCase to underscore_caseStringHelper::removeLineBreaks($string, $replaceWith = ' '): Remove line breaksStringHelper::removeRedundantWhiteSpaces($string): Remove redundant whitespaceStringHelper::replaceWhiteSpacesWithUnderscores($string): Replace spaces with underscoresStringHelper::machineReadable($string): Convert to machine-readable formatStringHelper::append($string, $stringToAppend): Append stringStringHelper::prepend($string, $stringToPrepend): Prepend stringStringHelper::removeChar($string, $char): Remove single characterStringHelper::removeChars($string, array $chars): Remove multiple charactersStringHelper::explodeAndTrim($delimiter, $string): Split string and trim each partStringHelper::replace($subject, array $replacementMap, $caseSensitive = true): Replace multiple valuesStringHelper::limitWords($str, $limit = 100, $end_char = null): Limit string to word countStringHelper::limitChars($str, $limit = 100, $end_char = null, $preserve_words = false): Limit string to character countStringHelper::getIncrementalId($prefix = '__undefined__'): Generate sequential IDStringHelper::isBlank($string): Check if string is empty or contains only whitespaceStringHelper::removeFromStart($string, $stringToRemove, $caseSensitive = true, $encoding = 'UTF-8'): Remove prefixStringHelper::removeFromEnd($string, $stringToRemove, $caseSensitive = true, $encoding = 'UTF-8'): Remove suffixStringHelper::linesToArray($string): Convert string with line breaks to arrayStringHelper::__($string, array $params = null): String translation helper
Date and time manipulation and validation utilities.
DateHelper::isDateTime($date, $format = null): Check if value is valid datetimeDateHelper::stringToDateTime($string, $timezone = null, $null = null): Convert string to DateTime objectDateHelper::formatOrNull($dateTime, $format = 'Y-m-d H:i:s', $null = null): Format datetime or return null if invalidDateHelper::diffHours($dateTime1, $dateTime2): Calculate hour differences between datetimesDateHelper::diffDays($dateTime1, $dateTime2): Calculate day differences between datetimesDateHelper::diffMonths($dateTime1, $dateTime2): Calculate month differences between datetimesDateHelper::diffYears($dateTime1, $dateTime2): Calculate year differences between datetimes
HTML element generation and attribute handling utilities.
HtmlHelper::chars($value, $double_encode = true): Convert special characters to HTML entitiesHtmlHelper::entities($value, $double_encode = true): Convert all applicable characters to HTML entitiesHtmlHelper::div($content, $attributesHelper = null): Create div elementHtmlHelper::p($content, $attributesHelper = null): Create paragraph elementHtmlHelper::span($content, $attributesHelper = null): Create span elementHtmlHelper::h1($content, $attributesHelper = null)throughh6(): Create heading elementsHtmlHelper::a($url, $content, $attributesHelper = null): Create anchor elementHtmlHelper::image($src, $attributesHelper = null): Create image elementHtmlHelper::autoParagraph($str, $br = true): Convert text to paragraphs
HtmlHelper::strong($content, $attributesHelper = null): Create strong (bold) elementHtmlHelper::em($content, $attributesHelper = null): Create emphasis (italic) elementHtmlHelper::code($content, $attributesHelper = null): Create code elementHtmlHelper::pre($content, $attributesHelper = null): Create preformatted text elementHtmlHelper::mark($content, $attributesHelper = null): Create highlighted text elementHtmlHelper::small($content, $attributesHelper = null): Create small text elementHtmlHelper::sub($content, $attributesHelper = null): Create subscript elementHtmlHelper::sup($content, $attributesHelper = null): Create superscript element
HtmlHelper::blockquote($content, $attributesHelper = null): Create blockquote elementHtmlHelper::cite($content, $attributesHelper = null): Create citation elementHtmlHelper::time($content, $datetime = null, $attributesHelper = null): Create time element with optional datetime attributeHtmlHelper::abbr($content, $title = null, $attributesHelper = null): Create abbreviation element with optional title
HtmlHelper::article($content, $attributesHelper = null): Create article elementHtmlHelper::section($content, $attributesHelper = null): Create section elementHtmlHelper::nav($content, $attributesHelper = null): Create navigation elementHtmlHelper::aside($content, $attributesHelper = null): Create aside elementHtmlHelper::header($content, $attributesHelper = null): Create header elementHtmlHelper::footer($content, $attributesHelper = null): Create footer elementHtmlHelper::main($content, $attributesHelper = null): Create main element
HtmlHelper::figure($content, $attributesHelper = null): Create figure elementHtmlHelper::figcaption($content, $attributesHelper = null): Create figure caption element
HtmlHelper::details($content, $open = false, $attributesHelper = null): Create details element with optional open stateHtmlHelper::summary($content, $attributesHelper = null): Create summary element for detailsHtmlHelper::dialog($content, $open = false, $modal = false, $attributesHelper = null): Create dialog element with optional open and modal states
HtmlHelper::meter($content, $value, $min = null, $max = null, $low = null, $high = null, $optimum = null, $attributesHelper = null): Create meter element with value rangesHtmlHelper::progress($content, $value = null, $max = null, $attributesHelper = null): Create progress element with optional value and max
JSON validation and manipulation utilities.
JsonHelper::isValid($value): Validate various data types and JSON strings- Support for complex JSON structures and nested objects
Number formatting and manipulation utilities.
NumberHelper::ordinal($number): Convert number to ordinal suffix (1st, 2nd, 3rd, etc.)
Random value generation utilities.
RandomHelper::trueFalse(): Generate random boolean valueRandomHelper::uniqid($prefix = ''): Generate unique identifier with optional prefix
Value validation and type checking utilities.
ValueHelper::emptyToNull(&$string): Convert empty value to nullValueHelper::isEmpty($value): Check if value is empty (works with function returns)ValueHelper::isInteger($value): Check if value is integer or string containing only digitsValueHelper::isFloat($value): Check if value is float or string containing valid float formatValueHelper::isDateTime($date, $format = null): Check if value is valid datetimeValueHelper::isBool($value): Check if value is boolean typeValueHelper::isTrue($value): Check if value is strictly TRUEValueHelper::isFalse($value): Check if value is strictly FALSEValueHelper::isTrueLike($value): Check if value evaluates to true in boolean contextValueHelper::isFalseLike($value): Check if value evaluates to false in boolean context
Counter implementation for tracking and incrementing values.
CounterHelper::f($initialValue = 0): Create counter instanceCounterHelper::plusOne(): Increment counterCounterHelper::minusOne(): Decrement counterCounterHelper::getCurrentValue(): Get current valueCounterHelper::getInitialValue(): Get initial valueCounterHelper::getDifference(): Calculate difference from initial value
CSV file handling and manipulation utilities.
CsvHelper::fileToArray($file, $hasTitleRow = false): Parse CSV file to arrayCsvHelper::arrayToCsvString($array, $delimiter = ',', $enclosure = '"'): Convert array to CSV string
Email validation and formatting utilities.
EmailHelper::clean($emails, $delimiters = [',', ';']): Clean and normalize email addressesEmailHelper::isValid($email): Validate email address format
File system operations and temporary file handling.
IOHelper::createTmpDir($dir = null, $prefix = null, $absolute = false): Create temporary directoryIOHelper::createTmpFile($dir = null, $prefix = null, $absolute = false): Create temporary fileIOHelper::rmdirRecursive($dir): Recursively remove directory
Time measurement and execution timing utilities.
TimerHelper::start($alias): Start a new timer with specified aliasTimerHelper::getDifference($alias): Get elapsed time for a running timerTimerHelper::stop($alias): Stop a timer and return elapsed time
Color manipulation and conversion utilities.
HexHelper::adjustBrightness($hex, $steps): Adjust brightness of a hex color code (-255 to 255)
Request environment detection and comprehensive HTTP request analysis utilities.
RequestHelper::isCli(): Check if script is running in CLI modeRequestHelper::isHttps(): Check if request is using HTTPS (enhanced with proxy detection)RequestHelper::isSecure(): Check if request is secure (HTTPS or localhost)RequestHelper::isLocalhost(): Check if request is from localhost
RequestHelper::getMethod(): Get the HTTP request method (GET, POST, etc.)RequestHelper::isMethod($method): Check if request method matches given methodRequestHelper::isGet(): Check if request is GETRequestHelper::isPost(): Check if request is POSTRequestHelper::isPut(): Check if request is PUTRequestHelper::isDelete(): Check if request is DELETERequestHelper::isHead(): Check if request is HEADRequestHelper::isOptions(): Check if request is OPTIONSRequestHelper::isPatch(): Check if request is PATCH
RequestHelper::isAjax(): Check if request is AJAX/XMLHttpRequestRequestHelper::isApi(): Check if request is likely an API requestRequestHelper::isMobile(): Check if request is from mobile deviceRequestHelper::isBot(): Check if request is from bot/crawler
RequestHelper::getClientIp($trustProxies = true): Get client IP address with proxy supportRequestHelper::getUserAgent(): Get user agent stringRequestHelper::getReferrer(): Get referrer URLRequestHelper::getProtocol(): Get request protocol (HTTP/1.1, HTTP/2, etc.)RequestHelper::getPort(): Get request portRequestHelper::getHost(): Get host name
RequestHelper::getContentType(): Get request content typeRequestHelper::isContentType($type): Check if content type matchesRequestHelper::isJson(): Check if request has JSON content typeRequestHelper::isXml(): Check if request has XML content typeRequestHelper::getContentLength(): Get content lengthRequestHelper::getAcceptedLanguages(): Get accepted languages from Accept-Language header
RequestHelper::getHeader($name, $default = null): Get specific request headerRequestHelper::hasHeader($name): Check if header existsRequestHelper::getAllHeaders(): Get all request headers
RequestHelper::isLegitimate(): Basic security check for legitimate requestsRequestHelper::getRequestTime(): Get request timestampRequestHelper::isWithinRateLimit($maxRequests, $timeWindow, $identifier = null): Basic rate limiting
RequestHelper::getRequestInfo(): Get comprehensive request information arrayRequestHelper::setTrustedProxyHeaders($headers): Set trusted proxy headersRequestHelper::getTrustedProxyHeaders(): Get current trusted proxy headers
Comprehensive URL manipulation, validation, and generation utilities for HTTP requests.
UrlHelper::protocolHostPort(): Get protocol, host, and port string based on server configurationUrlHelper::query($parameters = null, $mergeGetVariables = true): Build query string from parameters with optional $_GET mergingUrlHelper::currentUrl($includeQuery = true, $urlEncode = false): Get current full URL with optional query string and encodingUrlHelper::currentUri($includeQueryParams = true, $encode = false): Get current URI with optional query parameters and encoding
UrlHelper::isValidUrl($url, $allowedSchemes = ['http', 'https']): Validate URL with configurable allowed schemesUrlHelper::parseUrl($url): Parse URL components into structured arrayUrlHelper::buildUrl($components): Build URL from component arrayUrlHelper::isStandardPort($scheme, $port): Check if port is standard for given scheme
UrlHelper::addQueryParams($url, $params, $encode = true): Add or modify query parameters in URLUrlHelper::removeQueryParams($url, $paramsToRemove): Remove specific query parameters from URLUrlHelper::changeScheme($url, $scheme): Change URL scheme (e.g., HTTP to HTTPS)UrlHelper::normalize($url): Normalize URL by cleaning up common issues
UrlHelper::normalizePath($path): Normalize URL path by resolving . and .. segmentsUrlHelper::joinPaths(...$segments): Join multiple path segments into single pathUrlHelper::getDirectory($path): Get directory path from URL pathUrlHelper::getFilename($path): Get filename from URL pathUrlHelper::getExtension($path): Get file extension from URL path
UrlHelper::getDomain($url): Extract domain from URLUrlHelper::getSubdomain($url, $levels = 2): Extract subdomain with configurable root domain levelsUrlHelper::getRootDomain($url, $levels = 2): Get root domain with configurable levelsUrlHelper::isSameDomain($url1, $url2): Check if two URLs have same domain
UrlHelper::encode($string): URL encode string with RFC 3986 complianceUrlHelper::decode($string): URL decode stringUrlHelper::encodePath($path): Encode only path component of URLUrlHelper::encodeQuery($params, $rfc3986 = true): Encode query string parameters
UrlHelper::toAbsolute($relativeUrl, $baseUrl): Convert relative URL to absoluteUrlHelper::toRelative($absoluteUrl, $baseUrl): Convert absolute URL to relative
UrlHelper::currentUrlWithModifications($queryModifications = [], $queryRemovals = []): Get current URL with query modificationsUrlHelper::isSecureUrl($url): Check if URL uses HTTPS schemeUrlHelper::getStandardPort($scheme): Get standard port for schemeUrlHelper::sanitize($url, $allowedSchemes = ['http', 'https']): Sanitize URL by removing dangerous protocolsUrlHelper::modifiedQuery($params = [], $remove = []): Generate query string from current URL with modifications
- URL schemes:
SCHEME_HTTP,SCHEME_HTTPS,SCHEME_FTP,SCHEME_SFTP,SCHEME_FILE - Standard ports array:
STANDARD_PORTSwith common protocol ports
HTML form element generation utilities.
FormHelper::open($action = null, $method = 'GET', $attributesHelper = null): Create form opening tagFormHelper::close(): Create form closing tagFormHelper::text($name, $value = null, $attributesHelper = null): Create text inputFormHelper::password($name, $value = null, $attributesHelper = null): Create password inputFormHelper::email($name, $value = null, $attributesHelper = null): Create email inputFormHelper::color($name, $value = null, $attributesHelper = null): Create color inputFormHelper::date($name, $value = null, $attributesHelper = null): Create date inputFormHelper::datetime($name, $value = null, $attributesHelper = null): Create datetime inputFormHelper::datetimeLocal($name, $value = null, $attributesHelper = null): Create datetime-local inputFormHelper::month($name, $value = null, $attributesHelper = null): Create month inputFormHelper::number($name, $value = null, $attributesHelper = null): Create number inputFormHelper::range($name, $value, $min, $max, $attributesHelper = null): Create range inputFormHelper::search($name, $value = null, $attributesHelper = null): Create search inputFormHelper::tel($name, $value = null, $attributesHelper = null): Create telephone inputFormHelper::time($name, $value = null, $attributesHelper = null): Create time inputFormHelper::url($name, $value = null, $attributesHelper = null): Create URL inputFormHelper::week($name, $value = null, $attributesHelper = null): Create week inputFormHelper::hidden($name, $value = null, $attributesHelper = null): Create hidden inputFormHelper::textarea($name, $value = null, $attributesHelper = null): Create textareaFormHelper::button($name, $value = null, $attributesHelper = null): Create buttonFormHelper::submit($name, $value = null, $attributesHelper = null): Create submit buttonFormHelper::label($value, $forId = null, $formId = null, $attributesHelper = null): Create labelFormHelper::select($name, array $options, $checkedValue = null, $attributesHelper = null): Create selectFormHelper::selectMultiple($name, array $options, $checkedValue = null, $attributesHelper = null): Create multiple selectFormHelper::option($value, $text, $selected = false): Create optionFormHelper::optgroup($label, $htmlContent, $attributesHelper = null): Create option groupFormHelper::checkbox($name, $value = null, $checked = false, $attributesHelper = null): Create checkboxFormHelper::radio($name, $value = null, $checked = false, $attributesHelper = null): Create radio button
A powerful utility class for managing HTML attributes with proper escaping and validation.
// Create a new instance with initial attributes
$attrs = AttributesHelper::f(['class' => 'btn']);
// Add more classes and attributes
$attrs->addClass('btn-primary')
->addStyle('margin', '10px')
->addData('toggle', 'modal');
// Render as HTML attributes string
echo $attrs; // outputs: class="btn btn-primary" style="margin:10px" data-toggle="modal"- Type-safe attribute handling
- HTML escaping for security
- CSS style parsing and validation
- Data attribute management
- Class name management
AttributesHelper::f($input = null): Create new instance (recommended factory method)setAttribute(string $name, mixed $value): Set any attribute with validationsetId(string $value): Set the ID attributeaddClass(string|array $classes): Add one or more CSS classesaddData(string $name, mixed $value): Add a data attributeaddStyle(string $property, string $value): Add a CSS style propertyrender(): Convert to HTML attributes stringtoArray(): Get all attributes as an array
Bootstrap-specific HTML generation utilities.
BootstrapHelper::glyphIcon($name, $attributesHelper = null): Create Bootstrap glyphicon span element
use AndreasGlaser\Helpers\Html\BootstrapHelper;
// Basic glyphicon
echo BootstrapHelper::glyphIcon('home');
// Output: <span class="glyphicon glyphicon-home"></span>
// With additional attributes
echo BootstrapHelper::glyphIcon('search', [
'id' => 'search-icon',
'class' => 'icon-large text-primary',
'title' => 'Search',
'data-toggle' => 'tooltip'
]);
// Output: <span id="search-icon" class="icon-large text-primary glyphicon glyphicon-search" title="Search" data-toggle="tooltip"></span>
// Using AttributesHelper
$attrs = AttributesHelper::f()
->setId('my-icon')
->addClass('text-danger')
->addData('action', 'delete');
echo BootstrapHelper::glyphIcon('trash', $attrs);HTML table generation utilities.
TableHelper::f($headRows = null, $bodyRows = null, $attributesHelper = null): Create table instanceTableHelper::addHeadRow($rowHelper, $setCellAsHeaders = true): Add header rowTableHelper::addBodyRow($rowHelper): Add body rowTableHelper::render($renderer = null): Render table as HTML
Base class for HTML list generation.
BaseListHelper::f($items = null, $attributesHelper = null): Create list instanceBaseListHelper::addItem($content, $attributesHelper = null): Add item to listBaseListHelper::getItems(): Get all list itemsBaseListHelper::getAttributes(): Get list attributes
HTML unordered list generation utilities.
UnorderedListHelper::render($renderer = null): Render unordered list as HTML
HTML ordered list generation utilities.
OrderedListHelper::render($renderer = null): Render ordered list as HTML
HTML description list generation utilities.
DescriptionListHelper::addTerm($term, $description, $attributesHelper = null): Add term and descriptionDescriptionListHelper::render($renderer = null): Render description list as HTML
PHP template rendering and view management utilities.
PHPView::f($file = null, $data = []): Create view instancePHPView::setGlobal($key, $value): Set global data accessible to all viewsPHPView::getGlobalData(): Get all global dataPHPView::setFile($filePath): Set template file pathPHPView::set($key, $value): Set local data for view instancePHPView::getData(): Get all local dataPHPView::render($file = null): Render template with current dataPHPView::__toString(): Render template when used as string
Network-related validation utilities.
NetworkHelper::isValidIPv4($ip): Validate IPv4 address formatNetworkHelper::isValidIPv6($ip): Validate IPv6 address formatNetworkHelper::isValidIP($ip, $allowPrivate = true, $allowReserved = true): Validate IP address (both IPv4 and IPv6) with support for private and reserved range validationNetworkHelper::isValidPort($port, $allowSystemPorts = true, $allowUserPorts = true, $allowDynamicPorts = true): Validate port number with customizable range restrictionsNetworkHelper::isValidDomain($domain, $allowSingleLabel = false, $allowPunycode = true): Validate domain name with support for Punycode and single-label domainsNetworkHelper::isValidMac($mac, $allowColonFormat = true, $allowHyphenFormat = true, $allowBareFormat = true): Validate MAC address in various formatsNetworkHelper::isValidCidr($cidr): Validate CIDR notation for both IPv4 and IPv6NetworkHelper::isValidSubnetMask($mask): Validate IPv4 subnet maskNetworkHelper::getCommonPort($service): Get common port number for well-known services
NetworkHelper::getDnsRecords($domain, $type = 'ALL'): Get DNS records for a domain with support for all record types (A, AAAA, MX, NS, TXT, etc.)NetworkHelper::isValidMxRecord($domain): Check if a domain has valid MX recordsNetworkHelper::getReverseDns($ip): Get reverse DNS (PTR) record for an IP addressNetworkHelper::hasValidSpfRecord($domain): Check if a domain has a valid SPF recordNetworkHelper::hasDkimRecord($domain, $selector): Check if a domain has a valid DKIM record for a selector
NetworkHelper::isPortOpen($host, $port, $timeout = 2.0): Check if a specific port is open on a hostNetworkHelper::getOpenPorts($host, array $ports, $timeout = 1.0): Scan multiple ports on a hostNetworkHelper::getServiceByPort($port): Get service name for a port number (e.g., 80 → "http")
Type validation utilities that throw exceptions on type mismatches. All methods throw UnexpectedTypeException if the value doesn't match the expected type.
Expect::int($value): Validates that a value is an integerExpect::float($value): Validates that a value is a floatExpect::str($value): Validates that a value is a stringExpect::bool($value): Validates that a value is a booleanExpect::arr($value): Validates that a value is an arrayExpect::obj($value): Validates that a value is an objectExpect::res($value): Validates that a value is a resourceExpect::null($value): Validates that a value is null
Expect::numeric($value): Validates that a value is numeric (int, float, or numeric string)Expect::isCallable($value): Validates that a value is callable (function, closure, method array, etc.)Expect::scalar($value): Validates that a value is scalar (int, float, string, or bool)
Expect::countable($value): Validates that a value is countable (array or implements Countable)Expect::iterable($value): Validates that a value is iterable (array or implements Traversable)Expect::finite($value): Validates that a value is a finite number (not infinite or NaN)Expect::infinite($value): Validates that a value is an infinite numberExpect::nan($value): Validates that a value is NaN (Not a Number)
File system validation utilities that throw exceptions on validation failures. All methods throw IOException if the validation fails.
IOExpect::exists($path): Validates that a path exists (file or directory)IOExpect::doesNotExist($path): Validates that a path does not existIOExpect::isDir($path): Validates that a path exists and is a directoryIOExpect::isFile($path): Validates that a path exists and is a fileIOExpect::isLink($path): Validates that a path is a symbolic link
IOExpect::isReadable($path): Validates that a path is readableIOExpect::isWritable($path): Validates that a path is writableIOExpect::isExecutable($path): Validates that a path is executableIOExpect::parentDirWritable($path): Validates that parent directory exists and is writable
IOExpect::isDirEmpty($path): Validates that a directory is emptyIOExpect::isDirNotEmpty($path): Validates that a directory is not empty
IOExpect::isFileNotEmpty($path): Validates that a file is not emptyIOExpect::hasMinSize($path, $minSize): Validates that a file has minimum size in bytesIOExpect::hasMaxSize($path, $maxSize): Validates that a file has maximum size in bytesIOExpect::hasExtension($path, $extension): Validates that a file has specific extensionIOExpect::hasAllowedExtension($path, $extensions): Validates that a file has one of allowed extensionsIOExpect::hasMimeType($path, $expectedMimeType): Validates that a file matches specific MIME type
The library includes comprehensive unit tests for all components. Each helper class has a corresponding test class that verifies its functionality:
ArrayHelperTest: Tests array manipulation and path operationsAttributesHelperTest: Tests HTML attribute management and validationBootstrapHelperTest: Tests Bootstrap component generation and glyphicon creationCounterHelperTest: Tests counter operations and assertionsCsvHelperTest: Tests CSV file operations and string conversionDateHelperTest: Tests date formatting and difference calculationsEmailHelperTest: Tests email validation and cleaningExpectTest: Tests type validation and exception throwingFormHelperTest: Tests HTML form element generation and validationHtmlHelperTest: Tests HTML element generation and attributesIOExpectTest: Tests file system validation and IOException handlingIOHelperTest: Tests file system operationsJsonHelperTest: Tests JSON validation for various data typesNumberHelperTest: Tests number formatting and ordinal conversionRandomHelperTest: Tests random value generationRequestHelperTest: Tests comprehensive HTTP request analysis including environment detection, method analysis, client information, content analysis, and security featuresStringHelperTest: Tests string comparison and manipulation methodsUrlHelperTest: Tests comprehensive URL manipulation including validation, parsing, path operations, domain extraction, encoding, and utility methodsValueHelperTest: Tests value validation and type checking
Run the tests using:
composer install
./vendor/phpunit/phpunit/phpunituse AndreasGlaser\Helpers\ArrayHelper;
use AndreasGlaser\Helpers\StringHelper;
use AndreasGlaser\Helpers\DateHelper;
use AndreasGlaser\Helpers\ValueHelper;
use AndreasGlaser\Helpers\CsvHelper;
use AndreasGlaser\Helpers\EmailHelper;
use AndreasGlaser\Helpers\Html\FormHelper;
use AndreasGlaser\Helpers\Html\AttributesHelper;
use AndreasGlaser\Helpers\Validate\Expect;
use AndreasGlaser\Helpers\Validate\IOExpect;
// Array operations
$array = ['user' => ['profile' => ['name' => 'John']]];
$name = ArrayHelper::getByPath($array, 'user.profile.name'); // Returns 'John'
// String operations
$string = 'Hello World';
$contains = StringHelper::contains($string, 'World'); // Returns true
$startsWith = StringHelper::startsWith($string, 'Hello'); // Returns true
// Date operations
$date = new DateTime();
$hours = DateHelper::diffHours($date, new DateTime('+1 day')); // Returns 24
// Value validation
$isValid = ValueHelper::isDateTime('2024-03-20'); // Returns true
// CSV operations
$csvData = [
['Name', 'Email', 'Age'],
['John Doe', 'john@example.com', '30'],
['Jane Smith', 'jane@example.com', '25']
];
$csvString = CsvHelper::arrayToCsvString($csvData);
// Result: "Name,Email,Age\nJohn Doe,john@example.com,30\nJane Smith,jane@example.com,25"
// Read CSV file to array
$data = CsvHelper::fileToArray('users.csv', true); // true for header row
// With custom delimiter
$data = CsvHelper::fileToArray('data.csv', false, 0, ';'); // semicolon delimiter
// Email operations
$validEmail = EmailHelper::isValid('user@example.com'); // Returns true
$invalidEmail = EmailHelper::isValid('invalid-email'); // Returns false
// Clean and normalize email addresses
$emails = 'user@example.com, invalid-email, admin@test.com; contact@domain.org';
$cleanEmails = EmailHelper::clean($emails); // Returns ['user@example.com', 'admin@test.com', 'contact@domain.org']
// Clean with custom delimiters
$emails = 'user@example.com:admin@test.com#contact@domain.org';
$cleanEmails = EmailHelper::clean($emails, [':', '#']); // Returns ['user@example.com', 'admin@test.com', 'contact@domain.org']
// Clean array of emails
$emailArray = ['user@example.com', 'invalid', 'admin@test.com'];
$cleanEmails = EmailHelper::clean($emailArray); // Returns ['user@example.com', 'admin@test.com']
// Form generation
echo FormHelper::open('/users', 'POST', ['class' => 'user-form']);
echo FormHelper::text('name', 'John Doe', ['id' => 'name', 'required' => 'required']);
echo FormHelper::email('email', 'john@example.com', ['placeholder' => 'Enter email']);
echo FormHelper::select('country', ['US' => 'United States', 'CA' => 'Canada'], 'US');
echo FormHelper::textarea('bio', 'Tell us about yourself', ['rows' => 5]);
echo FormHelper::submit('submit', 'Create User', ['class' => 'btn btn-primary']);
echo FormHelper::close();
// HTML attribute management
$attrs = AttributesHelper::f(['class' => 'btn'])
->addClass('btn-primary')
->addStyle('margin', '10px')
->addData('toggle', 'modal');
echo $attrs; // outputs: class="btn btn-primary" style="margin:10px" data-toggle="modal"
// Type validation with exceptions
Expect::int(42); // Valid - no exception
Expect::str('hello'); // Valid - no exception
Expect::finite(42.5); // Valid - finite number
// File system validation
IOExpect::isFile('/path/to/file.txt'); // Throws IOException if not a file
IOExpect::isReadable('/path/to/file.txt'); // Throws IOException if not readable- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the MIT License - see the LICENSE file for details.
- Andreas Glaser - GitHub
If you find this library helpful, please consider giving it a star on GitHub!