{"id":25743821,"url":"https://github.com/andreas-glaser/php-helpers","last_synced_at":"2026-01-25T17:01:23.557Z","repository":{"id":34645530,"uuid":"38606400","full_name":"andreas-glaser/php-helpers","owner":"andreas-glaser","description":"A simple php library of various helper functions and classes.","archived":false,"fork":false,"pushed_at":"2025-07-25T09:02:59.000Z","size":547,"stargazers_count":13,"open_issues_count":0,"forks_count":2,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-10-23T09:54:29.407Z","etag":null,"topics":["helpers","php","utilities","validation"],"latest_commit_sha":null,"homepage":"https://github.com/andreas-glaser/php-helpers","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/andreas-glaser.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2015-07-06T08:22:00.000Z","updated_at":"2025-07-03T09:25:37.000Z","dependencies_parsed_at":"2022-08-28T11:11:25.235Z","dependency_job_id":null,"html_url":"https://github.com/andreas-glaser/php-helpers","commit_stats":null,"previous_names":[],"tags_count":53,"template":false,"template_full_name":null,"purl":"pkg:github/andreas-glaser/php-helpers","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreas-glaser%2Fphp-helpers","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreas-glaser%2Fphp-helpers/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreas-glaser%2Fphp-helpers/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreas-glaser%2Fphp-helpers/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/andreas-glaser","download_url":"https://codeload.github.com/andreas-glaser/php-helpers/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/andreas-glaser%2Fphp-helpers/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28755561,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-25T16:32:25.380Z","status":"ssl_error","status_checked_at":"2026-01-25T16:32:09.189Z","response_time":113,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["helpers","php","utilities","validation"],"created_at":"2025-02-26T10:30:42.081Z","updated_at":"2026-01-25T17:01:23.550Z","avatar_url":"https://github.com/andreas-glaser.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PHP Helpers\n\nA comprehensive collection of PHP helper functions and classes to simplify common programming tasks.\n\n## Requirements\n\n- PHP ^8.2|^8.3\n- ext-mbstring\n- ext-json\n\n## Installation\n\n```bash\ncomposer require andreas-glaser/php-helpers\n```\n\n## Features\n\n### Array Helper (`ArrayHelper.php`)\nA powerful utility class for array manipulation and operations.\n\n#### Key Functions:\n- `ArrayHelper::get(array $array, $key, $default = null)`: Get value by key with default fallback\n- `ArrayHelper::getKeyByValue(array $array, $value, $default = null, $strict = true)`: Get first key with matching value\n- `ArrayHelper::getByPath(array $array, $path, $throwException = false, $default = null)`: Get value using dot notation path\n- `ArrayHelper::setByPath(array $array, $path, $value)`: Set value using dot notation path\n- `ArrayHelper::unsetByPath(array $array, string $path)`: Remove value using dot notation path\n- `ArrayHelper::existsByPath(array $array, $path)`: Check if path exists\n- `ArrayHelper::issetByPath(array $array, $path)`: Check if path is set\n- `ArrayHelper::prepend(array $array, $value, $key = false)`: Add element at array start\n- `ArrayHelper::append(array $array, $value, $key = false)`: Add element at array end\n- `ArrayHelper::insertBefore(array \u0026$array, $position, array $values)`: Insert values before position\n- `ArrayHelper::insertAfter(array \u0026$array, $position, array $values)`: Insert values after position\n- `ArrayHelper::getFirstValue(array $array, $default = null)`: Get first array value\n- `ArrayHelper::getLastValue(array $array, $default = null)`: Get last array value\n- `ArrayHelper::getRandomValue(array $array)`: Get random array value\n- `ArrayHelper::removeFirstElement(array $array)`: Remove first element\n- `ArrayHelper::removeLastElement(array $array)`: Remove last element\n- `ArrayHelper::removeByValue(array $array, $value, $strict = true)`: Remove element by value\n- `ArrayHelper::keysCamelToUnderscore(array $array)`: Convert camelCase keys to snake_case\n- `ArrayHelper::unsetEmptyValues(array $array, $recursive = false)`: Remove empty values\n- `ArrayHelper::implodeIgnoreEmpty($glue, array $pieces)`: Join array elements ignoring empty values\n- `ArrayHelper::implodeKeys(string $glue, array $array)`: Join array keys with delimiter\n- `ArrayHelper::explodeIgnoreEmpty(string $delimiter, string $string)`: Split string ignoring empty values\n- `ArrayHelper::valueToUpper(array $array, $recursive = true)`: Convert values to uppercase\n- `ArrayHelper::isAssoc(array $array)`: Check if array is associative\n- `ArrayHelper::assocIndexesExist(array $arrayToCheck, array $arrayToCompareWith, $throwException = true)`: Check if indexes exist\n- `ArrayHelper::replaceValue(array $array, $value, $replacement, $recursively = true, $caseSensitive = true)`: Replace values in array\n- `ArrayHelper::merge(array $array1, array $array2)`: Merge arrays with proper handling of numeric keys\n- `ArrayHelper::getFirstIndex($array, $default = null)`: Get first array index\n- `ArrayHelper::unshiftAssoc($array, $key, $val)`: Add element at start with key\n- `ArrayHelper::removeFirstIndex(array $array)`: Remove first array index\n\n### String Helper (`StringHelper.php`)\nComprehensive string manipulation and comparison utilities.\n\n#### Key Functions:\n- `StringHelper::is($string, $stringToMatch, $caseSensitive = true)`: Compare strings with case sensitivity option\n- `StringHelper::isOneOf($string, array $stringsToCompare, $caseSensitive = true)`: Check if string matches any in array\n- `StringHelper::contains($haystack, $needle, $caseSensitive = true, $encoding = 'UTF-8')`: Check if string contains substring\n- `StringHelper::startsWith($haystack, $needle, $caseSensitive = true, $encoding = 'UTF-8')`: Check if string starts with prefix\n- `StringHelper::endsWith($haystack, $needle, $caseSensitive = true, $encoding = 'UTF-8')`: Check if string ends with suffix\n- `StringHelper::trimMulti($string, array $chars)`: Remove multiple characters from both ends\n- `StringHelper::lTrimMulti($string, array $chars)`: Remove multiple characters from left end\n- `StringHelper::rTrimMulti($string, array $chars)`: Remove multiple characters from right end\n- `StringHelper::camelToUnderscore($string)`: Convert camelCase to underscore_case\n- `StringHelper::removeLineBreaks($string, $replaceWith = ' ')`: Remove line breaks\n- `StringHelper::removeRedundantWhiteSpaces($string)`: Remove redundant whitespace\n- `StringHelper::replaceWhiteSpacesWithUnderscores($string)`: Replace spaces with underscores\n- `StringHelper::machineReadable($string)`: Convert to machine-readable format\n- `StringHelper::append($string, $stringToAppend)`: Append string\n- `StringHelper::prepend($string, $stringToPrepend)`: Prepend string\n- `StringHelper::removeChar($string, $char)`: Remove single character\n- `StringHelper::removeChars($string, array $chars)`: Remove multiple characters\n- `StringHelper::explodeAndTrim($delimiter, $string)`: Split string and trim each part\n- `StringHelper::replace($subject, array $replacementMap, $caseSensitive = true)`: Replace multiple values\n- `StringHelper::limitWords($str, $limit = 100, $end_char = null)`: Limit string to word count\n- `StringHelper::limitChars($str, $limit = 100, $end_char = null, $preserve_words = false)`: Limit string to character count\n- `StringHelper::getIncrementalId($prefix = '__undefined__')`: Generate sequential ID\n- `StringHelper::isBlank($string)`: Check if string is empty or contains only whitespace\n- `StringHelper::removeFromStart($string, $stringToRemove, $caseSensitive = true, $encoding = 'UTF-8')`: Remove prefix\n- `StringHelper::removeFromEnd($string, $stringToRemove, $caseSensitive = true, $encoding = 'UTF-8')`: Remove suffix\n- `StringHelper::linesToArray($string)`: Convert string with line breaks to array\n- `StringHelper::__($string, array $params = null)`: String translation helper\n\n### Date Helper (`DateHelper.php`)\nDate and time manipulation and validation utilities.\n\n#### Key Functions:\n- `DateHelper::isDateTime($date, $format = null)`: Check if value is valid datetime\n- `DateHelper::stringToDateTime($string, $timezone = null, $null = null)`: Convert string to DateTime object\n- `DateHelper::formatOrNull($dateTime, $format = 'Y-m-d H:i:s', $null = null)`: Format datetime or return null if invalid\n- `DateHelper::diffHours($dateTime1, $dateTime2)`: Calculate hour differences between datetimes\n- `DateHelper::diffDays($dateTime1, $dateTime2)`: Calculate day differences between datetimes\n- `DateHelper::diffMonths($dateTime1, $dateTime2)`: Calculate month differences between datetimes\n- `DateHelper::diffYears($dateTime1, $dateTime2)`: Calculate year differences between datetimes\n\n### HTML Helper (`HtmlHelper.php`)\nHTML element generation and attribute handling utilities.\n\n#### Key Functions:\n- `HtmlHelper::chars($value, $double_encode = true)`: Convert special characters to HTML entities\n- `HtmlHelper::entities($value, $double_encode = true)`: Convert all applicable characters to HTML entities\n- `HtmlHelper::div($content, $attributesHelper = null)`: Create div element\n- `HtmlHelper::p($content, $attributesHelper = null)`: Create paragraph element\n- `HtmlHelper::span($content, $attributesHelper = null)`: Create span element\n- `HtmlHelper::h1($content, $attributesHelper = null)` through `h6()`: Create heading elements\n- `HtmlHelper::a($url, $content, $attributesHelper = null)`: Create anchor element\n- `HtmlHelper::image($src, $attributesHelper = null)`: Create image element\n- `HtmlHelper::autoParagraph($str, $br = true)`: Convert text to paragraphs\n\n##### Text Formatting Elements:\n- `HtmlHelper::strong($content, $attributesHelper = null)`: Create strong (bold) element\n- `HtmlHelper::em($content, $attributesHelper = null)`: Create emphasis (italic) element\n- `HtmlHelper::code($content, $attributesHelper = null)`: Create code element\n- `HtmlHelper::pre($content, $attributesHelper = null)`: Create preformatted text element\n- `HtmlHelper::mark($content, $attributesHelper = null)`: Create highlighted text element\n- `HtmlHelper::small($content, $attributesHelper = null)`: Create small text element\n- `HtmlHelper::sub($content, $attributesHelper = null)`: Create subscript element\n- `HtmlHelper::sup($content, $attributesHelper = null)`: Create superscript element\n\n##### Semantic Elements:\n- `HtmlHelper::blockquote($content, $attributesHelper = null)`: Create blockquote element\n- `HtmlHelper::cite($content, $attributesHelper = null)`: Create citation element\n- `HtmlHelper::time($content, $datetime = null, $attributesHelper = null)`: Create time element with optional datetime attribute\n- `HtmlHelper::abbr($content, $title = null, $attributesHelper = null)`: Create abbreviation element with optional title\n\n##### Structural Elements:\n- `HtmlHelper::article($content, $attributesHelper = null)`: Create article element\n- `HtmlHelper::section($content, $attributesHelper = null)`: Create section element\n- `HtmlHelper::nav($content, $attributesHelper = null)`: Create navigation element\n- `HtmlHelper::aside($content, $attributesHelper = null)`: Create aside element\n- `HtmlHelper::header($content, $attributesHelper = null)`: Create header element\n- `HtmlHelper::footer($content, $attributesHelper = null)`: Create footer element\n- `HtmlHelper::main($content, $attributesHelper = null)`: Create main element\n\n##### Media Elements:\n- `HtmlHelper::figure($content, $attributesHelper = null)`: Create figure element\n- `HtmlHelper::figcaption($content, $attributesHelper = null)`: Create figure caption element\n\n##### Interactive Elements:\n- `HtmlHelper::details($content, $open = false, $attributesHelper = null)`: Create details element with optional open state\n- `HtmlHelper::summary($content, $attributesHelper = null)`: Create summary element for details\n- `HtmlHelper::dialog($content, $open = false, $modal = false, $attributesHelper = null)`: Create dialog element with optional open and modal states\n\n##### Progress \u0026 Measurement Elements:\n- `HtmlHelper::meter($content, $value, $min = null, $max = null, $low = null, $high = null, $optimum = null, $attributesHelper = null)`: Create meter element with value ranges\n- `HtmlHelper::progress($content, $value = null, $max = null, $attributesHelper = null)`: Create progress element with optional value and max\n\n### JSON Helper (`JsonHelper.php`)\nJSON validation and manipulation utilities.\n\n#### Key Functions:\n- `JsonHelper::isValid($value)`: Validate various data types and JSON strings\n- Support for complex JSON structures and nested objects\n\n### Number Helper (`NumberHelper.php`)\nNumber formatting and manipulation utilities.\n\n#### Key Functions:\n- `NumberHelper::ordinal($number)`: Convert number to ordinal suffix (1st, 2nd, 3rd, etc.)\n\n### Random Helper (`RandomHelper.php`)\nRandom value generation utilities.\n\n#### Key Functions:\n- `RandomHelper::trueFalse()`: Generate random boolean value\n- `RandomHelper::uniqid($prefix = '')`: Generate unique identifier with optional prefix\n\n### Value Helper (`ValueHelper.php`)\nValue validation and type checking utilities.\n\n#### Key Functions:\n- `ValueHelper::emptyToNull(\u0026$string)`: Convert empty value to null\n- `ValueHelper::isEmpty($value)`: Check if value is empty (works with function returns)\n- `ValueHelper::isInteger($value)`: Check if value is integer or string containing only digits\n- `ValueHelper::isFloat($value)`: Check if value is float or string containing valid float format\n- `ValueHelper::isDateTime($date, $format = null)`: Check if value is valid datetime\n- `ValueHelper::isBool($value)`: Check if value is boolean type\n- `ValueHelper::isTrue($value)`: Check if value is strictly TRUE\n- `ValueHelper::isFalse($value)`: Check if value is strictly FALSE\n- `ValueHelper::isTrueLike($value)`: Check if value evaluates to true in boolean context\n- `ValueHelper::isFalseLike($value)`: Check if value evaluates to false in boolean context\n\n### Counter Helper (`CounterHelper.php`)\nCounter implementation for tracking and incrementing values.\n\n#### Key Functions:\n- `CounterHelper::f($initialValue = 0)`: Create counter instance\n- `CounterHelper::plusOne()`: Increment counter\n- `CounterHelper::minusOne()`: Decrement counter\n- `CounterHelper::getCurrentValue()`: Get current value\n- `CounterHelper::getInitialValue()`: Get initial value\n- `CounterHelper::getDifference()`: Calculate difference from initial value\n\n### CSV Helper (`CsvHelper.php`)\nCSV file handling and manipulation utilities.\n\n#### Key Functions:\n- `CsvHelper::fileToArray($file, $hasTitleRow = false)`: Parse CSV file to array\n- `CsvHelper::arrayToCsvString($array, $delimiter = ',', $enclosure = '\"')`: Convert array to CSV string\n\n### Email Helper (`EmailHelper.php`)\nEmail validation and formatting utilities.\n\n#### Key Functions:\n- `EmailHelper::clean($emails, $delimiters = [',', ';'])`: Clean and normalize email addresses\n- `EmailHelper::isValid($email)`: Validate email address format\n\n### IO Helper (`IOHelper.php`)\nFile system operations and temporary file handling.\n\n#### Key Functions:\n- `IOHelper::createTmpDir($dir = null, $prefix = null, $absolute = false)`: Create temporary directory\n- `IOHelper::createTmpFile($dir = null, $prefix = null, $absolute = false)`: Create temporary file\n- `IOHelper::rmdirRecursive($dir)`: Recursively remove directory\n\n### Timer Helper (`TimerHelper.php`)\nTime measurement and execution timing utilities.\n\n#### Key Functions:\n- `TimerHelper::start($alias)`: Start a new timer with specified alias\n- `TimerHelper::getDifference($alias)`: Get elapsed time for a running timer\n- `TimerHelper::stop($alias)`: Stop a timer and return elapsed time\n\n### Color Helper (`Color/HexHelper.php`)\nColor manipulation and conversion utilities.\n\n#### Key Functions:\n- `HexHelper::adjustBrightness($hex, $steps)`: Adjust brightness of a hex color code (-255 to 255)\n\n### HTTP Helpers\n\n#### Request Helper (`Http/RequestHelper.php`)\nRequest environment detection and comprehensive HTTP request analysis utilities.\n\n#### Key Functions:\n\n##### Environment Detection:\n- `RequestHelper::isCli()`: Check if script is running in CLI mode\n- `RequestHelper::isHttps()`: Check if request is using HTTPS (enhanced with proxy detection)\n- `RequestHelper::isSecure()`: Check if request is secure (HTTPS or localhost)\n- `RequestHelper::isLocalhost()`: Check if request is from localhost\n\n##### HTTP Method Analysis:\n- `RequestHelper::getMethod()`: Get the HTTP request method (GET, POST, etc.)\n- `RequestHelper::isMethod($method)`: Check if request method matches given method\n- `RequestHelper::isGet()`: Check if request is GET\n- `RequestHelper::isPost()`: Check if request is POST\n- `RequestHelper::isPut()`: Check if request is PUT\n- `RequestHelper::isDelete()`: Check if request is DELETE\n- `RequestHelper::isHead()`: Check if request is HEAD\n- `RequestHelper::isOptions()`: Check if request is OPTIONS\n- `RequestHelper::isPatch()`: Check if request is PATCH\n\n##### Request Type Detection:\n- `RequestHelper::isAjax()`: Check if request is AJAX/XMLHttpRequest\n- `RequestHelper::isApi()`: Check if request is likely an API request\n- `RequestHelper::isMobile()`: Check if request is from mobile device\n- `RequestHelper::isBot()`: Check if request is from bot/crawler\n\n##### Client Information:\n- `RequestHelper::getClientIp($trustProxies = true)`: Get client IP address with proxy support\n- `RequestHelper::getUserAgent()`: Get user agent string\n- `RequestHelper::getReferrer()`: Get referrer URL\n- `RequestHelper::getProtocol()`: Get request protocol (HTTP/1.1, HTTP/2, etc.)\n- `RequestHelper::getPort()`: Get request port\n- `RequestHelper::getHost()`: Get host name\n\n##### Content Analysis:\n- `RequestHelper::getContentType()`: Get request content type\n- `RequestHelper::isContentType($type)`: Check if content type matches\n- `RequestHelper::isJson()`: Check if request has JSON content type\n- `RequestHelper::isXml()`: Check if request has XML content type\n- `RequestHelper::getContentLength()`: Get content length\n- `RequestHelper::getAcceptedLanguages()`: Get accepted languages from Accept-Language header\n\n##### Header Management:\n- `RequestHelper::getHeader($name, $default = null)`: Get specific request header\n- `RequestHelper::hasHeader($name)`: Check if header exists\n- `RequestHelper::getAllHeaders()`: Get all request headers\n\n##### Security and Validation:\n- `RequestHelper::isLegitimate()`: Basic security check for legitimate requests\n- `RequestHelper::getRequestTime()`: Get request timestamp\n- `RequestHelper::isWithinRateLimit($maxRequests, $timeWindow, $identifier = null)`: Basic rate limiting\n\n##### Utility Methods:\n- `RequestHelper::getRequestInfo()`: Get comprehensive request information array\n- `RequestHelper::setTrustedProxyHeaders($headers)`: Set trusted proxy headers\n- `RequestHelper::getTrustedProxyHeaders()`: Get current trusted proxy headers\n\n#### URL Helper (`Http/UrlHelper.php`)\nComprehensive URL manipulation, validation, and generation utilities for HTTP requests.\n\n##### Current URL/URI Methods:\n- `UrlHelper::protocolHostPort()`: Get protocol, host, and port string based on server configuration\n- `UrlHelper::query($parameters = null, $mergeGetVariables = true)`: Build query string from parameters with optional $_GET merging\n- `UrlHelper::currentUrl($includeQuery = true, $urlEncode = false)`: Get current full URL with optional query string and encoding\n- `UrlHelper::currentUri($includeQueryParams = true, $encode = false)`: Get current URI with optional query parameters and encoding\n\n##### URL Parsing and Validation:\n- `UrlHelper::isValidUrl($url, $allowedSchemes = ['http', 'https'])`: Validate URL with configurable allowed schemes\n- `UrlHelper::parseUrl($url)`: Parse URL components into structured array\n- `UrlHelper::buildUrl($components)`: Build URL from component array\n- `UrlHelper::isStandardPort($scheme, $port)`: Check if port is standard for given scheme\n\n##### URL Manipulation:\n- `UrlHelper::addQueryParams($url, $params, $encode = true)`: Add or modify query parameters in URL\n- `UrlHelper::removeQueryParams($url, $paramsToRemove)`: Remove specific query parameters from URL\n- `UrlHelper::changeScheme($url, $scheme)`: Change URL scheme (e.g., HTTP to HTTPS)\n- `UrlHelper::normalize($url)`: Normalize URL by cleaning up common issues\n\n##### Path Manipulation:\n- `UrlHelper::normalizePath($path)`: Normalize URL path by resolving . and .. segments\n- `UrlHelper::joinPaths(...$segments)`: Join multiple path segments into single path\n- `UrlHelper::getDirectory($path)`: Get directory path from URL path\n- `UrlHelper::getFilename($path)`: Get filename from URL path\n- `UrlHelper::getExtension($path)`: Get file extension from URL path\n\n##### Domain and Host Utilities:\n- `UrlHelper::getDomain($url)`: Extract domain from URL\n- `UrlHelper::getSubdomain($url, $levels = 2)`: Extract subdomain with configurable root domain levels\n- `UrlHelper::getRootDomain($url, $levels = 2)`: Get root domain with configurable levels\n- `UrlHelper::isSameDomain($url1, $url2)`: Check if two URLs have same domain\n\n##### Encoding and Decoding:\n- `UrlHelper::encode($string)`: URL encode string with RFC 3986 compliance\n- `UrlHelper::decode($string)`: URL decode string\n- `UrlHelper::encodePath($path)`: Encode only path component of URL\n- `UrlHelper::encodeQuery($params, $rfc3986 = true)`: Encode query string parameters\n\n##### URL Conversion and Transformation:\n- `UrlHelper::toAbsolute($relativeUrl, $baseUrl)`: Convert relative URL to absolute\n- `UrlHelper::toRelative($absoluteUrl, $baseUrl)`: Convert absolute URL to relative\n\n##### Utility Methods:\n- `UrlHelper::currentUrlWithModifications($queryModifications = [], $queryRemovals = [])`: Get current URL with query modifications\n- `UrlHelper::isSecureUrl($url)`: Check if URL uses HTTPS scheme\n- `UrlHelper::getStandardPort($scheme)`: Get standard port for scheme\n- `UrlHelper::sanitize($url, $allowedSchemes = ['http', 'https'])`: Sanitize URL by removing dangerous protocols\n- `UrlHelper::modifiedQuery($params = [], $remove = [])`: Generate query string from current URL with modifications\n\n##### Constants:\n- URL schemes: `SCHEME_HTTP`, `SCHEME_HTTPS`, `SCHEME_FTP`, `SCHEME_SFTP`, `SCHEME_FILE`\n- Standard ports array: `STANDARD_PORTS` with common protocol ports\n\n### HTML Helpers\n\n#### Form Helper (`Html/FormHelper.php`)\nHTML form element generation utilities.\n\n#### Key Functions:\n- `FormHelper::open($action = null, $method = 'GET', $attributesHelper = null)`: Create form opening tag\n- `FormHelper::close()`: Create form closing tag\n- `FormHelper::text($name, $value = null, $attributesHelper = null)`: Create text input\n- `FormHelper::password($name, $value = null, $attributesHelper = null)`: Create password input\n- `FormHelper::email($name, $value = null, $attributesHelper = null)`: Create email input\n- `FormHelper::color($name, $value = null, $attributesHelper = null)`: Create color input\n- `FormHelper::date($name, $value = null, $attributesHelper = null)`: Create date input\n- `FormHelper::datetime($name, $value = null, $attributesHelper = null)`: Create datetime input\n- `FormHelper::datetimeLocal($name, $value = null, $attributesHelper = null)`: Create datetime-local input\n- `FormHelper::month($name, $value = null, $attributesHelper = null)`: Create month input\n- `FormHelper::number($name, $value = null, $attributesHelper = null)`: Create number input\n- `FormHelper::range($name, $value, $min, $max, $attributesHelper = null)`: Create range input\n- `FormHelper::search($name, $value = null, $attributesHelper = null)`: Create search input\n- `FormHelper::tel($name, $value = null, $attributesHelper = null)`: Create telephone input\n- `FormHelper::time($name, $value = null, $attributesHelper = null)`: Create time input\n- `FormHelper::url($name, $value = null, $attributesHelper = null)`: Create URL input\n- `FormHelper::week($name, $value = null, $attributesHelper = null)`: Create week input\n- `FormHelper::hidden($name, $value = null, $attributesHelper = null)`: Create hidden input\n- `FormHelper::textarea($name, $value = null, $attributesHelper = null)`: Create textarea\n- `FormHelper::button($name, $value = null, $attributesHelper = null)`: Create button\n- `FormHelper::submit($name, $value = null, $attributesHelper = null)`: Create submit button\n- `FormHelper::label($value, $forId = null, $formId = null, $attributesHelper = null)`: Create label\n- `FormHelper::select($name, array $options, $checkedValue = null, $attributesHelper = null)`: Create select\n- `FormHelper::selectMultiple($name, array $options, $checkedValue = null, $attributesHelper = null)`: Create multiple select\n- `FormHelper::option($value, $text, $selected = false)`: Create option\n- `FormHelper::optgroup($label, $htmlContent, $attributesHelper = null)`: Create option group\n- `FormHelper::checkbox($name, $value = null, $checked = false, $attributesHelper = null)`: Create checkbox\n- `FormHelper::radio($name, $value = null, $checked = false, $attributesHelper = null)`: Create radio button\n\n#### Attributes Helper (`Html/AttributesHelper.php`)\nA powerful utility class for managing HTML attributes with proper escaping and validation.\n\n```php\n// Create a new instance with initial attributes\n$attrs = AttributesHelper::f(['class' =\u003e 'btn']);\n\n// Add more classes and attributes\n$attrs-\u003eaddClass('btn-primary')\n     -\u003eaddStyle('margin', '10px')\n     -\u003eaddData('toggle', 'modal');\n\n// Render as HTML attributes string\necho $attrs; // outputs: class=\"btn btn-primary\" style=\"margin:10px\" data-toggle=\"modal\"\n```\n\n##### Key Features:\n- Type-safe attribute handling\n- HTML escaping for security\n- CSS style parsing and validation\n- Data attribute management\n- Class name management\n\n##### Main Methods:\n- `AttributesHelper::f($input = null)`: Create new instance (recommended factory method)\n- `setAttribute(string $name, mixed $value)`: Set any attribute with validation\n- `setId(string $value)`: Set the ID attribute\n- `addClass(string|array $classes)`: Add one or more CSS classes\n- `addData(string $name, mixed $value)`: Add a data attribute\n- `addStyle(string $property, string $value)`: Add a CSS style property\n- `render()`: Convert to HTML attributes string\n- `toArray()`: Get all attributes as an array\n\n#### Bootstrap Helper (`Html/BootstrapHelper.php`)\nBootstrap-specific HTML generation utilities.\n\n#### Key Functions:\n- `BootstrapHelper::glyphIcon($name, $attributesHelper = null)`: Create Bootstrap glyphicon span element\n\n```php\nuse AndreasGlaser\\Helpers\\Html\\BootstrapHelper;\n\n// Basic glyphicon\necho BootstrapHelper::glyphIcon('home');\n// Output: \u003cspan class=\"glyphicon glyphicon-home\"\u003e\u003c/span\u003e\n\n// With additional attributes\necho BootstrapHelper::glyphIcon('search', [\n    'id' =\u003e 'search-icon',\n    'class' =\u003e 'icon-large text-primary',\n    'title' =\u003e 'Search',\n    'data-toggle' =\u003e 'tooltip'\n]);\n// Output: \u003cspan id=\"search-icon\" class=\"icon-large text-primary glyphicon glyphicon-search\" title=\"Search\" data-toggle=\"tooltip\"\u003e\u003c/span\u003e\n\n// Using AttributesHelper\n$attrs = AttributesHelper::f()\n    -\u003esetId('my-icon')\n    -\u003eaddClass('text-danger')\n    -\u003eaddData('action', 'delete');\necho BootstrapHelper::glyphIcon('trash', $attrs);\n```\n\n#### Table Helper (`Html/Table/TableHelper.php`)\nHTML table generation utilities.\n\n#### Key Functions:\n- `TableHelper::f($headRows = null, $bodyRows = null, $attributesHelper = null)`: Create table instance\n- `TableHelper::addHeadRow($rowHelper, $setCellAsHeaders = true)`: Add header row\n- `TableHelper::addBodyRow($rowHelper)`: Add body row\n- `TableHelper::render($renderer = null)`: Render table as HTML\n\n#### List Helpers\n\n##### Base List Helper (`Html/Lists/BaseListHelper.php`)\nBase class for HTML list generation.\n\n#### Key Functions:\n- `BaseListHelper::f($items = null, $attributesHelper = null)`: Create list instance\n- `BaseListHelper::addItem($content, $attributesHelper = null)`: Add item to list\n- `BaseListHelper::getItems()`: Get all list items\n- `BaseListHelper::getAttributes()`: Get list attributes\n\n##### Unordered List Helper (`Html/Lists/UnorderedListHelper.php`)\nHTML unordered list generation utilities.\n\n#### Key Functions:\n- `UnorderedListHelper::render($renderer = null)`: Render unordered list as HTML\n\n##### Ordered List Helper (`Html/Lists/OrderedListHelper.php`)\nHTML ordered list generation utilities.\n\n#### Key Functions:\n- `OrderedListHelper::render($renderer = null)`: Render ordered list as HTML\n\n##### Description List Helper (`Html/Lists/DescriptionListHelper.php`)\nHTML description list generation utilities.\n\n#### Key Functions:\n- `DescriptionListHelper::addTerm($term, $description, $attributesHelper = null)`: Add term and description\n- `DescriptionListHelper::render($renderer = null)`: Render description list as HTML\n\n### View Helper (`View/PHPView.php`)\nPHP template rendering and view management utilities.\n\n#### Key Functions:\n- `PHPView::f($file = null, $data = [])`: Create view instance\n- `PHPView::setGlobal($key, $value)`: Set global data accessible to all views\n- `PHPView::getGlobalData()`: Get all global data\n- `PHPView::setFile($filePath)`: Set template file path\n- `PHPView::set($key, $value)`: Set local data for view instance\n- `PHPView::getData()`: Get all local data\n- `PHPView::render($file = null)`: Render template with current data\n- `PHPView::__toString()`: Render template when used as string\n\n### Network Helper (`Validate/NetworkHelper.php`)\nNetwork-related validation utilities.\n\n#### Key Functions:\n- `NetworkHelper::isValidIPv4($ip)`: Validate IPv4 address format\n- `NetworkHelper::isValidIPv6($ip)`: Validate IPv6 address format\n- `NetworkHelper::isValidIP($ip, $allowPrivate = true, $allowReserved = true)`: Validate IP address (both IPv4 and IPv6) with support for private and reserved range validation\n- `NetworkHelper::isValidPort($port, $allowSystemPorts = true, $allowUserPorts = true, $allowDynamicPorts = true)`: Validate port number with customizable range restrictions\n- `NetworkHelper::isValidDomain($domain, $allowSingleLabel = false, $allowPunycode = true)`: Validate domain name with support for Punycode and single-label domains\n- `NetworkHelper::isValidMac($mac, $allowColonFormat = true, $allowHyphenFormat = true, $allowBareFormat = true)`: Validate MAC address in various formats\n- `NetworkHelper::isValidCidr($cidr)`: Validate CIDR notation for both IPv4 and IPv6\n- `NetworkHelper::isValidSubnetMask($mask)`: Validate IPv4 subnet mask\n- `NetworkHelper::getCommonPort($service)`: Get common port number for well-known services\n\n##### DNS Operations:\n- `NetworkHelper::getDnsRecords($domain, $type = 'ALL')`: Get DNS records for a domain with support for all record types (A, AAAA, MX, NS, TXT, etc.)\n- `NetworkHelper::isValidMxRecord($domain)`: Check if a domain has valid MX records\n- `NetworkHelper::getReverseDns($ip)`: Get reverse DNS (PTR) record for an IP address\n- `NetworkHelper::hasValidSpfRecord($domain)`: Check if a domain has a valid SPF record\n- `NetworkHelper::hasDkimRecord($domain, $selector)`: Check if a domain has a valid DKIM record for a selector\n\n##### Socket and Port Operations:\n- `NetworkHelper::isPortOpen($host, $port, $timeout = 2.0)`: Check if a specific port is open on a host\n- `NetworkHelper::getOpenPorts($host, array $ports, $timeout = 1.0)`: Scan multiple ports on a host\n- `NetworkHelper::getServiceByPort($port)`: Get service name for a port number (e.g., 80 → \"http\")\n\n### Validation Helpers\n\n#### Expect Helper (`Validate/Expect.php`)\nType validation utilities that throw exceptions on type mismatches. All methods throw `UnexpectedTypeException` if the value doesn't match the expected type.\n\n##### Basic Type Validation:\n- `Expect::int($value)`: Validates that a value is an integer\n- `Expect::float($value)`: Validates that a value is a float\n- `Expect::str($value)`: Validates that a value is a string\n- `Expect::bool($value)`: Validates that a value is a boolean\n- `Expect::arr($value)`: Validates that a value is an array\n- `Expect::obj($value)`: Validates that a value is an object\n- `Expect::res($value)`: Validates that a value is a resource\n- `Expect::null($value)`: Validates that a value is null\n\n##### Special Type Validation:\n- `Expect::numeric($value)`: Validates that a value is numeric (int, float, or numeric string)\n- `Expect::isCallable($value)`: Validates that a value is callable (function, closure, method array, etc.)\n- `Expect::scalar($value)`: Validates that a value is scalar (int, float, string, or bool)\n\n##### Built-in PHP Type Validation:\n- `Expect::countable($value)`: Validates that a value is countable (array or implements Countable)\n- `Expect::iterable($value)`: Validates that a value is iterable (array or implements Traversable)\n- `Expect::finite($value)`: Validates that a value is a finite number (not infinite or NaN)\n- `Expect::infinite($value)`: Validates that a value is an infinite number\n- `Expect::nan($value)`: Validates that a value is NaN (Not a Number)\n\n#### IOExpect Helper (`Validate/IOExpect.php`)\nFile system validation utilities that throw exceptions on validation failures. All methods throw `IOException` if the validation fails.\n\n##### Path Existence and Type Validation:\n- `IOExpect::exists($path)`: Validates that a path exists (file or directory)\n- `IOExpect::doesNotExist($path)`: Validates that a path does not exist\n- `IOExpect::isDir($path)`: Validates that a path exists and is a directory\n- `IOExpect::isFile($path)`: Validates that a path exists and is a file\n- `IOExpect::isLink($path)`: Validates that a path is a symbolic link\n\n##### Permission Validation:\n- `IOExpect::isReadable($path)`: Validates that a path is readable\n- `IOExpect::isWritable($path)`: Validates that a path is writable\n- `IOExpect::isExecutable($path)`: Validates that a path is executable\n- `IOExpect::parentDirWritable($path)`: Validates that parent directory exists and is writable\n\n##### Directory Content Validation:\n- `IOExpect::isDirEmpty($path)`: Validates that a directory is empty\n- `IOExpect::isDirNotEmpty($path)`: Validates that a directory is not empty\n\n##### File Content and Properties Validation:\n- `IOExpect::isFileNotEmpty($path)`: Validates that a file is not empty\n- `IOExpect::hasMinSize($path, $minSize)`: Validates that a file has minimum size in bytes\n- `IOExpect::hasMaxSize($path, $maxSize)`: Validates that a file has maximum size in bytes\n- `IOExpect::hasExtension($path, $extension)`: Validates that a file has specific extension\n- `IOExpect::hasAllowedExtension($path, $extensions)`: Validates that a file has one of allowed extensions\n- `IOExpect::hasMimeType($path, $expectedMimeType)`: Validates that a file matches specific MIME type\n\n\n## Testing\n\nThe library includes comprehensive unit tests for all components. Each helper class has a corresponding test class that verifies its functionality:\n\n- `ArrayHelperTest`: Tests array manipulation and path operations\n- `AttributesHelperTest`: Tests HTML attribute management and validation\n- `BootstrapHelperTest`: Tests Bootstrap component generation and glyphicon creation\n- `CounterHelperTest`: Tests counter operations and assertions\n- `CsvHelperTest`: Tests CSV file operations and string conversion\n- `DateHelperTest`: Tests date formatting and difference calculations\n- `EmailHelperTest`: Tests email validation and cleaning\n- `ExpectTest`: Tests type validation and exception throwing\n- `FormHelperTest`: Tests HTML form element generation and validation\n- `HtmlHelperTest`: Tests HTML element generation and attributes\n- `IOExpectTest`: Tests file system validation and IOException handling\n- `IOHelperTest`: Tests file system operations\n- `JsonHelperTest`: Tests JSON validation for various data types\n- `NumberHelperTest`: Tests number formatting and ordinal conversion\n- `RandomHelperTest`: Tests random value generation\n- `RequestHelperTest`: Tests comprehensive HTTP request analysis including environment detection, method analysis, client information, content analysis, and security features\n- `StringHelperTest`: Tests string comparison and manipulation methods\n- `UrlHelperTest`: Tests comprehensive URL manipulation including validation, parsing, path operations, domain extraction, encoding, and utility methods\n- `ValueHelperTest`: Tests value validation and type checking\n\nRun the tests using:\n\n```bash\ncomposer install\n./vendor/phpunit/phpunit/phpunit\n```\n\n## Usage\n\n```php\nuse AndreasGlaser\\Helpers\\ArrayHelper;\nuse AndreasGlaser\\Helpers\\StringHelper;\nuse AndreasGlaser\\Helpers\\DateHelper;\nuse AndreasGlaser\\Helpers\\ValueHelper;\nuse AndreasGlaser\\Helpers\\CsvHelper;\nuse AndreasGlaser\\Helpers\\EmailHelper;\nuse AndreasGlaser\\Helpers\\Html\\FormHelper;\nuse AndreasGlaser\\Helpers\\Html\\AttributesHelper;\nuse AndreasGlaser\\Helpers\\Validate\\Expect;\nuse AndreasGlaser\\Helpers\\Validate\\IOExpect;\n\n// Array operations\n$array = ['user' =\u003e ['profile' =\u003e ['name' =\u003e 'John']]];\n$name = ArrayHelper::getByPath($array, 'user.profile.name'); // Returns 'John'\n\n// String operations\n$string = 'Hello World';\n$contains = StringHelper::contains($string, 'World'); // Returns true\n$startsWith = StringHelper::startsWith($string, 'Hello'); // Returns true\n\n// Date operations\n$date = new DateTime();\n$hours = DateHelper::diffHours($date, new DateTime('+1 day')); // Returns 24\n\n// Value validation\n$isValid = ValueHelper::isDateTime('2024-03-20'); // Returns true\n\n// CSV operations\n$csvData = [\n    ['Name', 'Email', 'Age'],\n    ['John Doe', 'john@example.com', '30'],\n    ['Jane Smith', 'jane@example.com', '25']\n];\n$csvString = CsvHelper::arrayToCsvString($csvData);\n// Result: \"Name,Email,Age\\nJohn Doe,john@example.com,30\\nJane Smith,jane@example.com,25\"\n\n// Read CSV file to array\n$data = CsvHelper::fileToArray('users.csv', true); // true for header row\n// With custom delimiter\n$data = CsvHelper::fileToArray('data.csv', false, 0, ';'); // semicolon delimiter\n\n// Email operations\n$validEmail = EmailHelper::isValid('user@example.com'); // Returns true\n$invalidEmail = EmailHelper::isValid('invalid-email'); // Returns false\n\n// Clean and normalize email addresses\n$emails = 'user@example.com, invalid-email, admin@test.com; contact@domain.org';\n$cleanEmails = EmailHelper::clean($emails); // Returns ['user@example.com', 'admin@test.com', 'contact@domain.org']\n\n// Clean with custom delimiters\n$emails = 'user@example.com:admin@test.com#contact@domain.org';\n$cleanEmails = EmailHelper::clean($emails, [':', '#']); // Returns ['user@example.com', 'admin@test.com', 'contact@domain.org']\n\n// Clean array of emails\n$emailArray = ['user@example.com', 'invalid', 'admin@test.com'];\n$cleanEmails = EmailHelper::clean($emailArray); // Returns ['user@example.com', 'admin@test.com']\n\n// Form generation\necho FormHelper::open('/users', 'POST', ['class' =\u003e 'user-form']);\necho FormHelper::text('name', 'John Doe', ['id' =\u003e 'name', 'required' =\u003e 'required']);\necho FormHelper::email('email', 'john@example.com', ['placeholder' =\u003e 'Enter email']);\necho FormHelper::select('country', ['US' =\u003e 'United States', 'CA' =\u003e 'Canada'], 'US');\necho FormHelper::textarea('bio', 'Tell us about yourself', ['rows' =\u003e 5]);\necho FormHelper::submit('submit', 'Create User', ['class' =\u003e 'btn btn-primary']);\necho FormHelper::close();\n\n// HTML attribute management\n$attrs = AttributesHelper::f(['class' =\u003e 'btn'])\n    -\u003eaddClass('btn-primary')\n    -\u003eaddStyle('margin', '10px')\n    -\u003eaddData('toggle', 'modal');\necho $attrs; // outputs: class=\"btn btn-primary\" style=\"margin:10px\" data-toggle=\"modal\"\n\n// Type validation with exceptions\nExpect::int(42);           // Valid - no exception\nExpect::str('hello');      // Valid - no exception\nExpect::finite(42.5);      // Valid - finite number\n\n// File system validation\nIOExpect::isFile('/path/to/file.txt');    // Throws IOException if not a file\nIOExpect::isReadable('/path/to/file.txt'); // Throws IOException if not readable\n```\n\n## Contributing\n\n1. Fork the repository\n2. Create your feature branch (`git checkout -b feature/amazing-feature`)\n3. Commit your changes (`git commit -m 'Add some amazing feature'`)\n4. Push to the branch (`git push origin feature/amazing-feature`)\n5. Open a Pull Request\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Author\n\n- **Andreas Glaser** - [GitHub](https://github.com/andreas-glaser)\n\n## Support\n\nIf you find this library helpful, please consider giving it a star on GitHub!","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreas-glaser%2Fphp-helpers","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fandreas-glaser%2Fphp-helpers","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fandreas-glaser%2Fphp-helpers/lists"}