### Install JBZoo Utils with Composer
Source: https://github.com/jbzoo/utils/blob/master/README.md
This command installs the JBZoo Utils library using Composer, a dependency manager for PHP. It allows you to easily integrate the utility functions into your project.
```sh
composer require jbzoo/utils
```
--------------------------------
### Timer Utilities (PHP)
Source: https://github.com/jbzoo/utils/blob/master/README.md
Provides static methods for measuring and formatting elapsed time. Includes functions to format microseconds, get request time, and calculate time since script start.
```php
= 7.0).
Sys::canCollectCodeCoverage(): bool;
// Returns the path to the binary of the current runtime.
// Appends ' --php' to the path when the runtime is HHVM.
Sys::getBinary(): string;
Sys::getDocRoot(): ??string; // Returns current document root.
Sys::getHome(): ??string; // Returns a home directory of current user.
Sys::getMemory(bool $isPeak = true): string; // Get usage memory, human-readable.
Sys::getName(): string; // Returns type of PHP.
Sys::getNameWithVersion(): string; // Return type and version of current PHP.
Sys::getUserName(): ??string; // Returns current linux user who runs script.
Sys::getVendorUrl(): string; // Return URL of PHP official web-site. It depends on PHP vendor.
Sys::getVersion(): ??string; // Returns current PHP version.
// Returns true when the runtime used is PHP with the PHPDBG SAPI
// and the phpdbg_*_oplog() functions are available (PHP >= 7.0).
Sys::hasPHPDBGCodeCoverage(): bool;
Sys::hasXdebug(): bool; // Returns true when the runtime used is PHP and Xdebug is loaded.
Sys::iniGet(string $varName): string; // Alias fo ini_get function.
Sys::iniSet(string $phpIniKey, string $newValue): bool; // Alias fo ini_set function.
Sys::isFunc(Closure|string $funcName): bool; // Checks if function exists and callable.
Sys::isHHVM(): bool; // Returns true when the runtime used is HHVM.
Sys::isPHP(string $version, string $current = '8.2.9'): bool; // Compares PHP versions.
Sys::isPHPDBG(): bool; // Returns true when the runtime used is PHP with the PHPDBG SAPI.
Sys::isRealPHP(): bool; // Returns true when the runtime used is PHP without the PHPDBG SAPI.
Sys::isRoot(): bool; // Check is current user ROOT.
Sys::isWin(): bool; // Check is current OS Windows.
Sys::setMemory(string $newLimit = '256M'): void; // Set new memory limit.
Sys::setTime(int $newLimit = 0): void; // Set PHP execution time limit (doesn't work in safe mode).
```
--------------------------------
### Source Code Organization (File Structure)
Source: https://github.com/jbzoo/utils/blob/master/CLAUDE.md
Illustrates the typical file structure for source code within the JBZoo/Utils library, highlighting the placement of utility classes, aliases, and constants.
```file-structure
src/
├── aliases.php # Function aliases for common operations
├── defines.php # Global constants
├── Exception.php # Base exception class
└── [UtilityClass].php # Individual utility classes (Arr, Str, FS, etc.)
```
--------------------------------
### File System Utilities in PHP
Source: https://github.com/jbzoo/utils/blob/master/README.md
Provides a set of static methods for common file system operations. These include path manipulation, directory size calculation, file permission checks, recursive directory removal, and more. Some methods handle nullable string inputs for paths.
```php
FS::base(??string $path): string;
FS::clean(??string $path, string $dirSep = '/'): string;
FS::dirName(??string $path): string;
FS::dirSize(string $dir): int;
FS::executable(string $filename, bool $executable = true): bool;
FS::ext(??string $path): string;
FS::filename(??string $path): string;
FS::firstLine(string $filepath): ??string;
FS::format(int $bytes, int $decimals = 2): string;
FS::getRelative(string $path, ??string $rootPath = null, string $forceDS = '/'): string;
FS::isDir(??string $path): bool;
FS::isFile(string $path): bool;
FS::isReal(??string $path): bool;
FS::ls(string $dir): array;
FS::openFile(string $filepath): ??string;
FS::perms(string $file, ??int $perms = null): string;
FS::readable(string $filename, bool $readable = true): bool;
FS::real(??string $path): ??string;
FS::rmDir(string $dir, bool $traverseSymlinks = true): bool;
FS::stripExt(string $path): string;
FS::writable(string $filename, bool $writable = true): bool;
```
--------------------------------
### Convert Array to Description List with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts an array of strings into a formatted description list. Optionally aligns output by keys for better readability.
```php
Str::listToDescription(array $data, bool $alignByKeys = false): ??string;
```
--------------------------------
### URL Manipulation Utilities (PHP)
Source: https://github.com/jbzoo/utils/blob/master/README.md
Offers static methods for parsing, building, and manipulating URLs. Supports adding/removing query arguments, building URLs from parts, creating URLs, checking for absolute/HTTPS URLs, and converting file paths to URLs.
```php
.
Url::parseLink(string $text): string;
Url::path(): ??string; // Returns the current path.
Url::pathToRel(string $path): string; // Convert file path to relative URL.
Url::pathToUrl(string $path): string; // Convert file path to absolute URL.
Url::root(bool $addAuth = false): ??string; // Returns current root URL.
```
--------------------------------
### Check GD Library Availability
Source: https://github.com/jbzoo/utils/blob/master/README.md
Verifies if the GD library is enabled on the server. If `$throwException` is true and GD is not available, an exception will be thrown. Returns a boolean indicating availability.
```php
Image::checkGD(bool $throwException = true): bool;
```
--------------------------------
### Download File with HTTP Headers
Source: https://github.com/jbzoo/utils/blob/master/README.md
Forces a browser to display a file download dialog by setting appropriate HTTP headers. This function is cross-browser compatible and only executes if headers have not already been sent. It returns a boolean indicating success.
```php
Http::download(string $filename): bool;
```
--------------------------------
### Slug Generation and Transformation (PHP)
Source: https://github.com/jbzoo/utils/blob/master/README.md
This snippet demonstrates functions for creating URL-friendly slugs by transliterating characters, removing accents, and replacing non-alphanumeric characters with separators. It includes methods for generating slugs safe for URLs and CSS identifiers.
```php
// Transliterates characters to their ASCII equivalents.
// Part of the URLify.php Project .
Slug::downCode(string $text, string $language = ''): string;
// Converts any accent characters to their equivalent normal characters and converts any other non-alphanumeric
// characters to dashes, then converts any sequence of two or more dashes to a single dash. This function generates
// slugs safe for use as URLs, and if you pass true as the second parameter, it will create strings safe for
// use as CSS classes or IDs.
Slug::filter(??string $string, string $separator = '-', bool $cssMode = false): string;
// Converts all accent characters to ASCII characters.
// If there are no accent characters, then the string given is just returned.
Slug::removeAccents(string $string, string $language = ''): string;
// Checks to see if a string is utf8 encoded.
// NOTE: This function checks for 5-Byte sequences, UTF8 has Bytes Sequences with a maximum length of 4.
// Written by Tony Ferrara .
Slug::seemsUTF8(string $string): bool;
```
--------------------------------
### PHP Environment Variable String Conversion with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Retrieves an environment variable and converts its value to a clean string. Removes leading/trailing whitespace. Allows specifying a default value if the variable is not set. Returns a string.
```php
Env::string(string $envVarName, string $default = ''): string;
```
--------------------------------
### Create URL Slug with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a string into a URL-friendly slug by removing accents and special characters. Caching is an option.
```php
Str::slug(string $text = '', bool $isCache = false): string;
```
--------------------------------
### Parse PHPDoc Syntax
Source: https://github.com/jbzoo/utils/blob/master/README.md
Parses a PHPDoc string to extract information such as the description, parameters, and return types. The result is returned as an associative array.
```php
PhpDocs::parse(string $phpDoc): array;
```
--------------------------------
### Convert to HTML Entities with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts specific characters (>, <, ', ", &) to their HTML entity equivalents. It intelligently preserves already encoded entities.
```php
Str::htmlEnt(string $string, bool $encodedEntities = false): string;
```
--------------------------------
### Zero Pad String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Pads a given numeric string with leading zeroes to reach a specified length.
```php
Str::zeroPad(string $number, int $length): string;
```
--------------------------------
### Array Manipulation with JBZoo\Utils\Arr
Source: https://github.com/jbzoo/utils/blob/master/README.md
This section details various static methods for manipulating arrays provided by the JBZoo\Utils\Arr class. These functions cover adding elements, cleaning arrays, accessing first and last elements/keys, flattening, grouping, imploding, searching, sorting, and converting arrays to different formats. Some methods have options for preserving keys or handling nested structures.
```php
Arr::addEachKey(array $array, string $prefix): array;
Arr::clean(array $haystack): array;
Arr::cleanBeforeJson(array $array): array;
Arr::first(array $array): ?mixed;
Arr::firstKey(array $array): ?string|int|null;
// Flatten a multi-dimensional array into a one dimensional array.
// overwrite keys from shallow nested arrays
Arr::flat(array $array, bool $preserveKeys = true): array;
Arr::getField(array $arrayList, string $fieldName = 'id'): array;
Arr::getSchema(array $array): array;
Arr::groupByKey(array $arrayList, string $key = 'id'): array;
Arr::implode(string $glue, array $array): string;
Arr::in(?mixed $value, array $array, bool $returnKey = false): ?string|int|bool|null;
Arr::isAssoc(array $array): bool;
Arr::key(?mixed $key, array $array, bool $returnValue = false): ?mixed;
Arr::last(array $array): ?mixed;
Arr::lastKey(array $array): ?string|int|null;
Arr::map(Closure $function, array $array): array;
// Returns an array containing all the elements of arr1 after applying
// the callback function to each one.
// (Objects, resources, etc)
Arr::mapDeep(array $array, callable $callback, bool $onNoScalar = false): array;
Arr::removeByValue(array $array, ?string|int|float|bool|null $value): array;
// Searches for a given value in an array of arrays, objects and scalar values. You can optionally specify
// a field of the nested arrays and objects to search in.
Arr::search(array $array, ?string|int|float|bool|null $search, ??string $field = null): string|bool;
Arr::sortByArray(array $array, array $orderArray): array;
Arr::toComment(array $data): string;
Arr::unique(array $array, bool $keepKeys = false): array;
Arr::unshiftAssoc(array $array, string|int $key, ?mixed $value): array;
// Wraps its argument in an array unless it is already an array.
// Arr.wrap(null) # => []
// Arr.wrap([1, 2, 3]) # => [1, 2, 3]
// Arr.wrap(0) # => [0]
Arr::wrap(?mixed $object): array;
```
--------------------------------
### PHP Gravatar Built-in Placeholder Retrieval with JBZoo Email
Source: https://github.com/jbzoo/utils/blob/master/README.md
Retrieves a list of Gravatar's supported built-in placeholder image identifiers. Returns an array of strings. Useful for providing default image options when generating Gravatar URLs.
```php
Email::getGravatarBuiltInImages(): array;
```
--------------------------------
### Convert Test Name to Human Readable with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Transforms a test method name into a more human-readable string format.
```php
Str::testName2Human(string $input): string;
```
--------------------------------
### Copy Merge Alpha for PNGs
Source: https://github.com/jbzoo/utils/blob/master/README.md
A modified version of PHP's `imagecopymerge()` that preserves alpha transparency in 24-bit PNG images during the copy operation.
```php
Image::imageCopyMergeAlpha(GdImage $dstImg, GdImage $srcImg, array $dist, array $src, array $srcSizes, int $opacity): void;
```
--------------------------------
### XML Conversion with JBZoo Utils Xml (PHP)
Source: https://github.com/jbzoo/utils/blob/master/README.md
This section covers XML manipulation using the JBZoo\Utils\Xml class. It includes functions to convert arrays to DOMDocument objects, create DOMDocument from XML strings, convert DOM objects to arrays, and escape XML content.
```php
// Convert array to PHP DOMDocument object.
// Format of input array
// $source = [
// '_node' => '#document',
// '_text' => null,
// '_cdata' => null,
// '_attrs' => [],
// '_children' => [
// [
// '_node' => 'parent',
// '_text' => "Content of parent tag",
// '_cdata' => null,
// '_attrs' => ['parent-attribute' => 'value'],
// '_children' => [
// [
// '_node' => 'child',
// '_text' => "Content of child tag",
// '_cdata' => null,
// '_attrs' => [],
// '_children' => [],
// ],
// ]
// ]
// ]
// ];.
// Format of output
//
// Content of parent tagContent of child tag
Xml::array2Dom(array $xmlAsArray, ??DOMElement $domElement = null, ??DOMDocument $document = null): DOMDocument;
Xml::createFromString(??string $source = null, bool $preserveWhiteSpace = false): DOMDocument; // Create DOMDocument object from XML-string.
// Convert PHP \DOMDocument or \DOMNode object to simple array
// Format of input XML (as string)
//
// Content of parent tagContent of child tag.
// Format of output array
// $result = [
// '_node' => '#document',
// '_text' => null,
// '_cdata' => null,
// '_attrs' => [],
// '_children' => [
// [
// '_node' => 'parent',
// '_text' => "Content of parent tag",
// '_cdata' => null,
// '_attrs' => ['parent-attribute' => 'value'],
// '_children' => [
// [
// '_node' => 'child',
// '_text' => "Content of child tag",
// '_cdata' => null,
// '_attrs' => [],
// '_children' => [],
// ],
// ]
// ]
// ]
// ];
Xml::dom2Array(DOMNode $element): array;
Xml::escape(?string|int|float|null $rawXmlContent): string; // Escape string before save it as xml content.
```
--------------------------------
### PHP Smart Type Casting and String Manipulation Functions
Source: https://github.com/jbzoo/utils/blob/master/README.md
Demonstrates the usage of various smart functions provided by JBZoo Utils for type casting (int, float, bool) and string manipulation (alias, digits, alpha, alphanum). These functions offer flexible input handling and data sanitization.
```php
use function JBZoo\Utils\alias;
use function JBZoo\Utils\alpha;
use function JBZoo\Utils\alphanum;
use function JBZoo\Utils\bool;
use function JBZoo\Utils\digits;
use function JBZoo\Utils\float;
use function JBZoo\Utils\int;
int(' 10.0 ') === 10;
float(' 10.0 ') === 10.0;
bool(' yes ') === true;
bool(' no ') === false;
bool('1') === true;
bool('0') === false;
alias('Qwer ty') === 'qwer-ty';
digits('Qwer 1 ty2') === '12';
alpha('Qwer 1 ty2') === 'Qwerty';
alphanum(' #$% Qwer 1 ty2') === 'Qwer1ty2';
```
--------------------------------
### Pattern Matching with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Checks if a given string matches a specified pattern. Supports wildcard matching and case sensitivity can be adjusted.
```php
Str::like(string $pattern, string $haystack, bool $caseSensitive = true): bool;
```
--------------------------------
### Statistical Calculations (PHP)
Source: https://github.com/jbzoo/utils/blob/master/README.md
This snippet showcases various statistical functions provided by the Stats class. It includes methods for generating histograms, creating linearly spaced arrays, calculating mean, median, percentiles, standard deviation, and variance. It also offers functions to render average and median values in a human-readable format.
```php
Stats::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.
Stats::linSpace(float $min, float $max, int $num = 50, bool $endpoint = true): array; // Returns an array populated with $num numbers from $min to $max.
Stats::mean(??array $values): float; // Returns the mean (average) value of the given values.
Stats::median(array $data): float; // Calculate the median of a given population.
Stats::percentile(array $data, int|float $percentile = 95): float; // Calculate the percentile of a given population.
Stats::renderAverage(array $values, int $rounding = 3): string; // Render human readable string of average value and system error.
Stats::renderMedian(array $values, int $rounding = 3): string; // Render human readable string of average value and system error.
Stats::stdDev(array $values, bool $sample = false): float; // Returns the standard deviation of a given population.
Stats::variance(array $values, bool $sample = false): float; // Returns the variance for a given population.
```
--------------------------------
### Generate Unique String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Generates a unique string, optionally prefixed, typically used for temporary identifiers.
```php
Str::unique(string $prefix = 'unique'): string;
```
--------------------------------
### PHP DateTime Object Creation with JBZoo Dates
Source: https://github.com/jbzoo/utils/blob/master/README.md
Creates a PHP DateTime object from various input types like strings, integers, or null. It allows specifying a DateTimeZone for accurate time representation. Handles different date formats and timestamps.
```php
Dates::factory(?mixed $time = null, ?DateTimeZone|string|null $timeZone = null): DateTime;
```
--------------------------------
### Split SQL String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Splits a string containing multiple SQL queries into an array of individual queries. It strips comments (single-line, multi-line) before splitting.
```php
Str::splitSql(string $sql): array;
```
--------------------------------
### CSV Parsing with JBZoo\Utils\Csv
Source: https://github.com/jbzoo/utils/blob/master/README.md
This section details the JBZoo\Utils\Csv class, which offers a simple parser for CSV files. The `parse` method allows reading data from a CSV file, with options to specify the delimiter, enclosure character, and whether the CSV file has a header row.
```php
Csv::parse(string $csvFile, string $delimiter = ';', string $enclosure = '"', bool $hasHeader = true): array;
```
--------------------------------
### Convert String to Uppercase with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a given string to its uppercase equivalent.
```php
Str::up(string $string): string;
```
--------------------------------
### PHP Human-Readable Date Formatting with JBZoo Dates
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts date strings or Unix timestamps into a human-readable date format. Allows customization of the output format string. Useful for displaying dates in a user-friendly way.
```php
Dates::human(string|int $date, string $format = 'd M Y H:i'): string;
```
--------------------------------
### Convert String to Lowercase with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a given string to its lowercase equivalent.
```php
Str::low(string $string): string;
```
--------------------------------
### Check if String is Empty with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Provides an extended check for potentially empty strings, with an option for strict comparison.
```php
Str::isEmpty(?string|bool|null $value, bool $strict = false): bool;
```
--------------------------------
### PHP General Type Conversion for Env Variables with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts environment variable values that represent different data types (e.g., 'true', 'false', 'null', numbers) into their corresponding PHP types (string, int, float, bool, null). Uses bitmask options for conversion control. Returns the converted value or null.
```php
Env::convert(??string $value, int $options = 16): ?string|int|float|bool|null;
```
--------------------------------
### PHP Environment Variable Boolean Conversion with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Retrieves an environment variable and converts its value to a strict boolean. Supports common string representations of true/false. Allows specifying a default value if the variable is not set. Returns a boolean.
```php
Env::bool(string $envVarName, bool $default = false): bool;
```
--------------------------------
### Add Alpha Channel to GD Image
Source: https://github.com/jbzoo/utils/blob/master/README.md
Adds an alpha channel to a GD image resource, enabling transparency effects. The `$isBlend` parameter controls alpha blending.
```php
Image::addAlpha(GdImage $image, bool $isBlend = true): void;
```
--------------------------------
### PHP Environment Variable Integer Conversion with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Retrieves an environment variable and converts its value to a strict integer. Allows specifying a default value if the variable is not set. Returns an integer.
```php
Env::int(string $envVarName, int $default = 0): int;
```
--------------------------------
### PHP SQL Date Formatting with JBZoo Dates
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a given time into a format suitable for SQL date/time columns. Returns a string representation. Useful for inserting or updating date values in databases.
```php
Dates::sql(?string|int|null $time = null): string;
```
--------------------------------
### Check if mbstring is Loaded with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Determines if the Multibyte String (mbstring) extension is loaded and available in the PHP environment.
```php
Str::isMBString(): bool;
```
--------------------------------
### Data Filtering Utilities in PHP
Source: https://github.com/jbzoo/utils/blob/master/README.md
Offers static methods for filtering and sanitizing various data types. This includes string manipulation (e.g., alpha, alphanum, digits), type conversions (int, float, bool), and specialized filters for paths, commands, and HTML/XML content. It also supports applying custom filters via Closures.
```php
Filter::_(?mixed $value, Closure|string $filters = 'raw'): ?mixed;
Filter::alias(string $string): string;
Filter::alpha(??string $value): string;
Filter::alphanum(??string $value): string;
Filter::arr(?mixed $value, ?Closure|string|null $filter = null): array;
Filter::base64(string $value): string;
Filter::bool(?mixed $variable): bool;
Filter::className(string $input): string;
Filter::clean(string $string): string;
Filter::cmd(string $value): string;
Filter::data(JBZooDataData|array $data): JBZooDataData;
Filter::digits(??string $value): string;
Filter::esc(string $string): string;
Filter::float(?mixed $value, int $round = 10): float;
Filter::html(string $string): string;
Filter::int(?string|int|float|bool|null $value): int;
Filter::json(JBZooDataJSON|array $data): JBZooDataJSON;
Filter::low(string $string): string;
Filter::parseLines(array|string $input): array;
Filter::path(string $value): string;
Filter::raw(?mixed $variable): ?mixed;
Filter::strip(string $string): string;
Filter::stripQuotes(string $value): string;
Filter::stripSpace(string $string): string;
Filter::trim(string $value): string;
Filter::trimExtend(string $value): string;
Filter::ucFirst(string $input): string;
Filter::up(string $string): string;
Filter::xml(string $string): string;
```
--------------------------------
### Generate Random String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Generates a random string of a specified length. Can produce readable characters or a mix.
```php
Str::random(int $length = 10, bool $isReadable = true): string;
```
--------------------------------
### PHP General Environment Variable Retrieval with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Retrieves the value of an environment variable. Allows specifying a default value and conversion options for automatic type casting (e.g., to boolean, integer, float, null). Returns the variable's value or the default.
```php
Env::get(string $envVarName, ?string|int|float|bool|null $default = null, int $options = 16): ?string|int|float|bool|null;
```
--------------------------------
### Check if Image Format is Supported
Source: https://github.com/jbzoo/utils/blob/master/README.md
Determines if a given image format is supported by the library's image processing capabilities.
```php
Image::isSupportedFormat(string $format): bool;
```
--------------------------------
### PHP Environment Variable Float Conversion with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Retrieves an environment variable and converts its value to a strict float. Allows specifying a default value if the variable is not set. Returns a float.
```php
Env::float(string $envVarName, float $default = 0): float;
```
--------------------------------
### Safe String Truncation with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Truncates a string to a specified length without cutting words off. Appends a customizable string if truncation occurs.
```php
Str::truncateSafe(string $string, int $length, string $append = '...'): string;
```
--------------------------------
### PHP Human-Readable Time Conversion with JBZoo Dates
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a duration in seconds into a human-readable time format (H:i:s). It includes a minimum valuable seconds parameter to control precision. Useful for displaying time differences or durations.
```php
Dates::formatTime(float $seconds, int $minValuableSeconds = 2): string;
```
--------------------------------
### Convert Opacity to Alpha
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts an opacity value (float) into an alpha channel value (integer).
```php
Image::opacity2Alpha(float $opacity): int;
```
--------------------------------
### Limit String Words with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Truncates a string to a specified maximum number of words, appending a customizable string if truncation occurs.
```php
Str::limitWords(string $string, int $limit = 100, string $append = '...'): string;
```
--------------------------------
### Parse Text into Lines with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Parses a block of text into an array of individual lines. Can optionally convert the result into an associative array.
```php
Str::parseLines(string $text, bool $toAssoc = true): array;
```
--------------------------------
### PHP Random Email Generation with JBZoo Email
Source: https://github.com/jbzoo/utils/blob/master/README.md
Creates a random email address with a specified username length. The domain is fixed. Returns a string representing the generated email. Useful for testing or generating placeholder data.
```php
Email::random(int $userNameLength = 10): string;
```
--------------------------------
### PHP Gravatar URL Generation with JBZoo Email
Source: https://github.com/jbzoo/utils/blob/master/README.md
Generates a Gravatar URL for a given email address. Allows specifying image size (1-2048px, with defaults) and a default image option (URL or built-in identifier). Returns a string or null if parameters are invalid.
```php
Email::getGravatarUrl(string $email, int $size = 32, string $defaultImage = 'identicon'): ??string;
```
--------------------------------
### Prevent Caching with HTTP Headers
Source: https://github.com/jbzoo/utils/blob/master/README.md
Sets HTTP headers to prevent browser caching. It sends multiple no-cache headers to ensure compatibility across different browsers. The function returns a boolean indicating whether the headers were successfully set.
```php
Http::nocache(): bool;
```
--------------------------------
### Find First Occurrence of Substring with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Finds the position of the first occurrence of a substring within a string. An optional offset can be specified.
```php
Str::pos(string $haystack, string $needle, int $offset = 0): ??int;
```
--------------------------------
### Find First Occurrence of Substring (Alias) with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
A safe alias for finding the first occurrence of a substring within another string. Can return the part before the needle.
```php
Str::strStr(string $haystack, string $needle, bool $beforeNeedle = false): string;
```
--------------------------------
### Trim String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Trims whitespace and other special characters from the beginning and end of a string. Supports an extended mode for more aggressive trimming.
```php
Str::trim(string $value, bool $extendMode = false): string;
```
--------------------------------
### PHP Environment Variable Existence Check with JBZoo Env
Source: https://github.com/jbzoo/utils/blob/master/README.md
Checks if an environment variable with the specified name exists. Returns a boolean true if it exists, false otherwise. Useful for conditional logic based on environment configuration.
```php
Env::isExists(string $envVarName): bool;
```
--------------------------------
### PHP Sorting Email Domains with JBZoo Email
Source: https://github.com/jbzoo/utils/blob/master/README.md
Extracts domain names from an array of email addresses and returns them in alphabetical order. Useful for presenting domains in a structured, sorted list.
```php
Email::getDomainSorted(array $emails): array;
```
--------------------------------
### Case-Insensitive String Search with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Finds the first occurrence of a substring within another string, ignoring case. It can return the part before the needle if specified.
```php
Str::iStr(string $haystack, string $needle, bool $beforeNeedle = false): string;
```
--------------------------------
### Check Numeric Properties with JBZoo Utils Vars (PHP)
Source: https://github.com/jbzoo/utils/blob/master/README.md
This snippet demonstrates functions for checking if a number is even, odd, negative, positive, or within a specified range using the JBZoo\Utils\Vars class. It helps in validating and manipulating numeric values.
```php
Vars::isEven(int $number): bool;
Vars::isIn(float $number, float $min, float $max): bool;
Vars::isNegative(float $number): bool;
Vars::isOdd(int $number): bool;
Vars::isPositive(float $number, bool $zero = true): bool;
Vars::limit(float $number, float $min, float $max): int;
Vars::max(float $number, float $max): int;
Vars::min(float $number, float $min): int;
Vars::out(float $number, float $min, float $max): bool;
Vars::range(float $value, float $min, float $max): int;
Vars::relativePercent(float $normal, float $current): string;
```
--------------------------------
### Case-Insensitive String Position Search with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Finds the position of the first occurrence of a substring within a string, ignoring case. An optional offset can be specified.
```php
Str::iPos(string $haystack, string $needle, int $offset = 0): ??int;
```
--------------------------------
### PHP Extracting Email Domains with JBZoo Email
Source: https://github.com/jbzoo/utils/blob/master/README.md
Extracts domain names from one or more email addresses. Invalid email addresses in the input are skipped. Returns an array of domain names. Useful for domain analysis or grouping.
```php
Email::getDomain(?mixed $emails): array;
```
--------------------------------
### Limit String Characters with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Truncates a string to a specified maximum number of characters, appending a customizable string if truncation occurs.
```php
Str::limitChars(string $string, int $limit = 100, string $append = '...'): string;
```
--------------------------------
### Generate UUID v4 with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Generates a Version 4 Universally Unique Identifier (UUID) according to RFC 4122. These UUIDs are pseudo-random.
```php
Str::uuid(): string;
```
--------------------------------
### Serialize Data if Necessary
Source: https://github.com/jbzoo/utils/blob/master/README.md
Serializes the input data only if it is not already a string. This ensures that data is in a serialized format when needed, preventing redundant serialization.
```php
Ser::maybe(?mixed $data): ?mixed;
```
--------------------------------
### Clean String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Cleans a string by removing UTF-8 characters, HTML tags, and optionally converts to lowercase or adds slashes. Accents can also be removed.
```php
Str::clean(string $string, bool $toLower = false, bool $addSlashes = false, bool $removeAccents = true): string;
```
--------------------------------
### Convert Image String to Binary Data
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a string representation of an image into its raw binary data. This can be useful for processing image data stored as strings.
```php
Image::strToBin(string $imageString): ??string;
```
--------------------------------
### Validate Opacity Value
Source: https://github.com/jbzoo/utils/blob/master/README.md
Checks if a given opacity value is valid. The input is a float, and the output is an integer representing a validated opacity.
```php
Image::opacity(float $opacity): int;
```
--------------------------------
### Escape UTF-8 Strings with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Escapes UTF-8 strings to ensure they are safe for various contexts.
```php
Str::esc(string $string): string;
```
--------------------------------
### Strip Whitespace from String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Removes all whitespace characters from a given string.
```php
Str::stripSpace(string $string): string;
```
--------------------------------
### Fix Partially Corrupted Serialized Data
Source: https://github.com/jbzoo/utils/blob/master/README.md
Attempts to fix and unserialize data that is partially corrupted, specifically addressing 'unserialize(): Error at offset xxx of yyy bytes' errors often caused by character set mismatches or non-ASCII characters.
```php
Ser::fix(string $brokenSerializedData): string;
```
--------------------------------
### Split Camel Case String with JBZoo Utils Str
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts a camelCase string into a human-readable format, separated by a specified character. Option to convert to lowercase.
```php
Str::splitCamelCase(string $input, string $separator = '_', bool $toLower = true): string;
```
--------------------------------
### Check if Image Format is WEBP
Source: https://github.com/jbzoo/utils/blob/master/README.md
Verifies if the image format is WEBP. An optional format string can be provided.
```php
Image::isWebp(??string $format = null): bool;
```
--------------------------------
### PHP Timestamp Conversion with JBZoo Dates
Source: https://github.com/jbzoo/utils/blob/master/README.md
Converts various date inputs (DateTime objects, strings, timestamps) into a Unix timestamp (integer). Optionally uses the current time as default if no input is provided. Useful for internal calculations or comparisons.
```php
Dates::toStamp(?DateTime|string|int|null $time = null, bool $currentIsDefault = true): int;
```
--------------------------------
### PHP Relative Date Checking (Today, Tomorrow, Yesterday) with JBZoo Dates
Source: https://github.com/jbzoo/utils/blob/master/README.md
Checks if a given date is today, tomorrow, or yesterday. Returns a boolean. Useful for displaying relative dates or triggering actions based on the current day.
```php
Dates::isToday(string|int $time): bool;
Dates::isTomorrow(string|int $time): bool;
Dates::isYesterday(string|int $time): bool;
```