{"id":21823521,"url":"https://github.com/jbzoo/utils","last_synced_at":"2025-05-14T21:06:26.914Z","repository":{"id":1771124,"uuid":"44679560","full_name":"JBZoo/Utils","owner":"JBZoo","description":"Collection of useful PHP functions, mini-classes, and snippets for every day.","archived":false,"fork":false,"pushed_at":"2024-06-22T09:31:57.000Z","size":551,"stargazers_count":816,"open_issues_count":0,"forks_count":73,"subscribers_count":35,"default_branch":"master","last_synced_at":"2025-05-12T21:47:44.044Z","etag":null,"topics":["array-manipulations","enviroment","jbzoo","php","php-functions","snippets","string-manipulation","utilities","utility","utility-classes","utility-function","utility-library","utils"],"latest_commit_sha":null,"homepage":"","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/JBZoo.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,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2015-10-21T13:53:49.000Z","updated_at":"2025-04-22T08:43:04.000Z","dependencies_parsed_at":"2023-10-15T17:41:56.050Z","dependency_job_id":"ccdf52da-6892-46bd-9859-9d73dd923474","html_url":"https://github.com/JBZoo/Utils","commit_stats":{"total_commits":340,"total_committers":9,"mean_commits":37.77777777777778,"dds":0.4,"last_synced_commit":"346c3b249d1d3a3b5132e686b5599cd11b9ec073"},"previous_names":[],"tags_count":88,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JBZoo%2FUtils","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JBZoo%2FUtils/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JBZoo%2FUtils/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JBZoo%2FUtils/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JBZoo","download_url":"https://codeload.github.com/JBZoo/Utils/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254227611,"owners_count":22035669,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","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":["array-manipulations","enviroment","jbzoo","php","php-functions","snippets","string-manipulation","utilities","utility","utility-classes","utility-function","utility-library","utils"],"created_at":"2024-11-27T17:33:08.963Z","updated_at":"2025-05-14T21:06:21.862Z","avatar_url":"https://github.com/JBZoo.png","language":"PHP","readme":"# JBZoo / Utils\n\n[![CI](https://github.com/JBZoo/Utils/actions/workflows/main.yml/badge.svg?branch=master)](https://github.com/JBZoo/Utils/actions/workflows/main.yml?query=branch%3Amaster)    [![Coverage Status](https://coveralls.io/repos/github/JBZoo/Utils/badge.svg?branch=master)](https://coveralls.io/github/JBZoo/Utils?branch=master)    [![Psalm Coverage](https://shepherd.dev/github/JBZoo/Utils/coverage.svg)](https://shepherd.dev/github/JBZoo/Utils)    [![Psalm Level](https://shepherd.dev/github/JBZoo/Utils/level.svg)](https://shepherd.dev/github/JBZoo/Utils)    [![CodeFactor](https://www.codefactor.io/repository/github/jbzoo/utils/badge)](https://www.codefactor.io/repository/github/jbzoo/utils/issues)    \n[![Stable Version](https://poser.pugx.org/jbzoo/utils/version)](https://packagist.org/packages/jbzoo/utils/)    [![Total Downloads](https://poser.pugx.org/jbzoo/utils/downloads)](https://packagist.org/packages/jbzoo/utils/stats)    [![Dependents](https://poser.pugx.org/jbzoo/utils/dependents)](https://packagist.org/packages/jbzoo/utils/dependents?order_by=downloads)    [![GitHub License](https://img.shields.io/github/license/jbzoo/utils)](https://github.com/JBZoo/Utils/blob/master/LICENSE)\n\n\n\u003c!--ts--\u003e\n   * [Install](#install)\n   * [Usage](#usage)\n      * [Smart functions](#smart-functions)\n      * [JBZoo\\Utils\\Arr](#jbzooutilsarr)\n      * [JBZoo\\Utils\\Cli](#jbzooutilscli)\n      * [JBZoo\\Utils\\Csv](#jbzooutilscsv)\n      * [JBZoo\\Utils\\Dates](#jbzooutilsdates)\n      * [JBZoo\\Utils\u001bmail](#jbzooutilsemail)\n      * [JBZoo\\Utils\u001bnv](#jbzooutilsenv)\n      * [JBZoo\\Utils\\FS](#jbzooutilsfs)\n      * [JBZoo\\Utils\\Filter](#jbzooutilsfilter)\n      * [JBZoo\\Utils\\Http](#jbzooutilshttp)\n      * [JBZoo\\Utils\\IP](#jbzooutilsip)\n      * [JBZoo\\Utils\\Image](#jbzooutilsimage)\n      * [JBZoo\\Utils\\PhpDocs](#jbzooutilsphpdocs)\n      * [JBZoo\\Utils\\Ser](#jbzooutilsser)\n      * [JBZoo\\Utils\\Slug](#jbzooutilsslug)\n      * [JBZoo\\Utils\\Stats](#jbzooutilsstats)\n      * [JBZoo\\Utils\\Str](#jbzooutilsstr)\n      * [JBZoo\\Utils\\Sys](#jbzooutilssys)\n      * [JBZoo\\Utils\\Timer](#jbzooutilstimer)\n      * [JBZoo\\Utils\\Url](#jbzooutilsurl)\n      * [JBZoo\\Utils\\Vars](#jbzooutilsvars)\n      * [JBZoo\\Utils\\Xml](#jbzooutilsxml)\n   * [Links (ideas and some functions)](#links-ideas-and-some-functions)\n   * [Unit tests and check code style](#unit-tests-and-check-code-style)\n   * [License](#license)\n   * [See Also](#see-also)\n\u003c!--te--\u003e\n\n\nCollection of PHP functions, mini classes and snippets for everyday developer's routine life.\n\n\n## Install\n```sh\ncomposer require jbzoo/utils\n```\n\n## Usage\n\n### Smart functions\n```php\nuse function JBZoo\\Utils\\alias;\nuse function JBZoo\\Utils\\alpha;\nuse function JBZoo\\Utils\\alphanum;\nuse function JBZoo\\Utils\\bool;\nuse function JBZoo\\Utils\\digits;\nuse function JBZoo\\Utils\\float;\nuse function JBZoo\\Utils\\int;\n\nint(' 10.0 ') === 10;\nfloat(' 10.0 ') === 10.0;\n\nbool(' yes ') === true;\nbool(' no ') === false;\nbool('1') === true;\nbool('0') === false;\n\nalias('Qwer ty') === 'qwer-ty';\ndigits('Qwer 1 ty2') === '12';\nalpha('Qwer 1 ty2') === 'Qwerty';\nalphanum(' #$% Qwer 1 ty2') === 'Qwer1ty2';\n```\n\n\n### JBZoo\\Utils\\Arr\n\n```php\nArr::addEachKey(array $array, string $prefix): array; // Add some prefix to each key.\n\nArr::clean(array $haystack): array; // Clean array by custom rule.\n\nArr::cleanBeforeJson(array $array): array; // Clean array before serialize to JSON.\n\nArr::first(array $array): ?mixed; // Returns the first element in an array.\n\nArr::firstKey(array $array): ?string|int|null; // Returns the first key in an array.\n\n// Flatten a multi-dimensional array into a one dimensional array.\n//                            overwrite keys from shallow nested arrays\nArr::flat(array $array, bool $preserveKeys = true): array;\n\nArr::getField(array $arrayList, string $fieldName = 'id'): array; // Get one field from array of arrays (array of objects).\n\nArr::getSchema(array $array): array; // Returns type of variables as array schema.\n\nArr::groupByKey(array $arrayList, string $key = 'id'): array; // Group array by key and return list of grouped values.\n\nArr::implode(string $glue, array $array): string; // Array imploding for nested array.\n\nArr::in(?mixed $value, array $array, bool $returnKey = false): ?string|int|bool|null; // Check is value exists in the array.\n\nArr::isAssoc(array $array): bool; // Check is array is type assoc.\n\nArr::key(?mixed $key, array $array, bool $returnValue = false): ?mixed; // Check if key exists.\n\nArr::last(array $array): ?mixed; // Returns the last element in an array.\n\nArr::lastKey(array $array): ?string|int|null; // Returns the last key in an array.\n\nArr::map(Closure $function, array $array): array; // Recursive array mapping.\n\n// Returns an array containing all the elements of arr1 after applying\n// the callback function to each one.\n//                             (Objects, resources, etc)\nArr::mapDeep(array $array, callable $callback, bool $onNoScalar = false): array;\n\nArr::removeByValue(array $array, ?string|int|float|bool|null $value): array; // Remove all items from array by value.\n\n// Searches for a given value in an array of arrays, objects and scalar values. You can optionally specify\n// a field of the nested arrays and objects to search in.\nArr::search(array $array, ?string|int|float|bool|null $search, ??string $field = null): string|bool;\n\nArr::sortByArray(array $array, array $orderArray): array; // Sort an array by keys based on another array.\n\nArr::toComment(array $data): string; // Convert assoc array to comment style.\n\nArr::unique(array $array, bool $keepKeys = false): array; // Remove the duplicates from an array.\n\nArr::unshiftAssoc(array $array, string|int $key, ?mixed $value): array; // Add cell to the start of assoc array.\n\n// Wraps its argument in an array unless it is already an array.\n//   Arr.wrap(null)      # =\u003e []\n//   Arr.wrap([1, 2, 3]) # =\u003e [1, 2, 3]\n//   Arr.wrap(0)         # =\u003e [0]\nArr::wrap(?mixed $object): array;\n\n```\n\n\n### JBZoo\\Utils\\Cli\n\n```php\nCli::build(string $command, array $args = []): string; // Build params for cli options.\n\nCli::check(): bool; // Is command line mode.\n\nCli::err(string $message, bool $addEol = true): bool; // Print line to std error.\n\nCli::exec(string $command, array $args = [], ??string $cwd = null, bool $verbose = false): string; // Execute cli commands.\n\nCli::getNumberOfColumns(): int; // Returns the number of columns of the terminal.\n\n// Returns true if STDOUT supports colorization.\n// This code has been copied and adapted from \\Symfony\\Component\\Console\\Output\\OutputStream.\nCli::hasColorSupport(): bool;\n\nCli::isInteractive($fileDescriptor = 1): bool; // Returns if the file descriptor is an interactive terminal or not.\n\nCli::out(string $message, bool $addEol = true): bool; // Print line to std out.\n\n```\n\n\n### JBZoo\\Utils\\Csv\n\n```php\nCsv::parse(string $csvFile, string $delimiter = ';', string $enclosure = '\"', bool $hasHeader = true): array; // Simple parser for CSV files.\n\n```\n\n\n### JBZoo\\Utils\\Dates\n\n```php\nDates::factory(?mixed $time = null, ?DateTimeZone|string|null $timeZone = null): DateTime; // Build PHP \\DateTime object from mixed input.\n\nDates::formatTime(float $seconds, int $minValuableSeconds = 2): string; // Convert seconds to human-readable format \"H:i:s\".\n\nDates::human(string|int $date, string $format = 'd M Y H:i'): string; // Convert date string ot unix timestamp to human-readable date format.\n\nDates::is(??string $date): bool; // Check if string is date.\n\nDates::isThisMonth(string|int $time): bool; // Returns true if date passed is within this month.\n\nDates::isThisWeek(string|int $time): bool; // Returns true if date passed is within this week.\n\nDates::isThisYear(string|int $time): bool; // Returns true if date passed is within this year.\n\nDates::isToday(string|int $time): bool; // Returns true if date passed is today.\n\nDates::isTomorrow(string|int $time): bool; // Returns true if date passed is tomorrow.\n\nDates::isYesterday(string|int $time): bool; // Returns true if date passed was yesterday.\n\nDates::sql(?string|int|null $time = null): string; // Convert time for sql format.\n\nDates::timezone(?DateTimeZone|string|null $timezone = null): DateTimeZone; // Returns a DateTimeZone object based on the current timezone.\n\nDates::toStamp(?DateTime|string|int|null $time = null, bool $currentIsDefault = true): int; // Convert to timestamp.\n\n```\n\n\n### JBZoo\\Utils\\Email\n\n```php\nEmail::check(?mixed $emails): array; // Check if email(s) is(are) valid. You can send one or an array of emails.\n\n// Check for DNS MX records of the email domain.\n// Notice that a (temporary) DNS error will have the same result as no records were found.\n// Code coverage ignored because this method requires DNS requests that could not be reliable.\nEmail::checkDns(string $email): bool;\n\nEmail::getDomain(?mixed $emails): array; // Get domains from email addresses. The not valid email addresses will be skipped.\n\nEmail::getDomainSorted(array $emails): array; // Get domains from email addresses in alphabetical order.\n\nEmail::getGravatarBuiltInImages(): array; // Returns gravatar supported placeholders.\n\n// Generates a Gravatar URL.\n// Size of the image:\n// * The default size is 32px, and it can be anywhere between 1px up to 2048px.\n// * If requested any value above the allowed range, then the maximum is applied.\n// * If requested any value bellow the minimum, then the default is applied.\n// Default image:\n// * It can be a URL to an image.\n// * Or one of built-in options that Gravatar has. See Email::getGravatarBuiltInImages().\n// * If none is defined then a built-in default is used. See Email::getGravatarBuiltInDefaultImage().\nEmail::getGravatarUrl(string $email, int $size = 32, string $defaultImage = 'identicon'): ??string;\n\nEmail::isValid(??string $email): bool; // Returns true if string has valid email format.\n\nEmail::random(int $userNameLength = 10): string; // Create random email.\n\n```\n\n\n### JBZoo\\Utils\\Env\n\n```php\nEnv::bool(string $envVarName, bool $default = false): bool; // Convert value of environment variable to strict bool value.\n\nEnv::convert(??string $value, int $options = 16): ?string|int|float|bool|null; // Converts the type of values like \"true\", \"false\", \"null\" or \"123\".\n\nEnv::float(string $envVarName, float $default = 0): float; // Convert value of environment variable to strict float value.\n\nEnv::get(string $envVarName, ?string|int|float|bool|null $default = null, int $options = 16): ?string|int|float|bool|null; // Returns an environment variable.\n\nEnv::int(string $envVarName, int $default = 0): int; // Convert value of environment variable to strict integer value.\n\nEnv::isExists(string $envVarName): bool; // Returns true if environment variable exists.\n\nEnv::string(string $envVarName, string $default = ''): string; // Convert value of environment variable to clean string.\n\n```\n\n\n### JBZoo\\Utils\\FS\n\n```php\nFS::base(??string $path): string; // Returns name of file with ext from FS pathname.\n\nFS::clean(??string $path, string $dirSep = '/'): string; // Function to strip trailing / or \\ in a pathname.\n\nFS::dirName(??string $path): string; // Returns name for directory from FS pathname.\n\nFS::dirSize(string $dir): int; // Returns size of a given directory in bytes.\n\nFS::executable(string $filename, bool $executable = true): bool; // Set the executable bit on a file to the minimum value that allows the user running PHP to read to it.\n\nFS::ext(??string $path): string; // Returns extension of file from FS pathname.\n\nFS::filename(??string $path): string; // Returns filename without ext from FS pathname.\n\nFS::firstLine(string $filepath): ??string; // Quickest way for getting first file line.\n\nFS::format(int $bytes, int $decimals = 2): string; // Nice formatting for computer sizes (Bytes).\n\nFS::getRelative(string $path, ??string $rootPath = null, string $forceDS = '/'): string; // Find relative path of file (remove root part).\n\nFS::isDir(??string $path): bool; // Check is current path directory.\n\nFS::isFile(string $path): bool; // Check is current path regular file.\n\nFS::isReal(??string $path): bool; // Returns clean realpath if file or directory exists.\n\nFS::ls(string $dir): array; // Returns all paths inside a directory.\n\nFS::openFile(string $filepath): ??string; // Binary safe to open file.\n\nFS::perms(string $file, ??int $perms = null): string; // Returns the file permissions as a nice string, like -rw-r--r-- or false if the file is not found.\n\nFS::readable(string $filename, bool $readable = true): bool; // Set the readable bit on a file to the minimum value that allows the user running PHP to read to it.\n\nFS::real(??string $path): ??string; // Returns realpath (smart analog of PHP \\realpath()).\n\n// Removes a directory (and its contents) recursively.\n// Contributed by Askar (ARACOOL) \u003chttps://github.com/ARACOOOL\u003e.\nFS::rmDir(string $dir, bool $traverseSymlinks = true): bool;\n\nFS::stripExt(string $path): string; // Strip off the extension if it exists.\n\nFS::writable(string $filename, bool $writable = true): bool; // Set the writable bit on a file to the minimum value that allows the user running PHP to write to it.\n\n```\n\n\n### JBZoo\\Utils\\Filter\n\n```php\nFilter::_(?mixed $value, Closure|string $filters = 'raw'): ?mixed; // Apply custom filter to variable.\n\nFilter::alias(string $string): string; // Get safe string for sensitive external dependencies.\n\nFilter::alpha(??string $value): string; // Returns only alpha chars.\n\nFilter::alphanum(??string $value): string; // Returns only alpha and digits chars.\n\nFilter::arr(?mixed $value, ?Closure|string|null $filter = null): array; // Cleanup array. No empty values.\n\nFilter::base64(string $value): string; // Returns only chars for base64.\n\nFilter::bool(?mixed $variable): bool; // Converts many english words that equate to true or false to boolean.\n\nFilter::className(string $input): string; // Convert words to PHP Class name.\n\nFilter::clean(string $string): string; // Alias of \"Str::clean($string, true, true)\".\n\nFilter::cmd(string $value): string; // Cleanup system command.\n\nFilter::data(JBZoo\\Data\\Data|array $data): JBZoo\\Data\\Data; // Returns Data object from array.\n\nFilter::digits(??string $value): string; // Returns only digits chars.\n\nFilter::esc(string $string): string; // Alias of \"Str::esc($string)\".\n\nFilter::float(?mixed $value, int $round = 10): float; // Smart converter string to float.\n\nFilter::html(string $string): string; // Alias of \"Str::htmlEnt($string)\".\n\nFilter::int(?string|int|float|bool|null $value): int; // Smart convert any string to int.\n\nFilter::json(JBZoo\\Data\\JSON|array $data): JBZoo\\Data\\JSON; // Returns JSON object from array.\n\nFilter::low(string $string): string; // String to lower and trim.\n\nFilter::parseLines(array|string $input): array; // Parse lines to assoc list.\n\nFilter::path(string $value): string; // Returns only chars for base64url.\n\nFilter::raw(?mixed $variable): ?mixed; // RAW placeholder for internal API of the library.\n\nFilter::strip(string $string): string; // Get safe string without html tags and trimmed.\n\nFilter::stripQuotes(string $value): string; // Smart striping quotes, double and single.\n\nFilter::stripSpace(string $string): string; // Alias of \"Str::stripSpace($string)\".\n\nFilter::trim(string $value): string; // Alias for build-in function \\trim().\n\nFilter::trimExtend(string $value): string; // Extended trim function for remove all spaces, tabs, new lines and really special chars.\n\nFilter::ucFirst(string $input): string; // First char to upper, other to lower.\n\nFilter::up(string $string): string; // String to upper and trim.\n\nFilter::xml(string $string): string; // Alias of \"Xml::escape($string)\".\n\n```\n\n\n### JBZoo\\Utils\\Http\n\n```php\n// Transmit headers that force a browser to display the download file dialog.\n// Cross browser compatible. Only fires if headers have not already been sent.\nHttp::download(string $filename): bool;\n\nHttp::getHeaders(): array; // Get all HTTP headers.\n\n// Sets the headers to prevent caching for the different browsers.\n// Different browsers support different nocache headers, so several\n// headers must be sent so that all of them get the point that no caching should occur.\nHttp::nocache(): bool;\n\nHttp::utf8(string $contentType = 'text/html'): bool; // Transmit UTF-8 content headers if the headers haven't already been sent.\n\n```\n\n\n### JBZoo\\Utils\\IP\n\n```php\nIP::getNetMask(string $ipAddress): ??string; // Return network mask. For example, '192.0.0.0' =\u003e '255.255.255.0'.\n\n// Returns the IP address of the client.\n//                         ONLY use if your server is behind a proxy that sets these values\nIP::getRemote(bool $trustProxy = false): string;\n\nIP::v4InRange(string $ipAddress, string $range): bool; // Check if a given ip is in a network.\n\n```\n\n\n### JBZoo\\Utils\\Image\n\n```php\nImage::addAlpha(GdImage $image, bool $isBlend = true): void; // Add alpha chanel to image resource.\n\nImage::alpha(float $color): int; // Returns valid value of alpha-channel.\n\nImage::blur(float $blur): int; // Return valid value to blur image (1-10).\n\nImage::brightness(float $brightness): int; // Returns valid value to make image bright (-255..255).\n\nImage::checkGD(bool $throwException = true): bool; // Check if GD library is enabled on server.\n\nImage::color(float $color): int; // Returns valid value to change color segment of a image (0..255).\n\nImage::colorize(float $colorize): int; // Returns valid value to change color segment of a image (-255..255).\n\nImage::contrast(float $contrast): int; // Returns valid value to change contrast of a image (-100..100).\n\nImage::direction(string $direction): string; // Returns valid value of image direction: 'x', 'y', 'xy', 'yx'.\n\nImage::getInnerCoords(string $position, array $canvas, array $box, array $offset = []): ??array; // Determine position. Returns array with X and Y coordinates.\n\nImage::imageCopyMergeAlpha(GdImage $dstImg, GdImage $srcImg, array $dist, array $src, array $srcSizes, int $opacity): void; // Same as PHP's imagecopymerge() function, except preserves alpha-transparency in 24-bit PNGs.\n\nImage::isGif(??string $format = null): bool; // Checks if image has GIF format.\n\nImage::isJpeg(??string $format = null): bool; // Checks if image has JPEG/JPG format.\n\nImage::isPng(??string $format = null): bool; // Checks if image has PNG format.\n\nImage::isSupportedFormat(string $format): bool; // Check is format supported by lib.\n\nImage::isWebp(??string $format = null): bool; // Checks if image has WEBP format.\n\n// Converts a hex color value to its RGB equivalent.\n//                                 Where red, green, blue - integers 0-255, alpha - integer 0-127\nImage::normalizeColor(array|string $origColor): array;\n\nImage::opacity(float $opacity): int; // Check opacity value.\n\nImage::opacity2Alpha(float $opacity): int; // Convert opacity value to alpha.\n\nImage::percent(float $percent): int; // Return valid value of percent (0-100).\n\nImage::position(string $position): string; // Check position name.\n\nImage::quality(float $percent): int; // Returns valid value of image quality (0..100).\n\nImage::rotate(float $color): int; // Returns valid value of image rotation (-360..360).\n\nImage::smooth(float $smooth): int; // Returns valid value to change smoothness of a image (1..10).\n\nImage::strToBin(string $imageString): ??string; // Convert string to binary data.\n\n```\n\n\n### JBZoo\\Utils\\PhpDocs\n\n```php\n// Simple parse of PHPDocs.\n// Example or return value\n//  [\n//      'description' =\u003e 'Simple parse of PHPDocs. Example or return value',\n//      'params'      =\u003e [\n//          'param'  =\u003e ['string $phpDoc'],\n//          'return' =\u003e ['array']\n//      ]\n//  ].\nPhpDocs::parse(string $phpDoc): array;\n\n```\n\n\n### JBZoo\\Utils\\Ser\n\n```php\n// UnSerializes partially-corrupted arrays that occur sometimes. Addresses\n// specifically the `unserialize(): Error at offset xxx of yyy bytes` error.\n// NOTE: This error can *frequently* occur with mismatched character sets and higher-than-ASCII characters.\n// Contributed by Theodore R. Smith of PHP Experts, Inc. \u003chttp://www.phpexperts.pro/\u003e.\nSer::fix(string $brokenSerializedData): string;\n\n// Check value to find if it was serialized.\n// If $data is not a string, then returned value will always be false. Serialized data is always a string.\nSer::is(?mixed $data): bool;\n\nSer::maybe(?mixed $data): ?mixed; // Serialize data, if needed.\n\nSer::maybeUn(string $data): ?mixed; // Unserialize value only if it is serialized.\n\n```\n\n\n### JBZoo\\Utils\\Slug\n\n```php\n// Transliterates characters to their ASCII equivalents.\n// Part of the URLify.php Project \u003chttps://github.com/jbroadway/urlify/\u003e.\nSlug::downCode(string $text, string $language = ''): string;\n\n// Converts any accent characters to their equivalent normal characters and converts any other non-alphanumeric\n// characters to dashes, then converts any sequence of two or more dashes to a single dash. This function generates\n// slugs safe for use as URLs, and if you pass true as the second parameter, it will create strings safe for\n// use as CSS classes or IDs.\nSlug::filter(??string $string, string $separator = '-', bool $cssMode = false): string;\n\n// Converts all accent characters to ASCII characters.\n// If there are no accent characters, then the string given is just returned.\nSlug::removeAccents(string $string, string $language = ''): string;\n\n// Checks to see if a string is utf8 encoded.\n// NOTE: This function checks for 5-Byte sequences, UTF8 has Bytes Sequences with a maximum length of 4.\n// Written by Tony Ferrara \u003chttp://blog.ircmaxwell.com\u003e.\nSlug::seemsUTF8(string $string): bool;\n\n```\n\n\n### JBZoo\\Utils\\Stats\n\n```php\nStats::histogram(array $values, int $steps = 10, ??float $lowerBound = null, ??float $upperBound = null): array; // Generate a histogram. Note this is not a great function, and should not be relied upon for serious use.\n\nStats::linSpace(float $min, float $max, int $num = 50, bool $endpoint = true): array; // Returns an array populated with $num numbers from $min to $max.\n\nStats::mean(??array $values): float; // Returns the mean (average) value of the given values.\n\nStats::median(array $data): float; // Calculate the median of a given population.\n\nStats::percentile(array $data, int|float $percentile = 95): float; // Calculate the percentile of a given population.\n\nStats::renderAverage(array $values, int $rounding = 3): string; // Render human readable string of average value and system error.\n\nStats::renderMedian(array $values, int $rounding = 3): string; // Render human readable string of average value and system error.\n\nStats::stdDev(array $values, bool $sample = false): float; // Returns the standard deviation of a given population.\n\nStats::variance(array $values, bool $sample = false): float; // Returns the variance for a given population.\n\n```\n\n\n### JBZoo\\Utils\\Str\n\n```php\n// Make string safe\n// - Remove UTF-8 chars\n// - Remove all tags\n// - Trim\n// - Add Slashes (opt)\n// - To lower (opt).\nStr::clean(string $string, bool $toLower = false, bool $addSlashes = false, bool $removeAccents = true): string;\n\nStr::esc(string $string): string; // Escape UTF-8 strings.\n\n// Escape string before save it as xml content.\n// The function is moved. Please, use \\JBZoo\\Utils\\Xml::escape($string). It'll be deprecated soon.\nStr::escXml(string $string): string;\n\nStr::getClassName(?object|string|null $object, bool $toLower = false): ??string; // Get class name without namespace.\n\nStr::htmlEnt(string $string, bool $encodedEntities = false): string; // Convert \u003e, \u003c, ', \" and \u0026 to html entities, but preserves entities that are already encoded.\n\nStr::iPos(string $haystack, string $needle, int $offset = 0): ??int; // Finds position of first occurrence of a string within another, case-insensitive.\n\nStr::iStr(string $haystack, string $needle, bool $beforeNeedle = false): string; // Finds first occurrence of a string within another, case-insensitive.\n\n// Increments a trailing number in a string.\n// Used to easily create distinct labels when copying objects. The method has the following styles:\n//  - default: \"Label\" becomes \"Label (2)\"\n//  - dash:    \"Label\" becomes \"Label-2\".\nStr::inc(string $string, string $style = 'default', int $next = 0): string;\n\nStr::isEmpty(?string|bool|null $value, bool $strict = false): bool; // Extend version of checking if potetielly empty string is empty.\n\nStr::isEnd(string $haystack, string $needle, bool $caseSensitive = false): bool; // Checks if the $haystack ends with the text in the $needle. Case-sensitive.\n\nStr::isMBString(): bool; // Check is mbstring loaded.\n\nStr::isStart(string $haystack, string $needle, bool $caseSensitive = false): bool; // Checks if the $haystack starts with the text in the $needle.\n\nStr::len(string $string): int; // Get real string length if it's possible.\n\nStr::like(string $pattern, string $haystack, bool $caseSensitive = true): bool; // Check if a given string matches a given pattern.\n\nStr::limitChars(string $string, int $limit = 100, string $append = '...'): string; // Truncate the string to given length of characters.\n\nStr::limitWords(string $string, int $limit = 100, string $append = '...'): string; // Truncate the string to given length of words.\n\nStr::listToDescription(array $data, bool $alignByKeys = false): ??string; // Convert array of strings to list as pretty print description.\n\nStr::low(string $string): string; // Make a string lowercase.\n\nStr::parseLines(string $text, bool $toAssoc = true): array; // Parse text by lines.\n\nStr::pos(string $haystack, string $needle, int $offset = 0): ??int; // Find position of first occurrence of string in a string.\n\nStr::rChr(string $haystack, string $needle, bool $part = false): string; // Finds the last occurrence of a character in a string within another.\n\nStr::rPos(string $haystack, string $needle, int $offset = 0): ??int; // Find position of last occurrence of a string in a string.\n\nStr::random(int $length = 10, bool $isReadable = true): string; // Generate readable random string.\n\nStr::slug(string $text = '', bool $isCache = false): string; // Converts any accent characters to their equivalent normal characters.\n\nStr::splitCamelCase(string $input, string $separator = '_', bool $toLower = true): string; // Convert camel case to human-readable format.\n\n// Splits a string of multiple queries into an array of individual queries.\n// Single line or line end comments and multi line comments are stripped off.\nStr::splitSql(string $sql): array;\n\nStr::strStr(string $haystack, string $needle, bool $beforeNeedle = false): string; // Finds first occurrence of a string within another.\n\nStr::stripSpace(string $string): string; // Strip all whitespaces from the given string.\n\nStr::sub(string $string, int $start, int $length = 0): string; // Get part of string. Safe alias for substr().\n\nStr::subCount(string $haystack, string $needle): int; // Count the number of substring occurrences.\n\nStr::testName2Human(string $input): string; // Convert test name to human-readable string.\n\nStr::trim(string $value, bool $extendMode = false): string; // Trim whitespaces and other special chars.\n\nStr::truncateSafe(string $string, int $length, string $append = '...'): string; // Truncate a string to a specified length without cutting a word off.\n\nStr::unique(string $prefix = 'unique'): string; // Get unique string with prefix.\n\nStr::up(string $string): string; // Make a string uppercase.\n\n// Generates a universally unique identifier (UUID v4) according to RFC 4122\n// Version 4 UUIDs are pseudo-random!\n// Returns Version 4 UUID format: xxxxxxxx-xxxx-4xxx-Yxxx-xxxxxxxxxxxx where x is\n// any random hex digit and Y is a random choice from 8, 9, a, or b.\nStr::uuid(): string;\n\nStr::zeroPad(string $number, int $length): string; // Pads a given string with zeroes on the left.\n\n```\n\n\n### JBZoo\\Utils\\Sys\n\n```php\n// Returns true when Xdebug is supported or\n// the runtime used is PHPDBG (PHP \u003e= 7.0).\nSys::canCollectCodeCoverage(): bool;\n\n// Returns the path to the binary of the current runtime.\n// Appends ' --php' to the path when the runtime is HHVM.\nSys::getBinary(): string;\n\nSys::getDocRoot(): ??string; // Returns current document root.\n\nSys::getHome(): ??string; // Returns a home directory of current user.\n\nSys::getMemory(bool $isPeak = true): string; // Get usage memory, human-readable.\n\nSys::getName(): string; // Returns type of PHP.\n\nSys::getNameWithVersion(): string; // Return type and version of current PHP.\n\nSys::getUserName(): ??string; // Returns current linux user who runs script.\n\nSys::getVendorUrl(): string; // Return URL of PHP official web-site. It depends on PHP vendor.\n\nSys::getVersion(): ??string; // Returns current PHP version.\n\n// Returns true when the runtime used is PHP with the PHPDBG SAPI\n// and the phpdbg_*_oplog() functions are available (PHP \u003e= 7.0).\nSys::hasPHPDBGCodeCoverage(): bool;\n\nSys::hasXdebug(): bool; // Returns true when the runtime used is PHP and Xdebug is loaded.\n\nSys::iniGet(string $varName): string; // Alias fo ini_get function.\n\nSys::iniSet(string $phpIniKey, string $newValue): bool; // Alias fo ini_set function.\n\nSys::isFunc(Closure|string $funcName): bool; // Checks if function exists and callable.\n\nSys::isHHVM(): bool; // Returns true when the runtime used is HHVM.\n\nSys::isPHP(string $version, string $current = '8.2.9'): bool; // Compares PHP versions.\n\nSys::isPHPDBG(): bool; // Returns true when the runtime used is PHP with the PHPDBG SAPI.\n\nSys::isRealPHP(): bool; // Returns true when the runtime used is PHP without the PHPDBG SAPI.\n\nSys::isRoot(): bool; // Check is current user ROOT.\n\nSys::isWin(): bool; // Check is current OS Windows.\n\nSys::setMemory(string $newLimit = '256M'): void; // Set new memory limit.\n\nSys::setTime(int $newLimit = 0): void; // Set PHP execution time limit (doesn't work in safe mode).\n\n```\n\n\n### JBZoo\\Utils\\Timer\n\n```php\nTimer::format(float $milliSeconds): string; // Formats the elapsed time as a string.\n\nTimer::formatMS(float $seconds): string; // Formats the elapsed time as a string.\n\nTimer::getRequestTime(): float; // Get request time in microseconds.\n\nTimer::timeSinceStart(): float; // Formats the elapsed time since the start of the request as a string.\n\n```\n\n\n### JBZoo\\Utils\\Url\n\n```php\nUrl::addArg(array $newParams, ??string $uri = null): string; // Add or remove query arguments to the URL.\n\nUrl::build(array $queryParams): string; // Builds HTTP query from array.\n\n// Build a URL. The parts of the second URL will be merged into the first according to the flags' argument.\n//                                or associative array like parse_url() returns\n//                                would return\nUrl::buildAll(array|string $sourceUrl, array|string $destParts = [], int $flags = 1, array $newUrl = []): string;\n\nUrl::create(array $parts = []): string; // Create URL from array params.\n\nUrl::current(bool $addAuth = false): ??string; // Returns the current URL.\n\nUrl::delArg(array|string $keys, ??string $uri = null): string; // Removes an item or list from the query string.\n\nUrl::getAuth(): ??string; // Get current auth info.\n\nUrl::isAbsolute(string $path): bool; // Check if URL is not relative.\n\nUrl::isHttps(bool $trustProxyHeaders = false): bool; // Checks to see if the page is being server over SSL or not.\n\n// Turns all the links in a string into HTML links.\n// Part of the LinkifyURL Project \u003chttps://github.com/jmrware/LinkifyURL\u003e.\nUrl::parseLink(string $text): string;\n\nUrl::path(): ??string; // Returns the current path.\n\nUrl::pathToRel(string $path): string; // Convert file path to relative URL.\n\nUrl::pathToUrl(string $path): string; // Convert file path to absolute URL.\n\nUrl::root(bool $addAuth = false): ??string; // Returns current root URL.\n\n```\n\n\n### JBZoo\\Utils\\Vars\n\n```php\nVars::isEven(int $number): bool; // Is the current value even?\n\nVars::isIn(float $number, float $min, float $max): bool; // Returns true if the number is within the min and max.\n\nVars::isNegative(float $number): bool; // Is the current value negative; less than zero.\n\nVars::isOdd(int $number): bool; // Is the current value odd?\n\nVars::isPositive(float $number, bool $zero = true): bool; // Is the current value positive; greater than or equal to zero.\n\nVars::limit(float $number, float $min, float $max): int; // Limits the number between two bounds.\n\nVars::max(float $number, float $max): int; // Decrease the number to the maximum if above threshold.\n\nVars::min(float $number, float $min): int; // Increase the number to the minimum if below threshold.\n\nVars::out(float $number, float $min, float $max): bool; // Returns true if the number is outside the min and max.\n\n// Ensures $value is always within $min and $max range.\n// If lower, $min is returned. If higher, $max is returned.\nVars::range(float $value, float $min, float $max): int;\n\nVars::relativePercent(float $normal, float $current): string; // Get relative percent.\n\n```\n\n\n### JBZoo\\Utils\\Xml\n\n```php\n// Convert array to PHP DOMDocument object.\n// Format of input array\n// $source = [\n//     '_node'     =\u003e '#document',\n//     '_text'     =\u003e null,\n//     '_cdata'    =\u003e null,\n//     '_attrs'    =\u003e [],\n//     '_children' =\u003e [\n//         [\n//             '_node'     =\u003e 'parent',\n//             '_text'     =\u003e \"Content of parent tag\",\n//             '_cdata'    =\u003e null,\n//             '_attrs'    =\u003e ['parent-attribute' =\u003e 'value'],\n//             '_children' =\u003e [\n//                 [\n//                     '_node'     =\u003e 'child',\n//                     '_text'     =\u003e \"Content of child tag\",\n//                     '_cdata'    =\u003e null,\n//                     '_attrs'    =\u003e [],\n//                     '_children' =\u003e [],\n//                 ],\n//             ]\n//         ]\n//     ]\n// ];.\n// Format of output\n//     \u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n//     \u003cparent parent-attribute=\"value\"\u003eContent of parent tag\u003cchild\u003eContent of child tag\u003c/child\u003e\u003c/parent\u003e\nXml::array2Dom(array $xmlAsArray, ??DOMElement $domElement = null, ??DOMDocument $document = null): DOMDocument;\n\nXml::createFromString(??string $source = null, bool $preserveWhiteSpace = false): DOMDocument; // Create DOMDocument object from XML-string.\n\n// Convert PHP \\DOMDocument or \\DOMNode object to simple array\n// Format of input XML (as string)\n//     \u003c?xml version=\"1.0\" encoding=\"UTF-8\"?\u003e\n//     \u003cparent parent-attribute=\"value\"\u003eContent of parent tag\u003cchild\u003eContent of child tag\u003c/child\u003e\u003c/parent\u003e.\n// Format of output array\n// $result = [\n//     '_node'     =\u003e '#document',\n//     '_text'     =\u003e null,\n//     '_cdata'    =\u003e null,\n//     '_attrs'    =\u003e [],\n//     '_children' =\u003e [\n//         [\n//             '_node'     =\u003e 'parent',\n//             '_text'     =\u003e \"Content of parent tag\",\n//             '_cdata'    =\u003e null,\n//             '_attrs'    =\u003e ['parent-attribute' =\u003e 'value'],\n//             '_children' =\u003e [\n//                 [\n//                     '_node'     =\u003e 'child',\n//                     '_text'     =\u003e \"Content of child tag\",\n//                     '_cdata'    =\u003e null,\n//                     '_attrs'    =\u003e [],\n//                     '_children' =\u003e [],\n//                 ],\n//             ]\n//         ]\n//     ]\n// ];\nXml::dom2Array(DOMNode $element): array;\n\nXml::escape(?string|int|float|null $rawXmlContent): string; // Escape string before save it as xml content.\n\n```\n\n\n## Links (ideas and some functions)\n * utilphp - https://github.com/brandonwamboldt/utilphp\n * PHPBinString - https://github.com/Grandt/PHPBinString\n * URLify for PHP - https://github.com/jbroadway/urlify\n * LinkifyURL Project https://github.com/jmrware/LinkifyURL\n * http://www.phpexperts.pro\n * http://stackoverflow.com/a/11709412/430062\n * http://stackoverflow.com/questions/8321620/array-unique-vs-array-flip\n * http://shiflett.org/blog/2006/mar/server-name-versus-http-host\n * https://github.com/joomla-framework/string\n * Askar (ARACOOL) https://github.com/ARACOOOL\n * Sebastian Bergmann https://github.com/sebastianbergmann/php-timer\n * Sebastian Bergmann https://github.com/sebastianbergmann/environment\n * Oscar Otero https://github.com/oscarotero/env\n\n\n## Unit tests and check code style\n```sh\nmake\nmake test-all\n```\n\n\n## License\n\nMIT\n\n\n## See Also\n\n- [CI-Report-Converter](https://github.com/JBZoo/CI-Report-Converter) - Converting different error reports for deep compatibility with popular CI systems.\n- [Composer-Diff](https://github.com/JBZoo/Composer-Diff) - See what packages have changed after `composer update`.\n- [Composer-Graph](https://github.com/JBZoo/Composer-Graph) - Dependency graph visualization of composer.json based on mermaid-js.\n- [Mermaid-PHP](https://github.com/JBZoo/Mermaid-PHP) - Generate diagrams and flowcharts with the help of the mermaid script language.\n- [Image](https://github.com/JBZoo/Image) - Package provides object-oriented way to manipulate with images as simple as possible.\n- [Data](https://github.com/JBZoo/Data) - Extended implementation of ArrayObject. Use files as config/array. \n- [Retry](https://github.com/JBZoo/Retry) - Tiny PHP library providing retry/backoff functionality with multiple backoff strategies and jitter support.\n- [SimpleTypes](https://github.com/JBZoo/SimpleTypes) - Converting any values and measures - money, weight, exchange rates, length, ...\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjbzoo%2Futils","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjbzoo%2Futils","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjbzoo%2Futils/lists"}