diff --git a/.gitattributes b/.gitattributes index 1e7bf2f..655489b 100644 --- a/.gitattributes +++ b/.gitattributes @@ -9,6 +9,8 @@ /.editorconfig export-ignore /.gitattributes export-ignore /.gitignore export-ignore +/phpstan.neon export-ignore +/phpunit.xml export-ignore # Explicit text file types *.php text diff --git a/.github/codecov.yaml b/.github/codecov.yaml new file mode 100644 index 0000000..c72c2c3 --- /dev/null +++ b/.github/codecov.yaml @@ -0,0 +1,11 @@ +coverage: + status: + project: + default: + target: 70% + +component_management: + default_rules: + statuses: + - type: project + target: auto \ No newline at end of file diff --git a/.github/workflows/AddToTriage.yml b/.github/workflows/AddToTriage.yml new file mode 100644 index 0000000..4e55106 --- /dev/null +++ b/.github/workflows/AddToTriage.yml @@ -0,0 +1,15 @@ +name: Add to Triage + +on: + issues: + types: [opened] + pull_request: + types: [opened] + +permissions: read-all + +jobs: + build: + uses: The-FireHub-Project/.github/.github/workflows/AddToProject.yml@master + secrets: + GH_TOKEN: ${{ secrets.GH_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/Codecov.yml b/.github/workflows/Codecov.yml new file mode 100644 index 0000000..4a871bb --- /dev/null +++ b/.github/workflows/Codecov.yml @@ -0,0 +1,22 @@ +name: Code Coverage + +on: + pull_request: + branches: + - master + - develop + - 'support/v*' + +permissions: read-all + +jobs: + build: + uses: The-FireHub-Project/.github/.github/workflows/Codecov.yml@master + with: + phpVersion: '8.5' + phpExtensions: ${{ vars.PHP_EXTENSIONS }} + tools: "phpunit:13.x" + suites: '["unit"]' + secrets: + GH_TOKEN: ${{ secrets.GH_TOKEN }} + CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/PHPStan.yml b/.github/workflows/PHPStan.yml new file mode 100644 index 0000000..62e061a --- /dev/null +++ b/.github/workflows/PHPStan.yml @@ -0,0 +1,18 @@ +name: PHPStan + +on: + pull_request: + +permissions: read-all + +jobs: + build: + uses: The-FireHub-Project/.github/.github/workflows/RunCommandOnMatrix.yml@master + with: + title: "Run PHPStan" + phpVersions: ${{ vars.PHP_VERSIONS }} + phpExtensions: ${{ vars.PHP_EXTENSIONS }} + tools: "phpstan:2.x" + command: "phpstan analyse" + secrets: + GH_TOKEN: ${{ secrets.GH_TOKEN }} \ No newline at end of file diff --git a/.github/workflows/PHPUnit.yml b/.github/workflows/PHPUnit.yml new file mode 100644 index 0000000..3d8ae28 --- /dev/null +++ b/.github/workflows/PHPUnit.yml @@ -0,0 +1,18 @@ +name: PHPUnit + +on: + pull_request: + +permissions: read-all + +jobs: + build: + uses: The-FireHub-Project/.github/.github/workflows/RunCommandOnMatrix.yml@master + with: + title: "Run PHPUnit" + phpVersions: ${{ vars.PHP_VERSIONS }} + phpExtensions: ${{ vars.PHP_EXTENSIONS }} + tools: "phpunit:13.x" + command: "phpunit" + secrets: + GH_TOKEN: ${{ secrets.GH_TOKEN }} \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 751d2d4..19d806d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,4 +3,12 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), -and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). \ No newline at end of file +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [v0.1.0] – 2026-07-28 + +### Added + +- Implement Initial wrapper utility classes ([#2](https://github.com/The-FireHub-Project/Runtime/pull/2)) \ No newline at end of file diff --git a/CITATION.cff b/CITATION.cff index a215e68..0fec1e8 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -37,4 +37,4 @@ identifiers: value: "https://github.com/The-FireHub-Project/Runtime" description: The GitHub URL of this version. - type: other - value: "packagist:the-firehub-project/runtime" + value: "packagist:the-firehub-project/runtime" \ No newline at end of file diff --git a/README.md b/README.md index 90539d0..4abdcf6 100644 --- a/README.md +++ b/README.md @@ -7,12 +7,12 @@ PHP Runtime Foundation
release version diff --git a/composer.json b/composer.json index 35ed3c3..35d4429 100644 --- a/composer.json +++ b/composer.json @@ -6,7 +6,8 @@ "homepage": "https://the-firehub-project.github.io/runtime", "license": "Apache-2.0", "require": { - "php": "^8.5" + "php": "^8.5", + "ext-mbstring": "*" }, "require-dev": { "the-firehub-project/core-standard": "dev-develop", diff --git a/phpstan.neon b/phpstan.neon new file mode 100644 index 0000000..d0e5c9b --- /dev/null +++ b/phpstan.neon @@ -0,0 +1,6 @@ +includes: + - vendor/the-firehub-project/phpstan-rules/src/Config/base.neon + +parameters: + paths: + - src/ \ No newline at end of file diff --git a/phpunit.xml b/phpunit.xml new file mode 100644 index 0000000..27667c4 --- /dev/null +++ b/phpunit.xml @@ -0,0 +1,16 @@ + + + + + tests/Unit + + + + + src + + + \ No newline at end of file diff --git a/src/Arr/Access.php b/src/Arr/Access.php new file mode 100644 index 0000000..e7fbdd2 --- /dev/null +++ b/src/Arr/Access.php @@ -0,0 +1,384 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.5 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + EmptyArrayException, InvalidRandomKeyCountException +}; + +use function array_column; +use function array_find; +use function array_find_key; +use function array_first; +use function array_key_exists; +use function array_key_first; +use function array_key_last; +use function array_keys; +use function array_last; +use function array_rand; +use function array_search; +use function array_values; + +/** + * ### PHP Array Runtime Wrapper Utility - Access + * + * The Access class provides lightweight, deterministic wrappers for accessing and retrieving data from PHP arrays. + * + * It contains common runtime operations for locating values, extracting keys, retrieving columns, and navigating + * array elements while preserving native PHP behavior and performance. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array access operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Access extends NativeRuntime { + + /** + * ### Checks if the given key or index exists in the array + * + * Returns true if the given key is set in the array. + * Key can be any value possible for an array index. + * @since 1.0.0 + * + * @param array $array

+ * An array with keys to check. + *

+ * @param array-key $key

+ * Key to check. + *

+ * + * @return bool True if the key exists in an array, false otherwise. + * + * @note Method will search for the keys in the first dimension only. + * Nested keys in multidimensional arrays will not be found. + */ + public static function keyExists (array $array, int|string $key):bool { + + return array_key_exists($key, $array); + + } + + /** + * ### Searches the array for a given value and returns the first corresponding key if successful + * + * Performs a strict comparison when searching for the value. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * Array to search. + *

+ * @param mixed $value

+ * The searched value. + * If $value is a string, the comparison is done in a case-sensitive manner. + *

+ * + * @return TKey|false The key for value if it is found in the array, false otherwise. + * + * @warning This method may return Boolean false but may also return a non-Boolean value which evaluates to false. + * Read the section on Booleans for more information. + * Use the === operator for testing the return value of this function. + */ + public static function search (array $array, mixed $value):int|string|false { + + return array_search($value, $array, true); + + } + + /** + * ### Return the values from a single column in the input array + * + * Returns the values from a single column of the $array, identified by the $key. + * + * Optionally, an argument key may be provided to $index the values in the returned array by the values from the + * index argument column of the input array. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TIndex of null|array-key + * @template TArray of array + * + * @param TArray $array

+ * A multidimensional array (record set) from which to pull a column of values. + * + * If an array of objects is provided, then public properties can be directly pulled. + * + * In order for protected or private properties to be pulled, the class must implement both the __get() and + * __isset() magic methods. + *

+ * @param TKey $key

+ * The column of values to return. + * + * This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an + * associative array or property name. + * + * It may also be null to return complete arrays or objects (this is useful together with $index to reindex the + * array). + *

+ * @param TIndex $index [optional]

+ * The column to use as the index/keys for the returned array. + * + * This value may be the integer key of the column, or it may be the string key name. + * + * The value is cast as usual for array keys. + *

+ * + * @return ($index is null ? list : array) Array of values representing a single column + * from the input array. + */ + public static function column (array $array, int|string $key, null|int|string $index = null):array { + + return array_column($array, $key, $index); + + } + + /** + * ### Get the first item from an array + * + * Get the first item of the given $array without affecting the internal array pointer. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * An array. + *

+ * + * @return null|TValue First item from $array or null if an array is empty. + */ + public static function first (array $array):mixed { + + return array_first($array); + + } + + /** + * ### Get the last item from an array + * + * Get the last item of the given $array without affecting the internal array pointer. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * An array. + *

+ * + * @return null|TValue Last item from $array or null if an array is empty. + */ + public static function last (array $array):mixed { + + return array_last($array); + + } + + /** + * ### Get the first key from an array + * + * Get the first key of the given $array without affecting the internal array pointer. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * An array. + *

+ * + * @return null|TKey First key from $array or null if an array is empty. + */ + public static function firstKey (array $array):null|int|string { + + return array_key_first($array); + + } + + /** + * ### Get the last key from an array + * + * Get the last key of the given $array without affecting the internal array pointer. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * An array. + *

+ * + * @return null|TKey Last key from $array or null if an array is empty. + */ + public static function lastKey (array $array):null|int|string { + + return array_key_last($array); + + } + + /** + * ### Return all the keys or a subset of the keys for an array + * + * Returns the keys, numeric, and string, from the $array. + * + * If a $filter is specified, then only the keys for that value are returned. + * + * Otherwise, all the keys from the array are returned. + * @since 1.0.0 + * + * @template TKey of array-key + * + * @param array $array

+ * An array containing keys to return. + *

+ * @param mixed $filter [optional]

+ * If specified, then only keys containing these values are returned. + *

+ * + * @return list An array of all the keys in the input. + */ + public static function keys (array $array, mixed $filter = null):array { + + return $filter !== null + ? array_keys($array, $filter, true) + : array_keys($array); + + } + + /** + * ### Return all the values from an array + * + * Returns all the values from the array and indexes the array numerically. + * @since 1.0.0 + * + * @template TValue + * + * @param array $array

+ * The array. + *

+ * + * @return list An indexed array of values. + */ + public static function values (array $array):array { + + return array_values($array); + + } + + /** + * ### Returns the first element satisfying a callback function + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array that should be searched. + *

+ * @param callable(TValue, TKey):bool $callback

+ * The callback function to call to check each element. + *

+ * + * @return null|TValue The value of the first element for which the callback returns true, null otherwise. + */ + public static function find (array $array, callable $callback):mixed { + + return array_find($array, $callback); + + } + + /** + * ### Returns the key of the first element satisfying a callback function + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array that should be searched. + *

+ * @param callable(TValue, TKey):bool $callback

+ * The callback function to call to check each element. + *

+ * + * @return null|TKey The key of the first element for which the callback returns true, null otherwise. + */ + public static function findKey (array $array, callable $callback):null|int|string { + + return array_find_key($array, $callback); + + } + + /** + * ### Pick one or more random keys out of an array + * + * Picks one or more random entries out of an array and returns the key (or keys) of the random entries. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Inspection::count() To check the number of requested random keys. + * + * @template TKey of array-key + * + * @param non-empty-array $array

+ * The input array. + *

+ * @param positive-int $number [optional]

+ * Specifies how many entries should be picked. + *

+ * + * @throws \FireHub\Runtime\Exception\EmptyArrayException If the input array is empty. + * @throws \FireHub\Runtime\Exception\InvalidRandomKeyCountException If the number of requested random keys is less + * than one or exceeds the available array size. + * + * @return ($number is int<2, max> ? list : TKey) When picking only one entry, the method returns the key + * for a random entry. + * + * Otherwise, an array of keys for the random entries is returned. + * + * @caution This function doesn't generate cryptographically secure values and mustn't be used for cryptographic + * purposes, or purposes that require returned values to be unguessable. + */ + public static function random (array $array, int $number = 1):int|string|array { + + if ($array === []) throw new EmptyArrayException; + + if ($number < 1) { + throw new InvalidRandomKeyCountException( + 'The number of requested random keys must be greater than zero.', + [ + 'number' => $number, + 'minimum' => 1, + ] + ); + } + + if ($number > $maximum = Inspection::count($array)) { + throw new InvalidRandomKeyCountException( + 'The number of requested random keys exceeds the available array size.', + [ + 'number' => $number, + 'maximum' => $maximum, + ] + ); + } + + /** @var ($number is int<2, max> ? list : TKey) */ + return array_rand($array, $number); + + } + +} \ No newline at end of file diff --git a/src/Arr/Composition.php b/src/Arr/Composition.php new file mode 100644 index 0000000..c8ef5d3 --- /dev/null +++ b/src/Arr/Composition.php @@ -0,0 +1,230 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ArrayKeysAndValuesCountMismatchException; + +use function array_combine; +use function array_merge; +use function array_merge_recursive; +use function array_replace; +use function array_replace_recursive; + +/** + * ### PHP Array Runtime Wrapper Utility - Composition + * + * The Composition class provides lightweight, deterministic wrappers for composing arrays from multiple sources. + * + * It contains common runtime operations for merging arrays, replacing values, combining keys with values, and creating + * new array structures through composition while preserving native PHP behavior and performance. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array composition operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Composition extends NativeRuntime { + + /** + * ### Creates an array by using one array for keys and another for its values + * + * Creates an array by using the values from the $keys array as keys and the values from the $values array as the + * corresponding values. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Inspection::count() To check the number of keys and values. + * + * @template TKey of array-key + * @template TValue + * + * @param array $keys

+ * Array of values to be used as keys. + * + * Illegal values for a key will be converted to string. + *

+ * @param array $values

+ * Array of values to be used as values on a combined array. + *

+ * + * @throws \FireHub\Runtime\Exception\ArrayKeysAndValuesCountMismatchException If the number of keys and values + * doesn't match. + * + * @return array The combined array. + */ + public static function combine (array $keys, array $values):array { + + if (($key_count = Inspection::count($keys)) !== ($value_count = Inspection::count($values))) { + throw new ArrayKeysAndValuesCountMismatchException( + 'The number of keys and values must be equal.', + [ + 'keys' => $key_count, + 'values' => $value_count, + ] + ); + } + + return array_combine($keys, $values); + + } + + /** + * ### Merges the elements of one or more arrays + * + * Merges the elements of one or more arrays so that the values of one are appended to the end of + * the previous one. + * + * It returns the resulting array. + * + * If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. + * + * If, however, the arrays contain numeric keys, the later value will not overwrite the original value but will + * be appended. + * + * Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in + * the result array. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array ...$arrays [optional]

+ * Variable list of arrays to merge. + *

+ * + * @return array The resulting array. + * + * @note If the input arrays have the same string keys, then the later value for that key will overwrite + * the previous one. + * @note If the arrays contain numeric keys, the later value will be appended. + * @note Numeric keys will be renumbered. + */ + public static function merge (array ...$arrays):array { + + return array_merge(...$arrays); + + } + + /** + * ### Merge two or more arrays recursively + * + * Merges the elements of one or more arrays so that the values of one are appended to the end of the + * previous one. + * + * It returns the resulting array. + * + * If the input arrays have the same string keys, then the values for these keys are merged into an array. + * + * This is done recursively, so that if one of the values is an array itself, the function will merge it with a + * corresponding entry in another array too. + * + * If, however, the arrays have the same numeric key, the later value will not overwrite the original value but + * will be appended. + * @since 1.0.0 + * + * @param array ...$arrays [optional]

+ * Variable list of arrays to recursively merge. + *

+ * + * @return array The resulting array. + */ + public static function mergeRecursive (array ...$arrays):array { + + return array_merge_recursive(...$arrays); + + } + + /** + * ### Replaces elements from passed arrays into the first array + * + * Replaces the values of $array with values having the same keys in each of the following arrays. + * + * If a key from the first array exists in the second array, its value will be replaced by the value from the + * second array. + * + * If the key exists in the second array, and not the first, it will be created in the first array. + * + * If a key only exists in the first array, it will be left as is. + * + * If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting + * the previous values. + * + * Method is not recursive, it will replace values in the first array by whatever type is in the second array. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValueOriginal + * @template TValueReplacement + * + * @param array $array

+ * The array in which elements are replaced. + *

+ * @param array ...$replacements

+ * Arrays from which elements will be extracted. + * + * Values from later arrays overwrite the previous values. + *

+ * + * @return array The resulting array. + */ + public static function replace (array $array, array ...$replacements):array { + + return array_replace($array, ...$replacements); + + } + + /** + * ### Replace two or more arrays recursively + * + * Replaces the values of $array with the same values from all the following arrays. + * + * If a key from the first array exists in the second array, its value will be replaced by the value from the + * second array. + * + * If the key exists in the second array, and not the first, it will be created in the first array. + * + * If a key only exists in the first array, it will be left as is. + * + * If several arrays are passed for replacement, they will be processed in order, the later array overwriting the + * previous values. + * + * When the value in the first array is scalar, it will be replaced by the value in the second array, may it be + * scalar or array. + * + * When the value in the first array and the second array are both arrays, Arr::replaceRecursive() will replace + * their respective values recursively. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValueOriginal + * @template TValueReplacement + * + * @param array $array

+ * The array in which elements are replaced. + *

+ * @param array ...$replacements

+ * Arrays from which elements will be extracted. + * + * Values from later arrays overwrite the previous values. + *

+ + * @return array The resulting array. + */ + public static function replaceRecursive (array $array, array ...$replacements):array { + + /** @var array */ + return array_replace_recursive($array, ...$replacements); + + } + +} \ No newline at end of file diff --git a/src/Arr/Inspection.php b/src/Arr/Inspection.php new file mode 100644 index 0000000..0b09cc5 --- /dev/null +++ b/src/Arr/Inspection.php @@ -0,0 +1,173 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use Countable; + +use const COUNT_NORMAL; +use const COUNT_RECURSIVE; + +use function array_all; +use function array_any; +use function array_count_values; +use function array_is_list; +use function count; +use function in_array; + +/** + * ### PHP Array Runtime Wrapper Utility - Inspection + * + * This class is part of the FireHub Runtime layer and provides a lightweight, deterministic wrapper over native PHP + * functionality for its respective domain. + * + * It is designed to reduce boilerplate, standardize common runtime operations, and improve developer ergonomics + * through a consistent and expressive API while preserving native PHP behavior and performance. + * + * This component contains no domain logic, no framework coupling, and no business rules. + * @since 1.0.0 + */ +final class Inspection extends NativeRuntime { + + /** + * ### Checks if all array elements satisfy a callback function + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array that should be searched. + *

+ * @param callable(TValue, TKey):bool $callback

+ * The callback function to call to check each element. + *

+ * + * @return bool True if callback returns true for all elements, false otherwise. + */ + public static function all (array $array, callable $callback):bool { + + return array_all($array, $callback); + + } + + /** + * ### Checks if at least one array element satisfies a callback function + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array that should be searched. + *

+ * @param callable(TValue, TKey):bool $callback

+ * The callback function to call to check each element. + *

+ * + * @return bool True if there is at least one element for which callback returns true, false otherwise. + */ + public static function any (array $array, callable $callback):bool { + + return array_any($array, $callback); + + } + + /** + * ### Checks if a value exists in an array + * @since 1.0.0 + * + * @param array $array

+ * The array. + *

+ * @param mixed $value

+ * The searched value. + * If the value is a string, the comparison is done in a case-sensitive manner. + *

+ * + * @return bool Returns true if the given value exists in the array using strict comparison. + */ + public static function inArray (array $array, mixed $value):bool { + + return in_array($value, $array, true); + + } + + /** + * ### Checks whether a given array is a list + * + * Determines if the given array is a list. + * An array is considered a list if its keys consist of consecutive numbers from 0 to count($array)-1. + * @since 1.0.0 + * + * @param array $array

+ * The array is being evaluated. + *

+ * + * @phpstan-assert-if-true list $array + * + * @return ($array is list ? true : false) True if an array is a list, false otherwise. + * + * @note This function returns true on empty arrays. + */ + public static function isList (array $array):bool { + + return array_is_list($array); + + } + + /** + * ### Counts all elements in the array + * @since 1.0.0 + * + * @param array|Countable $value

+ * Array or Countable instance to count. + *

+ * @param bool $recursive [optional]

+ * Recursively count the array. + * + * This is particularly useful for counting all the elements of a multidimensional array. + *

+ * + * @return non-negative-int Number of elements in an array. + */ + public static function count (array|Countable $value, bool $recursive = false):int { + + return count($value, $recursive ? COUNT_RECURSIVE : COUNT_NORMAL); + + } + + /** + * ### Counts the occurrences of each distinct value in an array + * + * Returns an array using the values of $array (which must be int-s or strings) as keys and their frequency in an + * $array as values. + * @since 1.0.0 + * + * @template TValue of array-key + * + * @param array $array

+ * The array of values to count. + *

+ * + * @return array An associative array of values from input as keys and their count as + * value. + */ + public static function countValues (array $array):array { + + return array_count_values($array); + + } + +} \ No newline at end of file diff --git a/src/Arr/Math.php b/src/Arr/Math.php new file mode 100644 index 0000000..e4e770c --- /dev/null +++ b/src/Arr/Math.php @@ -0,0 +1,71 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function array_product; +use function array_sum; + +/** + * ### PHP Array Runtime Wrapper Utility - Math + * + * Provides runtime wrappers for performing mathematical operations on arrays, including aggregation and calculation + * of numerical values while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array mathematical operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Math extends NativeRuntime { + + /** + * ### Calculate the product of values in an array + * + * Returns the product of values in an array. + * @since 1.0.0 + * + * @template TValue of int|float + * + * @param array $array

+ * The array. + *

+ * + * @return int|float The product as an integer or float. + */ + public static function product (array $array):int|float { + + return array_product($array); + + } + + /** + * ### Calculate the sum of values in an array + * @since 1.0.0 + * + * @template TValue of int|float + * + * @param array $array

+ * The input array. + *

+ * + * @return int|float The sum of values as an integer or float; 0 if the array is empty. + */ + public static function sum (array $array):int|float { + + return array_sum($array); + + } + +} \ No newline at end of file diff --git a/src/Arr/Mutation.php b/src/Arr/Mutation.php new file mode 100644 index 0000000..5a0ff92 --- /dev/null +++ b/src/Arr/Mutation.php @@ -0,0 +1,148 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function array_pop; +use function array_push; +use function array_shift; +use function array_unshift; + +/** + * ### PHP Array Runtime Wrapper Utility - Mutation + * + * Provides runtime wrappers for modifying arrays through direct value insertion, removal, and queue or stack + * operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array mutation operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Mutation extends NativeRuntime { + + /** + * ### Pop the element off the end of an array + * + * Pops and returns the last element value of the $array, shortening the $array by one element. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * The array to get the value from. + *

+ * @phpstan-param-out TArray $array + * + * @return null|value-of The last value of an array. If an array is empty (or is not an array), null will + * be returned. + * + * @note This function will reset the array pointer of the input array after use. + */ + public static function pop (array &$array):mixed { + + return array_pop($array); + + } + + /** + * ### Push elements onto the end of an array + * + * Method treats an array as a stack and pushes the passed variables onto the end of an array. + * + * The length of an array increases by the number of variables pushed. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * @template TPushedValue + * + * @param array &$array

+ * The input array. + *

+ * @param TPushedValue ...$values [optional]

+ * The values to push onto the end of the array. + *

+ * @phpstan-param-out array $array + * + * @return int The new number of elements in the array. + * + * @note If you use push to add one element to the array, it is better to use $array[] = because in that way + * there is no overhead of calling a function. + */ + public static function push (array &$array, mixed ...$values):int { + + return array_push($array, ...$values); + + } + + /** + * ### Removes an item at the beginning of an array + * + * Shifts the first value of the array off and returns it, shortening the array by one element and moving + * everything down. + * + * All numerical array keys will be modified to start counting from zero while literal keys won't be affected. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * Array to shift. + *

+ * @phpstan-param-out TArray $array + * + * @return null|value-of The shifted value, or null if an array is empty or is not an array. + * + * @note This function will reset the array pointer of the input array after use. + */ + public static function shift (array &$array):mixed { + + return array_shift($array); + + } + + /** + * ### Prepend one or more elements to the beginning of an array + * + * Method prepends passed elements to the front of the array. + * + * Note that the list of elements is prepended as a whole so that the prepended elements stay in the same order. + * + * All numerical array keys will be modified to start counting from zero, while literal keys won't be changed. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * @template TUnshiftValue + * + * @param array &$array

+ * The input array. + *

+ * @param TUnshiftValue ...$values [optional]

+ * The values to prepend. + *

+ * @phpstan-param-out array $array + * + * @return int The new number of elements in the array. + * + * @note Resets array's internal pointer to the first element. + */ + public static function unshift (array &$array, mixed ...$values):int { + + return array_unshift($array, ...$values); + + } + +} \ No newline at end of file diff --git a/src/Arr/Ordering.php b/src/Arr/Ordering.php new file mode 100644 index 0000000..fc63e8b --- /dev/null +++ b/src/Arr/Ordering.php @@ -0,0 +1,238 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Meta\Enum\Order; +use FireHub\Runtime\Type\Arr\ { + SortFlag, SortType +}; + +use function array_multisort; +use function arsort; +use function asort; +use function krsort; +use function ksort; +use function rsort; +use function shuffle; +use function sort; +use function uasort; +use function uksort; +use function usort; + +/** + * ### PHP Array Runtime Wrapper Utility - Ordering + * + * Provides runtime wrappers for ordering, sorting, and rearranging array elements while preserving native PHP behavior + * and performance. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array ordering operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Ordering extends NativeRuntime { + + /** + * ### Sorts array + * @since 1.0.0 + * + * @uses \FireHub\Core\Meta\Enum\Order::ASC As default parameter. + * + * @template TArray of array + * + * @param TArray &$array

+ * Array to sort. + *

+ * @param bool $preserve_keys [optional]

+ * Whether you want to preserve keys from an original array or not. + *

+ * @param \FireHub\Core\Meta\Enum\Order $order [optional]

+ * Order type. + *

+ * @param \FireHub\Runtime\Type\Arr\SortType $type [optional]

+ * Sort type. + *

+ * @param \FireHub\Runtime\Type\Arr\SortFlag ...$flags [optional]

+ * Sort flags. + *

+ * @phpstan-param-out ($preserve_keys is true ? TArray : list>) $array + * + * @return true Always true. + * + * @note Resets array's internal pointer to the first element. + */ + public static function sort (array &$array, bool $preserve_keys = false, Order $order = Order::ASC, SortType $type = SortType::REGULAR, SortFlag ...$flags):true { + + $flags_value = $type->value; + + foreach ($flags as $flag) $flags_value |= $flag->value; + + return $order === Order::ASC + ? ($preserve_keys + ? asort($array, $flags_value) // @phpstan-ignore argument.type + : sort($array, $flags_value)) // @phpstan-ignore argument.type + : ($preserve_keys + ? arsort($array, $flags_value) // @phpstan-ignore argument.type + : rsort($array, $flags_value)); // @phpstan-ignore argument.type + + } + + /** + * ### Sorts an array by key + * @since 1.0.0 + * + * @uses \FireHub\Core\Meta\Enum\Order::ASC As default parameter. + * + * @template TArray of array + * + * @param TArray &$array

+ * Array to sort. + *

+ * @param \FireHub\Core\Meta\Enum\Order $order [optional]

+ * Order type. + *

+ * @param \FireHub\Runtime\Type\Arr\SortType $type [optional]

+ * Sort type. + *

+ * @param \FireHub\Runtime\Type\Arr\SortFlag ...$flags [optional]

+ * Sort flags. + *

+ * @phpstan-param-out TArray $array + * + * @return true Always true. + * + * @note Resets array's internal pointer to the first element. + */ + public static function sortByKeys (array &$array, Order $order = Order::ASC, SortType $type = SortType::REGULAR, SortFlag ...$flags):true { + + $flags_value = $type->value; + + foreach ($flags as $flag) $flags_value |= $flag->value; + + return $order === Order::ASC + ? ksort($array, $flags_value) + : krsort($array, $flags_value); + + } + + /** + * ### Sorts an array by values using a user-defined comparison function + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * Array to sort. + *

+ * @param callable(value-of, value-of):int<-1, 1> $callback

+ * The comparison function must return an integer less than, equal to, or greater than zero if the first argument + * is considered to be respectively less than, equal to, or greater than the second. + *

+ * @param bool $preserve_keys [optional]

+ * Whether you want to preserve keys from an original array or not. + *

+ * @phpstan-param-out ($preserve_keys is true ? TArray : list>) $array + * + * @return true Always true. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + */ + public static function sortBy (array &$array, callable $callback, bool $preserve_keys = false):true { + + return $preserve_keys + ? uasort($array, $callback) + : usort($array, $callback); + + } + + /** + * ### Sorts an array by key using a user-defined comparison function + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * Array to sort. + *

+ * @param callable(key-of, key-of):int<-1, 1> $callback

+ * The callback comparison function. + * + * Function cmp_function should accept two parameters which will be filled by pairs of array keys. + * + * The comparison function must return an integer less than, equal to, or greater than zero if the first argument + * is considered to be respectively less than, equal to, or greater than the second. + *

+ * @phpstan-param-out TArray $array + * + * @return true Always true. + * + * @note Resets array's internal pointer to the first element. + */ + public static function sortKeysBy (array &$array, callable $callback):true { + + return uksort($array, $callback); + + } + + /** + * ### Sort multiple on multidimensional arrays + * @since 1.0.0 + * + * @param array &$array

+ * An array being sorted. + *

+ * + * @return true True on success. + * + * @caution Associative (string) keys will be maintained, but numeric keys will be re-indexed. + * @note Resets array's internal pointer to the first element. + */ + public static function multiSort (array &...$array):bool { + + return array_multisort(...$array); + + } + + /** + * ### Shuffle array + * + * This function shuffles (randomizes the order of the elements in) an array. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * The array. + *

+ * @phpstan-param-out TArray $array + * + * @return true Always returns true. + * + * @caution This function doesn't generate cryptographically secure values and mustn't be used for cryptographic + * purposes, or purposes that require returned values to be unguessable. + * @note This function assigns new keys to the elements in an array. + * It will remove any existing keys that may have been assigned, rather than reordering the keys. + * @note Resets array's internal pointer to the first element. + */ + public static function shuffle (array &$array):true { + + return shuffle($array); + + } + +} \ No newline at end of file diff --git a/src/Arr/Pointer.php b/src/Arr/Pointer.php new file mode 100644 index 0000000..c3f4cd6 --- /dev/null +++ b/src/Arr/Pointer.php @@ -0,0 +1,232 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.5 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function current; +use function end; +use function key; +use function next; +use function prev; +use function reset; + +/** + * ### PHP Array Runtime Wrapper Utility - Pointer + * + * The Pointer class provides lightweight, deterministic wrappers for PHP array internal pointer operations. + * + * It contains runtime utilities for navigating and manipulating the internal array pointer, including moving between + * elements, retrieving the current position, and resetting or advancing traversal state while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for low-level array pointer + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Pointer extends NativeRuntime { + + /** + * ### Return the current element in an array + * + * Every array has an internal pointer to its "current" element, which is initialized to the first element + * inserted into the array. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array. + *

+ * + * @return value-of|false The Iterables::current() function simply returns the value of the array element + * that is being pointed to with the internal pointer. + * + * It doesn't move the pointer in any way. + * + * If the internal pointer points beyond the end of the element list or the array is empty, Iterables::current() + * returns false. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * + * Read the section on Booleans for more information. + * + * Use the === operator for testing the return value of this function. + * @note The results of calling Iterables::current() on an empty array and on an array whose internal pointer points + * beyond the end of the elements is indistinguishable from a bool false element. + * + * To properly traverse an array which may contain false elements, see the foreach control structure. + * + * To still use Iterables::current() and properly check if the value is really an element of the array, the + * Iterables::key() of the Iterables::current() element should be checked to be strictly different from null. + */ + public static function current (array $array):mixed { + + return current($array); + + } + + /** + * ### Fetch a key from an array + * + * Key returns the index element of the current array position. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array. + *

+ * + * @return null|key-of The Iterables::key() function simply returns the key of the array element that's + * currently being pointed to by the internal pointer. + * + * It doesn't move the pointer in any way. + * + * If the internal pointer points beyond the end of the element list or the array is empty, Iterables::key() + * returns null. + */ + public static function key (array $array):null|int|string { + + return key($array); + + } + + /** + * ### Rewind the internal array pointer + * + * Method Iterables::prev() behaves like Iterables::next(), except it rewinds the internal array pointer one place + * instead of advancing it. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * The input array. + *

+ * @phpstan-param-out TArray $array + * + * @return null|value-of Returns the array value in the previous place that is pointed to by the internal + * array pointer, or false if there are no more elements. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * Read the section on Booleans for more information. + * + * Use the === operator for testing the return value of this function. + * @note The beginning of an array is indistinguishable from a bool false element. To make the distinction, check + * that the Iterables#key() of the Iterables#prev() element is not null. + */ + public static function prev (array &$array):mixed { + + return prev($array); + + } + + /** + * ### Advance the internal pointer of an array + * + * Method Iterables::next() behaves like Iterables::current(), with one difference. + * + * It advances the internal array pointer one place forward before returning the element value. + * + * That means it returns the next array value and advances the internal array pointer by one. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * The array being affected. + *

+ * @phpstan-param-out TArray $array + * + * @return value-of|false Returns the array value in the next place that is pointed to by the internal array + * pointer, or false if there are no more elements. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * + * Read the section on Booleans for more information. + * + * Use the === operator for testing the return value of this function. + * @note The end of an array is indistinguishable from a bool false element. + * To properly traverse an array which may contain false elements, see the foreach function. + * + * To still use Iterables::next() and properly check if the end of the array has been reached, verify that the + * Iterables::key() is null. + */ + public static function next (array &$array):mixed { + + return next($array); + + } + + /** + * ### Set the internal pointer of an array to its first element + * + * Method Iterables::reset() rewinds the array's internal pointer to the first element and returns the value of + * the first array element. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * The input array. + *

+ * @phpstan-param-out TArray $array + * + * @return value-of|false Returns the value of the first array element, or false if the array is empty. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * + * Read the section on Booleans for more information. + * + * Use the === operator for testing the return value of this function. + * @note The return value for an empty array is indistinguishable from the return value in the case of an array + * which has a bool false first element. + * + * To properly check the value of the first element in an array which may contain false elements, first check the + * Iterables#count() of the array, or check that Iterables#key() is not null, after calling Iterables#reset(). + */ + public static function reset (array &$array):mixed { + + return reset($array); + + } + + /** + * ### Set the internal pointer of an array to its last element + * + * Method Iterables::end() advances the array's internal pointer to the last element and returns its value. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray &$array

+ * The input array. + *

+ * @phpstan-param-out TArray $array + * + * @return value-of|false Returns the value of the last element or false for an empty array. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * + * Read the section on Booleans for more information. + * + * Use the === operator for testing the return value of this function. + */ + public static function end (array &$array):mixed { + + return end($array); + + } + +} \ No newline at end of file diff --git a/src/Arr/SetOperation.php b/src/Arr/SetOperation.php new file mode 100644 index 0000000..bf625ac --- /dev/null +++ b/src/Arr/SetOperation.php @@ -0,0 +1,589 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function array_diff; +use function array_diff_assoc; +use function array_diff_key; +use function array_diff_uassoc; +use function array_diff_ukey; +use function array_intersect; +use function array_intersect_assoc; +use function array_intersect_key; +use function array_intersect_uassoc; +use function array_intersect_ukey; +use function array_udiff; +use function array_udiff_assoc; +use function array_udiff_uassoc; +use function array_uintersect; +use function array_uintersect_assoc; +use function array_uintersect_uassoc; + +/** + * ### PHP Array Runtime Wrapper Utility - SetOperation + * + * Provides runtime wrappers for performing set-based operations on arrays, including difference, intersection, + * and user-defined comparison while preserving native PHP behavior and performance. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array set operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class SetOperation extends NativeRuntime { + + /** + * ### Computes the difference of arrays using values for comparison + * + * Compares an array against one or more other arrays and returns the values in an array that aren't present in any + * of the other arrays. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param array ...$excludes [optional]

+ * An array to compare against. + *

+ * + * @return TArray An array containing all the entries from $array that aren't present in any of the other arrays. + * + * @note This function only checks one dimension of an n-dimensional array. + * You can check deeper dimensions by using Arr::difference($array1[0], $array2[0]). + */ + public static function difference (array $array, array ...$excludes):array { + + /** @var TArray */ + return array_diff($array, ...$excludes); + + } + + /** + * ### Computes the difference of arrays using values for comparison by using a callback for comparison + * + * Computes the difference of arrays by using a callback function for data comparison. + * This is unlike Arr::difference() which uses an internal function for comparing the data. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(value-of|value-of, value-of|value-of):int<-1, 1> $callback

+ * The comparison function must return an integer less than, equal to, or greater than zero if the first argument + * is considered to be respectively less than, equal to, or greater than the second. + *

+ * + * @return TArray An array containing all the entries from $array that aren't present in any of + * the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note Note that this function only checks one dimension of an n-dimensional array. + * Of course, you can check deeper dimensions by using + * Arr::differenceFunc($array1[0], $array2[0], 'data_compare_func'). + */ + public static function differenceUsing (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_udiff($array, $excludes, $callback); + + } + + /** + * ### Computes the difference of arrays using keys for comparison + * + * Compares the keys from an array against the keys from arrays and returns the difference. + * This function is like Arr::difference() except the comparison is done on the keys instead of the values. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param array ...$excludes [optional]

+ * An array to compare against. + *

+ * + * @return TArray Returns an array containing all the entries from an array whose keys are absent from all the + * other arrays. + * + * @note This function only checks one dimension of an n-dimensional array. + * Of course, you can check deeper dimensions by using Arr::differenceKey($array1[0], $array2[0]). + */ + public static function differenceKey (array $array, array ...$excludes):array { + + /** @var TArray */ + return array_diff_key($array, ...$excludes); + + } + + /** + * ### Computes the difference of arrays using keys for comparison by using a callback for data comparison + * + * Compares the keys from an array against the keys from arrays and returns the difference. + * This function is like Arr::difference() except the comparison is done on the keys instead of the values. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(key-of|key-of, key-of|key-of):int<-1, 1> $callback

+ * The comparison function. + *

+ * + * @return TArray An array containing all the entries from $array that aren't present in any of the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note This function only checks one dimension of an n-dimensional array. + * Of course, you can check deeper dimensions by using + * Arr::differenceKeyFunc($array1[0], $array2[0], 'callback_func'). + */ + public static function differenceUsingKey (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_diff_ukey($array, $excludes, $callback); + + } + + /** + * ### Computes the difference of arrays with additional index check + * + * Compares an array against arrays and returns the difference. + * Unlike Arr::difference(), the array keys are also used in the comparison. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param array ...$excludes [optional]

+ * An array to compare against. + *

+ * + * @return TArray An array containing all the entries from $array that aren't present in any of + * the other arrays. + * + * @note This function only checks one dimension of an n-dimensional array. + * It is possible to check deeper dimensions by using, for example, Arr::differenceAssoc($array1[0], $array2[0]). + * @note Ensure arguments are passed in the correct order when comparing similar arrays with more keys. + * The new array should be the first in the list. + */ + public static function differenceAssoc (array $array, array ...$excludes):array { + + /** @var TArray */ + return array_diff_assoc($array, ...$excludes); + + } + + /** + * ### Computes the difference of arrays with additional index check by using a callback for value comparison + * + * Computes the difference of arrays with an additional index check, compares data by a callback function. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(value-of|value-of, value-of|value-of):int<-1, 1> $callback

+ * The comparison function. + *

+ * + * @return TArray An array containing all the entries from $array that aren't present in any of the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note Note that this function only checks one dimension of an n-dimensional array. + * Of course, you can check deeper dimensions by using, for example, + * Arr::differenceAssocFuncValue($array1[0], $array2[0], some_comparison_func'). + */ + public static function differenceAssocUsingValue (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_udiff_assoc($array, $excludes, $callback); + + } + + /** + * ### Computes the difference of arrays with additional index check by using a callback for key comparison + * + * Compares an array against arrays and returns the difference. + * + * Unlike Arr::difference(), the array keys are used in the comparison. + * + * Unlike Arr::differenceAssoc(), a user-supplied callback function is used for the indices' comparison, + * not an internal function. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(key-of|key-of, key-of|key-of):int<-1, 1> $callback

+ * The comparison function. + *

+ * + * @return TArray Returns an array containing all the entries from $array that aren't present in any of the other + * arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note This function only checks one dimension of an n-dimensional array. + * It is possible to check deeper dimensions by using, for example, + * Arr::differenceAssocFuncKey($array1[0], $array2[0], 'key_compare_func'). + */ + public static function differenceAssocUsingKey (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_diff_uassoc($array, $excludes, $callback); + + } + + /** + * ### Computes the difference of arrays with additional index check by using a callback for key-value comparison + * + * Computes the difference of arrays with additional index check, compares data, and indexes by a callback function. + * Note that the keys are used in the comparison unlike Arr::difference() and Arr::differenceFunc(). + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(value-of|value-of, value-of|value-of):int<-1, 1> $callback_value

+ * The comparison function for value. + *

+ * @param callable(key-of|key-of, key-of|key-of):int<-1, 1> $callback_key

+ * The comparison function for a key. + *

+ * + * @return TArray An array containing all the entries from $array that aren't present in any of + * the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note This function only checks one dimension of an n-dimensional array. + * It is possible to check deeper dimensions by using, for example, + * Arr::differenceAssocFuncKeyValue($array1[0], $array2[0], 'data_compare_func', 'key_compare_func'). + */ + public static function differenceAssocUsingKeyValue (array $array, array $excludes, callable $callback_value, callable $callback_key):array { + + /** @var TArray */ + return array_udiff_uassoc($array, $excludes, $callback_value, $callback_key); + + } + + /** + * ### Computes the intersection of arrays using values for comparison + * + * Returns an array containing all the values of an array that are present in all the arguments. + * Note that keys are preserved. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array with main values to check. + *

+ * @param array ...$arrays [optional]

+ * An array to compare values against. + *

+ * + * @return TArray The filtered array. + * + * @note Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. + * In words: when the string representation is the same. + */ + public static function intersect (array $array, array ...$arrays):array { + + /** @var TArray */ + return array_intersect($array, ...$arrays); + + } + + /** + * ### Computes the intersection of arrays using values for comparison by using a callback for data comparison + * + * Computes the intersection of arrays, compares data by a callback function. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(value-of|value-of, value-of|value-of):int<-1, 1> $callback

+ * The comparison function. + *

+ * + * @return TArray Arrays containing all the entries from $array that are present in any of the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. + * In words: when the string representation is the same. + */ + public static function intersectUsing (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_uintersect($array, $excludes, $callback); + + } + + /** + * ### Computes the intersection of arrays using keys for comparison + * + * Returns an array containing all the entries of an array which have keys that are present in all the arguments. + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array with main values to check. + *

+ * @param array ...$arrays [optional]

+ * An array to compare values against. + *

+ * + * @return TArray The filtered array. + */ + public static function intersectKey (array $array, array ...$arrays):array { + + return array_intersect_key($array, ...$arrays); + + } + + /** + * ### Computes the intersection of arrays using keys for comparison by using a callback for data comparison + * + * Returns an array containing all the values of an array which have matching keys that are present in all the + * arguments. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(key-of|key-of, key-of|key-of):int<-1, 1> $callback

+ * The comparison function. + *

+ * + * @return TArray An array containing all the entries from $array that are present in any of the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + */ + public static function intersectUsingKey (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_intersect_ukey($array, $excludes, $callback); + + } + + /** + * ### Computes the intersection of arrays with additional index check + * + * Returns an array containing all the values of an array that are present in all the arguments. + * Note that the keys are also used in the comparison, unlike in Arr::intersect(). + * @since 1.0.0 + * + * @template TArray of array + * + * @param TArray $array

+ * The array with main values to check. + *

+ * @param array ...$arrays [optional]

+ * An array to compare values against. + *

+ * + * @return TArray The filtered array. + * + * @note The two values from the key → value pairs are considered equal only if (string) $elem1 === (string) $elem2. + * In other words, a strict type check is executed, so the string representation must be the same. + */ + public static function intersectAssoc (array $array, array ...$arrays):array { + + /** @var TArray */ + return array_intersect_assoc($array, ...$arrays); + + } + + /** + * ### Computes the intersection of arrays with additional index check by using a callback for value comparison + * + * Computes the intersection of arrays with additional index check, compares data by a callback function. + * Note that the keys are used in the comparison unlike in Arr::intersectFunc(). + * The data is compared by using a callback function. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(value-of|value-of, value-of|value-of):int<-1, 1> $callback $callback

+ * The comparison function. + *

+ * + * @return TArray An array containing all the entries from $array that are present in any of the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + */ + public static function intersectAssocUsingValue (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_uintersect_assoc($array, $excludes, $callback); + + } + + /** + * ### Computes the intersection of arrays with additional index check by using a callback for key comparison + * + * Computes the intersection of arrays with additional index check, compares data and indexes by separate + * callback functions. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(key-of|key-of, key-of|key-of):int<-1, 1> $callback

+ * The comparison function. + *

+ * + * @return TArray An array containing all the entries from $array that are present in any of the other arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note The comparison function must return an integer less than, equal to, or greater than zero if + * the first argument is considered to be respectively less than, equal to, or greater than the second. + */ + public static function intersectAssocUsingKey (array $array, array $excludes, callable $callback):array { + + /** @var TArray */ + return array_intersect_uassoc($array, $excludes, $callback); + + } + + /** + * ### Computes the intersection of arrays with additional index check by using a callback for key-value comparison + * + * Computes the intersection of arrays with additional index check, compares data and indexes by separate + * callback functions. + * @since 1.0.0 + * + * @template TArray of array + * @template TCompareArray of array + * + * @param TArray $array

+ * The array to compare from. + *

+ * @param TCompareArray $excludes

+ * An array to compare against. + *

+ * @param callable(value-of|value-of, value-of|value-of):int<-1, 1> $callback_value

+ * The comparison function for value. + *

+ * @param callable(key-of|key-of, key-of|key-of):int<-1, 1> $callback_key

+ * The comparison function for a key. + *

+ * + * @return TArray An array containing all the entries from $array that are present in any of the other + * arrays. + * + * @caution Returning non-integer values from the comparison function, such as float, will result in an internal + * cast to int of the callback's return value. + * So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as + * equal. + * @note The comparison function must return an integer less than, equal to, or greater than zero if + * the first argument is considered to be respectively less than, equal to, or greater than the second. + */ + public static function intersectAssocUsingKeyValue (array $array, array $excludes, callable $callback_value, callable $callback_key):array { + + /** @var TArray */ + return array_uintersect_uassoc($array, $excludes, $callback_value, $callback_key); + + } + +} \ No newline at end of file diff --git a/src/Arr/Structure.php b/src/Arr/Structure.php new file mode 100644 index 0000000..d040866 --- /dev/null +++ b/src/Arr/Structure.php @@ -0,0 +1,340 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + InvalidArrayLengthException, InvalidChunkLengthException, InvalidRangeStepException +}; + +use function array_chunk; +use function array_fill; +use function array_fill_keys; +use function array_pad; +use function array_slice; +use function array_splice; +use function range; + +/** + * ### PHP Array Runtime Wrapper Utility - Transform + * + * The Structure class provides lightweight, deterministic wrappers for creating and restructuring PHP arrays. + * + * It contains common runtime operations for defining array shapes, combining arrays, filling arrays with values, + * padding arrays, extracting segments, replacing portions, and generating sequential value ranges while preserving + * native PHP behavior and performance. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array structure operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Structure extends NativeRuntime { + + /** + * ### Split an array into chunks + * + * Chunks an array into arrays with $length elements. + * + * The last chunk may contain less than $length elements. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array. + *

+ * @param positive-int $length

+ * The size of each chunk. + * Must be greater than zero. + *

+ * @param bool $preserve_keys [optional]

+ * When set to true, keys will be preserved. + * + * Default is false that will reindex the chunk numerically. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidChunkLengthException If the length is less than 1. + * + * @return ($preserve_keys is true ? list> : list>) Multidimensional numerically + * indexed array, starting with zero, with each dimension contains $length elements. + */ + public static function chunk (array $array, int $length, bool $preserve_keys = false):array { + + if ($length < 1) { + throw new InvalidChunkLengthException( + 'The length of each chunk must be a positive integer.', + [ + 'length' => $length, + 'minimum' => 1, + ] + ); + } + + return array_chunk($array, $length, $preserve_keys); + + } + + /** + * ### Fill an array with values + * + * Fills an array with $length entries of the value for the $value parameter, keys starting at the $start_index + * parameter. + * @since 1.0.0 + * + * @template TValue + * + * @param TValue $value

+ * Value to use for filling. + *

+ * @param int $start_index

+ * The first index of the returned array. + *

+ * @param positive-int $length

+ * Number of elements to insert. Must be greater than or equal to zero. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidArrayLengthException If $length is invalid. + * + * @return array Filled array. + */ + public static function fill (mixed $value, int $start_index, int $length):array { + + if ($length < 1) { + throw new InvalidArrayLengthException( + 'The array length must be greater than zero.', + [ + 'length' => $length, + 'minimum' => 1, + ] + ); + } + + return array_fill($start_index, $length, $value); + + } + + /** + * ### Fill an array with values, specifying keys + * + * Fills an array with the value of the $value parameter, using the values of the $keys array as keys. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $keys

+ * Array of values that will be used as keys. + * + * Illegal values for a key will be converted to string. + *

+ * @param TValue $value

+ * Value to use for filling. + *

+ * + * @return array The filled array. + */ + public static function fillKeys (array $keys, mixed $value):array { + + return array_fill_keys($keys, $value); + + } + + /** + * ### Pad array to the specified length with a value + * + * Returns a copy of the array padded to the size specified by $length with $value. + * If the length is positive, then the array is padded on the right if it is negative, then on the left. + * If the absolute value of a length is less than or equal to the length of the array, then no padding takes place. + * @since 1.0.0 + * + * @template TValue + * @template TPaddedValue + * + * @param array $array

+ * Initial array of values to pad. + *

+ * @param int $length

+ * New size of the array. + * If the length is positive, then the array is padded on the right if it is negative, then on the left. + * + * If the absolute value of a length is less than or equal to the length of the array, then no padding takes place. + * + *

+ * @param TPaddedValue $value

+ * Value to pad if input is less than length. + *

+ * + * @return array A copy of the input padded to the size specified by $length with + * value $value. + * + * @caution Keys can be re-numbered. + */ + public static function pad (array $array, int $length, mixed $value):array { + + return array_pad($array, $length, $value); + + } + + /** + * ### Extract a slice of the array + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The input array. + *

+ * @param int $offset

+ * If the offset is non-negative, the sequence will start at that offset in the array. + * + * If the offset is negative, the sequence will start that far from the end of the array. + *

+ * @param null|int $length [optional]

+ * If length is given and is positive, then the sequence will have that many elements in it. + * + * If length is given and is negative, then the sequence will stop that many elements from the end of the array. + * + * If it is omitted, then the sequence will have everything from offset up until the end of the array. + *

+ * @param bool $preserve_keys [optional]

+ * Note that array_slice will reorder and reset the array indices by default. + * + * You can change this behavior by setting preserve_keys to true. + *

+ * + * @return ( $preserve_keys is true + * ? array + * : ($array is list + * ? list + * : array) + * ) Converted value. + * + * @note Named keys will always retain their name. + */ + public static function slice (array $array, int $offset, ?int $length = null, bool $preserve_keys = false):array { + + return array_slice($array, $offset, $length, $preserve_keys); + + } + + /** + * ### Remove a portion of the array and replace it with something else + * + * Removes the elements designated by offset and length from the parameter $array and replaces them with the + * elements of the replacement array, if supplied. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * @template TReplacedValue + * + * @param array &$array

+ * Array to splice. + *

+ * @param int $offset

+ * If the offset is positive, then the start of the removed portion is at that offset from the beginning of the + * input array. + * + * If the offset is negative, then it starts that far from the end of the input array. + *

+ * @param null|int $length [optional]

+ * If the length is omitted, removes everything from offset to the end of the array. + * + * If the length is specified and is positive, then that many elements will be removed. + * + * If the length is specified and is negative, then the end of the removed portion will be that many elements from + * the end of the array. + *

+ * @param TReplacedValue $replacement [optional]

+ * If a replacement array is specified, then the removed elements will be replaced with elements from this array. + * + * If offset and length are such that nothing is removed, then the elements from the replacement array or array + * are inserted in the place specified by the offset. + * + * Keys in a replacement array aren't preserved. + *

+ * @phpstan-param-out ($array is list ? list : array) $array + * + * @return array Spliced array. + * + * @note Numerical keys in an array aren't preserved. + * + * @note If the replacement is not an array, it will be typecast to one (in other words (array) $replacement). + * + * This may result in unexpected behavior when using an object or null replacement. + */ + public static function splice (array &$array, int $offset, ?int $length = null, mixed $replacement = []):array { + + return array_splice($array, $offset, $length, $replacement); // @phpstan-ignore paramOut.type + + } + + /** + * ### Create an array containing a range of elements + * @since 1.0.0 + * + * @template TStart of int|float|string + * @template TEnd of int|float|string + * @template TStep of int|float + * + * @param TStart $start

+ * First value of the sequence. + *

+ * @param TEnd $end

+ * The sequence is ended upon reaching the end value. + *

+ * @param TStep $step [optional]

+ * If a step value is given, it will be used as the increment between elements in the sequence. + * + * Step should be given as a positive number. If not specified, a step will default to 1. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidRangeStepException If the step is zero or range step must be greater + * than zero when the start is greater than the end. + * + * @return (TStart is string + * ? array + * : (TEnd is string + * ? array + * : (TStart is float + * ? array + * : (TEnd is float + * ? array + * : (TStep is float + * ? array + * : array)))) + * ) Sequence of elements as an array with the first element being start going up to end, with each value of the + * sequence being step values apart. + * + * @note Character sequence values are limited to a length of one. + * + * If a length greater than one is entered only the first character is used. + */ + public static function range (int|float|string $start, int|float|string $end, int|float $step = 1):array { + + if ($step === 0) throw new InvalidRangeStepException('The range step must not be zero.'); + + if ($end > $start && $step < 0) { + throw new InvalidRangeStepException( + 'The range step must be greater than zero when the start is greater than the end.' + ); + } + + return range($start, $end, $step); + + } + +} \ No newline at end of file diff --git a/src/Arr/Transform.php b/src/Arr/Transform.php new file mode 100644 index 0000000..3018242 --- /dev/null +++ b/src/Arr/Transform.php @@ -0,0 +1,340 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Arr; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Type\Arr\ { + KeyCase, UniqueMode +}; + +use const ARRAY_FILTER_USE_BOTH; + +use function array_change_key_case; +use function array_filter; +use function array_flip; +use function array_map; +use function array_reduce; +use function array_reverse; +use function array_unique; +use function array_walk; +use function array_walk_recursive; + +/** + * ### PHP Array Runtime Wrapper Utility - Transform + * + * The Transform class provides lightweight, deterministic wrappers for transforming and modifying PHP arrays. + * + * It contains common runtime operations for changing array structure, replacing values, mapping data, filtering + * elements, and producing transformed array representations while preserving native PHP behavior and performance. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for array transformation + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Transform extends NativeRuntime { + + /** + * ### Iteratively reduce the array to a single value using a callback function + * + * Iteratively applies the $callback function to the elements of the $array to reduce the array to a single value. + * @since 1.0.0 + * + * @template TValue + * @template TReturn + * + * @param array $array

+ * The input array. + *

+ * @param callable(null|TReturn, TValue):TReturn $callback

+ * The callable function. + *

+ * @param null|TReturn $initial [optional]

+ * If the optional initial is available, it will be used at the beginning of the process, or as a final result in + * case the array is empty. + *

+ * + * @return ($initial is null ? null|TReturn : TReturn) Resulting value or null if the array is empty and the + * initial is not passed. + */ + public static function reduce (array $array, callable $callback, mixed $initial = null):mixed { + + return func_num_args() < 3 + ? array_reduce($array, $callback) + : array_reduce($array, $callback, $initial); + + } + + /** + * ### Changes the case of all keys in an array + * + * Returns an array with all keys from an array lowercased or uppercased. + * Numbered indices are left as is. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Arr\KeyCase::LOWER As default parameter. + * + * @template TValue + * + * @param array $array

+ * The array to work on. + *

+ * @param \FireHub\Runtime\Type\Arr\KeyCase $style [optional]

+ * Either LOWER or UPPER key case style. + *

+ * + * @return array An array with its keys lower or uppercased. + */ + public static function keyCase (array $array, KeyCase $style = KeyCase::LOWER):array { + + return array_change_key_case($array, $style->value); + + } + + /** + * ### Filters elements of an array using a callback function + * + * Iterates over each value in the $array, passing them to the $callback function. + * + * If the $callback function returns true, the current value from an $array is returned into the result array. + * + * Array keys are preserved and may result in gaps if the $array was indexed. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array to iterate. + *

+ * @param null|callable(TValue, TKey):bool $callback [optional]

+ * The callback function to use. + * + * If no callback is supplied, all empty and false entries of an array will be removed. + *

+ * + * @return array Filtered array. + * + * @note The result array can be re-indexed using the Arr::values() function. + * @note If no callback is provided, all falsey values are removed. + * @caution If the array is changed from the callback function (for example, an element added, deleted, or unset), + * then the behavior of this function is undefined. + */ + public static function filter (array $array, ?callable $callback = null):array { + + return array_filter( + $array, + $callback ?? static fn(mixed $value): bool => (bool) $value, + ARRAY_FILTER_USE_BOTH + ); + + } + + + /** + * ### Exchanges all keys with their associated values in an array + * + * Returns an array in flip order; in other words, keys from an $array become values, and values from an $array + * become keys. + * + * Note that the values of $array need to be valid keys; in other words, they need to be either int or string. + * + * A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be + * included in the result. + * + * If a value has several occurrences, the latest key will be used as its value, and all others will be lost. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue of array-key + * + * @param array $array

+ * The array to flip. + *

+ * + * @return array The flipped array. + */ + public static function flip (array $array):array { + + return array_flip($array); + + } + + /** + * ### Applies the callback to the elements of the given array + * + * Returns an array containing the results of applying the $callback to the corresponding value of an $array + * used as arguments for the callback. + * + * The number of parameters that the $callback function accepts should match the number of arrays passed to + * Arr::map(). Excess input arrays are ignored. + * + * An ArgumentCountError is thrown if an insufficient number of arguments is provided. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * @template TReturn + * + * @param array $array

+ * Array to run through the callback function. + *

+ * @param callable(TValue):TReturn $callback

+ * Callback function to run for each element in each array. + * + * Null can be passed as a value to $callback to perform a zip operation on multiple arrays. + * + * If only an array is provided, Arr::map() will return the input array. + *

+ * + * @return ($array is list + * ? list + * : array + * ) Returns an array containing the results of applying the callback function to the corresponding value of array. + */ + public static function map (array $array, callable $callback):array { + + return array_map($callback, $array); + + } + + /** + * ### Apply a user function to every member of an array + * + * Applies the user-defined callback function to each element of the array $array. + * + * Method is not affected by the internal array pointer of an array. + * + * Method will walk through the entire array regardless of pointer position. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * @template TReturn + * + * @param array &$array

+ * The array to apply a user function. + *

+ * @param callable(TValue, TKey):TReturn $callback

+ * Typically, the function name takes on two parameters. + * + * The array parameter's value is the first, and the key/index second. + * + * If a function name needs to be working with the actual values of the array, specify the first parameter of the + * function name as a reference. + * + * Then, any changes made to those elements will be made in the original array itself. + * + * Users may not change the array itself from the callback function, for example, add/delete elements, unset + * elements, and so on. + *

+ * @phpstan-param-out array $array + * + * @return true True on success. + */ + public static function walk (array &$array, callable $callback):true { + + return array_walk($array, $callback); // @phpstan-ignore paramOut.type + + } + + /** + * ### Apply a user function recursively to every member of an array + * + * Applies the user-defined callback function to each element of the array. + * + * This function will recurse into deeper arrays. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * @template TReturn + * + * @param array &$array

+ * The array to apply a user function. + *

+ * @param callable(TValue, TKey):TReturn $callback

+ * Typically, the function name takes on two parameters. + * + * The array parameter's value is the first, and the key/index second. + * + * If a function name needs to be working with the actual values of the array, specify the first parameter of the + * function name as a reference. + * + * Then, any changes made to those elements will be made in the original array itself. + * + * Users may not change the array itself from the callback function. + * + * For example, Add/delete elements, unset elements, and so on. + *

+ * @phpstan-param-out array $array + * + * @return true True on success. + */ + public static function walkRecursive (array &$array, callable $callback):true { + + return array_walk_recursive($array, $callback); // @phpstan-ignore paramOut.type + + } + + /** + * ### Reverse the order of array items + * + * Takes an input array and returns a new array with the order of the elements reversed. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * Array to reverse. + *

+ * @param bool $preserve_keys [optional]

+ * Whether you want to preserve keys from an original array or not. + * + * Non-numeric keys aren't affected by this setting and will always be preserved. + *

+ * + * @return ($preserve_keys is true ? array : list) The reversed array. + */ + public static function reverse (array $array, bool $preserve_keys = false):array { + + return array_reverse($array, $preserve_keys); + + } + + /** + * ### Removes duplicate values from an array + * + * Takes an input array and returns a new array without duplicate values. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param array $array

+ * The array to remove duplicates. + *

+ * + * @return array The filtered array. + * + * @note The new array will preserve keys. + * @note This method is not intended to work on multidimensional arrays. + */ + public static function unique (array $array, UniqueMode $compare = UniqueMode::REGULAR):array { + + return array_unique($array, $compare->value); // @phpstan-ignore argument.type + + } + +} \ No newline at end of file diff --git a/src/Char/MB.php b/src/Char/MB.php new file mode 100644 index 0000000..9606bf0 --- /dev/null +++ b/src/Char/MB.php @@ -0,0 +1,93 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Char; + +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; + +use function mb_chr; +use function mb_ord; + +/** + * ### PHP Multibyte Character Runtime Wrapper Utility - MB + * + * Provides runtime wrappers for multibyte character operations using PHP multibyte string functions. + * + * This component provides encoding-aware character processing, including Unicode-compatible inspection, + * conversion, and transformation operations for multibyte string data. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for multibyte character + * processing while preserving native PHP behavior, encoding support, and runtime performance. + * @since 1.0.0 + */ +final class MB { + + /** + * ### Return character by Unicode code point value + * + * Returns a string containing the character specified by the Unicode code point value, encoded in the specified + * encoding. + * + * This function complements Char\MB::ord(). + * @since 1.0.0 + * + * @see https://en.wikipedia.org/wiki/List_of_Unicode_characters List of codepoint values + * + * @param int $codepoint

+ * The codepoint value. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return string|false A string containing the requested character if it can be represented in the specified + * encoding or false on failure. + */ + public static function chr (int $codepoint, ?Encoding $encoding = null):string|false { + + return mb_chr($codepoint, $encoding?->value); + + } + + /** + * ### Get Unicode code point of character + * + * Returns the Unicode code point value of the given character. + * + * This function complements Char\MB::chr(). + * @since 1.0.0 + * + * @see https://en.wikipedia.org/wiki/List_of_Unicode_characters List of codepoint values + * + * @param string $character

+ * A character. + * - Empty string is treated as NUL ("\0") + * - Strings longer than one character are truncated to the first character + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

. + * + * @return non-negative-int|false The Unicode code point for the first character of string. + */ + public static function ord (string $character, ?Encoding $encoding = null):int|false { + + /** @var non-negative-int|false */ + return mb_ord($character ?: "\0", $encoding?->value); + + } + +} \ No newline at end of file diff --git a/src/Char/SB.php b/src/Char/SB.php new file mode 100644 index 0000000..92432c1 --- /dev/null +++ b/src/Char/SB.php @@ -0,0 +1,106 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Char; + +use FireHub\Runtime\Exception\InvalidCharacterCodepointException; + +use function chr; +use function ord; + +/** + * ### PHP Single-Byte Character Runtime Wrapper Utility - SB + * + * Provides low-level runtime wrappers for single-byte character operations using PHP native string behavior. + * + * This component operates directly on byte-oriented strings and provides access to character inspection, + * conversion, and transformation operations without Unicode awareness. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for single-byte character + * processing while preserving native PHP behavior, performance, and compatibility. + * @since 1.0.0 + */ +final class SB { + + /** + * ### Generate a single-byte string from a number + * + * Returns a one-character string containing the character specified by interpreting $codepoint as an unsigned + * integer. + * + * This can be used to create a one-character string in a single-byte encoding such as ASCII, ISO-8859, or + * Windows 1252, by passing the position of a desired character in the encoding's mapping table. + * However, note that this function is not aware of any string encoding, and in particular can't be passed a + * Unicode code point value to generate a string in a multibyte encoding like UTF-8 or UTF-16. + * + * This function complements Char\SB::ord(). + * @since 1.0.0 + * + * @see https://www.man7.org/linux/man-pages/man7/ascii.7.html List of codepoint values + * + * @param int<0, 255> $codepoint

+ * An integer between 0 and 255. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidCharacterCodepointException If the codepoint value is outside the + * valid range (0..255). + * + * @return string A single-character string containing the specified byte. + */ + public static function chr (int $codepoint):string { + + if ($codepoint < 0 || $codepoint > 255) { + throw new InvalidCharacterCodepointException( + 'The character codepoint must be between 0 and 255 for single-byte characters.', + [ + 'codepoint' => $codepoint, + 'minimum' => 0, + 'maximum' => 255, + ] + ); + } + + return chr($codepoint); + + } + + /** + * ### Convert the first byte of a string to a value between 0 and 255 + * + * Interprets the binary value of the first byte from $character as an unsigned integer between 0 and 255. + * If the string is in a single-byte encoding, such as ASCII, ISO-8859, or Windows 1252, this is equivalent to + * returning the position of a character in the character set's mapping table. + * + * However, note that this function is not aware of any string encoding, and in particular will never identify a + * Unicode code point in a multibyte encoding such as UTF-8 or UTF-16. + * + * This function complements Char\SB::chr(). + * @since 1.0.0 + * + * @see https://www.man7.org/linux/man-pages/man7/ascii.7.html List of codepoint values + * + * @param string $character

+ * A character. + * - Empty string is treated as NUL ("\0") + * - Strings longer than one byte are truncated to the first byte + *

+ * + * @return int<0, 255> An integer between 0 and 255. + */ + public static function ord (string $character):int { + + return ord($character[0] ?? "\0"); + + } + +} \ No newline at end of file diff --git a/src/Constant.php b/src/Constant.php new file mode 100644 index 0000000..c84a789 --- /dev/null +++ b/src/Constant.php @@ -0,0 +1,114 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + CannotDefineConstantException, ConstantAlreadyDefinedException, UndefinedConstantException +}; + +use function constant; +use function define; +use function defined; + +/** + * ### PHP Runtime Constant Utility + * + * Provides low-level wrappers for inspecting, defining, and retrieving PHP constants while preserving native runtime behavior. + * + * This component exposes native constant operations through a consistent FireHub Runtime API without introducing + * additional abstraction or changing PHP semantics. + * @since 1.0.0 + */ +final class Constant extends NativeRuntime { + + /** + * ### Checks whether a given named constant exists + * + * This function works also with class constants and enum cases. + * @since 1.0.0 + * + * @param non-empty-string $name

+ * The constant name. + *

+ * + * @return bool True if the named constant given by the name parameter has been defined, false otherwise. + * + * @note This function works also with class constants and enum cases. + */ + public static function defined (string $name):bool { + + return defined($name); + + } + + /** + * ### Defines a named constant at runtime + * + * Creates a new global constant with the given name and value. + * @since 1.0.0 + * + * @uses Constant::defined() To check if the constant already exists before attempting to define it. + * + * @param non-empty-string $name

+ * The name of the constant. + *

+ * @param null|array|scalar $value

+ * The value of the constant. + *

+ * + * @throws \FireHub\Runtime\Exception\ConstantAlreadyDefinedException If constant with the same name already + * exists. + * @throws \FireHub\Runtime\Exception\CannotDefineConstantException If failed to define constant. + * + * @return true True on success. + */ + public static function define (string $name, null|array|bool|float|int|string $value):true { + + return self::defined($name) + ? throw new ConstantAlreadyDefinedException + : (define($name, $value) + ?: throw new CannotDefineConstantException); + + } + + /** + * ### Returns the value of a constant + * + * Method Constant::value() is useful if you need to retrieve the value of a constant but don't know its name. + * In other words, it is stored in a variable or returned by a function. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Constant::defined() To check if the constant is defined before attempting to retrieve + * its value. + * + * @param non-empty-string $name

+ * The constant name. + *

+ * + * @throws \FireHub\Runtime\Exception\UndefinedConstantException If the constant is not defined. + * + * @return mixed The value of the constant. + * + * @note This function works also with class constants and enum cases. + */ + public static function value (string $name):mixed { + + return self::defined($name) + ? constant($name) + : throw new UndefinedConstantException; + + } + +} \ No newline at end of file diff --git a/src/Data.php b/src/Data.php new file mode 100644 index 0000000..2c11da0 --- /dev/null +++ b/src/Data.php @@ -0,0 +1,214 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Type\Data\Type; +use FireHub\Runtime\Exception\ { + ArrayToStringConversionException, CannotSerializeException, CannotUnserializeException, + FailedToConvertTypeException, ResourceTypeConversionException +}; +use Throwable; + +use function get_debug_type; +use function gettype; +use function serialize; +use function settype; +use function unserialize; + +/** + * ### PHP Data Runtime Utility + * + * Provides low-level runtime utilities for inspecting, converting, serializing, and manipulating native PHP data + * values while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for common PHP data operations + * without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Data extends NativeRuntime { + + /** + * ### Gets the type name of a variable in a way that is suitable for debugging + * + * - null + * - bool + * - int + * - float + * - string + * - array + * - resource (stream) + * - resource (closed) + * - stdClass + * - class(at)anonymous + * @since 1.0.0 + * + * @param mixed $value

+ * The variable being type-checked. + *

+ * + * @return string Type name. + */ + public static function getDebugType (mixed $value):string { + + return get_debug_type($value); + + } + + /** + * ### Gets data type + * @since 1.0.0 + * + * @param mixed $value

+ * The variable being type-checked. + *

+ * + * @return \FireHub\Runtime\Type\Data\Type Type of data. + */ + public static function getType (mixed $value):Type { + + return Type::from(gettype($value)); + + } + + /** + * ### Sets data type + * @since 1.0.0 + * + * @uses self::getType() To get the $value type. + * @uses \FireHub\Runtime\Type\Data\Type::STRING As a data type. + * @uses \FireHub\Runtime\Type\Data\Type::RESOURCE As a data type. + * @uses \FireHub\Runtime\Type\Data\Type::CLOSED_RESOURCE As a data type. + * + * @param mixed $value

+ * The variable being converted to type. + *

+ * @param \FireHub\Runtime\Type\Data\Type $type

+ * Type to convert variable to. + *

+ * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException If the $type is Type::ARRAY. + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException If the $type is Type::RESOURCE or Type::CLOSED_RESOURCE. + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException If the conversion fails. + * + * @return ( + * $type is Type::ARRAY + * ? array + * : ($type is Type::STRING + * ? string + * : ($type is Type::INT + * ? int + * : ($type is Type::FLOAT + * ? float + * : ($type is Type::OBJECT + * ? object + * : ($type is Type::BOOL + * ? bool + * : ($type is Type::NULL + * ? null + * : ($type is Type::RESOURCE + * ? false + * : mixed))))))) + * ) Converted value. + */ + public static function setType (mixed $value, Type $type):mixed { + + if ($type === Type::STRING && self::getType($value) === Type::ARRAY) + throw new ArrayToStringConversionException; + + if ($type === Type::RESOURCE || $type === Type::CLOSED_RESOURCE) + throw new ResourceTypeConversionException('Cannot convert resource to type.'); + + $result = settype($value, $type->value); + + if (!$result) throw new FailedToConvertTypeException('Failed to convert value to type.'); + + return $value; + + } + + /** + * ### Generates storable representation of data + * + * Generates a storable representation of a value. + * + * This is useful for storing or passing PHP values around without losing their type and structure. + * To make the serialized string into a PHP value again, use Data::unserialize(). + * @since 1.0.0 + * + * @param null|scalar|array|object $value

+ * The value is to be serialized. + *

+ * + * @throws \FireHub\Runtime\Exception\CannotSerializeException If try to serialize an anonymous class, + * function, or resource. + * + * @return string String containing a byte-stream representation of a value that can be stored anywhere. + * + * @warning When Data::serialize() serializes objects, the leading backslash is not included in the class name + * of namespaced classes for maximum compatibility. + * @note This is a binary string that may include null bytes and needs to be stored and handled as such. + * For example, Data::serialize() output should generally be stored in a BLOB field in a database, rather than + * a CHAR or TEXT field. + */ + public static function serialize (null|string|int|float|bool|array|object $value):string { + + try { + + return serialize($value); + + } catch (Throwable $error) { + + throw new CannotSerializeException( + 'Failed to serialize value.', + previous: $error); + + } + + } + + /** + * ### Creates a PHP value from a stored representation + * @since 1.0.0 + * + * @param non-empty-string $data

+ * The serialized string. + *

+ * @param bool|class-string[] $allowed_classes [optional]

+ * Either an array of class names which should be accepted, false to accept no classes, or true to accept all + * classes. + *

+ * @param int $max_depth [optional]

+ * The maximum depth of structures is permitted during unserialization and is intended to prevent stack overflows. + *

+ * + * @throws \FireHub\Runtime\Exception\CannotUnserializeException If couldn't unserialize data, $data is already + * false, or $data is NULL. + * + * @return mixed The converted value is returned. + */ + public static function unserialize (string $data, bool|array $allowed_classes = false, int $max_depth = 4096):mixed { + + if ($data === 'b:0;' || $data === 'N;') throw new CannotUnserializeException; + + return ($unserialized_data = unserialize( + $data, + ['allowed_classes' => $allowed_classes, 'max_depth' => $max_depth]) // @phpstan-ignore argument.type + ) !== false + ? $unserialized_data + : throw new CannotUnserializeException; + + } + +} \ No newline at end of file diff --git a/src/DataIs.php b/src/DataIs.php new file mode 100644 index 0000000..33dc172 --- /dev/null +++ b/src/DataIs.php @@ -0,0 +1,293 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use Countable; + +use function is_array; +use function is_bool; +use function is_callable; +use function is_countable; +use function is_float; +use function is_int; +use function is_iterable; +use function is_numeric; +use function is_object; +use function is_resource; +use function is_scalar; +use function is_string; + +/** + * ### PHP Data Type Inspection Runtime Utility + * + * Provides low-level runtime utilities for inspecting PHP values and determining their native data types using + * built-in type checking operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for validating value types + * without introducing conversion, transformation, or additional abstraction logic. + * @since 1.0.0 + */ +final class DataIs extends NativeRuntime { + + /** + * ### Checks whether the value is an array + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert array $value + * @phpstan-assert-if-false !array $value + * + * @return bool True if the value is an array, false otherwise. + */ + public static function array (mixed $value):bool { + + return is_array($value); + + } + + /** + * ### Checks whether the value is boolean + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert bool $value + * @phpstan-assert-if-false !bool $value + * + * @return bool True if the value is boolean, false otherwise. + */ + public static function bool (mixed $value):bool { + + return is_bool($value); + + } + + /** + * ### Checks whether the value can be called as a function + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert callable $value + * @phpstan-assert-if-false !callable $value + * + * @return bool True if the value is callable, false otherwise. + */ + public static function callable (mixed $value):bool { + + return is_callable($value); + + } + + /** + * ### Checks whether the value is a countable value + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert array|Countable $value + * @phpstan-assert-if-false !(array|Countable) $value + * + * @return bool True if value is countable, false otherwise. + */ + public static function countable (mixed $value):bool { + + return is_countable($value); + + } + + /** + * ### Checks whether the value is a float + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert float $value + * @phpstan-assert-if-false !float $value + * + * @return bool True if value is float, false otherwise. + */ + public static function float (mixed $value):bool { + + return is_float($value); + + } + + /** + * ### Checks whether the value is an integer + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert int $value + * @phpstan-assert-if-false !int $value + * + * @return bool True if the value is integer, false otherwise. + */ + public static function int (mixed $value):bool { + + return is_int($value); + + } + + /** + * ### Checks whether the value is an iterable value + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert iterable $value + * @phpstan-assert-if-false !iterable $value + * + * @return bool True if value is iterable, false otherwise. + */ + public static function iterable (mixed $value):bool { + + return is_iterable($value); + + } + + /** + * ### Checks whether the value is null + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert null $value + * @phpstan-assert-if-false !null $value + * + * @return bool True if the value is null, false otherwise. + */ + public static function null (mixed $value):bool { + + return null === $value; + + } + + /** + * ### Checks whether the value is a number or a numeric string + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert int|float|numeric-string $value + * @phpstan-assert-if-false !(int|float|numeric-string) $value + * + * @return bool True if the value is numeric, false otherwise. + */ + public static function numeric (mixed $value):bool { + + return is_numeric($value); + + } + + /** + * ### Checks whether the value is an object + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert object $value + * @phpstan-assert-if-false !object $value + * + * @return bool True if value is an object, false otherwise. + */ + public static function object (mixed $value):bool { + + return is_object($value); + + } + + /** + * ### Checks whether the value is a resource + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert resource $value + * @phpstan-assert-if-false !resource $value + * + * @return bool True if value is a resource, false otherwise, or if the resource is closed. + */ + public static function resource (mixed $value):bool { + + return is_resource($value); + + } + + /** + * ### Checks whether the value is a scalar + * + * Scalar values include: string, int, float, and bool. + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert scalar $value + * @phpstan-assert-if-false !scalar $value + * + * @return bool True if the value is scalar, false otherwise. + */ + public static function scalar (mixed $value):bool { + + return is_scalar($value); + + } + + /** + * ### Checks whether the value is a string + * @since 1.0.0 + * + * @param mixed $value

+ * Value to check. + *

+ * + * @phpstan-assert string $value + * @phpstan-assert-if-false !string $value + * + * @return bool True if value is string, false otherwise. + */ + public static function string (mixed $value):bool { + + return is_string($value); + + } + +} \ No newline at end of file diff --git a/src/Date/Calendar.php b/src/Date/Calendar.php new file mode 100644 index 0000000..08e5a27 --- /dev/null +++ b/src/Date/Calendar.php @@ -0,0 +1,111 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Date; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function checkdate; +use function getdate; +use function localtime; + +/** + * ### Calendar Date Utilities + * + * Provides low-level wrappers for inspecting and working with calendar dates using native PHP calendar functions + * while preserving native runtime behavior. + * @since 1.0.0 + */ +final class Calendar extends NativeRuntime { + + /** + * ### Check for a valid date + * + * Checks the validity of the date formed by the arguments. + * + * A date is considered valid if each parameter is properly defined. + * @since 1.0.0 + * + * @param int<1, 32767> $year

+ * The year is between 1 and 32,767 inclusive. + *

+ * @param int<1, 12> $month

+ * The month is between 1 and 12 inclusive. + *

+ * @param int<1, 31> $day

+ * The day is within the allowed number of days for the given month. + * + * Leap years are taken into consideration. + *

+ * + * @return bool True, if the date given is valid, otherwise returns false. + */ + public static function check (int $year, int $month, int $day):bool { + + return checkdate($month, $day, $year); + + } + + /** + * ### Get date/time information + * @since 1.0.0 + * + * @param null|int $timestamp [optional]

+ * The optional timestamp parameter is an int Unix timestamp that defaults to the current local time if + * the timestamp is omitted or null. + *

+ * + * @return array{ + * seconds: int<0, 59>, + * minutes: int<0, 59>, + * hours: int<0, 23>, + * mday: int<1, 31>, + * wday: int<0, 6>, + * mon: int<1, 12>, + * year: int, + * yday: int<0, 365>, + * weekday: 'Friday'|'Monday'|'Saturday'|'Sunday'|'Thursday'|'Tuesday'|'Wednesday', + * month: 'April'|'August'|'December'|'February'|'January'|'July'|'June'|'March'|'May'|'November'|'October'|'September', + * timestamp: int, + * dts: 0|1 + * } Associative array of information related to the timestamp. + */ + public static function info (?int $timestamp = null):array { + + $get_date = ($get_date = getdate($timestamp)) + [ + 'timestamp' => $get_date[0], + 'dts' => localtime($timestamp, true)['tm_isdst'] ?? 0 + ]; + + unset($get_date[0]); + + /** @var array{ + * seconds: int<0, 59>, + * minutes: int<0, 59>, + * hours: int<0, 23>, + * mday: int<1, 31>, + * wday: int<0, 6>, + * mon: int<1, 12>, + * year: int, + * yday: int<0, 365>, + * weekday: 'Friday'|'Monday'|'Saturday'|'Sunday'|'Thursday'|'Tuesday'|'Wednesday', + * month: 'April'|'August'|'December'|'February'|'January'|'July'|'June'|'March'|'May'|'November'|'October'|'September', + * timestamp: int, + * dts: 0|1 + * } + */ + return $get_date; + + } + +} \ No newline at end of file diff --git a/src/Date/Format.php b/src/Date/Format.php new file mode 100644 index 0000000..9c23d98 --- /dev/null +++ b/src/Date/Format.php @@ -0,0 +1,93 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Date; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\FailedToFormatTimestampAsIntException; + +use function date; +use function gmdate; +use function idate; + +/** + * ### Date Formatting Utilities + * + * Provides low-level wrappers for formatting Unix timestamps into human-readable date and time representations while + * preserving native PHP formatting behavior. + */ +final class Format extends NativeRuntime { + + /** + * ### Format a Unix timestamp + * + * Returns a string formatted according to the given format string using the given integer timestamp (Unix + * timestamp) or the current time if no timestamp is given. + * + * In other words, timestamp is optional and defaults to the value of Clock::time(). + * @since 1.0.0 + * + * @link https://www.php.net/manual/en/datetime.format.php To check valid $format formats. + * + * @param string $format [optional]

+ * The format of the outputted date string. + *

+ * @param null|int $timestamp [optional]

+ * The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a + * timestamp is not given. + *

+ * @param bool $gmt [optional]

+ * Format a GMT/UTC date/time. + *

+ * + * @return string String formatted according to the given format string using the given integer timestamp. + */ + public static function string (string $format = 'Y-m-d H:i:s.u', ?int $timestamp = null, bool $gmt = false):string { + + return $gmt ? gmdate($format, $timestamp) : date($format, $timestamp); + + } + + /** + * ### Format a Unix timestamp as integer + * + * Returns a formatted number, according to the given format string using the given integer timestamp or the current + * local time if no timestamp is given + * + * In other words, timestamp is optional and defaults to the value of Clock::time(). + * @since 1.0.0 + * + * @see https://www.php.net/manual/en/function.idate.php + * + * @param 'B'|'d'|'h'|'H'|'i'|'I'|'L'|'m'|'s'|'t'|'U'|'w'|'W'|'y'|'Y'|'z'|'Z' $format

+ * Single format character. + *

+ * @param null|int $timestamp [optional]

+ * The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a + * timestamp is not given. + *

+ * + * @throws \FireHub\Runtime\Exception\FailedToFormatTimestampAsIntException If failed to format a Unix timestamp + * as integer. + * + * @return int Formatted date as an integer. + */ + public static function integer (string $format, ?int $timestamp = null):int { + + return ($i_date = idate($format, $timestamp)) !== false + ? $i_date + : throw new FailedToFormatTimestampAsIntException; + + } + +} \ No newline at end of file diff --git a/src/Date/Parse.php b/src/Date/Parse.php new file mode 100644 index 0000000..0d4ba0b --- /dev/null +++ b/src/Date/Parse.php @@ -0,0 +1,134 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Date; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + CannotParseTimestampException, ParseFromFormatException +}; +use ValueError; + +use function date_parse; +use function date_parse_from_format; +use function strtotime; + +/** + * ### Date Parsing Utilities + * + * Provides low-level wrappers for parsing date and time strings into structured date information while preserving + * native PHP behavior. + * @since 1.0.0 + */ +final class Parse extends NativeRuntime { + + /** + * ### Returns associative array with detailed info about the given date/time + * + * Method parses the given datetime string according to the same rules as Parse::stringToTimestamp(). + * @since 1.0.0 + * + * @param non-empty-string $datetime

+ * String representing the date/time. + *

+ * + * @return array Associative array with detailed info about the given date/time. + * + * @warning The number of array elements in the warning and errors arrays might be lower than warning_count or + * error_count if they occurred at the same position. + */ + public static function date (string $datetime):array { + + return date_parse($datetime); + + } + + /** + * ### Get info about the given date formatted according to the specified format + * @since 1.0.0 + * + * @param non-empty-string $format

+ * Format accepted by date with some extras. + *

+ * @param non-empty-string $datetime

+ * String representing the date/time. + *

+ * + * @throws \FireHub\Runtime\Exception\ParseFromFormatException If $datetime contains NULL-bytes. + * + * @return array{ + * year: int|false, month: int|false, day: int|false, hour: int|false, minute: int|false, second: int|false, + * fraction: float|false, warning_count: int, warnings: array, error_count: int, errors: array, + * is_localtime: bool, zone_type?: bool|int, zone?: bool|int, is_dst?: bool, tz_abbr?: string, tz_id?: string, + * relative?: array{ + * year: int, month: int, day: int, hour: int, minute: int, second: int, weekday?: int, weekdays?: int, + * first_day_of_month?: bool, last_day_of_month?: bool + * } + * } Associative array with detailed info about a given date/time. + * + * @warning The number of array elements in the warning and errors arrays might be lower than warning_count or + * error_count if they occurred at the same position- + */ + public static function dateFromFormat (string $format, string $datetime):array { + + try { + + return date_parse_from_format($format, $datetime); + + } catch (ValueError) { + + throw new ParseFromFormatException('$datetime contains NULL-bytes'); + + } + + } + + /** + * ### Parse about any English textual datetime description into a Unix timestamp + * + * The method expects to be given a string containing an English date format. It will try to parse that format + * into a Unix timestamp (the number of seconds since January 1, 1970 00:00:00 UTC), relative to the timestamp + * given in baseTimestamp, or the current time if baseTimestamp is not supplied. + * @since 1.0.0 + * + * @see https://www.php.net/manual/en/datetime.formats.php To check how to pass $datetime parameter. + * + * @param non-empty-string $datetime

+ * A date/time string. + *

+ * @param null|int $timestamp [optional]

+ * The timestamp which is used as a base for the calculation of relative dates. + *

+ * + * @throws \FireHub\Runtime\Exception\CannotParseTimestampException If we couldn't convert string + * to timestamp. + * + * @return int A timestamp. + * + * @note If the number of the year is specified in a two-digit format, the values between 00-69 are mapped to + * 2000-2069 and 70-99 to 1970-1999. + * See the notes below for possible differences on 32bit systems (possible dates might end on 2038-01-19 03:14:07). + * @note The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 + * 03:14:07 UTC (These are the dates that correspond to the minimum and maximum values for a 32-bit signed + * integer.). + * For 64-bit versions of PHP, the valid range of a timestamp is effectively infinite, as 64 bits can represent + * approximately 293 billion years in either direction. + */ + public static function timestamp (string $datetime, ?int $timestamp = null):int { + + return ($str_to_time = strtotime($datetime, $timestamp)) !== false + ? $str_to_time : throw new CannotParseTimestampException; + + } + +} \ No newline at end of file diff --git a/src/Date/Solar.php b/src/Date/Solar.php new file mode 100644 index 0000000..6acef70 --- /dev/null +++ b/src/Date/Solar.php @@ -0,0 +1,61 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Date; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function date_sun_info; + +/** + * ### Solar Calculation Utilities + * + * Provides low-level wrappers for calculating sunrise, sunset, twilight, and other solar information using native + * PHP date functions. + * @since 1.0.0 + */ +final class Solar extends NativeRuntime { + + /** + * ### Gets information about sunset/sunrise and twilight begin/end + * @since 1.0.0 + * + * @param int $timestamp

+ * Unix timestamp. + *

+ * @param float $latitude

+ * Latitude in degrees. + *

+ * @param float $longitude

+ * Longitude in degrees. + *

+ * + * @return array{ + * sunrise: int|bool, + * sunset: int|bool, + * transit: int|bool, + * civil_twilight_begin: int|bool, + * civil_twilight_end: int|bool, + * nautical_twilight_begin: int|bool, + * nautical_twilight_end: int|bool, + * astronomical_twilight_begin: int|bool, + * astronomical_twilight_end: int|bool + * } Array with sunset and twilight details. + */ + public static function info (int $timestamp, float $latitude, float $longitude):array { + + return date_sun_info($timestamp, $latitude, $longitude); + + } + +} \ No newline at end of file diff --git a/src/Date/Timestamp.php b/src/Date/Timestamp.php new file mode 100644 index 0000000..0294d45 --- /dev/null +++ b/src/Date/Timestamp.php @@ -0,0 +1,101 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Date; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\CannotCreateTimestampException; + +use function gmmktime; +use function mktime; + +/** + * ### Unix Timestamp Utilities + * + * Provides low-level wrappers for creating Unix timestamps using native PHP date and time functions while preserving + * native runtime behavior. + * @since 1.0.0 + */ +final class Timestamp extends NativeRuntime { + + /** + * ### Format a Unix timestamp + * + * Returns the Unix timestamp corresponding to the arguments given. + * + * This timestamp is a long integer containing the number of seconds between the Unix Epoch (January, 1 1970 + * 00:00:00 GMT) and the time specified. + * @since 1.0.0 + * + * @param int<0, 24> $hour

+ * The number of hours relative to the start of the day is determined by month, day, and year. + * Negative values reference the hour before midnight of the day in question. + * Values greater than 23 reference the appropriate hour on the following day(s). + *

+ * @param null|int<0, 59> $minute [optional]

+ * The number of the minutes relative to the start of the hour. + * + * Negative values reference the minute in the previous hour. + * + * Values greater than reference 59 the appropriate minute in the following hour(s). + *

+ * @param null|int<0, 59> $second [optional]

+ * The number of seconds relative to the start of the minute. + * + * Negative values reference the second in the previous minute. + * + * Values greater than 59 reference the appropriate second in the following minute(s). + *

+ * @param null|int $year [optional]

+ * The year. + *

+ * @param null|int<0, 12> $month [optional]

+ * The number of the month relative to the end of the previous year. + * + * Values 1 to 12 reference the normal calendar months of the year in question. + * + * Values less than 1 (including negative values) reference the months in the previous year in reverse order, so + * 0 is December, -1 is November, and so on. + * + * Values greater than 12 reference the appropriate month in the following year(s). + *

+ * @param null|int<0, 31> $day [optional]

+ * The number of the days relative to the end of the previous month. + * + * Values 1 to 28, 29, 30, or 31 (depending upon the month) reference the normal days in the relevant month. + * + * Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day + * of the previous month, -1 is the day before that, and so on. + * + * Values greater than the number of days in the relevant month reference the appropriate day in the following + * month(s). + *

+ * @param bool $gmt [optional]

+ * Get a GMT/UTC timestamp. + *

+ * + * @throws \FireHub\Runtime\Exception\CannotCreateTimestampException If the timestamp doesn't fit in a PHP integer. + * + * @return int The Unix timestamp of the arguments given. + */ + public static function create (int $hour, ?int $minute = null, ?int $second = null, ?int $year = null, ?int $month = null, ?int $day = null, bool $gmt = false):int { + + return ( + $timestamp = $gmt + ? gmmktime($hour, $minute, $second, $month, $day, $year) + : mktime($hour, $minute, $second, $month, $day, $year) + ) !== false ? $timestamp : throw new CannotCreateTimestampException; + + } + +} \ No newline at end of file diff --git a/src/Date/Timezone.php b/src/Date/Timezone.php new file mode 100644 index 0000000..2b9862c --- /dev/null +++ b/src/Date/Timezone.php @@ -0,0 +1,96 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Date; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Date\Zone; +use FireHub\Runtime\Exception\ { + FailedToGetTimezoneException, FailedToSetTimezoneException +}; + +use function date_default_timezone_get; +use function date_default_timezone_set; +use function timezone_abbreviations_list; + +/** + * ### Time Zone Utilities + * + * Provides low-level wrappers for retrieving, configuring, and inspecting PHP time zone settings while preserving + * native runtime behavior. + * @since 1.0.0 + */ +final class Timezone extends NativeRuntime { + + /** + * ### Gets the default timezone used by all date/time functions in a script + * + * In order of preference, this function returns the default timezone by: + * - Reading the timezone set using the setDefaultTimezone() method (if any). + * - Reading the value of the 'date.timezone' ini option (if set). + * + * If none of the above succeeds, DateAndTimeZone::getDefaultTimezone() will return a default timezone of UTC. + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\FailedToGetTimezoneException If we can't get the default timezone. + * + * @return \FireHub\Core\Type\Date\Zone Timezone enum. + */ + public static function getDefault ():Zone { + + return Zone::tryFrom(date_default_timezone_get()) + ?? throw new FailedToGetTimezoneException; + + } + + /** + * ### Sets the default timezone used by all date/time functions in a script + * + * Method sets the default timezone used by all date/time functions. + * + * Instead of using this function to set the default timezone in your script, you can also use the INI setting + * 'date.timezone' to set the default timezone. + * @since 1.0.0 + * + * @param \FireHub\Core\Type\Date\Zone $zone

+ * The timezone identifier. + *

+ * + * @throws \FireHub\Runtime\Exception\FailedToSetTimezoneException If failed to set the default timezone. + * + * @return true Always true. + */ + public static function setDefault (Zone $zone):true { + + return date_default_timezone_set($zone->value) + ?: throw new FailedToSetTimezoneException; + + } + + /** + * ### Get an associative array containing dst, offset, and the timezone name alias + * @since 1.0.0 + * + * @return array> List of timezone abbreviations. + */ + public static function abbreviationList ():array { + + return timezone_abbreviations_list(); + + } + +} \ No newline at end of file diff --git a/src/Exception/ArrayKeysAndValuesCountMismatchException.php b/src/Exception/ArrayKeysAndValuesCountMismatchException.php new file mode 100644 index 0000000..e757788 --- /dev/null +++ b/src/Exception/ArrayKeysAndValuesCountMismatchException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a mismatch between array keys and values count + * @since 1.0.0 + */ +final class ArrayKeysAndValuesCountMismatchException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The number of keys and values in the provided arrays must match.'; + +} \ No newline at end of file diff --git a/src/Exception/ArrayToStringConversionException.php b/src/Exception/ArrayToStringConversionException.php new file mode 100644 index 0000000..8873017 --- /dev/null +++ b/src/Exception/ArrayToStringConversionException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an array conversion to a string + * @since 1.0.0 + */ +final class ArrayToStringConversionException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided array cannot be converted to a string.'; + +} \ No newline at end of file diff --git a/src/Exception/CannotCreateTimestampException.php b/src/Exception/CannotCreateTimestampException.php new file mode 100644 index 0000000..a0c1374 --- /dev/null +++ b/src/Exception/CannotCreateTimestampException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a failed timestamp creation + * @since 1.0.0 + */ +final class CannotCreateTimestampException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided timestamp cannot be created.'; + +} \ No newline at end of file diff --git a/src/Exception/CannotDefineConstantException.php b/src/Exception/CannotDefineConstantException.php new file mode 100644 index 0000000..01a2675 --- /dev/null +++ b/src/Exception/CannotDefineConstantException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid constant provided to an operation that requires a valid constant + * @since 1.0.0 + */ +final class CannotDefineConstantException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided constant cannot be defined.'; + +} \ No newline at end of file diff --git a/src/Exception/CannotListFolderException.php b/src/Exception/CannotListFolderException.php new file mode 100644 index 0000000..8f6b983 --- /dev/null +++ b/src/Exception/CannotListFolderException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a folder cannot be listed + * @since 1.0.0 + */ +final class CannotListFolderException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided folder cannot be listed.'; + +} \ No newline at end of file diff --git a/src/Exception/CannotParseTimestampException.php b/src/Exception/CannotParseTimestampException.php new file mode 100644 index 0000000..50e88d7 --- /dev/null +++ b/src/Exception/CannotParseTimestampException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a failed timestamp parsing + * @since 1.0.0 + */ +final class CannotParseTimestampException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided timestamp cannot be parsed.'; + +} \ No newline at end of file diff --git a/src/Exception/CannotSerializeException.php b/src/Exception/CannotSerializeException.php new file mode 100644 index 0000000..a5aa239 --- /dev/null +++ b/src/Exception/CannotSerializeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a value that cannot be serialized + * @since 1.0.0 + */ +final class CannotSerializeException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided value cannot be serialized.'; + +} \ No newline at end of file diff --git a/src/Exception/CannotUnserializeException.php b/src/Exception/CannotUnserializeException.php new file mode 100644 index 0000000..0fcb69a --- /dev/null +++ b/src/Exception/CannotUnserializeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a value that cannot be unserialized + * @since 1.0.0 + */ +final class CannotUnserializeException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided value cannot be unserialized.'; + +} \ No newline at end of file diff --git a/src/Exception/ChangeSymlinkGroupException.php b/src/Exception/ChangeSymlinkGroupException.php new file mode 100644 index 0000000..1aeada7 --- /dev/null +++ b/src/Exception/ChangeSymlinkGroupException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid symlink group provided to an operation that requires a valid symlink group + * @since 1.0.0 + */ +final class ChangeSymlinkGroupException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided symlink group cannot be changed.'; + +} \ No newline at end of file diff --git a/src/Exception/ChangeSymlinkOwnerException.php b/src/Exception/ChangeSymlinkOwnerException.php new file mode 100644 index 0000000..8ab65aa --- /dev/null +++ b/src/Exception/ChangeSymlinkOwnerException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid symlink owner provided to an operation that requires a valid symlink owner + * @since 1.0.0 + */ +final class ChangeSymlinkOwnerException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided symlink group cannot be changed.'; + +} \ No newline at end of file diff --git a/src/Exception/ClassAliasException.php b/src/Exception/ClassAliasException.php new file mode 100644 index 0000000..57aebb2 --- /dev/null +++ b/src/Exception/ClassAliasException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid class alias provided to an operation that requires a valid class alias + * @since 1.0.0 + */ +final class ClassAliasException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided class alias is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/ClassDoesntExistException.php b/src/Exception/ClassDoesntExistException.php new file mode 100644 index 0000000..708a5bc --- /dev/null +++ b/src/Exception/ClassDoesntExistException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a non-existent class provided to an operation that requires a valid class + * @since 1.0.0 + */ +final class ClassDoesntExistException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided class does not exist.'; + +} \ No newline at end of file diff --git a/src/Exception/ConfigurationOptionNotFoundException.php b/src/Exception/ConfigurationOptionNotFoundException.php new file mode 100644 index 0000000..377da17 --- /dev/null +++ b/src/Exception/ConfigurationOptionNotFoundException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a missing configuration option + * @since 1.0.0 + */ +final class ConfigurationOptionNotFoundException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided configuration option does not exist.'; + +} \ No newline at end of file diff --git a/src/Exception/ConfigurationRetrievalException.php b/src/Exception/ConfigurationRetrievalException.php new file mode 100644 index 0000000..bf7cee2 --- /dev/null +++ b/src/Exception/ConfigurationRetrievalException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed configuration retrieval + * @since 1.0.0 + */ +final class ConfigurationRetrievalException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The configuration could not be retrieved.'; + +} \ No newline at end of file diff --git a/src/Exception/ConstantAlreadyDefinedException.php b/src/Exception/ConstantAlreadyDefinedException.php new file mode 100644 index 0000000..a050fe1 --- /dev/null +++ b/src/Exception/ConstantAlreadyDefinedException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an attempt to redefine an already defined constant + * @since 1.0.0 + */ +final class ConstantAlreadyDefinedException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided constant is already defined.'; + +} \ No newline at end of file diff --git a/src/Exception/CopyFileException.php b/src/Exception/CopyFileException.php new file mode 100644 index 0000000..8393cf6 --- /dev/null +++ b/src/Exception/CopyFileException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed file copy operation + * @since 1.0.0 + */ +final class CopyFileException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file cannot be copied.'; + +} \ No newline at end of file diff --git a/src/Exception/CreateFolderException.php b/src/Exception/CreateFolderException.php new file mode 100644 index 0000000..0f4b051 --- /dev/null +++ b/src/Exception/CreateFolderException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a folder could not be created + * @since 1.0.0 + */ +final class CreateFolderException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided folder cannot be created.'; + +} \ No newline at end of file diff --git a/src/Exception/CreateLinkException.php b/src/Exception/CreateLinkException.php new file mode 100644 index 0000000..6a7b929 --- /dev/null +++ b/src/Exception/CreateLinkException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a link could not be created + * @since 1.0.0 + */ +final class CreateLinkException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided link could not be created.'; + +} \ No newline at end of file diff --git a/src/Exception/CreateSymbolicException.php b/src/Exception/CreateSymbolicException.php new file mode 100644 index 0000000..baa9df4 --- /dev/null +++ b/src/Exception/CreateSymbolicException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a symbolic could not be created + * @since 1.0.0 + */ +final class CreateSymbolicException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided symbolic could not be created.'; + +} \ No newline at end of file diff --git a/src/Exception/DeleteFileException.php b/src/Exception/DeleteFileException.php new file mode 100644 index 0000000..028a007 --- /dev/null +++ b/src/Exception/DeleteFileException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed file delete operation + * @since 1.0.0 + */ +final class DeleteFileException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file cannot be deleled.'; + +} \ No newline at end of file diff --git a/src/Exception/DeleteFolderException.php b/src/Exception/DeleteFolderException.php new file mode 100644 index 0000000..cbdb428 --- /dev/null +++ b/src/Exception/DeleteFolderException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a folder could not be deleted + * @since 1.0.0 + */ +final class DeleteFolderException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided folder could not be deleted.'; + +} \ No newline at end of file diff --git a/src/Exception/DiskSpaceException.php b/src/Exception/DiskSpaceException.php new file mode 100644 index 0000000..8fadfa1 --- /dev/null +++ b/src/Exception/DiskSpaceException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid disk space provided to an operation that requires a valid disk space + * @since 1.0.0 + */ +final class DiskSpaceException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'Disk space for path is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/EmptyArrayException.php b/src/Exception/EmptyArrayException.php new file mode 100644 index 0000000..2048f22 --- /dev/null +++ b/src/Exception/EmptyArrayException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an empty array provided to an operation that requires at least one element + * @since 1.0.0 + */ +final class EmptyArrayException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided array must not be empty.'; + +} \ No newline at end of file diff --git a/src/Exception/EmptyPadException.php b/src/Exception/EmptyPadException.php new file mode 100644 index 0000000..20005b8 --- /dev/null +++ b/src/Exception/EmptyPadException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an empty pad provided to an operation that requires a non-empty pad + * @since 1.0.0 + */ +final class EmptyPadException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided pad must not be empty.'; + +} \ No newline at end of file diff --git a/src/Exception/EmptyPathException.php b/src/Exception/EmptyPathException.php new file mode 100644 index 0000000..c71cdfd --- /dev/null +++ b/src/Exception/EmptyPathException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an empty path provided to an operation that requires a valid path + * @since 1.0.0 + */ +final class EmptyPathException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path is empty.'; + +} \ No newline at end of file diff --git a/src/Exception/EmptySeparatorException.php b/src/Exception/EmptySeparatorException.php new file mode 100644 index 0000000..4b14ca7 --- /dev/null +++ b/src/Exception/EmptySeparatorException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an empty separator provided to an operation that requires a non-empty separator + * @since 1.0.0 + */ +final class EmptySeparatorException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided separator must not be empty.'; + +} \ No newline at end of file diff --git a/src/Exception/EncodingConversionFailedException.php b/src/Exception/EncodingConversionFailedException.php new file mode 100644 index 0000000..e82945b --- /dev/null +++ b/src/Exception/EncodingConversionFailedException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an encoding conversion failure + * @since 1.0.0 + */ +final class EncodingConversionFailedException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided encoding conversion failed.'; + +} \ No newline at end of file diff --git a/src/Exception/ExtensionNotFoundException.php b/src/Exception/ExtensionNotFoundException.php new file mode 100644 index 0000000..eb496df --- /dev/null +++ b/src/Exception/ExtensionNotFoundException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an extension not being installed + * @since 1.0.0 + */ +final class ExtensionNotFoundException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided extension is not installed.'; + +} \ No newline at end of file diff --git a/src/Exception/FailedToConvertTypeException.php b/src/Exception/FailedToConvertTypeException.php new file mode 100644 index 0000000..872fbf6 --- /dev/null +++ b/src/Exception/FailedToConvertTypeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a failed type conversion + * @since 1.0.0 + */ +final class FailedToConvertTypeException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'Failed to convert the provided value to the expected type.'; + +} \ No newline at end of file diff --git a/src/Exception/FailedToFormatTimestampAsIntException.php b/src/Exception/FailedToFormatTimestampAsIntException.php new file mode 100644 index 0000000..3a52f29 --- /dev/null +++ b/src/Exception/FailedToFormatTimestampAsIntException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a failed timestamp conversion to an integer + * @since 1.0.0 + */ +final class FailedToFormatTimestampAsIntException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'Failed to format the provided timestamp as an integer.'; + +} \ No newline at end of file diff --git a/src/Exception/FailedToGetTimezoneException.php b/src/Exception/FailedToGetTimezoneException.php new file mode 100644 index 0000000..87ee355 --- /dev/null +++ b/src/Exception/FailedToGetTimezoneException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by failed timezone retrieval + * @since 1.0.0 + */ +final class FailedToGetTimezoneException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided timezone cannot be retrieved.'; + +} \ No newline at end of file diff --git a/src/Exception/FailedToSetConfigurationOptionException.php b/src/Exception/FailedToSetConfigurationOptionException.php new file mode 100644 index 0000000..795e76d --- /dev/null +++ b/src/Exception/FailedToSetConfigurationOptionException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed configuration option setting + * @since 1.0.0 + */ +final class FailedToSetConfigurationOptionException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided configuration option cannot be set.'; + +} \ No newline at end of file diff --git a/src/Exception/FailedToSetTimezoneException.php b/src/Exception/FailedToSetTimezoneException.php new file mode 100644 index 0000000..28c58d2 --- /dev/null +++ b/src/Exception/FailedToSetTimezoneException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a failed timezone setting + * @since 1.0.0 + */ +final class FailedToSetTimezoneException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided timezone cannot be set.'; + +} \ No newline at end of file diff --git a/src/Exception/FileNotFoundException.php b/src/Exception/FileNotFoundException.php new file mode 100644 index 0000000..e763522 --- /dev/null +++ b/src/Exception/FileNotFoundException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a non-existent file provided to an operation that requires a valid file + * @since 1.0.0 + */ +final class FileNotFoundException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file does not exist.'; + +} \ No newline at end of file diff --git a/src/Exception/FileReadException.php b/src/Exception/FileReadException.php new file mode 100644 index 0000000..9afcd4f --- /dev/null +++ b/src/Exception/FileReadException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed file read operation + * @since 1.0.0 + */ +final class FileReadException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file cannot be read.'; + +} \ No newline at end of file diff --git a/src/Exception/FileWriteException.php b/src/Exception/FileWriteException.php new file mode 100644 index 0000000..c980e9f --- /dev/null +++ b/src/Exception/FileWriteException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed file write operation + * @since 1.0.0 + */ +final class FileWriteException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file cannot be written.'; + +} \ No newline at end of file diff --git a/src/Exception/GetSymbolicException.php b/src/Exception/GetSymbolicException.php new file mode 100644 index 0000000..0b443d3 --- /dev/null +++ b/src/Exception/GetSymbolicException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a symbolic could not be retrieved + * @since 1.0.0 + */ +final class GetSymbolicException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided symbolic cannot be retrieved.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidArrayLengthException.php b/src/Exception/InvalidArrayLengthException.php new file mode 100644 index 0000000..ef377e2 --- /dev/null +++ b/src/Exception/InvalidArrayLengthException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid array length + * @since 1.0.0 + */ +final class InvalidArrayLengthException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided array length is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidCharacterCodepointException.php b/src/Exception/InvalidCharacterCodepointException.php new file mode 100644 index 0000000..58cac59 --- /dev/null +++ b/src/Exception/InvalidCharacterCodepointException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid character codepoint + * @since 1.0.0 + */ +final class InvalidCharacterCodepointException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided character codepoint is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidChunkLengthException.php b/src/Exception/InvalidChunkLengthException.php new file mode 100644 index 0000000..389f4fa --- /dev/null +++ b/src/Exception/InvalidChunkLengthException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid chunk length + * @since 1.0.0 + */ +final class InvalidChunkLengthException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided chunk length is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidConfigurationQuantityException.php b/src/Exception/InvalidConfigurationQuantityException.php new file mode 100644 index 0000000..e9ab169 --- /dev/null +++ b/src/Exception/InvalidConfigurationQuantityException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by an invalid configuration quantity + * @since 1.0.0 + */ +final class InvalidConfigurationQuantityException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided configuration quantity is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidEncodingException.php b/src/Exception/InvalidEncodingException.php new file mode 100644 index 0000000..736d06d --- /dev/null +++ b/src/Exception/InvalidEncodingException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid encoding provided to an operation that requires a valid encoding + * @since 1.0.0 + */ +final class InvalidEncodingException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided encoding is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidNumberBaseException.php b/src/Exception/InvalidNumberBaseException.php new file mode 100644 index 0000000..f32d2f6 --- /dev/null +++ b/src/Exception/InvalidNumberBaseException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an invalid number base provided to an operation that requires a valid number base + * @since 1.0.0 + */ +final class InvalidNumberBaseException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided number base is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidPathParentLevelException.php b/src/Exception/InvalidPathParentLevelException.php new file mode 100644 index 0000000..4827d77 --- /dev/null +++ b/src/Exception/InvalidPathParentLevelException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid parent level provided to an operation that requires a valid parent level + * @since 1.0.0 + */ +final class InvalidPathParentLevelException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided parent level is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidPatternException.php b/src/Exception/InvalidPatternException.php new file mode 100644 index 0000000..f5db9a1 --- /dev/null +++ b/src/Exception/InvalidPatternException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid pattern provided to an operation that requires a valid pattern + * @since 1.0.0 + */ +final class InvalidPatternException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided pattern is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidRandomKeyCountException.php b/src/Exception/InvalidRandomKeyCountException.php new file mode 100644 index 0000000..5a14008 --- /dev/null +++ b/src/Exception/InvalidRandomKeyCountException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid number of requested random array keys + * @since 1.0.0 + */ +final class InvalidRandomKeyCountException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided value is outside the valid range.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidRangeStepException.php b/src/Exception/InvalidRangeStepException.php new file mode 100644 index 0000000..8031822 --- /dev/null +++ b/src/Exception/InvalidRangeStepException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid range step + * @since 1.0.0 + */ +final class InvalidRangeStepException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided range step is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/InvalidSleepDurationException.php b/src/Exception/InvalidSleepDurationException.php new file mode 100644 index 0000000..0beb8d2 --- /dev/null +++ b/src/Exception/InvalidSleepDurationException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid sleep duration provided to an operation that requires a valid sleep duration + * @since 1.0.0 + */ +final class InvalidSleepDurationException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided sleep duration is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/JsonDecodeException.php b/src/Exception/JsonDecodeException.php new file mode 100644 index 0000000..a750153 --- /dev/null +++ b/src/Exception/JsonDecodeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed JSON decoding + * @since 1.0.0 + */ +final class JsonDecodeException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided JSON string cannot be decoded.'; + +} \ No newline at end of file diff --git a/src/Exception/JsonEncodeException.php b/src/Exception/JsonEncodeException.php new file mode 100644 index 0000000..db3393c --- /dev/null +++ b/src/Exception/JsonEncodeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed JSON encoding + * @since 1.0.0 + */ +final class JsonEncodeException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided value cannot be encoded to JSON.'; + +} \ No newline at end of file diff --git a/src/Exception/LinkInfoException.php b/src/Exception/LinkInfoException.php new file mode 100644 index 0000000..05d904b --- /dev/null +++ b/src/Exception/LinkInfoException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by invalid link info provided to an operation that requires valid link info + * @since 1.0.0 + */ +final class LinkInfoException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided link info is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/MatchInFolderException.php b/src/Exception/MatchInFolderException.php new file mode 100644 index 0000000..445b32f --- /dev/null +++ b/src/Exception/MatchInFolderException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a path that matches a folder + * @since 1.0.0 + */ +final class MatchInFolderException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path matches a folder.'; + +} \ No newline at end of file diff --git a/src/Exception/ParseFromFormatException.php b/src/Exception/ParseFromFormatException.php new file mode 100644 index 0000000..0de64fa --- /dev/null +++ b/src/Exception/ParseFromFormatException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by an invalid format provided to an operation that requires a valid format + * @since 1.0.0 + */ +final class ParseFromFormatException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided format is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/PathGroupException.php b/src/Exception/PathGroupException.php new file mode 100644 index 0000000..ccede9f --- /dev/null +++ b/src/Exception/PathGroupException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path group provided to an operation that requires a valid file group + * @since 1.0.0 + */ +final class PathGroupException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path group is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/PathInodeException.php b/src/Exception/PathInodeException.php new file mode 100644 index 0000000..e133c5e --- /dev/null +++ b/src/Exception/PathInodeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path inode provided to an operation that requires a valid file inode + * @since 1.0.0 + */ +final class PathInodeException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path inode is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/PathOwnerException.php b/src/Exception/PathOwnerException.php new file mode 100644 index 0000000..d706de6 --- /dev/null +++ b/src/Exception/PathOwnerException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path owner provided to an operation that requires a valid file owner + * @since 1.0.0 + */ +final class PathOwnerException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path is not owned by the current user.'; + +} \ No newline at end of file diff --git a/src/Exception/PathPermissionsException.php b/src/Exception/PathPermissionsException.php new file mode 100644 index 0000000..360b6a7 --- /dev/null +++ b/src/Exception/PathPermissionsException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path permission provided to an operation that requires a valid file permission + * @since 1.0.0 + */ +final class PathPermissionsException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path permissions are invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/PathResolutionException.php b/src/Exception/PathResolutionException.php new file mode 100644 index 0000000..7d3699d --- /dev/null +++ b/src/Exception/PathResolutionException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed path resolution + * @since 1.0.0 + */ +final class PathResolutionException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path cannot be resolved.'; + +} \ No newline at end of file diff --git a/src/Exception/PathSizeException.php b/src/Exception/PathSizeException.php new file mode 100644 index 0000000..28b63ab --- /dev/null +++ b/src/Exception/PathSizeException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path size provided to an operation that requires a valid file size + * @since 1.0.0 + */ +final class PathSizeException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path size is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/PathStatisticsException.php b/src/Exception/PathStatisticsException.php new file mode 100644 index 0000000..5a9fc68 --- /dev/null +++ b/src/Exception/PathStatisticsException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path statistics provided to an operation that requires a valid file statistics + * @since 1.0.0 + */ +final class PathStatisticsException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path statistics are invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/PathTimestampException.php b/src/Exception/PathTimestampException.php new file mode 100644 index 0000000..c53b54a --- /dev/null +++ b/src/Exception/PathTimestampException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by an invalid path timestamp provided to an operation that requires a valid file timestamp + * @since 1.0.0 + */ +final class PathTimestampException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided path timestamp is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/ProcessIdUnavailableException.php b/src/Exception/ProcessIdUnavailableException.php new file mode 100644 index 0000000..b800b4b --- /dev/null +++ b/src/Exception/ProcessIdUnavailableException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by an unavailable process ID + * @since 1.0.0 + */ +final class ProcessIdUnavailableException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The process ID is unavailable.'; + +} \ No newline at end of file diff --git a/src/Exception/RandomByteLengthTooSmallException.php b/src/Exception/RandomByteLengthTooSmallException.php new file mode 100644 index 0000000..c7b668e --- /dev/null +++ b/src/Exception/RandomByteLengthTooSmallException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a random byte length being too small + * @since 1.0.0 + */ +final class RandomByteLengthTooSmallException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided random byte length is too small.'; + +} \ No newline at end of file diff --git a/src/Exception/RandomMaximumBelowMinimumException.php b/src/Exception/RandomMaximumBelowMinimumException.php new file mode 100644 index 0000000..e24d4dd --- /dev/null +++ b/src/Exception/RandomMaximumBelowMinimumException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a random maximum being below the minimum value + * @since 1.0.0 + */ +final class RandomMaximumBelowMinimumException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided random maximum is below the minimum value.'; + +} \ No newline at end of file diff --git a/src/Exception/RandomNumberAboveGeneratorMaximumException.php b/src/Exception/RandomNumberAboveGeneratorMaximumException.php new file mode 100644 index 0000000..cf3817a --- /dev/null +++ b/src/Exception/RandomNumberAboveGeneratorMaximumException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a random number being above the maximum value + * @since 1.0.0 + */ +final class RandomNumberAboveGeneratorMaximumException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided random number is above the maximum value.'; + +} \ No newline at end of file diff --git a/src/Exception/RandomNumberBelowMinimumException.php b/src/Exception/RandomNumberBelowMinimumException.php new file mode 100644 index 0000000..c57da3f --- /dev/null +++ b/src/Exception/RandomNumberBelowMinimumException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a random number being below the minimum value + * @since 1.0.0 + */ +final class RandomNumberBelowMinimumException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided random number is below the minimum value.'; + +} \ No newline at end of file diff --git a/src/Exception/ReadFileException.php b/src/Exception/ReadFileException.php new file mode 100644 index 0000000..02c23b5 --- /dev/null +++ b/src/Exception/ReadFileException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed file read operation + * @since 1.0.0 + */ +final class ReadFileException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file cannot be read.'; + +} \ No newline at end of file diff --git a/src/Exception/RegisterAutoloadFailedException.php b/src/Exception/RegisterAutoloadFailedException.php new file mode 100644 index 0000000..eec82ef --- /dev/null +++ b/src/Exception/RegisterAutoloadFailedException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed autoloader registration + * @since 1.0.0 + */ +final class RegisterAutoloadFailedException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided autoloader cannot be registered.'; + +} \ No newline at end of file diff --git a/src/Exception/RegisterTickFailedException.php b/src/Exception/RegisterTickFailedException.php new file mode 100644 index 0000000..0fb34c6 --- /dev/null +++ b/src/Exception/RegisterTickFailedException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed tick registration + * @since 1.0.0 + */ +final class RegisterTickFailedException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided tick cannot be registered.'; + +} \ No newline at end of file diff --git a/src/Exception/RenameFileException.php b/src/Exception/RenameFileException.php new file mode 100644 index 0000000..2c573a9 --- /dev/null +++ b/src/Exception/RenameFileException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed file rename operation + * @since 1.0.0 + */ +final class RenameFileException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided file cannot be renamed.'; + +} \ No newline at end of file diff --git a/src/Exception/ResourceTypeConversionException.php b/src/Exception/ResourceTypeConversionException.php new file mode 100644 index 0000000..1970702 --- /dev/null +++ b/src/Exception/ResourceTypeConversionException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by a resource type conversion + * @since 1.0.0 + */ +final class ResourceTypeConversionException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided resource type conversion failed.'; + +} \ No newline at end of file diff --git a/src/Exception/SapiUnavailableException.php b/src/Exception/SapiUnavailableException.php new file mode 100644 index 0000000..af73d75 --- /dev/null +++ b/src/Exception/SapiUnavailableException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents a failure caused by the SAPI being unavailable + * @since 1.0.0 + */ +final class SapiUnavailableException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The SAPI is unavailable.'; + +} \ No newline at end of file diff --git a/src/Exception/SecureNumberException.php b/src/Exception/SecureNumberException.php new file mode 100644 index 0000000..0e0b8c9 --- /dev/null +++ b/src/Exception/SecureNumberException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by an invalid secure number + * @since 1.0.0 + */ +final class SecureNumberException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided secure number is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/SecureRandomBytesException.php b/src/Exception/SecureRandomBytesException.php new file mode 100644 index 0000000..3c911d4 --- /dev/null +++ b/src/Exception/SecureRandomBytesException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed secure random bytes generation + * @since 1.0.0 + */ +final class SecureRandomBytesException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided secure random bytes cannot be generated.'; + +} \ No newline at end of file diff --git a/src/Exception/StringSplitLengthException.php b/src/Exception/StringSplitLengthException.php new file mode 100644 index 0000000..e977c32 --- /dev/null +++ b/src/Exception/StringSplitLengthException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an invalid string split length + * @since 1.0.0 + */ +final class StringSplitLengthException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided string split length is invalid.'; + +} \ No newline at end of file diff --git a/src/Exception/UndefinedConstantException.php b/src/Exception/UndefinedConstantException.php new file mode 100644 index 0000000..1ac405b --- /dev/null +++ b/src/Exception/UndefinedConstantException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\InvalidArgumentException; + +/** + * ### Represents an undefined constant provided to an operation that requires a valid constant + * @since 1.0.0 + */ +final class UndefinedConstantException extends InvalidArgumentException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided constant is undefined.'; + +} \ No newline at end of file diff --git a/src/Exception/UnregisterAutoloadFailedException.php b/src/Exception/UnregisterAutoloadFailedException.php new file mode 100644 index 0000000..aa55966 --- /dev/null +++ b/src/Exception/UnregisterAutoloadFailedException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\SystemException; + +/** + * ### Represents a failure caused by a failed autoloader unregistration + * @since 1.0.0 + */ +final class UnregisterAutoloadFailedException extends SystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The provided autoloader cannot be unregistered.'; + +} \ No newline at end of file diff --git a/src/Exception/UploadedFileMoveException.php b/src/Exception/UploadedFileMoveException.php new file mode 100644 index 0000000..bfe1d7d --- /dev/null +++ b/src/Exception/UploadedFileMoveException.php @@ -0,0 +1,31 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.3 + * @package Runtime + */ + +namespace FireHub\Runtime\Exception; + +use FireHub\Core\Exception\Runtime\FileSystemException; + +/** + * ### Represents a failure caused by a failed uploaded file move operation + * @since 1.0.0 + */ +final class UploadedFileMoveException extends FileSystemException { + + /** + * @inheritDoc + * + * @since 1.0.0 + */ + protected const string DEFAULT_MESSAGE = 'The uploaded file cannot be moved.'; + +} \ No newline at end of file diff --git a/src/FileSystem/File.php b/src/FileSystem/File.php new file mode 100644 index 0000000..0c8371d --- /dev/null +++ b/src/FileSystem/File.php @@ -0,0 +1,393 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + CopyFileException, DeleteFileException, EmptyPathException, FileNotFoundException, FileWriteException, + ReadFileException, RenameFileException, UploadedFileMoveException +}; + +use const FILE_APPEND; +use const FILE_IGNORE_NEW_LINES; +use const FILE_SKIP_EMPTY_LINES; +use const LOCK_EX; + +use function copy; +use function file; +use function file_exists; +use function file_get_contents; +use function file_put_contents; +use function is_file; +use function is_uploaded_file; +use function move_uploaded_file; +use function readfile; +use function rename; +use function unlink; + +/** + * ### PHP Runtime File Utilities + * + * Provides low-level wrappers for creating, reading, writing, copying, moving, and removing files while preserving + * native PHP file system behavior. + * + * This component exposes PHP file manipulation capabilities through a consistent FireHub Runtime API without + * altering native runtime semantics. + * @since 1.0.0 + */ +final class File extends NativeRuntime { + + /** + * ### Checks whether a file or folder exists + * @since 1.0.0 + * + * @param string $path

+ * Path to the file or folder. + *

+ * + * @return bool True if the file or directory specified by filename exists, false otherwise. + * + * @note Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions + * may return unexpected results for files which are larger than 2GB. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + * @tip On Windows, use //computer_name/share/filename or \\computer_name\share\filename to check files on network + * shares. + */ + public static function exist (string $path):bool { + + return file_exists($path); + + } + + /** + * ### Tells whether the path is a regular file + * @since 1.0.0 + * + * @param string $path

+ * Path to the file. + *

+ * + * @return bool True if the filename exists and is a regular file, false otherwise. + * + * @note Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions + * may return unexpected results for files which are larger than 2GB. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + */ + public static function isFile (string $path):bool { + + return is_file($path); + + } + + /** + * ### Tells whether the file was uploaded via HTTP POST + * + * Returns true if the file named by filename was uploaded via HTTP POST. + * + * This is useful to help ensure that a malicious user hasn't tried to trick the script into working on files + * upon which it shouldn't be working. + * + * This sort of check is especially important if there is any chance that anything done with uploaded files could + * reveal their contents to the user, or even to other users on the same system. + * + * For proper working, the function File#isUploaded() needs an argument like $_FILES['userfile']['tmp_name'], + * – the name of the uploaded file on the client's machine $_FILES['userfile']['name'] doesn't work. + * @since 1.0.0 + * + * @param string $path

+ * Path to the file. + *

+ * + * @return bool True on success or false on failure. + */ + public static function isUploaded (string $path):bool { + + return is_uploaded_file($path); + + } + + /** + * ### Copies file + * + * Makes a copy of the file $path to $to. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the file. + *

+ * @param non-empty-string $to

+ * The destination path. + * + * If dest is a URL, the copy operation may fail if the wrapper doesn't support overwriting of existing files. + *

+ * + * @throws \FireHub\Runtime\Exception\CopyFileException If failed to copy a file. + * + * @return true True on success. + * + * @warning If the destination file already exists, it will be overwritten. + */ + public static function copy (string $path, string $to):true { + + return copy($path, $to) + ?: throw new CopyFileException; + + } + + /** + * ### Renames a file or directory + * + * Attempts to rename $path to $to, moving it between directories if necessary. + * + * If renaming a file and $to exists, it will be overwritten. + * + * If renaming a directory and $to exists, this function will emit a warning. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * The old name path. + *

+ * @param non-empty-string $to

+ * The new name. + *

+ * + * @throws \FireHub\Runtime\Exception\RenameFileException If failed to rename a file. + * + * @return true True on success. + * + * @note On Windows, if $new_name already exists, it must be writable, otherwise File::rename() fails and issues + * E_WARNING. + */ + public static function rename (string $path, string $to):true { + + return rename($path, $to) + ?: throw new RenameFileException; + + } + + /** + * ### Deletes a file + * + * Attempts to remove the folder named by $path. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the file. + *

+ * + * @throws \FireHub\Runtime\Exception\DeleteFileException If we couldn't delete the file. + * + * @return true True on success. + */ + public static function delete (string $path):true { + + return unlink($path) + ?: throw new DeleteFileException; + + } + + /** + * ### Moves an uploaded file to a new location + * + * This function checks to ensure that the file designated by $from is a valid upload file (meaning that it was + * uploaded via PHP's HTTP POST upload mechanism). + * + * If the file is valid, it will be moved to the filename given by $to. + * @since 1.0.0 + * + * @param non-empty-string $from

+ * Filename of the uploaded file. + *

+ * @param non-empty-string $to

+ * Destination of the moved file. + *

+ * + * @throws \FireHub\Runtime\Exception\UploadedFileMoveException If we couldn't move the uploaded file. + * + * @return true True on success. + * + * @warning If the destination file already exists, it will be overwritten. + * @note File::moveUploaded() is open_basedir aware. + * However, restrictions are placed only on the path as to allow moving of uploaded files in which from may + * conflict with such restrictions. + * File::moveUploaded() ensures the safety of this operation by allowing only those files uploaded through PHP + * to be moved. + */ + public static function moveUploaded (string $from, string $to):true { + + return move_uploaded_file($from, $to) + ?: throw new UploadedFileMoveException; + + } + + /** + * ### Outputs a file + * + * Reads a file and writes it to the output buffer. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * The filename path being read. + *

+ * + * @throws \FireHub\Runtime\Exception\ReadFileException If we couldn't put a read file on a path, or a path is + * empty. + * @throws \FireHub\Runtime\Exception\EmptyPathException If the path is empty. + * + * @return non-negative-int The number of bytes read from the file. + * + * @note File::read() will not present any memory issues, even when sending large files, on its own. + * If you encounter an out-of-memory error, ensures that output buffering is off with ob_get_level(). + */ + public static function read (string $path):int { + + if ($path === '') throw new EmptyPathException; + + return ($bytes = readfile($path)) !== false + ? $bytes + : throw new ReadFileException; + + } + + /** + * ### Reads the entire file into a string + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path of the file to read. + *

+ * @param int $offset [optional]

+ * The offset where the reading starts on the original stream. + * + * Negative offsets count from the end of the stream. + * + * Seeking ($offset) is not supported with remote files. + * + * Attempting to seek on non-local files may work with small offsets, but this is unpredictable because it works + * on the buffered stream. + *

+ * @param null|non-negative-int $length [optional]

+ * Maximum length of data read. The default is to read until the end of the file is reached. + * + * Note that this parameter is applied to the stream processed by the filters. + *

+ * + * @throws \FireHub\Runtime\Exception\ReadFileException If we can't get content from a path. + * + * @return string The read data. + * + * @note If you're opening a URI with special characters, such as spaces, you need to encode the URI with + * urlencode(). + */ + public static function getContent (string $path, int $offset = 0, ?int $length = null):string { + + return ($content = file_get_contents($path, false, null, $offset, $length)) !== false + ? $content : throw new ReadFileException; + + } + + /** + * ### Reads the entire file into an array + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the file. + *

+ * @param bool $skip_empty_lines [optional]

+ * Skip empty lines. + *

+ * @param bool $ignore_new_lines [optional]

+ * Omit a newline at the end of each array element. + *

+ * + * @throws \FireHub\Runtime\Exception\ReadFileException If we can't get content from a path. + * + * @return list The file contents as an array of lines. + * + * @warning When using SSL, Microsoft IIS will violate the protocol by closing the connection without sending a + * close_notify indicator. + * PHP will report this as "SSL: Fatal Protocol Error" when you reach the end of the data. + * To work around this, the value of error_reporting should be lowered to a level that doesn't include warnings. + * PHP can detect buggy IIS server software when you open the stream using the https:// wrapper and will suppress + * the warning. + * When using fsockopen() to create a ssl:// socket, the developer is responsible for detecting and suppressing + * this warning. + * @note Each line in the resulting array will include the line ending, unless $ignore_new_lines is used. + * @tip If PHP doesn't properly recognize the line endings when reading files either on or created by a + * Macintosh computer enabling the auto_detect_line_endings runtime configuration option may help resolve the + * problem. + * @tip A URL can be used as a $path. + */ + public static function getContentArray (string $path, bool $skip_empty_lines = false, bool $ignore_new_lines = false):array { + + return ($content = file($path, match (true) { + $skip_empty_lines && $ignore_new_lines => FILE_SKIP_EMPTY_LINES | FILE_IGNORE_NEW_LINES, + $skip_empty_lines => FILE_SKIP_EMPTY_LINES, + $ignore_new_lines => FILE_IGNORE_NEW_LINES, + default => 0 + })) !== false + ? $content : throw new ReadFileException; + + } + + /** + * ### Write data to a file + * @since 1.0.0 + * + * @uses self::isFile() To tell whether the $file is a regular file. + * + * @param non-empty-string $path

+ * Path to the file where to write the data. + *

+ * @param string|string[] $data

+ * The data to write. + *

+ * @param bool $append [optional]

+ * Append the data to the file instead of overwriting it. + *

+ * @param bool $lock [optional]

+ * Acquire an exclusive lock on the file while proceeding to the writing. + *

+ * @param bool $create_file [optional]

+ * Is true, the method will create a new file if one doesn't exist. + *

+ * + * @throws \FireHub\Runtime\Exception\FileNotFoundException If $path is not file. + * @throws \FireHub\Runtime\Exception\FileWriteException If the $create_file option is off or couldn't put + * content on a path. + * + * @return non-negative-int The number of bytes that were written to the file. + */ + public static function putContent (string $path, array|string $data, bool $append = false, bool $lock = true, bool $create_file = true):int { + + if (!$create_file && !self::isFile($path)) throw new FileNotFoundException( + context: [ + 'path' => $path, + 'create_file' => $create_file, + 'file_exists' => self::isFile($path), + ] + ); + + return file_put_contents($path, $data, match (true) { + $append && $lock => FILE_APPEND | LOCK_EX, + $append => FILE_APPEND, + $lock => LOCK_EX, + default => 0 + }) ?: throw new FileWriteException; + + } + +} \ No newline at end of file diff --git a/src/FileSystem/Folder.php b/src/FileSystem/Folder.php new file mode 100644 index 0000000..3ed0ab4 --- /dev/null +++ b/src/FileSystem/Folder.php @@ -0,0 +1,206 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\FileSystem\PermissionMode; +use FireHub\Core\Meta\Enum\ { + Order, FileSystem\PathSearchFlag +}; +use FireHub\Runtime\Exception\ { + CannotListFolderException, CreateFolderException, DeleteFolderException, MatchInFolderException +}; + +use const GLOB_ERR; +use const GLOB_MARK; +use const GLOB_NOSORT; +use const GLOB_ONLYDIR; +use const SCANDIR_SORT_ASCENDING; +use const SCANDIR_SORT_DESCENDING; +use const SCANDIR_SORT_NONE; + +use function glob; +use function is_dir; +use function mkdir; +use function rmdir; +use function scandir; + +/** + * ### PHP Runtime Folder Utilities + * + * Provides low-level wrappers for managing file system folders, including creation, removal, scanning, and + * directory inspection while preserving native PHP behavior. + * + * This component exposes PHP directory management capabilities through a consistent FireHub Runtime API without + * altering native runtime semantics. + * @since 1.0.0 + */ +final class Folder extends NativeRuntime { + + /** + * ### Tells whether the filename is a regular folder + * @since 1.0.0 + * + * @param string $path

+ * Path to the folder. + * + * If the filename is a relative filename, it will be checked relative to the current working folder. + * + * If the filename is a symbolic or hard link, then the link will be resolved and checked. + * + * If you've enabled open_basedir, further restrictions may apply. + *

+ * + * @return bool True if the filename exists and is a regular folder, false otherwise. + * + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + */ + public static function exists (string $path):bool { + + return is_dir($path); + + } + + /** + * ### Makes folder + * + * Attempts to create the folder specified by $path. + * @since 1.0.0 + * + * @uses \FireHub\Core\Type\FileSystem\PermissionMode::decimal() To get decimal value of a permission mode. + * + * @param non-empty-string $path

+ * Path to folder ot disk partition. + *

+ * @param \FireHub\Core\Type\FileSystem\PermissionMode $mode

+ * The permissions. + *

+ * @param bool $recursive [optional]

+ * If true, then any parent folders to the $path specified will also be created, with the same permissions. + *

+ * + * @throws \FireHub\Runtime\Exception\CreateFolderException If we couldn't create a folder. + * + * @return true True on success. + */ + public static function create (string $path, PermissionMode $mode, bool $recursive = false):true { + + return mkdir($path, $mode->decimal(), $recursive) + ?: throw new CreateFolderException; + + } + + /** + * ### Deletes folder + * + * Attempts to remove the folder named by $path. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to folder. + *

+ * + * @throws \FireHub\Runtime\Exception\DeleteFolderException If we couldn't delete the folder. + * + * @return true True on success. + */ + public static function delete (string $path):true { + + return rmdir($path) + ?: throw new DeleteFolderException; + + } + + /** + * ### Find path-names matching a pattern + * + * This method searches for all the path-names matching patterns according to the rules used by the libc glob() + * function, which is similar to the rules used by common shells. + * @since 1.0.0 + * + * @param string $pattern

+ * The pattern. + * + * No tilde expansion or parameter substitution is done. + * - * – Matches zero or more characters. + * - ? – Matches exactly one character (any character). + * - [...] – Matches one character from a group of characters. If the first character is !, matches any character + * not in the group. + * - \ – Escapes the following character. + *

+ * @param \FireHub\Core\Meta\Enum\FileSystem\PathSearchFlag ...$flags

+ * The flags. + *

+ * + * @throws \FireHub\Runtime\Exception\MatchInFolderException If there was an error while searching for a path. + * + * @return list An array containing the matched files/folders, an empty array if no file matched. + * + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + * @note This function isn't available on some systems (for example, old Sun OS). + */ + public static function match (string $pattern, PathSearchFlag ...$flags):array { + + $options = 0; + + foreach ($flags as $flag) { + $options |= match ($flag) { + PathSearchFlag::ERROR => GLOB_ERR, + PathSearchFlag::MARK => GLOB_MARK, + PathSearchFlag::NO_SORT => GLOB_NOSORT, + PathSearchFlag::ONLY_DIRECTORY => GLOB_ONLYDIR, + }; + } + + return ($glob = glob($pattern, $options)) !== false + ? $glob : throw new MatchInFolderException; + + } + + /** + * ### List files and folders inside the specified folder + * @since 1.0.0 + * + * @param non-empty-string $folder

+ * The folder that will be scanned. + *

+ * @param null|\FireHub\Core\Meta\Enum\Order $order [optional]

+ * Result order. + *

+ * + * @throws \FireHub\Runtime\Exception\CannotListFolderException If $folder is empty, or we couldn't list files + * and directories inside the specified folder. + * + * @return list An array of filenames. + */ + public static function list (string $folder, ?Order $order = null):array { + + $result = scandir( + $folder, + match ($order) { + Order::ASC => SCANDIR_SORT_ASCENDING, + Order::DESC => SCANDIR_SORT_DESCENDING, + null => SCANDIR_SORT_NONE, + } + ); + + return $result !== false + ? $result + : throw new CannotListFolderException; + + } + +} \ No newline at end of file diff --git a/src/FileSystem/Link.php b/src/FileSystem/Link.php new file mode 100644 index 0000000..b59fae6 --- /dev/null +++ b/src/FileSystem/Link.php @@ -0,0 +1,214 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + ChangeSymlinkGroupException, ChangeSymlinkOwnerException, CreateLinkException, CreateSymbolicException, + GetSymbolicException, LinkInfoException +}; + +use function is_link; +use function lchgrp; +use function lchown; +use function link; +use function linkinfo; +use function readlink; +use function symlink; + +/** + * ### PHP Runtime File Link Utilities + * + * Provides low-level wrappers for creating, reading, resolving, and inspecting file system links, including + * symbolic and hard links while preserving native PHP behavior. + * + * This component exposes PHP link management capabilities through a consistent FireHub Runtime API without + * altering native runtime semantics. + * @since 1.0.0 + */ +final class Link extends NativeRuntime { + + /** + * ### Tells whether the path is a symbolic link + * @since 1.0.0 + * + * @param string $link

+ * Path to the link. + *

+ * + * @return bool True if the filename exists and is a symbolic link, false otherwise. + * + * @note The results of this function are cached.
+ * See Metadata::clearCache() for more details. + */ + public static function symbolicExists (string $link):bool { + + return is_link($link); + + } + + /** + * ### Create a hard link + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the file. + *

+ * @param non-empty-string $link

+ * The link name. + *

+ * + * @throws \FireHub\Runtime\Exception\CreateLinkException If we couldn't create a hard link + * for a path. + * + * @return true True on success. + * + * @note This function will not work on remote files as the file to be examined must be accessible via + * the server's filesystem. + * @note For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled. + */ + public static function hard (string $path, string $link):true { + + return link($path, $link) + ?: throw new CreateLinkException; + + } + + /** + * ### Creates a symbolic link + * + * Creates a symbolic link to the existing $path with the specified name $link. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the symlink. + *

+ * @param non-empty-string $link

+ * The link name. + *

+ * + * @throws \FireHub\Runtime\Exception\CreateSymbolicException If we couldn't create symlink for a path with a link. + * + * @return true True on success. + */ + public static function symbolic (string $path, string $link):true { + + return symlink($path, $link) + ?: throw new CreateSymbolicException(); + + } + + /** + * ### Returns the target of a symbolic link + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the symlink. + *

+ * + * @throws \FireHub\Runtime\Exception\GetSymbolicException If we couldn't symlink target for a path. + * + * @return string The contents of the symbolic link path. + */ + public function getSymbolic (string $path):string { + + return readlink($path) + ?: throw new GetSymbolicException; + + } + + /** + * ### Gets information about a link (hard or symbolic) + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the link. + *

+ * + * @throws \FireHub\Runtime\Exception\LinkInfoException If we couldn't get information about a link.' + * + * @return int|int<1, max> Non-negative integer on success, -1 in case the link was not found. + */ + public static function info (string $path):int { + + return linkinfo($path) + ?: throw new LinkInfoException; + + } + + /** + * ### Changes group ownership of symlink + * + * Attempts to change the group of the symlink filenames to group. + * + * Only the superuser may change the group of symlinks arbitrarily. + * + * Other users may change the group of symlinks to any group of which that user is a member. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the symlink. + *

+ * @param non-empty-string|int $group

+ * The group is specified by name or number. + *

+ * + * @throws \FireHub\Runtime\Exception\ChangeSymlinkGroupException If we couldn't change a symlink group. + * + * @return true True on success. + * + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + * @note This function is not implemented on Windows platforms. + * @tip Use posix_getgrgid() to resolve it to a group name. + */ + public static function symlinkGroup (string $path, string|int $group):true { + + return lchgrp($path, $group) + ?: throw new ChangeSymlinkGroupException; + + } + + /** + * ### Changes user ownership of symlink + * + * Attempts to change the owner of the symlink $path to user $user. + * + * Only the superuser may change the owner of a symlink. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to the symlink. + *

+ * @param non-empty-string|int $user

+ * Username or number. + *

+ * + * @throws \FireHub\Runtime\Exception\ChangeSymlinkOwnerException If we couldn't change symlink ownership. + * + * @return true True on success. + * + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + * @note This function is not implemented on Windows platforms. + * @tip Use posix_getpwuid() to resolve it to a username. + */ + public static function symlinkOwner (string $path, string|int $user):true { + + return lchown($path, $user) + ?: throw new ChangeSymlinkOwnerException; + + } + +} \ No newline at end of file diff --git a/src/FileSystem/Metadata.php b/src/FileSystem/Metadata.php new file mode 100644 index 0000000..4bfeb9e --- /dev/null +++ b/src/FileSystem/Metadata.php @@ -0,0 +1,526 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\ { + Arr, DataIs, Number, Str +}; +use FireHub\Core\Type\FileSystem\PermissionMode; +use FireHub\Core\Meta\Enum\ { + FileSystem\Permission, Number\Base +}; +use FireHub\Runtime\Exception\ { + PathGroupException, PathInodeException, PathOwnerException, PathPermissionsException, PathSizeException, + PathStatisticsException, PathTimestampException +}; + +use function chgrp; +use function chmod; +use function chown; +use function clearstatcache; +use function fileatime; +use function filectime; +use function filemtime; +use function fileinode; +use function filegroup; +use function fileowner; +use function fileperms; +use function filesize; +use function lstat; +use function stat; +use function touch; + +/** + * ### PHP Runtime File Metadata Utilities + * + * Provides low-level wrappers for retrieving file system metadata, including timestamps, ownership, permissions, + * identifiers, and file information while preserving native PHP behavior. + * + * This component exposes PHP metadata inspection capabilities through a consistent FireHub Runtime API without + * altering native runtime semantics. + * @since 1.0.0 + */ +final class Metadata extends NativeRuntime { + + /** + * ### Gets file size + * @param non-empty-string $path

+ * Path to the file. + *

+ * + * @return non-negative-int The size of the file in bytes. + * + * @note Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions + * may return unexpected results for files which are larger than 2GB. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + *@throws \FireHub\Runtime\Exception\PathSizeException If we couldn't get file size for a file. + * + * @since 1.0.0 + * + */ + public static function size (string $path):int { + + return ($size = filesize($path)) !== false + ? $size : throw new PathSizeException( + 'We couldn\'t get file size for a file.' + ); + + } + + /** + * ### Gets last access time of a path + * @param string $path

+ * Path to file or folder. + *

+ * + * @return non-negative-int The time the file was last accessed (the time is returned as a Unix timestamp). + * + * @note The atime of a file is supposed to change whenever the data blocks of a file are being read. + * This can be costly performance-wise when an application regularly accesses a huge number of files or + * directories. + * Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such + * applications; USENET news spools are a common example. + * On such filesystems this function will be useless. + * @note Note that time resolution may differ from one file system to another. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + *@throws \FireHub\Runtime\Exception\PathTimestampException If failed get last accessed time for a path. + * + * @since 1.0.0 + * + */ + public static function lastAccessed (string $path):int { + + return ($time = fileatime($path)) !== false + ? $time : throw new PathTimestampException; + + } + + /** + * ### Gets last modification time of a path + * + * Represents when the data or content is changed or modified, not including that of metadata such as ownership or + * owner group. + * @param string $path

+ * Path to file or folder. + *

+ * + *@return non-negative-int The time the file was last modified (the time is returned as a Unix timestamp). + * + * @note Note that time resolution may differ from one file system to another. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + *@throws \FireHub\Runtime\Exception\PathTimestampException If failed get last modified time for a path. + * + * @since 1.0.0 + * + */ + public static function lastModified (string $path):int { + + return ($time = filemtime($path)) !== false + ? $time : throw new PathTimestampException; + + } + + /** + * ### Gets inode change time of a path + * + * Represents the time when the metadata or inode data of a file is altered, such as the change of permissions, + * ownership, or group. + * @param string $path

+ * Path to file or folder. + *

+ * + * @return non-negative-int The time the file was last changed (the time is returned as a Unix timestamp). + * + * @note In most Unix filesystems, a file is considered changed when its inode data is changed; that is, when the + * permissions, owner, group, or other metadata from the inode is updated. + * See also Metadata#lastModified() (which is what you want to use when you want to create "Last Modified" + * footers on web pages) and Metadata#lastAccessed(). + * @note On Windows, this function will return creating time but on UNIX inode change time. + * @note Note that time resolution may differ from one file system to another. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + *@throws \FireHub\Runtime\Exception\PathTimestampException If failed get last changed time for a path. + * + * @since 1.0.0 + * + */ + public static function lastChanged (string $path):int { + + return ($time = filectime($path)) !== false + ? $time : throw new PathTimestampException; + + } + + /** + * ### Gets file inode + * + * Inode are special disk blocks they are created when the file system is created. + * @param non-empty-string $path

+ * Path to file or folder. + *

+ * + * @return non-negative-int The inode number of the file. + * + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + *@throws \FireHub\Runtime\Exception\PathInodeException If failed to get inode for a path. + * + * @since 1.0.0 + * + */ + public static function inode (string $path):int { + + return ($inode = fileinode($path)) !== false + ? $inode : throw new PathInodeException; + + } + + /** + * ### Sets last access and modification time of a path + * + * Attempts to set the access and modification times of the file named in the filename parameter to the value + * given in mtime. Note that the access time is always modified, regardless of the number of parameters. + * @param non-empty-string $path

+ * Path to file or folder. + *

+ * @param null|int $last_accessed [optional]

+ * f not null, the access time of the given filename is set to the value of atime. + * + * Otherwise, it is set to the value passed to the mtime parameter. + * + * If both are null, the current system time is used. + *

+ * @param null|int $last_modified [optional]

+ * The modifed time. + * + * If $last_modified is null, the current system time() is used. + *

+ * + * @return true True on success. + * + * @note If the file doesn't exist, it will be created. + * @note Note that time resolution may differ from one file system to another. + *@throws \FireHub\Runtime\Exception\PathTimestampException If failed to set the last access and modification + * time of a path. + * + * @since 1.0.0 + * + */ + public static function setTimestamps (string $path, ?int $last_accessed = null, ?int $last_modified = null):true { + + return touch($path, $last_modified, $last_accessed) + ?: throw new PathTimestampException; + + } + + /** + * ### Gets a file or folder group + * + * Gets the file or folder group. The group ID is returned in numerical format. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path of the file or folder. + *

+ * + * @throws \FireHub\Runtime\Exception\PathGroupException If we couldn't get a group for a file. + * + * @return non-negative-int The group ID of the file. + * + * @warning This method doesn't work on Windows. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + * @tip Use posix_getgrgid() to resolve it to a group name. + */ + public static function getGroup (string $path):int { + + return ($group = filegroup($path)) === false + ? throw new PathGroupException + : $group; + + } + + /** + * ### Changes file or folder group + * + * Attempts to change the group of the files or folder $path to $group. + * + * Only the superuser may change the group of files arbitrarily; other users may change the group of files to any + * group of which that user is a member. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path of the file or folder. + *

+ * @param non-empty-string|int $group

+ * A group name or number. + *

+ * + * @throws \FireHub\Runtime\Exception\PathGroupException If we couldn't set a group for file + * or folder. + * + * @return true True on success. + * + * @warning This method doesn't work on Windows. + * @tip Use posix_getgrgid() to resolve it to a group name. + */ + public static function setGroup (string $path, string|int $group):true { + + return chgrp($path, $group) + ?: throw new PathGroupException; + + } + + /** + * ### Gets a file or folder owner + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path of the file or folder. + *

+ * + * @throws \FireHub\Runtime\Exception\PathOwnerException If we couldn't get an owner for a file or folder. + * + * @return non-negative-int The user ID of the owner for the file or folder. + * + * @warning This method doesn't work on Windows. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + * @tip Use posix_getpwuid() to resolve it to a username. + */ + public static function getOwner (string $path):int { + + return ($owner = fileowner($path)) === false + ? throw new PathOwnerException + : $owner; + + } + + /** + * ### Gets a file or folder owner + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Pth of the file or folder. + *

+ * @param non-empty-string|int $user

+ * A username or number. + *

+ * + * @throws \FireHub\Runtime\Exception\PathOwnerException If we couldn't get an owner for a file or folder. + * + * @return true True on success. + * + * @warning This method doesn't work on Windows. + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + * @tip Use posix_getpwuid() to resolve it to a username. + */ + public static function setOwner (string $path, string|int $user):true { + + return chown($path, $user) + ?: throw new PathOwnerException; + + } + + /** + * ### Gets path permissions + * + * Gets permissions for the given path. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Str\SB\Access::part() To get part of the decoct() function. + * @uses \FireHub\Runtime\Number::baseConverter() To convert a number to a base. + * @uses \FireHub\Core\Meta\Enum\Number\Base::DECIMAL To convert a number to a base. + * @uses \FireHub\Core\Meta\Enum\Number\Base::OCTAL To convert a number to a base. + * + * @param non-empty-string $path

+ * The path. + *

+ * + * @throws \FireHub\Runtime\Exception\PathPermissionsException If failed to permissions for a path. + * @throws \FireHub\Runtime\Exception\InvalidNumberBaseException If failed to convert a number to a base. + * + * @return \FireHub\Core\Type\FileSystem\PermissionMode Path permissions. + * + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + */ + public static function getPermissions (string $path):PermissionMode { + + $permissions = fileperms($path); + + if ($permissions === false) throw new PathPermissionsException; + + $permissions = Str\SB\Access::part( + Number::baseConverter((string)$permissions, Base::DECIMAL, Base::OCTAL), + -3 + ); + + return new PermissionMode( + Permission::from((int)$permissions[0]), + Permission::from((int)$permissions[1]), + Permission::from((int)$permissions[2]) + ); + + } + + /** + * ### Sets path permissions + * + * Attempts to change the mode of the specified path to that given in permissions. + * @since 1.0.0 + * + * @uses \FireHub\Core\Type\FileSystem\PermissionMode::decimal() To get decimal value of a permission mode. + * + * @param non-empty-string $path

+ * The path. + *

+ * @param \FireHub\Core\Type\FileSystem\PermissionMode $mode

+ * The permissions. + *

+ * + * @throws \FireHub\Runtime\Exception\PathPermissionsException If failed to set permissions for a path. + * + * @return True Only true. + * + * @note The current user is the user under which PHP runs. + * It is probably different from the user you use for normal shell or FTP access. + * The mode can be changed only by the user who owns the file on most systems. + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + */ + public static function setPermissions (string $path, PermissionMode $mode):true { + + return chmod($path, $mode->decimal() + ) ?: throw new PathPermissionsException; + + } + + /** + * ### Gives information about a file or folder + * + * Gathers the statistics of the file named by filename. + * + * If the filename is a symbolic link, statistics are from the file itself, not the symlink – use $symlink + * argument to change that behavior. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Transform::filter() To filter string keys in statistics. + * @uses \FireHub\Runtime\DataIs::string() To find whether the statistics key is string or not. + * + * @param non-empty-string $path

+ * Path to the file or folder. + *

+ * @param bool $symlink [optional]

+ * If true, the method gives information about a file or symbolic link. + *

+ * + * @throws \FireHub\Runtime\Exception\PathStatisticsException If we couldn't get statistics for a path. + * + * @return array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } Statistics about a file or folder. + */ + public static function statistics (string $path, bool $symlink = false):array { + + /** @var array{ + * dev: int, + * ino: int, + * mode: int, + * nlink: int, + * uid: int, + * gid: int, + * rdev: int, + * size: int, + * atime: int, + * mtime: int, + * ctime: int, + * blksize: int, + * blocks: int + * } + */ + return Arr\Transform::filter( + ($statistics = $symlink ? lstat($path) : stat($path)) !== false + ? $statistics + : throw new PathStatisticsException, + static fn(int $value, int|string $key) => DataIs::string($key) + ); + + } + + /** + * ### Clears file status cache + * + * When you use FileSystem#statistics() or any of the other functions listed in the affected functions list (below), + * PHP caches the information those functions return to provide faster performance. + * + * However, in certain cases, you may want to clear the cached information. + * + * For instance, if the same file is being checked multiple times within a single script, and that file is in + * danger of being removed or changed during that script's operation, you may elect to clear the status cache. + * + * In these cases, you can use the Metadata::clearCache() function to clear the information that PHP caches + * about a file. + * + * You should also note that PHP doesn't cache information about non-existent files. + * + * So, if you call File::exist() on a file which doesn't exist, it will return false until you create + * the file. + * + * If you create the file, it will return true even if you then delete the file. + * + * However, File::delete() clears the cache automatically. + * @since 1.0.0 + * + * @param bool $clear_realpath_cache [optional]

+ * Whether to also clear the realpath cache. + *

+ * @param string $path [optional]

+ * Clear the realpath cache for a specific filename only. + * + * Only used if $clear_realpath_cache is true. + *

+ * + * @return void + * + * @phpstan-impure + * + * @note This function caches information about specific filenames, so you only need to call Metadata::clearCache + * () if you are performing multiple operations on the same filename and require the information about that + * particular file to not be cached. + */ + public static function clearCache (bool $clear_realpath_cache = false, string $path = ''):void { + + clearstatcache($clear_realpath_cache, $path); + + } + +} \ No newline at end of file diff --git a/src/FileSystem/Path.php b/src/FileSystem/Path.php new file mode 100644 index 0000000..4c29460 --- /dev/null +++ b/src/FileSystem/Path.php @@ -0,0 +1,173 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + InvalidPathParentLevelException, PathResolutionException +}; + +use function basename; +use function dirname; +use function pathinfo; +use function realpath; + +/** + * ### PHP Runtime File System Path Utilities + * + * Provides low-level wrappers for manipulating and resolving file system paths, including path extraction, + * normalization, and path information inspection while preserving native PHP behavior. + * + * This component exposes PHP path handling capabilities through a consistent FireHub Runtime API without altering + * native runtime semantics. + * @since 1.0.0 + */ +final class Path extends NativeRuntime { + + /** + * ### Returns a trailing name component of a path + * + * Given a string containing the path to a file or directory, this function will return the trailing name component. + * @since 1.0.0 + * + * @param non-empty-string $path

+ * A path. On Windows, both slash (/) and backslash (\) are used as directory separator characters. + * In other environments, it is the forward slash (/). + *

+ * @param string $suffix [optional]

+ * If the name component ends in suffix, this will also be cut off. + *

+ * + * @return string The base name of the given path. + * + * @caution Method is locale-aware, so for it to see the correct basename with multibyte character paths, + * the matching locale must be set using the setlocale() function. + * If a path contains characters which are invalid for the current locale, the behavior of + * FileSystem::basename() is undefined. + * @note Method operates naively on the input string and is not aware of the actual filesystem or path + * components such as "..". + */ + public static function basename (string $path, string $suffix = ''):string { + + return basename($path, $suffix); + + } + + /** + * ### Returns parent folder path + * + * Given a string containing the path of a file or directory, this function will return the parent folder's path + * that is $level up from the current folder. + * @since 1.0.0 + * + * @param string $path

+ * A path. + *

+ * @param positive-int $levels [optional]

+ * The number of parent folders to go up. + * This must be an integer greater than 0. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPathParentLevelException If $levels is less than 1. + * + * @return string The parent folder name of the given path. + * If there are no slashes in a path, a dot is returned, indicating the current folder. + * + * @caution Be careful when using this function in a loop that can reach the top-level directory as this can + * result in an infinite loop. + */ + public static function parent (string $path, int $levels = 1):string { + + return $levels >= 1 + ? dirname($path, $levels) + : throw new InvalidPathParentLevelException( + 'The number of parent levels must be greater than zero.', + [ + 'levels' => $levels, + 'minimum' => 1, + ] + ); + + } + + /** + * ### Returns information about a file path + * @since 1.0.0 + * + * @param non-empty-string $path

+ * The path to be parsed. + *

+ * + * @return array{ + * 'dirname': string|null, + * 'basename': string, + * 'extension': string|null, + * 'filename': string + * } Information about a file path. + * + * @caution Path::pathInfo() is locale-aware, so for it to parse a path containing multibyte characters + * correctly, the matching locale must be set using the setlocale() function. + * @note Path::pathInfo() operates naively on the input string and is not aware of the actual filesystem, + * or path components such as "..". + * @note On Windows systems only, the \ character will be interpreted as a directory separator. + * On other systems it will be treated like any other character. + */ + public static function info (string $path):array { + + $path_info = pathinfo($path); + + return [ + 'dirname' => $path_info['dirname'] ?? null, // @phpstan-ignore nullCoalesce.unnecessary + 'basename' => $path_info['basename'], + 'extension' => $path_info['extension'] ?? null, + 'filename' => $path_info['filename'] + ]; + + } + + /** + * ### Returns canonical absolute pathname + * + * Expands all symbolic links and resolves references to /./, /../ and extra / characters in the input path and + * returns the canonical absolute pathname. + * + * Trailing delimiters, such as \ and /, are also removed. + * @since 1.0.0 + * + * @param string $path

+ * The path being checked. + *

+ * + * @throws \FireHub\Runtime\Exception\PathResolutionException If we couldn't get an absolute path for a path or + * file doesn't exist, or a script doesn't have executable permissions. + * + * @return non-empty-string The canonical absolute pathname. + * + * @note The running script must have executable permissions in all directories in the hierarchy, otherwise + * Path::absolute() will return false. + * @note For case-insensitive filesystems, absolutePath() may or may not normalize the character case. + * @note The function Path::absolute() will not work for a file which is inside a Phar as such a path would be + * virtual path, not a real one. + * @note On Windows, one level only expands junctions and symbolic links to directories. + * @note Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions + * may return unexpected results for files which are larger than 2GB. + */ + public static function absolute (string $path):string { + + return realpath($path) + ?: throw new PathResolutionException; + + } + +} \ No newline at end of file diff --git a/src/FileSystem/Permission.php b/src/FileSystem/Permission.php new file mode 100644 index 0000000..865a737 --- /dev/null +++ b/src/FileSystem/Permission.php @@ -0,0 +1,95 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function is_executable; +use function is_readable; +use function is_writable; + +/** + * ### PHP Runtime File System Permission Utilities + * + * Provides low-level wrappers for inspecting and modifying file system permissions, ownership, and access + * capabilities while preserving native PHP behavior. + * + * This component exposes PHP permission management capabilities through a consistent FireHub Runtime API without + * altering native runtime semantics. + * @since 1.0.0 + */ +final class Permission extends NativeRuntime { + + /** + * ### Tells whether the path is executable + * @since 1.0.0 + * + * @param string $path

+ * Path to the file. + *

+ * + * @return bool True if the filename exists and is an executable file, false otherwise. + * + * @note On POSIX systems, a file is executable if the executable bit of the file permissions is set. + * On Windows, a file is considered executable if it is a properly executable file as reported by the Win API + * GetBinaryType(); for BC reasons, files with a .bat or .cmd extension are also considered executable. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + */ + public static function isExecutable (string $path):bool { + + return is_executable($path); + + } + + /** + * ### Tells whether a file exists and is readable + * @since 1.0.0 + * + * @param string $path

+ * Path to the file or folder. + *

+ * + * @return bool True if the file or directory specified by $path exists and is readable, false otherwise. + * + * @note The check is done using the real UID/GID instead of the effective one. + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + */ + public static function isReadable (string $path):bool { + + return is_readable($path); + + } + + /** + * Tells whether the path is writable + * @since 1.0.0 + * + * @param string $path

+ * Path to the file. + *

+ * + * @return bool True if the filename exists and is writable. + * + * @note The results of this function are cached. + * See Metadata::clearCache() for more details. + */ + public static function isWritable (string $path):bool { + + return is_writable($path); + + } + +} \ No newline at end of file diff --git a/src/FileSystem/Storage.php b/src/FileSystem/Storage.php new file mode 100644 index 0000000..6d14e86 --- /dev/null +++ b/src/FileSystem/Storage.php @@ -0,0 +1,82 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\FileSystem; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\DiskSpaceException; + +use function disk_free_space; +use function disk_total_space; + +/** + * ### PHP Runtime File System Storage Utilities + * + * Provides low-level wrappers for inspecting available file system storage capacity, including total and free disk + * space while preserving native PHP behavior. + * + * This component exposes PHP storage information capabilities through a consistent FireHub Runtime API without + * altering native runtime semantics. + * @since 1.0.0 + */ +final class Storage extends NativeRuntime { + + /** + * ### Gets total size of a filesystem or disk partition + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to folder ot disk partition. + *

+ * + * @throws \FireHub\Runtime\Exception\DiskSpaceException If we couldn't get disk space for a path. + * + * @return float Returns the total number of bytes as a float. + * + * @note Given a filename instead of a folder, the behavior of the function is unspecified and may differ + * between operating systems and PHP versions. + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + */ + public static function totalSpace (string $path):float { + + return ($space = disk_total_space($path)) !== false + ? $space : throw new DiskSpaceException; + + } + + /** + * ### Gets free space of a filesystem or disk partition + * @since 1.0.0 + * + * @param non-empty-string $path

+ * Path to folder ot disk partition. + *

+ * + * @throws \FireHub\Runtime\Exception\DiskSpaceException If we couldn't get disk space for a path. + * + * @return float Returns the total free space of bytes as a float. + * + * @note Given a filename instead of a folder, the behavior of the function is unspecified and may differ + * between operating systems and PHP versions. + * @note This function will not work on remote files as the file to be examined must be accessible via the + * server's filesystem. + */ + public static function freeSpace (string $path):float { + + return ($space = disk_free_space($path)) !== false + ? $space : throw new DiskSpaceException; + + } + +} \ No newline at end of file diff --git a/src/Func.php b/src/Func.php new file mode 100644 index 0000000..1b6d71a --- /dev/null +++ b/src/Func.php @@ -0,0 +1,113 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function call_user_func; +use function call_user_func_array; +use function function_exists; + +/** + * ### PHP Runtime Function Utilities + * + * Provides low-level wrappers for inspecting and invoking callable functions using native PHP function utilities + * while preserving native runtime behavior. + * + * This component exposes PHP callable execution capabilities through a consistent FireHub Runtime API without + * altering function invocation semantics. + * @since 1.0.0 + */ +final class Func extends NativeRuntime { + + /** + * ### Checks if the function name exists + * + * Checks the list of defined functions, both built-in (internal) and user-defined, for function. + * @since 1.0.0 + * + * @param non-empty-string $name

+ * The function name. + *

+ * + * @phpstan-assert-if-true callable-string $name + * @phpstan-assert-if-false !callable-string $name + * + * @return bool True if the interface exists, false otherwise. + * + * @note This function will return false for constructs, such as include_once and echo. + * @note A function name may exist even if the function itself is unusable due to configuration or compiling + * options. + */ + public static function isFunction (string $name):bool { + + return function_exists($name); + + } + + /** + * ### Call the callback + * + * Calls the callback given by the first parameter and passes the remaining parameters as arguments. + * @since 1.0.0 + * + * @template TReturn + * @template TParameters + * + * @param callable(TParameters...):TReturn $callback

+ * The callable to be called. + *

+ * @param TParameters ...$arguments

+ * Zero or more parameters to be passed to the callback. + *

+ * + * @return TReturn The return value of the callback. + * + * @note Callbacks registered with this method will not be called if there is an uncaught exception thrown + * in a previous callback. + */ + public static function call (callable $callback, mixed ...$arguments):mixed { + + return call_user_func($callback, ...$arguments); + + } + + /** + * ### Call the callback with an array of parameters + * + * Calls the callback given by the first parameter with the parameters in $arguments. + * @since 1.0.0 + * + * @template TReturn + * @template TParameters + * + * @param callable(TParameters...):TReturn $callback

+ * The callable to be called. + *

+ * @param array $arguments

+ * The parameters that are to be passed to the function as an indexed array. + *

+ * + * @return TReturn The return value of the callback. + * + * @note Callbacks registered with this method will not be called if there is an uncaught exception thrown + * in a previous callback. + */ + public static function callWithArray (callable $callback, array $arguments):mixed { + + return call_user_func_array($callback, $arguments); + + } + +} \ No newline at end of file diff --git a/src/Introspection.php b/src/Introspection.php new file mode 100644 index 0000000..716ed83 --- /dev/null +++ b/src/Introspection.php @@ -0,0 +1,112 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function get_declared_classes; +use function get_declared_interfaces; +use function get_declared_traits; +use function get_defined_constants; +use function get_defined_functions; + +/** + * ### PHP Runtime Introspection Utilities + * + * Provides low-level wrappers for inspecting the current PHP runtime environment, including declared classes, + * interfaces, traits, functions, and constants while preserving native runtime behavior. + * + * This component exposes native runtime introspection capabilities through a consistent FireHub Runtime API without + * altering PHP execution semantics. + * @since 1.0.0 + */ +final class Introspection extends NativeRuntime { + + /** + * ### Gets the declared classes + * @since 1.0.0 + * + * @return list Array of the names for the declared classes in the current script. + * + * @note Note that depending on what extensions you've compiled or loaded into PHP, additional classes could be + * present. + * This means that you will not be able to define your own classes using these names. + */ + public static function classes ():array { + + return get_declared_classes(); + + } + + /** + * ### Gets the declared interfaces + * @since 1.0.0 + * + * @return list Array of the names for the declared interfaces in the current script. + */ + public static function interfaces ():array { + + return get_declared_interfaces(); + + } + + /** + * ### Gets the declared traits + * @since 1.0.0 + * + * @return list Array of the names for the declared traits in the current script. + */ + public static function traits ():array { + + return get_declared_traits(); + + } + + /** + * ### Gets the declared constants + * + * Returns the names and values of all the constants currently defined. + * + * This includes those created by extensions as well as those created with the Constant::define() function. + * @since 1.0.0 + * + * @param bool $categorize [optional]

+ * Causing this function to return a multidimensional array with categories in the keys of the first dimension + * and constants and their values in the second dimension. + *

+ * + * @return ($categorize is true ? array> : array) Array of + * constant name => constant value array, optionally grouped by extension name registering the constant. + */ + public static function definedConstants (bool $categorize = false):array { + + return get_defined_constants($categorize); + + } + + /** + * ### Gets the declared functions + * @since 1.0.0 + * + * @return array{internal: non-empty-array, user: array} + * A multidimensional array containing a list of all defined functions, both built-in (internal) and user-defined. + * The internal functions will be accessible via $arr['internal'], and the user-defined ones using $arr['user']. + */ + public static function definedFunctions ():array { + + return get_defined_functions(); + + } + +} \ No newline at end of file diff --git a/src/Iterator.php b/src/Iterator.php new file mode 100644 index 0000000..9cdedb5 --- /dev/null +++ b/src/Iterator.php @@ -0,0 +1,116 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use Traversable; + +use function iterator_apply; +use function iterator_count; +use function iterator_to_array; + +/** + * ### PHP Runtime Iterator Utilities + * + * Provides low-level wrappers for processing and converting iterator objects using native PHP iterator functions + * while preserving native runtime behavior. + * + * This component exposes iterator traversal and conversion capabilities through a consistent FireHub Runtime API + * without altering PHP iterator semantics. + * @since 1.0.0 + */ +final class Iterator extends NativeRuntime { + + /** + * ### Copy the iterator into an array + * + * Copy the elements of an iterator into an array. + * @since 1.0.0 + * + * @template TKey of array-key + * @template TValue + * + * @param iterable $iterator

+ * The iterator being copied. + *

+ * @param bool $preserve_keys [optional]

+ * Whether to use the iterator element keys as index. + * + * If a key is an array or object, a warning will be generated. + * + * Null keys will be converted to an empty string, float keys will be truncated to their int counterpart, + * resource keys will generate a warning and be converted to their resource ID, and bool keys will be converted + * to integers. + *

+ * + * @return ($preserve_keys is true ? array : list) An array containing items of the iterator. + * + * @note If this parameter $preserve_keys is not set or set to true, duplicate keys will be overwritten. + * The last value with a given key will be in the returned array. + * Set this parameter as false to get all the values in any case. + */ + public static function toArray (iterable $iterator, bool $preserve_keys = true):array { + + return iterator_to_array($iterator, $preserve_keys); + + } + + /** + * ### Count the elements in an iterator + * + * Count the elements in an iterator. + * + * Method is not guaranteed to retain the current position of the iterator. + * @since 1.0.0 + * + * @param iterable $iterator

+ * The iterator being counted. + *

+ * + * @return non-negative-int Number of elements in iterator. + */ + public static function count (iterable $iterator):int { + + return iterator_count($iterator); + + } + + /** + * ### Call a function for every element in an iterator + * @since 1.0.0 + * + * @template TKey + * @template TValue + * + * @param Traversable $iterator

+ * The iterator objects to iterate over. + *

+ * @param callable(mixed...):bool $callback

+ * The callback function to call on every element. + * + * The function must return true to continue iterating over the iterator. + *

+ * @param null|array $arguments

+ * An array of arguments; each element of args is passed to the callback as a separate argument. + *

+ * + * @return int Iteration count. + */ + public static function apply (Traversable $iterator, callable $callback, ?array $arguments = null):int { + + return iterator_apply($iterator, $callback, $arguments); + + } + +} \ No newline at end of file diff --git a/src/Json.php b/src/Json.php new file mode 100644 index 0000000..c9ee254 --- /dev/null +++ b/src/Json.php @@ -0,0 +1,189 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Json\ { + Flag, Flag\Decode, Flag\Encode, Flag\Validate +}; +use FireHub\Runtime\Exception\ { + JsonDecodeException, JsonEncodeException +}; +use JsonException; + +use function json_decode; +use function json_encode; +use function json_validate; + +/** + * ### PHP Runtime JSON Utilities + * + * Provides low-level wrappers for encoding, decoding, and validating JSON data using native PHP JSON functions + * while preserving native runtime behavior. + * + * This component exposes JSON processing capabilities through a consistent FireHub Runtime API + * without altering PHP JSON semantics. + * @since 1.0.0 + */ +final class Json extends NativeRuntime { + + /** + * ### JSON representation of a value + * + * Returns a string containing the JSON representation of the supplied value. + * + * If the parameter is an array or object, it will be serialized recursively. + * + * If a value to be serialized is an object, then by default only publicly visible properties will be included. + * + * Alternatively, a class may implement JsonSerializable to control how its values are serialized to JSON. + * + * The encoding is affected by the supplied flags, and additionally, the encoding of float values depends on the + * value of serialize_precision. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Transform::reduce() To reduce flags. + * @uses \FireHub\Runtime\Arr\Transform::unique() To get unique flags. + * + * @param mixed $value

+ * The value being encoded. + * + * Can be any type except a resource. + *

+ * @param positive-int $depth [optional]

+ * Set the maximum depth. + *

+ * @param \FireHub\Runtime\Json\Flag|\FireHub\Runtime\Json\Flag\Encode ...$flags

+ * JSON flags. + *

+ * + * @throws \FireHub\Runtime\Exception\JsonEncodeException If JSON encoding throws an error. + * + * @return non-empty-string JSON encoded string. + * + * @note All string data for $value parameter must be UTF-8 encoded. + * @note Method always uses Flag::THROW_ON_ERROR internally. + */ + public static function encode (mixed $value, int $depth = 512, Flag|Encode ...$flags):string { + + try { + + return json_encode($value, Arr\Transform::reduce( + Arr\Transform::unique($flags), + static fn(null|int $carry, Flag|Encode $flag) => $flag !== Flag::THROW_ON_ERROR + ? $carry | $flag->value + : $carry, + 0 + ) | Flag::THROW_ON_ERROR->value, $depth) + ?: throw new JsonEncodeException('Failed to encode JSON.'); + + } catch (JsonException $error) { + + throw new JsonEncodeException(previous: $error); + + } + + } + + /** + * ### Decodes a JSON string + * + * Takes a JSON-encoded string and converts it into a PHP value. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Transform::reduce() To reduce flags. + * @uses \FireHub\Runtime\Arr\Transform::unique() To get unique flags. + * + * @param string $json

+ * The JSON string being decoded. + *

+ * @param bool $as_array [optional]

+ * If true, the method will return a decoded JSON string as an associative array, otherwise it will return an object. + *

+ * @param positive-int $depth [optional]

+ * Set the maximum depth. + *

+ * @param \FireHub\Runtime\Json\Flag|\FireHub\Runtime\Json\Flag\Decode ...$flags

+ * JSON flags. + *

+ * + * @throws \FireHub\Runtime\Exception\JsonDecodeException If JSON decoding throws an error. + * + * @return mixed Value encoded in JSON as an appropriate PHP type, or null is returned if the JSON can't be decoded + * or if the encoded data is deeper than the nesting limit. + * + * @note All string data for $json parameter must be UTF-8 encoded. + * @note Method always uses Flag::THROW_ON_ERROR internally. + * @tip This method already performs validation during decoding, so calling Json::validate() immediately before + * Json::decode() will unnecessarily parse the string twice. + */ + public static function decode (string $json, bool $as_array = false, int $depth = 512, Flag|Decode ...$flags):mixed { + + try { + + return json_decode($json, $as_array, $depth, Arr\Transform::reduce( + Arr\Transform::unique($flags), + static fn(null|int $carry, Flag|Decode $flag) => $flag !== Flag::THROW_ON_ERROR + ? $carry | $flag->value + : $carry, + 0 + ) | Flag::THROW_ON_ERROR->value) + ?: throw new JsonDecodeException; + + } catch (JsonException $error) { + + throw new JsonDecodeException(previous: $error); + + } + + } + + /** + * ### Checks if a string contains valid JSON + * + * Json#validate() uses less memory than Json#decode if the decoded JSON payload is not used because it doesn't + * need to build the array or object structure containing the payload. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Arr\Transform::reduce() To reduce flags. + * @uses \FireHub\Runtime\Arr\Transform::unique() To get unique flags. + * + * @param string $json

+ * The string to validate. + *

+ * @param positive-int $depth [optional]

+ * Set the maximum depth. + *

+ * @param \FireHub\Runtime\Json\Flag\Validate ...$flags

+ * JSON flags. + *

+ * + * @return bool True if the given string is syntactically valid JSON, false otherwise. + * + * @caution Calling Json#validate immediately before Json#decode will unnecessarily parse the string twice, as + * Json::decode implicitly performs validation during decoding. + * Json::validate should therefore only be used if the decoded JSON payload is not immediately used and knowing + * whether the string contains valid JSON is needed. + */ + public static function validate (string $json, int $depth = 512, Validate ...$flags):bool { + + return json_validate($json, $depth, Arr\Transform::reduce( // @phpstan-ignore argument.type + Arr\Transform::unique($flags), + static fn(null|int $carry, Validate $flag) => $carry | $flag->value, + 0 + )); + + } + +} \ No newline at end of file diff --git a/src/Json/Flag.php b/src/Json/Flag.php new file mode 100644 index 0000000..c445bee --- /dev/null +++ b/src/Json/Flag.php @@ -0,0 +1,46 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Json; + +/** + * ### PHP Runtime JSON Flags + * + * Provides common JSON flags shared across native PHP JSON processing functions, including encoding, decoding, and + * validation operations while preserving native runtime behavior. + * + * This enum exposes reusable JSON configuration flags through a consistent FireHub Runtime API without altering PHP + * JSON semantics. + * @since 1.0.0 + */ +enum Flag:int { + + /** + * ### Ignore invalid UTF-8 characters + * @since 1.0.0 + */ + case INVALID_UTF8_IGNORE = 1048576; + + /** + * ### Convert invalid UTF-8 characters to \0xfffd (Unicode Character 'REPLACEMENT CHARACTER') + * @since 1.0.0 + */ + case INVALID_UTF8_SUBSTITUTE = 2097152; + + /** + * ### Throws JsonException if an error occurs instead of setting the global error state + * @since 1.0.0 + */ + case THROW_ON_ERROR = 4194304; + +} \ No newline at end of file diff --git a/src/Json/Flag/Decode.php b/src/Json/Flag/Decode.php new file mode 100644 index 0000000..7f0efa9 --- /dev/null +++ b/src/Json/Flag/Decode.php @@ -0,0 +1,39 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Json\Flag; + +/** + * ### PHP Runtime JSON Decoding Flags + * + * Provides JSON decoding flags used by the native PHP json_decode() function while preserving native runtime behavior. + * + * This enum exposes JSON deserialization configuration options through a consistent FireHub Runtime API without + * altering PHP JSON decoding semantics. + * @since 1.0.0 + */ +enum Decode:int { + + /** + * ### Decodes JSON objects as a PHP array + * @since 1.0.0 + */ + case OBJECT_AS_ARRAY = 1; + + /** + * ### Decodes large integers as their original string value + * @since 1.0.0 + */ + case BIGINT_AS_STRING = 2; + +} \ No newline at end of file diff --git a/src/Json/Flag/Encode.php b/src/Json/Flag/Encode.php new file mode 100644 index 0000000..2576011 --- /dev/null +++ b/src/Json/Flag/Encode.php @@ -0,0 +1,99 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Json\Flag; + +/** + * ### PHP Runtime JSON Encoding Flags + * + * Provides JSON encoding flags used by the native PHP json_encode() function while preserving native runtime behavior. + * + * This enum exposes JSON serialization configuration options through a consistent FireHub Runtime API without + * altering PHP JSON encoding semantics. + * @since 1.0.0 + */ +enum Encode:int { + + /** + * ### All < and > are converted to \u003C and \u003E + * @since 1.0.0 + */ + case HEX_TAG = 1; + + /** + * ### All & are converted to \u0026 + * @since 1.0.0 + */ + case HEX_AMP = 2; + + /** + * ### All ' are converted to \u0027 + * @since 1.0.0 + */ + case HEX_APOS = 3; + + /** + * ### All " are converted to \u0022 + * @since 1.0.0 + */ + case HEX_QUOT = 8; + + /** + * ### Outputs an object rather than an array when a non-associative array is used + * @since 1.0.0 + */ + case FORCE_OBJECT = 16; + + /** + * ### Encodes numeric strings as numbers + * @since 1.0.0 + */ + case NUMERIC_CHECK = 32; + + /** + * ### Don't escape / + * @since 1.0.0 + */ + case UNESCAPED_SLASHES = 64; + + /** + * ### Use whitespace in returned data to format it + * @since 1.0.0 + */ + case PRETTY_PRINT = 128; + + /** + * ### Encode multibyte Unicode characters literally (default is to escape as \uXXXX) + * @since 1.0.0 + */ + case UNESCAPED_UNICODE = 256; + + /** + * ### Substitute some un-encodable values instead of failing + * @since 1.0.0 + */ + case PARTIAL_OUTPUT_ON_ERROR = 512; + + /** + * ### Ensures that float values are always encoded as a float value + * @since 1.0.0 + */ + case PRESERVE_ZERO_FRACTION = 1024; + + /** + * ### The line terminators are kept unescaped when UNESCAPED_UNICODE is supplied + * @since 1.0.0 + */ + case UNESCAPED_LINE_TERMINATORS = 2048; + +} \ No newline at end of file diff --git a/src/Json/Flag/Error.php b/src/Json/Flag/Error.php new file mode 100644 index 0000000..9a697b8 --- /dev/null +++ b/src/Json/Flag/Error.php @@ -0,0 +1,99 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Json\Flag; + +/** + * ### PHP Runtime JSON Error Codes + * + * Provides JSON error codes returned by native PHP JSON processing functions while preserving native runtime behavior. + * + * This enum exposes JSON error states through a consistent FireHub Runtime API without altering PHP JSON error + * handling semantics. + * @since 1.0.0 + */ +enum Error:int { + + /** + * ### No error has occurred + * @since 1.0.0 + */ + case ERROR_NONE = 0; + + /** + * ### The maximum stack depth has been exceeded + * @since 1.0.0 + */ + case ERROR_DEPTH = 1; + + /** + * ### Occurs with underflow or with the mode mismatch + * @since 1.0.0 + */ + case ERROR_STATE_MISMATCH = 2; + + /** + * ### Control character error, possibly incorrectly encoded + * @since 1.0.0 + */ + case ERROR_CTRL_CHAR = 3; + + /** + * ### Syntax error + * @since 1.0.0 + */ + case ERROR_SYNTAX = 4; + + /** + * ### Malformed UTF-8 characters, possibly incorrectly encoded + * @since 1.0.0 + */ + case ERROR_UTF8 = 5; + + /** + * ### The object or array passed to json_encode() include recursive references and can't be encoded + * @since 1.0.0 + */ + case ERROR_RECURSION = 6; + + /** + * ### The value passed to json_encode() includes either NAN or INF + * @since 1.0.0 + */ + case ERROR_INF_OR_NAN = 7; + + /** + * ### A value of an unsupported type was given to json_encode(), such as a resource + * @since 1.0.0 + */ + case ERROR_UNSUPPORTED_TYPE = 8; + + /** + * ### A key starting with \u0000 character was in the string passed to json_decode() when decoding a JSON object into a PHP object + * @since 1.0.0 + */ + case ERROR_INVALID_PROPERTY_NAME = 9; + + /** + * ### Single unpaired UTF-16 surrogate in Unicode escape contained in the JSON string passed to json_decode() + * @since 1.0.0 + */ + case ERROR_UTF16 = 10; + + /** + * ### The value passed to json_encode() includes a non-backed enum which can't be serialized + * @since 1.0.0 + */ + case ERROR_NON_BACKED_ENUM = 11; + +} \ No newline at end of file diff --git a/src/Json/Flag/Validate.php b/src/Json/Flag/Validate.php new file mode 100644 index 0000000..be3242a --- /dev/null +++ b/src/Json/Flag/Validate.php @@ -0,0 +1,34 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Json\Flag; + +/** + * ### PHP Runtime JSON Validation Flags + * + * Provides JSON validation flags used by the native PHP json_validate() function while preserving native runtime + * behavior. + * + * This enum exposes JSON validation configuration options through a consistent FireHub Runtime API without altering + * PHP JSON validation semantics. + * @since 1.0.0 + */ +enum Validate:int { + + /** + * ### Ignore invalid UTF-8 characters + * @since 1.0.0 + */ + case INVALID_UTF8_IGNORE = 1048576; + +} \ No newline at end of file diff --git a/src/Math.php b/src/Math.php new file mode 100644 index 0000000..99fef79 --- /dev/null +++ b/src/Math.php @@ -0,0 +1,783 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Math\ { + LogBase, RoundMode +}; + +use function abs; +use function acos; +use function acosh; +use function asin; +use function asinh; +use function atan; +use function atan2; +use function atanh; +use function ceil; +use function cos; +use function cosh; +use function fdiv; +use function floor; +use function fmod; +use function deg2rad; +use function exp; +use function hypot; +use function intdiv; +use function is_finite; +use function is_infinite; +use function is_nan; +use function log; +use function log10; +use function log1p; +use function max; +use function min; +use function pow; +use function rad2deg; +use function round; +use function sin; +use function sinh; +use function sqrt; +use function tan; +use function tanh; + +/** + * ### PHP Runtime Math Utilities + * + * Provides low-level wrappers for mathematical calculations using native PHP math functions while preserving native + * runtime behavior. + * + * This component exposes mathematical operations and numeric utilities through a consistent FireHub Runtime API + * without altering PHP math semantics. + * @since 1.0.0 + */ +final class Math extends NativeRuntime { + + /** + * ### Finds whether a value is a legal finite number + * + * Checks whether the $number is legally finite on this platform. + * @since 1.0.0 + * + * @param float $number

+ * The value to check. + *

+ * + * @return bool True if number is a legal finite number within the allowed range for a PHP float on this platform, + * false otherwise. + */ + public static function isFinite (float $number):bool { + + return is_finite($number); + + } + + /** + * ### Finds whether a value is infinite + * + * Returns true if a num is infinite (positive or negative), like the result of log(0) or any value too big to fit + * into a float on this platform. + * @since 1.0.0 + * + * @param float $number

+ * The value to check. + *

+ * + * @return bool True if the number is infinite, false otherwise. + */ + public static function isInfinite (float $number):bool { + + return is_infinite($number); + + } + + /** + * ### Finds whether a value is not a number + * + * Checks whether a num is 'not a number', like the result of acos(1.01). + * @since 1.0.0 + * + * @param float $number

+ * Value to check. + *

+ * + * @return bool True if a number is 'not a number', false otherwise. + */ + public static function isNan (float $number):bool { + + return is_nan($number); + + } + + /** + * ### Integer division + * @since 1.0.0 + * + * @param int $dividend

+ * Number to be divided. + *

+ * @param non-zero-int $divisor

+ * Number which divides the $dividend. + *

+ * + * @return int The integer quotient of the division of $dividend by $divisor. + */ + public static function divideInt (int $dividend, int $divisor):int { + + return intdiv($dividend, $divisor); + + } + + /** + * ### Divides two numbers, according to IEEE 754 + * + * Returns the floating point result of dividing the num1 by the num2. + * + * If the num2 is zero, then one of INF, -INF, or NAN will be returned. + * @since 1.0.0 + * + * @param float $dividend

+ * Number to be divided. + *

+ * @param float $divisor

+ * Number which divides the $dividend. + *

+ * + * @return float The floating point result of the division of $dividend by $divisor. + */ + public static function divideFloat (float $dividend, float $divisor):float { + + return fdiv($dividend, $divisor); + + } + + /** + * ### Get the floating point remainder (modulo) of the division of the arguments + * + * Returns the floating point remainder of dividing the dividend ($dividend) by the divisor ($divisor). + * + * The remainder (r) is defined as: $dividend = i * $divisor + r, for some integer i. + * + * If $divisor is non-zero, r has the same sign as $dividend and a magnitude less than the size of $divisor. + * @since 1.0.0 + * + * @param float $dividend

+ * The dividend. + *

+ * @param float $divisor

+ * The divisor. + *

+ * + * @return float The floating point remainder (modulo) of the division for the arguments. + */ + public static function remainder (float $dividend, float $divisor):float { + + return fmod($dividend, $divisor); + + } + + /** + * ### Absolute value + * + * Returns the absolute value of $number. + * @since 1.0.0 + * + * @param float|int $number

+ * The numeric value to process. + *

+ * + * @return ($number is int ? int : float) The absolute value of number. + */ + public static function abs (float|int $number):float|int { + + return abs($number); + + } + + /** + * ### Round fractions up + * + * Returns the next highest integer value by rounding up $number if necessary. + * @since 1.0.0 + * + * @param float|int $number

+ * The value to round up. + *

+ * + * @return int Rounded number up to the next highest integer. + */ + public static function ceil (float|int $number):int { + + return (int)ceil($number); + + } + + /** + * ### Round fractions down + * + * Returns the next lowest integer value (as float) by rounding down $number if necessary. + * @since 1.0.0 + * + * @param float|int $number

+ * The value to round down. + *

+ * + * @return int Rounded number up to the next lowest integer. + */ + public static function floor (float|int $number):int { + + return (int)floor($number); + + } + + /** + * ### Rounds a float + * + * Returns the rounded value of $number to specified $precision (number of digits after the decimal point). + * + * $precision can also be negative or zero (default). + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Math\RoundMode::toNative() To get native PHP rounding mode. + * + * @param float|int $number

+ * The value to round. + *

+ * @param int $precision [optional]

+ * Number of decimal digits to round to. + * + * If the precision is positive, the num is rounded to precision significant digits after the decimal point. + * + * If the precision is negative, num is rounded to precision significant digits before the decimal point, + * in other words, to the nearest multiple of pow(10, $precision). + * + * For example, for precision of -1 num is rounded to tens, for precision of -2 to hundreds, and so on. + *

+ * @param \FireHub\Runtime\Math\RoundMode $mode [optional]

+ * Specify the mode in which rounding occurs. + *

+ * + * @return ($precision is positive-int ? float : int) Rounded number float. + */ + public static function round (float|int $number, int $precision = 0, RoundMode $mode = RoundMode::HALF_AWAY_FROM_ZERO):float|int { + + $result = round($number, $precision, $mode->toNative()); + + return $precision > 0 ? $result : (int)$result; + + } + + /** + * ### Natural logarithm + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Math\LogBase::value() To get log value. + * + * @param float|int $number

+ * The value to calculate the logarithm for. + *

+ * @param \FireHub\Runtime\Math\LogBase|float $base [optional]

+ * The optional logarithmic base to use (defaults to 'e' and so to the natural logarithm). + *

+ * + * @return float The logarithm of $number to $base, if given, or the natural logarithm. + */ + public static function log (float|int $number, float|LogBase $base = LogBase::E):float { + + return log($number, $base instanceof LogBase ? $base->value() : $base); + + } + + /** + * ### Natural logarithm of 1 + number + * + * Returns log(1 + $number), computed accurately even when $number is close to zero. + * @since 1.0.0 + * + * @param float|int $number

+ * The argument to process. + *

+ * + * @return float log(1 + num). + */ + public static function log1p (float|int $number):float { + + return log1p($number); + + } + + /** + * ### Base-10 logarithm + * + * Returns the logarithm of $number in base 10. + * @since 1.0.0 + * + * @param float|int $number

+ * The argument to process. + *

+ * + * @return float The base-10 logarithm of num. + */ + public static function log10 (float|int $number):float { + + return log10($number); + + } + + /** + * ### Find the highest value + * @since 1.0.0 + * + * @template TValue + * + * @param TValue $value

+ * Any comparable value. + *

+ * @param TValue ...$values

+ * Any comparable values. + *

+ * + * @return TValue Value considered "highest" according to standard comparisons. + * + * @caution Be careful when passing arguments of different types because the method can produce unpredictable + * results. + */ + public static function max (mixed $value, mixed ...$values):mixed { + + return max([$value, ...$values]); + + } + + /** + * ### Find the lowest value + * @since 1.0.0 + * + * @template TValue + * + * @param TValue $value

+ * Any comparable value. + *

+ * @param TValue ...$values

+ * Any comparable values. + *

+ * + * @return TValue Value considered "lowest" according to standard comparisons. + * + * @caution Be careful when passing arguments of different types because the method can produce unpredictable + * results. + */ + public static function min (mixed $value, mixed ...$values):mixed { + + return min([$value, ...$values]); + + } + + /** + * ### Exponential expression + * @since 1.0.0 + * + * @param float|int $base

+ * The base to use. + *

+ * @param float|int $exponent

+ * The exponent. + *

+ * + * @return ( + * $base is non-negative-int + * ? ($exponent is non-negative-int + * ? int + * : float) + * : float + * ) If both arguments are non-negative integers and the result can be represented as an integer, the result will + * be returned with an int type, otherwise it will be returned as a float. + * + * @note It is possible to use the ** operator instead. + */ + public static function pow (float|int $base, float|int $exponent):float|int { + + return pow($base, $exponent); + + } + + /** + * ### Converts the number in degrees to the radian equivalent + * @since 1.0.0 + * + * @param int|float $number

+ * Angular value in degrees. + *

+ * + * @return float Radian equivalent of number. + */ + public static function deg2rad (int|float $number):float { + + return deg2rad($number); + + } + + /** + * ### Converts the radian number to the equivalent number in degrees + * @since 1.0.0 + * + * @param int|float $number

+ * Radian value. + *

+ * + * @return float Equivalent of number in degrees. + */ + public static function rad2deg (int|float $number):float { + + return rad2deg($number); + + } + + /** + * ### Calculates the exponent of e + * @since 1.0.0 + * + * @param int|float $number

+ * The argument to process. + *

+ * + * @return float 'e' raised to the power of number. + * + * @note 'e' is the base of the natural system of logarithms, or approximately 2.718282. + */ + public static function exp (int|float $number):float { + + return exp($number); + + } + + /** + * ### Returns exp($number) – 1, computed in a way that is accurate even when the value of the number is close to zero + * + * Returns the equivalent of `exp($number) - 1` with improved accuracy when the value is close to zero. + * Avoids precision loss caused by subtracting two nearly equal floating-point numbers. + * @since 1.0.0 + * + * @param int|float $number

+ * The argument to process. + *

+ * + * @return float 'e' raised to the power of number. + * + * @note 'e' to the power of num minus one. + */ + public static function expm1 (int|float $number):float { + + return expm1($number); + + } + + /** + * ### Calculate the length of the hypotenuse of a right-angle triangle + * + * Method returns the length of the hypotenuse of a right-angle triangle with sides of length x and y, or the + * distance of the point (x, y) from the origin. + * + * This is equivalent to sqrt($x*$x + $y*$y). + * @since 1.0.0 + * + * @param int|float $x

+ * Length of the first side. + *

+ * @param int|float $y

+ * Length of the second side. + *

+ * + * @return float Calculated length of the hypotenuse. + */ + public static function hypot (int|float $x, int|float $y):float { + + return hypot($x, $y); + + } + + /** + * ### Square root + * @since 1.0.0 + * + * @param int|float $number

+ * The argument to process. + *

+ * + * @return float The square root of a num or the special value NAN for negative numbers. + */ + public static function sqrt (int|float $number):float { + + return sqrt($number); + + } + + /** + * ### Cosine + * + * Method returns the cosine of the $number parameter. + * + * The $number parameter is in radians. + * @since 1.0.0 + * + * @param float $number

+ * An angle in radians. + *

+ * + * @return float The cosine of an angle. + */ + public static function cos (float $number):float { + + return cos($number); + + } + + /** + * ### Arc cosine + * + * Returns the arc cosine of num in radians. + * + * Math::acos() is the inverse function of Math::cos() which means that $number == Math#cos(Math#acos + * ($number)) for every value of a that is within Math::acos() range. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float The arc cosine of the number in radians. + */ + public static function acos (float $number):float { + + return acos($number); + + } + + /** + * ### Hyperbolic cosine + * + * Returns the hyperbolic cosine of $number, defined as (exponent($number) + exponent(-$number))/2. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Hyperbolic cosine of number. + */ + public static function cosh (float $number):float { + + return cosh($number); + + } + + /** + * ### Inverse hyperbolic cosine + * + * Returns the inverse hyperbolic cosine of $number, in other words, the value whose hyperbolic cosine is $number. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Inverse hyperbolic cosine of number. + */ + public static function acosh (float $number):float { + + return acosh($number); + + } + + /** + * ### Sine + * + * Method returns the sine of the num parameter. + * + * The num parameter is in radians. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Sine of number. + */ + public static function sin (float $number):float { + + return sin($number); + + } + + /** + * ### Arc sine + * + * Returns the arc sine of $number in radians. + * + * Math#sineArc() is the inverse function of Math::sin(), which means that $num == Math#sin(Math#asin($number)) + * for every value of a that is within Math::asin() range. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float The arc sine of number in radians. + */ + public static function asin (float $number):float { + + return asin($number); + + } + + /** + * ### Hyperbolic sine + * + * Returns the hyperbolic sine of num, defined as (exponent($number) – exponent(-$number))/2. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Hyperbolic sine of number. + */ + public static function sinh (float $number):float { + + return sinh($number); + + } + + /** + * ### Inverse hyperbolic tangent + * + * Returns the inverse hyperbolic sine of $number, in other words, the value whose hyperbolic sine is $number. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float The inverse hyperbolic sine of number. + */ + public static function asinh (float $number):float { + + return asinh($number); + + } + + /** + * ### Tangent + * + * Returns the tangent of the num parameter. + * + * The num parameter is in radians. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process in radians. + *

+ * + * @return float Tangent of number. + */ + public static function tan (float $number):float { + + return tan($number); + + } + + /** + * ### Arc tangent + * + * Returns the arc tangent of num in radians. + * + * Math#atan() is the inverse function of Math::tan(), which means that $num == Math#tan(Math#atan($number)) + * for every value of a that is within Math::atan() range. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Arc tangent of num in radians. + */ + public static function atan (float $number):float { + + return atan($number); + + } + + /** + * ### Arc tangent of two variables + * + * This method calculates the arc tangent of the two variables x and y. + * + * It is similar to calculating the arc tangent of y / x, except that the signs of both arguments are used to + * determine the quadrant of the result. + * + * The function returns the result in radians, which is between -PI and PI (inclusive). + * @since 1.0.0 + * + * @param float $x

+ * Divisor parameter. + *

+ * @param float $y

+ * Dividend parameter. + *

+ * + * @return float Arc tangent of y/x in radians. + */ + public static function atan2 (float $x, float $y):float { + + return atan2($y, $x); + + } + + /** + * ### Hyperbolic tangent + * + * Returns the hyperbolic tangent of $number, defined as tanh($number)/cosh($number). + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Hyperbolic tangent of number. + */ + public static function tanh (float $number):float { + + return tanh($number); + + } + + /** + * ### Inverse hyperbolic tangent + * + * Returns the inverse hyperbolic tangent of $number, in other words, the value whose hyperbolic tangent is $number. + * @since 1.0.0 + * + * @param float $number

+ * The argument to process. + *

+ * + * @return float Inverse hyperbolic tangent of $number. + */ + public static function atanh (float $number):float { + + return atanh($number); + + } + +} \ No newline at end of file diff --git a/src/Math/LogBase.php b/src/Math/LogBase.php new file mode 100644 index 0000000..b6278b9 --- /dev/null +++ b/src/Math/LogBase.php @@ -0,0 +1,81 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Runtime\Math; + +use const M_E; +use const M_LN10; +use const M_LN2; +use const M_LOG10E; +use const M_LOG2E; + +/** + * ### PHP Runtime Logarithmic Bases + * + * Provides predefined logarithmic constants used for calculating logarithms with different mathematical bases while + * preserving native runtime behavior. + * + * This enum exposes common logarithmic base values through a consistent FireHub Runtime API. + * @since 1.0.0 + */ +enum LogBase { + + /** + * ### e + * @since 1.0.0 + */ + case E; + + /** + * ### log_2 e + * @since 1.0.0 + */ + case LOG2E; + + /** + * ### log_10 e + * @since 1.0.0 + */ + case LOG10E; + + /** + * ### log_e 2 + * @since 1.0.0 + */ + case LN2; + + /** + * ### log_e 10 + * @since 1.0.0 + */ + case LN10; + + /** + * ### Get the numerical value of the logarithmic base + * @since 1.0.0 + * + * @return float Log value. + */ + public function value ():float { + + return match ($this) { + self::E => M_E, + self::LOG2E => M_LOG2E, + self::LOG10E => M_LOG10E, + self::LN2 => M_LN2, + self::LN10 => M_LN10 + }; + + } + +} \ No newline at end of file diff --git a/src/Math/RoundMode.php b/src/Math/RoundMode.php new file mode 100644 index 0000000..3cbac5f --- /dev/null +++ b/src/Math/RoundMode.php @@ -0,0 +1,95 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime\Tests + */ + +namespace FireHub\Runtime\Math; + +use RoundingMode; + +/** + * ### PHP Runtime Number Rounding Modes + * + * Provides rounding strategies for numeric operations while preserving native runtime behavior. + * @since 1.0.0 + */ +enum RoundMode { + + /** + * ### Rounds number away from zero when it is halfway there, making 1.5 into 2 and -1.5 into -2 + * @since 1.0.0 + */ + case HALF_AWAY_FROM_ZERO; + + /** + * ### Rounds number towards zero when it is halfway there, making 1.5 into 1 and -1.5 into -1 + * @since 1.0.0 + */ + case HALF_TOWARDS_ZERO; + + /** + * ### Rounds towards the nearest even value when it is halfway there, making both 1.5 and 2.5 into 2 + * @since 1.0.0 + */ + case HALF_EVEN; + + /** + * ### Rounds number towards the nearest odd value when it is halfway there, making 1.5 into 1 and 2.5 into 3 + * @since 1.0.0 + */ + case HALF_ODD; + + /** + * ### Round to the nearest integer with a smaller or equal absolute value + * @since 1.0.0 + */ + case TOWARDS_ZERO; + + /** + * ### Round to the nearest integer with a greater or equal absolute value + * @since 1.0.0 + */ + case AWAY_FROM_ZERO; + + /** + * ### Round to the largest integer that is smaller or equal + * @since 1.0.0 + */ + case NEGATIVE_INFINITY; + + /** + * ### Round to the smallest integer that is greater or equal + * @since 1.0.0 + */ + case POSITIVE_INFINITY; + + /** + * ### Calculate the native rounding mode + * @since 1.0.0 + * + * @return RoundingMode Calculated round. + */ + public function toNative ():RoundingMode { + + return match ($this) { + self::HALF_AWAY_FROM_ZERO => RoundingMode::HalfAwayFromZero, + self::HALF_TOWARDS_ZERO => RoundingMode::HalfTowardsZero, + self::HALF_EVEN => RoundingMode::HalfEven, + self::HALF_ODD => RoundingMode::HalfOdd, + self::TOWARDS_ZERO => RoundingMode::TowardsZero, + self::AWAY_FROM_ZERO => RoundingMode::AwayFromZero, + self::NEGATIVE_INFINITY => RoundingMode::NegativeInfinity, + self::POSITIVE_INFINITY => RoundingMode::PositiveInfinity + }; + + } + +} \ No newline at end of file diff --git a/src/Number.php b/src/Number.php new file mode 100644 index 0000000..859a06a --- /dev/null +++ b/src/Number.php @@ -0,0 +1,124 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Meta\Enum\Number\Base; +use FireHub\Runtime\Exception\InvalidNumberBaseException; + +use function base_convert; +use function number_format; + +/** + * ### PHP Number Utilities + * + * Provides low-level utilities for working with numeric values, including number base conversion, representation + * transformation, and number formatting. + * + * This component provides helpers for converting numbers between different bases such as binary, octal, decimal, and + * hexadecimal, as well as formatting numbers for display. + * @since 1.0.0 + */ +final class Number extends NativeRuntime { + + /** + * ### Format a number with grouped thousands + * + * Formats a number with grouped thousands and optionally decimal digits using the rounding half-up rule. + * @since 1.0.0 + * + * @param int|float $number

+ * The number being formatted. + *

+ * @param int $decimals

+ * Sets the number of decimal digits. + * + * If 0, the decimal_separator is omitted from the return value. + * + * When the value is negative, the num is rounded to decimal significant digits before the decimal point. + *

+ * @param string $decimal_separator [optional]

+ * Sets the separator for the decimal point. + *

+ * @param string $thousands_separator [optional]

+ * Sets the separator for thousands. + *

+ * + * @return non-empty-string A formatted version of the number. + */ + public static function format (int|float $number, int $decimals, string $decimal_separator = '.', string $thousands_separator = ','):string { + + /** @var non-empty-string */ + return number_format( + $number, + $decimals, + $decimal_separator, + $thousands_separator + ); + + } + + /** + * ### Convert a number between arbitrary bases + * + * Converts a number from one base representation to another. + * + * Supported bases range from binary (base 2) to base 36. + * Digits above base 10 are represented using letters a-z. + * @since 1.0.0 + * + * @param string $number

+ * The number to convert. + * + * Any invalid characters in $number are silently ignored. As of PHP 7.4.0 supplying any invalid characters is + * deprecated. + *

+ * @param int<2, 36>|\FireHub\Core\Meta\Enum\Number\Base $from_base

+ * The base of the number in $number. + *

+ * @param int<2, 36>|\FireHub\Core\Meta\Enum\Number\Base $to_base

+ * The base to convert the number to. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidNumberBaseException If $from_base or $to_base is not between 2 and 36. + * + * @return string $number converted to base $to_base. + */ + public static function baseConverter (string $number, int|Base $from_base, int|Base $to_base):string { + + $from_base = $from_base instanceof Base + ? $from_base->value + : $from_base; + + $to_base = $to_base instanceof Base + ? $to_base->value + : $to_base; + + if ($from_base < 2 || $from_base > 36 || $to_base < 2 || $to_base > 36) { + throw new InvalidNumberBaseException( + 'The base must be between 2 and 36.', + [ + 'from_base' => $from_base, + 'to_base' => $to_base, + 'minimum' => 2, + 'maximum' => 36, + ] + ); + } + + return base_convert($number, $from_base, $to_base); + + } + +} \ No newline at end of file diff --git a/src/ObjectModel/Identity.php b/src/ObjectModel/Identity.php new file mode 100644 index 0000000..9be9a80 --- /dev/null +++ b/src/ObjectModel/Identity.php @@ -0,0 +1,89 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\ObjectModel; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function spl_object_hash; +use function spl_object_id; + +/** + * ### Object Identity Management + * + * Provides low-level utilities for retrieving unique runtime identifiers and hashes of object instances. + * + * This component exposes native PHP object identity operations used for object comparison, tracking, and indexing. + * @since 1.0.0 + */ +final class Identity extends NativeRuntime { + + /** + * ### Return the integer object handle for a given object + * + * This function returns a unique identifier for the object. + * + * The object id is unique for the lifetime of the object. + * + * Once the object is destroyed, its id may be reused for other objects. + * + * This behavior is similar to Identity::hash(). + * @since 1.0.0 + * + * @param object $object

+ * Any object. + *

+ * + * @return positive-int An integer identifier that is unique for each currently existing object and is always + * the same for each object. + * + * @note When an object is destroyed, its id may be reused for other objects. + */ + public static function id (object $object):int { + + /** @var positive-int */ + return spl_object_id($object); + + } + + /** + * ### Return hash id for a given object + * + * This function returns a unique identifier for the object. + * + * This id can be used as a hash key for storing objects or for identifying an object, as long as the object is + * not destroyed. + * + * Once the object is destroyed, its hash may be reused for other objects. + * @since 1.0.0 + * + * @param object $object

+ * Any object. + *

+ * + * @return non-empty-string A string that is unique for each currently existing object and is always the same + * for each object. + * + * @note When an object is destroyed, its hash may be reused for other objects. + * @note Object hashes should be compared for identity with === and !==, because the returned hash could be a + * numeric string. + * For example, 0000000000000e600000000000000000. + */ + public static function hash (object $object):string { + + /** @var non-empty-string */ + return spl_object_hash($object); + + } + +} \ No newline at end of file diff --git a/src/ObjectModel/Inspection.php b/src/ObjectModel/Inspection.php new file mode 100644 index 0000000..60a70ad --- /dev/null +++ b/src/ObjectModel/Inspection.php @@ -0,0 +1,166 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\ObjectModel; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function class_exists; +use function enum_exists; +use function interface_exists; +use function method_exists; +use function property_exists; +use function trait_exists; + +/** + * ### Object and Class Inspection + * + * Provides low-level utilities for inspecting classes, objects, interfaces, traits, enums, methods, and properties. + * + * This component exposes native PHP inspection operations for retrieving structural information and checking the + * existence of runtime-defined entities without introducing reflection abstractions or additional behavior. + * @since 1.0.0 + */ +final class Inspection extends NativeRuntime { + + /** + * ### Checks if a class name exists + * + * This method checks whether the given class has been defined. + * @since 1.0.0 + * + * @uses self::isEnum() To check if the class is an enum. + * + * @param class-string $name

+ * The class name. + *

+ * @param bool $autoload [optional]

+ * Whether to autoload if not already loaded. + *

+ * + * @return bool True if class exist, false otherwise. + */ + public static function isClass (string $name, bool $autoload = true):bool { + + return class_exists($name, $autoload) && !self::isEnum($name); // @phpstan-ignore argument.type + + } + + /** + * ### Checks if interface name exists + * + * Checks if the given interface has been defined. + * @since 1.0.0 + * + * @param interface-string $name

+ * The interface name. + *

+ * @param bool $autoload [optional]

+ * Whether to autoload if not already loaded. + *

+ * + * @return bool True if the interface exists, false otherwise. + */ + public static function isInterface (string $name, bool $autoload = true):bool { + + return interface_exists($name, $autoload); + + } + + /** + * ### Checks if a trait name exists + * @since 1.0.0 + * + * @param trait-string $name

+ * The trait name. + *

+ * @param bool $autoload [optional]

+ * Whether to autoload if not already loaded. + *

+ * + * @return bool True if the trait exists, false otherwise. + */ + public static function isTrait (string $name, bool $autoload = true):bool { + + return trait_exists($name, $autoload); + + } + + /** + * ### Checks if an enum name exists + * + * This method checks whether the given enum has been defined. + * @since 1.0.0 + * + * @param enum-string $name

+ * The enum name. + *

+ * @param bool $autoload [optional]

+ * Whether to autoload if not already loaded. + *

+ * + * @return bool True if enum exists, false otherwise. + */ + public static function isEnum (string $name, bool $autoload = true):bool { + + return enum_exists($name, $autoload); + + } + + /** + * ### Checks if the class method exists + * @since 1.0.0 + * + * @param class-string|object $object_or_class

+ * An object instance or a class name. + *

+ * @param non-empty-string $method

+ * The method name. + *

+ * + * @return bool True if the method given by method has been defined for the given object_or_class, false otherwise. + * + * @note Using this function will use any registered autoloader if the class is not already known. + */ + public static function methodExists (string|object $object_or_class, string $method):bool { + + return method_exists($object_or_class, $method); + + } + + /** + * ### Checks if the object or class has a property + * + * This method checks if the given property exists in the specified class. + * @since 1.0.0 + * + * @param class-string|object $object_or_class

+ * The class name or an object of the class to test for. + *

+ * @param non-empty-string $property

+ * The name of the property. + *

+ * + * @return bool True if the property exists, false if it doesn't exist. + * + * @note As opposed with isset(), Inspection::propertyExist() returns true even if the property has the value null. + * @note This method can't detect properties that are magically accessible using the __get magic method. + * @note Using this function will use any registered autoloaders if the class is not already known. + */ + public static function propertyExists (string|object $object_or_class, string $property):bool { + + return property_exists($object_or_class, $property); + + } + +} \ No newline at end of file diff --git a/src/ObjectModel/Metadata.php b/src/ObjectModel/Metadata.php new file mode 100644 index 0000000..06d639d --- /dev/null +++ b/src/ObjectModel/Metadata.php @@ -0,0 +1,161 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\ObjectModel; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\DataIs; +use FireHub\Runtime\Exception\ { + ClassAliasException, ClassDoesntExistException +}; + +use function class_alias; +use function get_class_methods; +use function get_class_vars; +use function get_mangled_object_vars; +use function get_object_vars; + +/** + * #### Object and Class Metadata + * + * Provides low-level utilities for retrieving runtime metadata from classes and objects. + * + * This component exposes native PHP metadata operations such as aliases, declared members, and internal object + * information without introducing reflection-based abstractions. + * @since 1.0.0 + */ +final class Metadata extends NativeRuntime { + + /** + * ### Creates an alias for a class + * + * Creates an alias named alias based on the user-defined class. + * + * The aliased class is exactly the same as the original class. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the original class exists before creating + * an alias. + * + * @param class-string $class

+ * The original class. + *

+ * @param class-string $alias

+ * The alias name for the class. + *

+ * @param bool $autoload [optional]

+ * Whether to autoload if the original class is not found. + *

+ * + * + * @throws \FireHub\Runtime\Exception\ClassAliasException If failed to create alias for the class. + * + * @return true True on success. + * + * @note Class names are case-insensitive in PHP, and this is reflected in this function. + * Aliases created by Metadata::alias() are declared in lowercase + * This means that for a class MyClass, the Metadata::alias('MyClass', 'My_Class_Alias') call will declare a new + * class alias named my_class_alias. + */ + public static function alias (string $class, string $alias, bool $autoload = true):true { + + return Inspection::isClass($class) && class_alias($class, $alias, $autoload) + ?: throw new ClassAliasException; + + } + + /** + * ### Gets the accessible non-static properties and their values + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the class exists before getting its + * properties. + * @uses \FireHub\Runtime\DataIs::object() To check if the $object_or_class parameter is an object. + * + * @param class-string|object $object_or_class

+ * The class name or an object instance. + *

+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return array Returns an associative array of declared properties visible from the current + * scope, with their values. + * + * @note The result depends on the current scope. + * @note Using this function will use any registered autoloader if the class is not already known. + */ + public static function properties (string|object $object_or_class):array { + + /** @var array */ + return match (true) { + DataIs::object($object_or_class) => get_object_vars($object_or_class), + default => Inspection::isClass($object_or_class) + ? get_class_vars($object_or_class) + : throw new ClassDoesntExistException + }; + + } + + /** + * ### Gets the mangled object properties + * + * Returns an array whose elements are the object's properties. + * + * The keys are the member variable names, with a few notable exceptions: private variables have the class name + * prepended to the variable name, and protected variables have a * prepended to the variable name. + * + * These prepended values have NUL bytes on either side. + * + * Uninitialized typed properties are silently discarded. + * @since 1.0.0 + * + * @param object $object

+ * An object instance. + *

+ * + * @return array An array containing all properties, regardless of visibility, of an object. + */ + public static function mangledProperties (object $object):array { + + /** @var array */ + return get_mangled_object_vars($object); + + } + + /** + * ### Gets the class or object methods names + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the class exists before getting its methods. + * @uses \FireHub\Runtime\DataIs::object() To check if the $object_or_class parameter is an object. + * + * @param class-string|object $object_or_class

+ * The class name or an object instance. + *

+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return array Returns an array of method names defined for the class, or false if the class doesn't + * exist. + * + * @note The result depends on the current scope. + */ + public static function methods (string|object $object_or_class):array { + + return Inspection::isClass(DataIs::object($object_or_class) ? $object_or_class::class : $object_or_class) + ? get_class_methods($object_or_class) + : throw new ClassDoesntExistException; + + } + +} \ No newline at end of file diff --git a/src/ObjectModel/Relation.php b/src/ObjectModel/Relation.php new file mode 100644 index 0000000..a4eb59c --- /dev/null +++ b/src/ObjectModel/Relation.php @@ -0,0 +1,216 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\ObjectModel; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\DataIs; +use FireHub\Runtime\Exception\ClassDoesntExistException; + +use function class_implements; +use function class_parents; +use function class_uses; +use function get_parent_class; +use function is_a; +use function is_subclass_of; + +/** + * ### Object and Class Relations + * + * Provides low-level utilities for resolving inheritance, implementation, and type relationships between classes, + * interfaces, traits, and objects. + * + * This component exposes native PHP relationship checks and hierarchy traversal operations while preserving native + * runtime behavior. + * @since 1.0.0 + */ +final class Relation extends NativeRuntime { + + /** + * ### Checks whether the object or class is of a given type or subtype + * + * Checks if the given $object_or_class is of this object type or has this object type as one of its supertypes. + * @since 1.0.0 + * + * @template TObject of object + * + * @param class-string|object $object_or_class

+ * A class name or an object instance. + *

+ * @param class-string $class

+ * The class or interface name. + *

+ * @param bool $autoload [optional]

+ * Whether to allow this function to load the class automatically through the __autoload magic method. + *

+ * + * @phpstan-assert-if-true TObject|class-string $object_or_class + * + * @return bool True if the object is of this object type or has this object type as one of its supertypes, + * false otherwise. + */ + public static function instanceOf (string|object $object_or_class, string $class, bool $autoload = true):bool { + + return is_a($object_or_class, $class, $autoload); + + } + + /** + * ### Checks if a class has this class as one of its parents or implements it + * + * Checks if the given object_or_class has the class $class as one of its parents or implements it. + * @since 1.0.0 + * + * @template TObject of object + * + * @param class-string|object $object_or_class

+ * The tested class. + * + * No error is generated if the class doesn't exist. + *

+ * @param class-string $class

+ * The class or interface name. + *

+ * @param bool $autoload [optional]

+ * Whether to allow this function to load the class automatically through the __autoload magic method. + *

+ * + * @phpstan-assert-if-true TObject $object_or_class + * + * @return bool True if the object is of this object or lass type or has this object type as one of its supertypes, + * false otherwise. + */ + public static function isSubClassOf (string|object $object_or_class, string $class, bool $autoload = true):bool { + + return is_subclass_of($object_or_class, $class, $autoload); + + } + + /** + * ### Retrieves the parent class name for an object or class + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the class exists before getting its parent. + * @uses \FireHub\Runtime\DataIs::object() To check if the $object_or_class parameter is an object. + * + * @param class-string|object $object_or_class

+ * The tested object or class name. + * + * This parameter is optional if called from the object's method. + *

+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return class-string|false The name of the parent class for the class that $object_or_class is an instance + * or the name, or false if object_or_class doesn't have a parent. + */ + public static function parentClass (string|object $object_or_class):string|false { + + return Inspection::isClass(DataIs::object($object_or_class) ? $object_or_class::class : $object_or_class) + ? get_parent_class($object_or_class) + : throw new ClassDoesntExistException; + + } + + /** + * ### Return the parent classes of the given class + * + * This function returns an array with the name of the parent classes for the given object_or_class. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the class exists before getting its parents. + * @uses \FireHub\Runtime\DataIs::object() To check if the $object_or_class parameter is an object. + * + * @param class-string|object $object_or_class

+ * An object (class instance) or a string (class or interface name). + *

+ * @param bool $autoload [optional]

+ * Whether to allow this function to load the class automatically through the __autoload magic method. + *

+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return array An array on success. + */ + public static function parents (object|string $object_or_class, bool $autoload = true):array { + + /** @var array */ + return Inspection::isClass(DataIs::object($object_or_class) ? $object_or_class::class : $object_or_class) + ? class_parents($object_or_class, $autoload) + : throw new ClassDoesntExistException; + + } + + /** + * ### Return the interfaces which are implemented by the given class or interface + * + * This function returns an array with the names of the interfaces that the given object_or_class and its parents + * implement. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the class exists before getting its + * interfaces. + * @uses \FireHub\Runtime\DataIs::object() To check if the $object_or_class parameter is an object. + * + * @param class-string|object $object_or_class

+ * An object (class instance) or a string (class or interface name). + *

+ * @param bool $autoload [optional]

+ * Whether to allow this function to load the class automatically through the __autoload magic method. + *

+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return array An array. + */ + public static function implements (object|string $object_or_class, bool $autoload = true):array { + + /** @var array */ + return Inspection::isClass(DataIs::object($object_or_class) ? $object_or_class::class : $object_or_class) + ? class_implements($object_or_class, $autoload) + : throw new ClassDoesntExistException; + + } + + /** + * ### Return the traits used by the given class + * + * This function returns an array with the names of the traits that the given object_or_class uses. + * + * This does, however, not include any traits used by a parent class. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\ObjectModel\Inspection::isClass() To check if the class exists before getting its traits. + * @uses \FireHub\Runtime\DataIs::object() To check if the $object_or_class parameter is an object. + * + * @param class-string|object $object_or_class

+ * An object (class instance) or a string (class or interface name). + *

+ * @param bool $autoload [optional]

+ * Whether to allow this function to load the class automatically through the __autoload magic method. + *

+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return array An array. + */ + public static function uses (object|string $object_or_class, bool $autoload = true):array { + + /** @var array */ + return Inspection::isClass(DataIs::object($object_or_class) ? $object_or_class::class : $object_or_class) + ? class_uses($object_or_class, $autoload) + : throw new ClassDoesntExistException; + + } + +} \ No newline at end of file diff --git a/src/Random.php b/src/Random.php new file mode 100644 index 0000000..5c9fc5e --- /dev/null +++ b/src/Random.php @@ -0,0 +1,182 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + RandomByteLengthTooSmallException, RandomMaximumBelowMinimumException, RandomNumberAboveGeneratorMaximumException, + RandomNumberBelowMinimumException, SecureRandomBytesException, SecureNumberException +}; +use Random\RandomException; + +use function mt_getrandmax; +use function mt_rand; +use function random_bytes; +use function random_int; + +/** + * ### PHP Runtime Random Utilities + * + * Provides low-level wrappers for generating pseudo-random and cryptographically secure random values using native + * PHP random functions while preserving native runtime behavior. + * + * This component exposes native random number and random byte generation through a consistent FireHub Runtime API + * without altering PHP randomness semantics. + * @since 1.0.0 + */ +final class Random extends NativeRuntime { + + /** + * ### Generate a random value via the Mersenne Twister Random Number Generator + * @since 1.0.0 + * + * @param non-negative-int $min [optional]

+ * Optional lowest value to be returned. + *

+ * @param null|non-negative-int $max [optional]

+ * Optional highest value to be returned. + *

+ * + * @throws \FireHub\Runtime\Exception\RandomNumberBelowMinimumException If $min is less than 0. + * @throws \FireHub\Runtime\Exception\RandomMaximumBelowMinimumException If $max is less than $min. + * @throws \FireHub\Runtime\Exception\RandomNumberAboveGeneratorMaximumException If $max is greater than + * mt_getrandmax(). + * + * @return non-negative-int A random integer value between min and max. + */ + public static function number (int $min = 0, ?int $max = null):int { + + if ($min < 0) + throw new RandomNumberBelowMinimumException( + 'The minimum value must be greater than or equal to zero.', + [ + 'minimum' => 0, + 'value' => $min, + ] + ); + + if ($max !== null && $max < $min) + throw new RandomMaximumBelowMinimumException( + 'The maximum value must be greater than or equal to the minimum value.', + [ + 'minimum' => $min, + 'maximum' => $max, + ] + ); + + if ($max !== null && $max > $maximum = mt_getrandmax()) + throw new RandomNumberAboveGeneratorMaximumException( + 'The maximum value must be less than or equal to the maximum value supported by the generator.', + [ + 'maximum' => $maximum, + 'value' => $max, + ] + ); + + return mt_rand($min, $max ?? ($maximum ?? 0)); + + } + + /** + * ### Get a cryptographically secure, uniformly selected integer + * + * The randomness generated by this function is suitable for all applications, including the generation of + * long-term secrets, such as encryption keys. + * @since 1.0.0 + * + * @param int $min

+ * Optional lowest value to be returned. + *

+ * @param int $max

+ * Optional highest value to be returned. + *

+ * + * @throws \FireHub\Runtime\Exception\RandomMaximumBelowMinimumException If $max is less than $min. + * @throws \FireHub\Runtime\Exception\SecureNumberException If a cryptographically secure source of randomness is + * unavailable. + * + * @return int A cryptographically secure, uniformly selected integer from the closed interval [min, max]. + * Both min and max are possible return values. + * + * @caution This method is significantly slower than non-cryptographic random number generators like Random::number. + */ + public static function secureNumber (int $min, int $max):int { + + if ($max < $min) + throw new RandomMaximumBelowMinimumException; + + try { + + return random_int($min, $max); + + } catch (RandomException $e) { + + throw new SecureNumberException( + 'Failed to generate a cryptographically secure random number.', + previous: $e + ); + + } + + } + + /** + * ### Get cryptographically secure random bytes + * + * Generates a string containing uniformly selected random bytes with the requested length. + * + * As the returned bytes are selected completely randomly, the resulting string is likely to contain unprintable + * characters or invalid UTF-8 sequences. It may be necessary to encode it before transmission or display. + * + * The randomness generated by this function is suitable for all applications, including the generation of + * long-term secrets, such as encryption keys. + * @since 1.0.0 + * + * @param positive-int $length

+ * The length of the random string that should be returned in bytes; must be 1 or greater. + *

+ * + * @throws \FireHub\Runtime\Exception\RandomByteLengthTooSmallException If the length is less than 1. + * @throws \FireHub\Runtime\Exception\SecureRandomBytesException If a cryptographically secure source of randomness + * is unavailable. + * + * @return non-empty-string A string containing the requested number of cryptographically secure random bytes. + */ + public static function bytes (int $length):string { + + if ($length < 1) + throw new RandomByteLengthTooSmallException( + 'The length of the random string must be greater than zero.', + [ + 'length' => $length, + 'minimum' => 1, + ] + ); + + try { + + return random_bytes($length); + + } catch (RandomException $e) { + + throw new SecureRandomBytesException( + 'Failed to generate a cryptographically secure random string.', + previous: $e + ); + + } + + } + +} \ No newline at end of file diff --git a/src/ResourceManager.php b/src/ResourceManager.php new file mode 100644 index 0000000..144e0bd --- /dev/null +++ b/src/ResourceManager.php @@ -0,0 +1,100 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Type\Resource as ResourceType; + +use function get_resource_id; +use function get_resource_type; +use function get_resources; + +/** + * ### PHP Runtime Resource Utilities + * + * Provides low-level wrappers for inspecting PHP resources, including retrieving resource identifiers, resource types, + * and currently active resources while preserving native runtime behavior. + * + * This component exposes PHP resource management capabilities through a consistent FireHub Runtime API without + * altering native resource semantics. + * @since 1.0.0 + */ +final class ResourceManager extends NativeRuntime { + + /** + * ### Returns an integer identifier for the given resource + * + * This function provides a type-safe way of generating the integer identifier for a resource. + * @since 1.0.0 + * + * @param resource $resource

+ * The evaluated resource handle. + *

+ * + * @return positive-int The identifier for the given resource. + * + * @phpstan-ignore class.nameCase + */ + public static function id (mixed $resource):int { + + /** @var positive-int */ + return get_resource_id($resource); + + } + + /** + * ### Gets the resource type + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Resource::UNKNOWN If the resource type is unknown. + * + * @param resource $resource

+ * The evaluated resource handle. + *

+ * + * @return \FireHub\Runtime\Type\Resource Resource type or null if is not a resource. + */ + public static function type (mixed $resource):ResourceType { + + return ResourceType::tryFrom(get_resource_type($resource) ?? ResourceType::UNKNOWN->value) // @phpstan-ignore nullCoalesce.expr + ?? ResourceType::UNKNOWN; + + } + + /** + * ### Get active resources + * + * Returns an array of all currently active resources, optionally filtered by resource type. + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Resource::UNKNOWN If the resource type is unknown. + * @uses \FireHub\Runtime\Arr\Transform::map() To transform the array of resource identifiers into an array of + * resource types. + * + * @param null|\FireHub\Runtime\Type\Resource $type [optional]

+ * If defined, this will cause the method to only return resources of the given type. + *

+ * + * @return array Resource type or null if is not a resource. + */ + public static function active (?ResourceType $type = null):array { + + return Arr\Transform::map( + get_resources($type?->value), + static fn($value) => ResourceType::tryFrom(get_resource_type($value)) ?? ResourceType::UNKNOWN, + ); + + } + +} \ No newline at end of file diff --git a/src/Shutdown.php b/src/Shutdown.php new file mode 100644 index 0000000..5463d6e --- /dev/null +++ b/src/Shutdown.php @@ -0,0 +1,73 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function register_shutdown_function; + +/** + * ### PHP Runtime Shutdown Utilities + * + * Provides low-level wrappers for registering shutdown callbacks using native PHP shutdown handling mechanisms while + * preserving runtime behavior. + * + * This component exposes shutdown execution hooks through a consistent FireHub Runtime API without altering PHP + * shutdown lifecycle semantics. + * @since 1.0.0 + */ +final class Shutdown extends NativeRuntime { + + /** + * ### Register a function for execution on shutdown + * + * Registers a callback to be executed after script execution finishes or exit() is called. + * + * Multiple calls to this method can be made, and each will be called in the same order as they were registered. + * + * If you call exit() within one registered shutdown function, processing will stop completely, and no other + * registered shutdown functions will be called. + * + * Shutdown functions may also call Shutdown::register() themselves to add a shutdown function to the end of + * the queue. + * @since 1.0.0 + * + * @param callable $callback

+ * The shutdown callback to register. + * + * The shutdown callbacks are executed as part of the request, so it is possible to send output from them and + * access output buffers. + *

+ * @param mixed ...$arguments

+ * It is possible to pass parameters to the shutdown function by passing additional parameters. + *

+ * + * @return void + * + * @note The working directory of the script can change inside the shutdown function under some web servers, + * for example, Apache. + * @note Shutdown functions will not be executed if the process is killed with a SIGTERM or SIGKILL signal. + * While you can't intercept a SIGKILL, you can use pcntl_signal() to install a handler for a SIGTERM which uses + * exit() to end cleanly. + * @note Shutdown functions run separately from the time tracked by max_execution_time. + * That means even if a process is terminated for running too long, shutdown functions will still be called. + * Additionally, if the max_execution_time runs out while a shutdown function is running, it will not be terminated. + */ + public static function register (callable $callback, mixed ...$arguments):void { + + register_shutdown_function($callback, ...$arguments); + + } + +} \ No newline at end of file diff --git a/src/SplAutoload.php b/src/SplAutoload.php new file mode 100644 index 0000000..cbe4798 --- /dev/null +++ b/src/SplAutoload.php @@ -0,0 +1,144 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ { + RegisterAutoloadFailedException, UnregisterAutoloadFailedException +}; + +/** + * ### PHP Runtime Autoloading Utilities + * + * Provides low-level wrappers for PHP SPL autoloading functions, including registering, unregistering, invoking, and + * inspecting autoload callbacks while preserving native runtime behavior. + * + * This component exposes PHP autoloading capabilities through a consistent FireHub Runtime API without altering + * autoload execution semantics. + * @since 1.0.0 + */ +final class SplAutoload extends NativeRuntime { + + /** + * ### Register a callback function as an autoloader + * + * Register a function with the spl provided autoloaded queue. + * + * If the queue is not yet activated, it will be activated. + * + * If there must be multiple autoload functions, this method allows for this. + * + * It effectively creates a queue of autoload functions and runs through each of them in the order they are defined. + * @since 1.0.0 + * + * @param null|callable(string):void $callback [optional]

+ * The autoload function being registered. + * + * If no callback is provided, then the default autoloader will be used. + *

+ * @param bool $prepend [optional]

+ * Whether to prepend the autoloader on the stack instead of appending it. + *

+ * + * @throws \FireHub\Runtime\Exception\RegisterAutoloadFailedException If failed to register a callback function as + * an autoloader. + * + * @return true True if autoloader was registered. + */ + public static function register (?callable $callback = null, bool $prepend = false):true { + + return spl_autoload_register($callback, true, $prepend) + ?: throw new RegisterAutoloadFailedException; + + } + + /** + * ### Unregister autoload implementation + * + * Removes a function from the autoloaded queue. + * + * If the queue is activated and empty after removing the given function, then it will be deactivated. + * + * When this function results in the queue being deactivated, any autoload function that previously existed will + * not be reactivated. + * @since 1.0.0 + * + * @param callable(string):void $callback

+ * The autoload function that will be unregistered. + *

+ * + * @throws \FireHub\Runtime\Exception\UnregisterAutoloadFailedException If failed to unregister autoloader + * implementation. + * + * @return true True if autoloader was unregistered. + */ + public static function unregister (callable $callback):true { + + return spl_autoload_unregister($callback) + ?: throw new UnregisterAutoloadFailedException; + + } + + /** + * ### Get all registered autoload functions + * @since 1.0.0 + * + * @return list An array of all registered autoload functions, or if no function is registered, + * or autoloaded queue is not activated; then the return value will be an empty array. + */ + public static function functions ():array { + + return spl_autoload_functions(); + + } + + /** + * ### Try all registered autoload functions to load the requested class + * @since 1.0.0 + * + * @param class-string $class

+ * Fully qualified class name that is being called. + *

+ * + * @return void + * + * @note This method can be used to manually search for a class or interface using the registered autoloader + * functions. + */ + public static function load (string $class):void { + + spl_autoload_call($class); + + } + + /** + * ### Register and return default file extensions for the default autoloader + * @since 1.0.0 + * + * @param null|string $file_extensions [optional]

+ * If null, it simply returns the current list of extensions each separated by comma. + * + * To modify the list of file extensions, invoke the functions with the new list of file extensions to use in a + * single string with each extension separated by comma. + *

+ * + * @return string A list of default file extensions for the default autoloader. + */ + public static function extensions (?string $file_extensions = null):string { + + return spl_autoload_extensions($file_extensions); + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Access.php b/src/Str/MB/Access.php new file mode 100644 index 0000000..42865e5 --- /dev/null +++ b/src/Str/MB/Access.php @@ -0,0 +1,213 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Exception\StringSplitLengthException; + +use function mb_str_split; +use function mb_strrchr; +use function mb_strrichr; +use function mb_stristr; +use function mb_strstr; +use function mb_substr; +use function mb_substr_count; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Access + * + * Provides runtime wrappers for accessing multibyte string data, including character positions, character extraction, + * and encoding-aware string element access while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for multibyte string access + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Access extends NativeRuntime { + + /** + * ### Get part of string + * + * Performs a multibyte safe Access::part() operation based on the number of characters. + * Position is counted from the beginning of $string. + * The first character's position is 0. + * The second character's position is 1, and so on. + * @since 1.0.0 + * + * @param string $string

+ * The string to extract the substring from. + *

+ * @param int $start

+ * If start is non-negative, the returned string will start at the start position in string, counting from zero. + * + * For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', + * and so forth. + * + * If the start is negative, the returned string will start at the start character from the end of the string. + *

+ * @param null|int $length [optional]

+ * Maximum number of characters to use from string. + * If omitted or NULL is passed, extract all characters to the end of the string. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return string The portion of string specified by the start and length parameters. + */ + public static function part (string $string, int $start, ?int $length = null, ?Encoding $encoding = null):string { + + return mb_substr($string, $start, $length, $encoding?->value); + + } + + /** + * ### Get the number of times the searched substring occurs in the string + * @since 1.0.0 + * + * @param string $string

+ * The string being checked. + *

+ * @param string $search

+ * The string being found. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return non-negative-int The number of times the searched substring occurs in the string. + */ + public static function partCount (string $string, string $search, ?Encoding $encoding = null):int { + + return mb_substr_count($string, $search, $encoding?->value); + + } + + /** + * ### Finds the last occurrence of a character in a string within another + * + * This function finds the last occurrence of a $find in the $string and returns the portion of $string. + * @since 1.0.0 + * + * @param string $string

+ * The string being searched. + *

+ * @param string $character

+ * String to find. + *

+ * @param bool $before_needle [optional]

+ * If true, return the part of the string before the last occurrence (excluding the find string). + *

+ * @param bool $case_sensitive [optional]

+ * Is string to find case-sensitive or not. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return string|false The portion of string, or false if the $find is not found. + */ + public static function lastCharacter (string $string, string $character, bool $before_needle = false, bool $case_sensitive = true, ?Encoding $encoding = null):string|false { + + if ($case_sensitive) return mb_strrchr($string, $character, $before_needle, $encoding?->value); + + return mb_strrichr($string, $character, $before_needle, $encoding?->value); + + } + + /** + * ### Find the first occurrence of a string + * + * Returns part of $string starting from and including the first occurrence of $find to the end of $string. + * @since 1.0.0 + * + * @param string $find

+ * String to find. + *

+ * @param string $string

+ * The string being searched. + *

+ * @param bool $before_needle [optional]

+ * If true, return the part of the string before the first occurrence (excluding the find string). + *

+ * @param bool $case_sensitive [optional]

+ * Is string to find case-sensitive or not. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return string|false The portion of string or false if the $find is not found. + */ + public static function firstOccurrence (string $string, string $find, bool $before_needle = false, bool $case_sensitive = true, ?Encoding $encoding = null):string|false { + + if ($case_sensitive) return mb_strstr($string, $find, $before_needle, $encoding?->value); + + return mb_stristr($string, $find, $before_needle, $encoding?->value); + + } + + /** + * ### Given a multibyte string, return an array of its characters + * + * This function will return an array of strings, it is a version of MB::split() with support for encodings of + * variable character size as well as fixed-size encodings of 1,2 or 4 byte characters. + * + * If the $length parameter is specified, the string is broken down into chunks of the specified length in + * characters (not bytes). + * + * The $encoding parameter can be optionally specified, and it is good practice to do so. + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * @param positive-int $length [optional]

+ * Maximum length of the chunk. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @throws \FireHub\Runtime\Exception\StringSplitLengthException If the $length parameter is less than 1. + * + * @return list If the optional $length parameter is specified, the returned array will be broken + * down into chunks with each being $length in length, except the final chunk, which may be shorter if the string + * doesn't divide evenly. + * + * The default $length is 1, meaning every chunk will be one character in size. + */ + public static function split (string $string, int $length = 1, ?Encoding $encoding = null):array { + + return $length >= 1 + ? mb_str_split($string, $length, $encoding?->value) + : throw new StringSplitLengthException( + 'The split length must be greater than zero.', + [ + 'string' => $string, + 'length' => $length, + 'encoding' => $encoding?->value, + 'minimum' => 1, + ] + ); + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Casing.php b/src/Str/MB/Casing.php new file mode 100644 index 0000000..f6fea94 --- /dev/null +++ b/src/Str/MB/Casing.php @@ -0,0 +1,98 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Type\Str\CaseMode; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Casing + * + * Provides runtime wrappers for changing the letter case of multibyte string data using encoding-aware character + * transformation operations while preserving native PHP multibyte behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for multibyte string case + * transformation operations with support for Unicode-aware character processing. + * @since 1.0.0 + */ +final class Casing extends NativeRuntime { + + /** + * ### Perform case folding on a string + * + * Performs case folding on a string, converted in the way specified by $caseFolding. + * @since 1.0.0 + * + * @param string $string

+ * The string being converted. + *

+ * @param \FireHub\Runtime\Type\Str\CaseMode $case_mode

+ * The mode of the conversion. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return ( + * $case_mode is CaseMode::UPPER + * ? uppercase-string + * : ($case_mode is CaseMode::LOWER + * ? lowercase-string + * : string) + * ) Converted string. + */ + public static function convert (string $string, CaseMode $case_mode, ?Encoding $encoding = null):string { + + return mb_convert_case($string, $case_mode->value, $encoding?->value); + + } + + /** + * ### Make the first character of a string uppercased + * @since 1.0.0 + * + * @param string $string

+ * The string being converted. + *

+ * + * @return ($string is empty ? '' : non-empty-string) String with the first character uppercased. + */ + public static function capitalize (string $string):string { + + return mb_ucfirst($string); + + } + + /** + * ### Make the first character of string lowercased + * + * Returns a string with the first character of $string lowercased if that character is an ASCII character in the + * range "A" (0x41) to "Z" (0x5a). + * @since 1.0.0 + * + * @param string $string

+ * The string being converted. + *

+ * + * @return ($string is empty ? '' : non-empty-string) String with the first character lowercased. + */ + public static function uncapitalize (string $string):string { + + return mb_lcfirst($string); + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Configuration.php b/src/Str/MB/Configuration.php new file mode 100644 index 0000000..f864a4c --- /dev/null +++ b/src/Str/MB/Configuration.php @@ -0,0 +1,68 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Exception\InvalidEncodingException; + +use function mb_internal_encoding; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Configuration + * + * Provides runtime wrappers for configuring multibyte string behavior, including internal character encoding + * settings used by the PHP mbstring extension. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for managing multibyte string + * runtime configuration while preserving native PHP behavior, encoding support, and runtime performance. + * @since 1.0.0 + */ +final class Configuration extends NativeRuntime { + + /** + * ### Set/Get internal character encoding + * @since 1.0.0 + * + * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Encoding is the character encoding name used for the HTTP input character encoding conversion, HTTP output + * character encoding conversion, and the default character encoding for string functions defined by the mbstring + * module. + * + * You should notice that the internal encoding is totally different from the one for multibyte regex. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException If the current runtime encoding is not supported by FireHub. + * + * @return ($encoding is null ? \FireHub\Core\Type\Str\Encoding : true) If encoding is set, then + * returns true. + * In this case, the character encoding for multibyte regex is NOT changed. + * If encoding is omitted, then the current character encoding name is returned. + */ + public static function encoding (?Encoding $encoding = null):true|Encoding { + + return $encoding !== null + ? mb_internal_encoding($encoding->value) + : (($new_encoding = Encoding::tryFrom($internal_encoding = mb_internal_encoding())) !== null + ? $new_encoding + : throw new InvalidEncodingException( + 'Unsupported internal encoding returned by mbstring.', + [ + 'encoding' => $internal_encoding, + ] + )); + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Inspection.php b/src/Str/MB/Inspection.php new file mode 100644 index 0000000..2aa2d45 --- /dev/null +++ b/src/Str/MB/Inspection.php @@ -0,0 +1,114 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Arr; +use FireHub\Core\Type\Str\Encoding; + +use function mb_check_encoding; +use function mb_detect_encoding; +use function mb_list_encodings; +use function mb_strlen; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Inspection + * + * Provides runtime wrappers for inspecting multibyte string data, including character length, encoding validation, + * encoding detection, and available character encoding information while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for multibyte string inspection + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Inspection extends NativeRuntime { + + /** + * ### Get string length + * @since 1.0.0 + * + * @param string $string

+ * The string being measured for length. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return non-negative-int String length. + */ + public static function length (string $string, ?Encoding $encoding = null):int { + + return mb_strlen($string, $encoding?->value); + + } + + /** + * ### Check if strings are valid for the specified encoding + * @since 1.0.0 + * + * @param string $string

+ * The string to check encoding on. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding

+ * The expected encoding. + *

+ * + * @return bool True on success or false on failure. + */ + public static function checkEncoding (string $string, ?Encoding $encoding = null):bool { + + return mb_check_encoding($string, $encoding?->value); + + } + + /** + * ### Detect character encoding + * + * Detects the most likely character encoding for string from an ordered list of candidates. + * @since 1.0.0 + * + * @uses \FireHub\Core\Type\Str\Encoding::cases() To get the Encoding enum cases. + * @uses \FireHub\Runtime\Arr\Access::column() To get the encoding values from the Encoding enum. + * + * @param string $string

+ * The string to detect encoding. + *

+ * + * @return null|\FireHub\Core\Type\Str\Encoding The detected character encoding, or null if the string + * is not valid in any of the listed encodings. + */ + public static function detectEncoding (string $string):?Encoding { + + $encodings = Arr\Access::column(Encoding::cases(), 'value'); + + return Encoding::tryFrom( + mb_detect_encoding($string, $encodings, true) ?: '' + ); + + } + + /** + * ### List of all supported encodings + * @since 1.0.0 + * + * @return non-empty-list Returns a numerically indexed array of all available encodings. + */ + public static function listEncodings ():array { + + return mb_list_encodings(); + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Regex.php b/src/Str/MB/Regex.php new file mode 100644 index 0000000..7479071 --- /dev/null +++ b/src/Str/MB/Regex.php @@ -0,0 +1,205 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Exception\ { + InvalidEncodingException, InvalidPatternException +}; + +use function mb_ereg; +use function mb_ereg_replace; +use function mb_ereg_replace_callback; +use function mb_eregi; +use function mb_eregi_replace; +use function mb_regex_encoding; +use function mb_split; + +/** + * ### Multibyte Regular Expression Utilities + * + * Provides low-level wrappers for multibyte regular expression operations using PHP's mbstring regular expression + * functions while preserving native runtime behavior. + * @since 1.0.0 + */ +final class Regex extends NativeRuntime { + + /** + * ### Perform a regular expression match + * + * Searches subject for a match to the regular expression given in a pattern. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param string $string

+ * The string being evaluated. + *

+ * @param bool $case_sensitive [optional]

+ * Case-sensitive match. + *

+ * @param mixed &$result [optional]

+ * Case-sensitive match. + *

+ * @param-out list $result + * + * @return bool True if the string matches the regular expression pattern, false if not. + */ + public static function match (string $pattern, string $string, bool $case_sensitive = true, mixed &$result = null):bool { + + return $case_sensitive + ? mb_ereg($pattern, $string, $result) // @phpstan-ignore paramOut.type + : mb_eregi($pattern, $string, $result); // @phpstan-ignore paramOut.type + + } + + /** + * ### Perform a regular expression search and replace + * + * Searches $subject for matches to $pattern and replaces them with $replacement. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param string $replacement

+ * The string to replace. + *

+ * @param string $string

+ * The string being evaluated. + *

+ * @param bool $case_sensitive [optional]

+ * Case-sensitive replace type. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If an error occurred while performing a regular + * expression search and replace type. + * @throws \FireHub\Runtime\Exception\InvalidEncodingException If string is not valid for the current encoding. + * + * @return string Replaced string. + * + * @warning Never use the e modifier when working on untrusted input. + * No automatic escaping will happen (as known from MB::Replace()). + * Not taking care of this will most likely create remote code execution vulnerabilities in your application. + * @note The internal encoding or the character encoding specified by encoding() will be used as character + * encoding for this function. + */ + public static function replace (string $pattern, string $replacement, string $string, bool $case_sensitive = true):string { + + $replaced = ($case_sensitive + ? mb_ereg_replace($pattern, $replacement, $string) + : mb_eregi_replace($pattern, $replacement, $string) + ); + + return $replaced !== false + ? ($replaced ?? throw new InvalidEncodingException) + : throw new InvalidPatternException; + + } + + /** + * ### Perform a regular expression search and replace using a callback + * + * Searches $subject for matches to $pattern and replaces them with $replacement. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param callable(array $matches):string $callback

+ * A callback that will be called and passed an array of matched elements in the subject string. + * + * The callback should return the replacement string. + * + * This is the callback signature. + *

+ * @param string $string

+ * The string being evaluated. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If an error occurred while performing a regular + * expression search and replace type. + * @throws \FireHub\Runtime\Exception\InvalidEncodingException If string is not valid for the current encoding. + * + * @return string Replaced string. + */ + public static function replaceUsing (string $pattern, callable $callback, string $string):string { + + $replaced = mb_ereg_replace_callback($pattern, $callback, $string); + + return $replaced !== false + ? ($replaced ?? throw new InvalidEncodingException) + : throw new InvalidPatternException; + + } + + /** + * ### Split string by a regular expression + * + * Split the given string by a regular expression. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param string $string

+ * The input string. + *

+ * @param int $limit [optional]

+ * The maximum possible replacements for each pattern in each subject string. + * + * Defaults to -1 (no limit). + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If error while performing a regular expression split. + * + * @return list Array containing substrings of $string split along boundaries matched by $pattern. + */ + public static function split (string $pattern, string $string, int $limit = -1):array { + + return mb_split($pattern, $string, $limit) + ?: throw new InvalidPatternException; + + } + + /** + * ### Set/Get character encoding for multibyte regex + * @since 1.0.0 + * + * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException If encoding is invalid or failed to get regex + * encoding. + * + * @return ($encoding is null ? \FireHub\Core\Type\Str\Encoding : true) If encoding is set, then returns + * true. In this case, the internal character encoding is NOT changed. If encoding is omitted, then the current + * character encoding name for a multibyte regex is returned. + */ + public static function encoding (?Encoding $encoding = null):true|Encoding { + + return match ($regex_encoding = mb_regex_encoding($encoding?->value)) { + true => true, + false => throw new InvalidEncodingException, + default => Encoding::tryFrom($regex_encoding) + ?? throw new InvalidEncodingException + }; + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Search.php b/src/Str/MB/Search.php new file mode 100644 index 0000000..a2af8db --- /dev/null +++ b/src/Str/MB/Search.php @@ -0,0 +1,100 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Str\Encoding; + +use function mb_stripos; +use function mb_strpos; +use function mb_strripos; +use function mb_strrpos; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Search + * + * Provides runtime wrappers for searching within multibyte string data, including encoding-aware substring lookup, + * character occurrence detection, position retrieval, and string matching operations while preserving native PHP + * behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for character-aware string search + * operations with support for Unicode and multibyte encodings without introducing domain logic, framework coupling, + * or additional abstraction overhead. + * @since 1.0.0 + */ +final class Search extends NativeRuntime { + + /** + * ### Find the position of the first occurrence for a substring in a string + * @since 1.0.0 + * + * @param string $search

+ * A string to find position. + *

+ * @param string $string

+ * The string to search in. + *

+ * @param bool $case_sensitive [optional]

+ * Search case-sensitive position. + *

+ * @param int $offset [optional]

+ * If specified, search will start this number of characters counted from the beginning of the string. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return false|non-negative-int Numeric position of the first occurrence or false if none exist. + */ + public static function firstPosition (string $search, string $string, bool $case_sensitive = true, int $offset = 0, ?Encoding $encoding = null):false|int { + + if ($case_sensitive) return mb_strpos($string, $search, $offset, $encoding?->value); + + return mb_stripos($string, $search, $offset, $encoding?->value); + + } + + /** + * ### Find the position of the last occurrence for a substring in a string + * @since 1.0.0 + * + * @param string $search

+ * A string to find position. + *

+ * @param string $string

+ * The string to search in. + *

+ * @param bool $case_sensitive [optional]

+ * Search case-sensitive position. + *

+ * @param int $offset [optional]

+ * If specified, search will start this number of characters counted from the beginning of the string. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @return false|non-negative-int Numeric position of the last occurrence or false if none exist. + */ + public static function lastPosition (string $search, string $string, bool $case_sensitive = true, int $offset = 0, ?Encoding $encoding = null):false|int { + + if ($case_sensitive) return mb_strrpos($string, $search, $offset, $encoding?->value); + + return mb_strripos($string, $search, $offset, $encoding?->value); + + } + +} \ No newline at end of file diff --git a/src/Str/MB/Transform.php b/src/Str/MB/Transform.php new file mode 100644 index 0000000..9cdadd9 --- /dev/null +++ b/src/Str/MB/Transform.php @@ -0,0 +1,197 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\MB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Core\Meta\Enum\Side; +use FireHub\Runtime\Exception\ { + EmptyPadException, EncodingConversionFailedException +}; + +use const STR_PAD_BOTH; +use const STR_PAD_LEFT; +use const STR_PAD_RIGHT; + +use function mb_convert_encoding; +use function mb_ltrim; +use function mb_rtrim; +use function mb_str_pad; +use function mb_trim; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Transform + * + * Provides runtime wrappers for transforming multibyte string data using encoding-aware character manipulation + * operations while preserving native PHP multibyte behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for multibyte string + * transformation operations with support for Unicode-aware character processing. + * @since 1.0.0 + */ +final class Transform extends NativeRuntime { + + /** + * ### Pad a multibyte string to a certain length with another multibyte string + * + * This method returns the $string padded on the left, the right, or both sides to the specified padding length. + * + * If the optional argument $pad is not supplied, the $string is padded with spaces; otherwise it is padded with + * characters from $pad up to the limit. + * @since 1.0.0 + * + * @uses \FireHub\Core\Meta\Enum\Side::RIGHT If padding string to the right. + * @uses \FireHub\Core\Meta\Enum\Side::LEFT If padding string to the left. + * @uses \FireHub\Core\Meta\Enum\Side::BOTH If padding string on the both sides. + * + * @param string $string

+ * The string being padded. + *

+ * @param int $length

+ * If the value of $length is negative, less than, or equal to the length of the input string, no padding takes + * place. + *

+ * @param non-empty-string $pad [optional]

+ * The pad may be truncated if the required number of padding characters can't be evenly divided by the pad's + * length. + *

+ * @param \FireHub\Core\Meta\Enum\Side $side [optional]

+ * Pad side. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @throws \FireHub\Runtime\Exception\EmptyPadException If the pad is empty. + * + * @return string Padded string. + */ + public static function pad (string $string, int $length, string $pad = ' ', Side $side = Side::RIGHT, ?Encoding $encoding = null):string { + + if ($pad === '') throw new EmptyPadException; + + return mb_str_pad( + $string, + $length, + $pad, + match ($side) { + Side::LEFT => STR_PAD_LEFT, + Side::RIGHT => STR_PAD_RIGHT, + Side::BOTH => STR_PAD_BOTH, + }, + $encoding?->value + ); + + } + + /** + * ### Strip whitespace (or other characters) from the beginning and end of a string + * + * Performs a multibyte safe MB::trim() operation and returns a string with whitespace stripped from + * the beginning and end of the string. + * + * Without the second parameter, MB::trim() will strip these characters: + * + * - " " (Unicode U+0020), an ordinary space. + * - "\t" (Unicode U+0009), a tab. + * - "\n" (Unicode U+000A), a new line (line feed). + * - "\r" (Unicode U+000D), a carriage return. + * - "\0" (Unicode U+0000), the NUL-byte. + * - "\v" (Unicode U+000B), a vertical tab. + * - "\f" (Unicode U+000C), a form feed. + * - "\u00A0" (Unicode U+00A0), a NO-BREAK SPACE. + * - "\u1680" (Unicode U+1680), an OGHAM SPACE MARK. + * - "\u2000" (Unicode U+2000), an EN QUAD. + * - "\u2001" (Unicode U+2001), an EM QUAD. + * - "\u2002" (Unicode U+2002), an EN SPACE. + * - "\u2003" (Unicode U+2003), an EM SPACE. + * - "\u2004" (Unicode U+2004), a THREE-PER-EM SPACE. + * - "\u2005" (Unicode U+2005), a FOUR-PER-EM SPACE. + * - "\u2006" (Unicode U+2006), a SIX-PER-EM SPACE. + * - "\u2007" (Unicode U+2007), a FIGURE SPACE. + * - "\u2008" (Unicode U+2008), a PUNCTUATION SPACE. + * - "\u2009" (Unicode U+2009), a THIN SPACE. + * - "\u200A" (Unicode U+200A), a HAIR SPACE. + * - "\u2028" (Unicode U+2028), a LINE SEPARATOR. + * - "\u2029" (Unicode U+2029), a PARAGRAPH SEPARATOR. + * - "\u202F" (Unicode U+202F), a NARROW NO-BREAK SPACE. + * - "\u205F" (Unicode U+205F), a MEDIUM MATHEMATICAL SPACE. + * - "\u3000" (Unicode U+3000), a IDEOGRAPHIC SPACE. + * - "\u0085" (Unicode U+0085), a NEXT LINE (NEL). + * - "\u180E" (Unicode U+180E), a MONGOLIAN VOWEL SEPARATOR. + * @since 1.0.0 + * + * @uses \FireHub\Core\Meta\Enum\Side::BOTH If trimming string on the both sides. + * @uses \FireHub\Core\Meta\Enum\Side::LEFT If trimming string on the left side. + * @uses \FireHub\Core\Meta\Enum\Side::RIGHT If trimming string on the right side. + * + * @param string $string

+ * The string that will be trimmed. + *

+ * @param \FireHub\Core\Meta\Enum\Side $side [optional]

+ * Side to trim string. + *

+ * @param null|string $characters [optional]

+ * Optionally, the stripped characters can also be specified using the character parameter. + * + * List all characters that need to be stripped. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $encoding [optional]

+ * Character encoding. If it is null, the internal character encoding value will be used. + *

+ * + * @return string The trimmed string. + */ + public static function trim (string $string, Side $side = Side::BOTH, ?string $characters = null, ?Encoding $encoding = null):string { + + return match($side) { + Side::LEFT => mb_ltrim($string, $characters, $encoding?->value), + Side::RIGHT => mb_rtrim($string, $characters, $encoding?->value), + Side::BOTH => mb_trim($string, $characters, $encoding?->value) + }; + + } + + /** + * ### Convert a string from one character encoding to another + * + * Converts string from $from, or the current internal encoding, to $to. + * + * If a string is an array, all its $string values will be converted recursively. + * @since 1.0.0 + * + * @param string $string

+ * The string to be converted. + *

+ * @param \FireHub\Core\Type\Str\Encoding $to

+ * The desired encoding of the result. + *

+ * @param null|\FireHub\Core\Type\Str\Encoding $from [optional]

+ * Character encoding. + * If it is null, the internal character encoding value will be used. + *

+ * + * @throws \FireHub\Runtime\Exception\EncodingConversionFailedException If the conversion fails. + * + * @return string Encoded string. + */ + public static function convertEncoding (string $string, Encoding $to, ?Encoding $from = null):string { + + return mb_convert_encoding($string, $to->value, $from?->value) + ?: throw new EncodingConversionFailedException; + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Access.php b/src/Str/SB/Access.php new file mode 100644 index 0000000..2e36035 --- /dev/null +++ b/src/Str/SB/Access.php @@ -0,0 +1,215 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\StringSplitLengthException; + +use function str_split; +use function strpbrk; +use function strrchr; +use function stristr; +use function strstr; +use function substr; +use function substr_count; + +/** + * ### PHP Byte-Oriented String Runtime Wrapper Utility - Access + * + * Provides runtime wrappers for accessing byte-oriented string data, including byte positions, character extraction, + * and direct string element access while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for byte-oriented string access + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Access extends NativeRuntime { + + /** + * ### Get part of string + * + * Returns the portion of the string specified by the $start and $length parameters. + * @since 1.0.0 + * + * @param string $string

+ * The string to extract the substring from. + *

+ * @param int $start

+ * If start is non-negative, the returned string will start at the start position in string, counting from zero. + * For instance, in the string 'FireHub', the character at position 0 is 'F', the character at position 2 is 'r', + * and so forth. + * + * If the start is negative, the returned string will start at the start character from the end of the string. + *

+ * @param null|int $length [optional]

+ * Maximum number of characters to use from string. + * + * If omitted or NULL is passed, extract all characters to the end of the string. + *

+ * + * @return ($string is empty ? '' : string) The portion of string specified by the start and length parameters. + */ + public static function part (string $string, int $start, ?int $length = null):string { + + return substr($string, $start, $length); + + } + + /** + * ### Get the number of times the searched substring occurs in the string + * + * Returns the number of times the needle substring occurs in the haystack string. + * + * Note that the needle is case-sensitive. + * @since 1.0.0 + * + * @param string $string

+ * The string being checked. + *

+ * @param string $search

+ * The string being found. + *

+ * @param int $start [optional]

+ * The offset is where to start counting. + * + * If the offset is negative, counting starts from the end of the string. + *

+ * @param null|int $length [optional]

+ * The maximum length after the specified offset to search for the substring. + * + * It outputs a warning if the offset plus the length is greater than the $string length. + * + * A negative length counts from the end of $string. + *

+ * + * @return non-negative-int The number of times the searched substring occurs in the string. + * + * @note This method doesn't count overlapped substring. + */ + public static function partCount (string $string, string $search, int $start = 0, ?int $length = null):int { + + return substr_count($string, $search, $start, $length); + + } + + /** + * ### Find part of a string with characters + * @since 1.0.0 + * + * @param string $characters

+ * Characters to find. This parameter is case-sensitive. + *

+ * @param string $string

+ * The string where characters are looked for. + *

+ * + * @return ($string is empty ? '' : non-falsy-string)|false String starting from the character found, or false if it + * is not found. + */ + public static function firstCharacterFrom (string $characters, string $string):string|false { + + return strpbrk($string, $characters); + + } + + /** + * ### Finds the last occurrence of any character from $find within in a string + * + * This function finds the last occurrence of a $find in the $string and returns the portion of $string. + * @since 1.0.0 + * + * @param string $string

+ * The string being searched. + *

+ * @param string $character

+ * Character to find. + *

+ * @param bool $before_needle [optional]

+ * If true, return the part of the string before the last occurrence (excluding the find string). + *

+ * + * @return ($string is empty ? '' : non-falsy-string)|false The portion of string, or false if the $find + * is not found. + */ + public static function lastCharacter (string $string, string $character, bool $before_needle = false):string|false { + + return strrchr($string, $character, $before_needle); + + } + + /** + * ### Find the first occurrence of a string + * + * Returns part of $string starting from and including the first occurrence of $find to the end of $string. + * @since 1.0.0 + * + * @param string $string

+ * The string being searched. + *

+ * @param string $find

+ * String to find. + *

+ * @param bool $before_needle [optional]

+ * If true, return the part of the string before the first occurrence (excluding the find string). + *

+ * @param bool $case_sensitive [optional]

+ * Searched values are case-sensitive. + *

+ * + * @return ($string is empty ? '' : non-falsy-string)|false The portion of string or false if the $find + * is not found. + */ + public static function firstOccurrence (string $string, string $find, bool $before_needle = false, bool $case_sensitive = true):string|false { + + if ($case_sensitive) return strstr($string, $find, $before_needle); + + return stristr($string, $find, $before_needle); + + } + + /** + * ### Convert a string to an array + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * @param positive-int $length [optional]

+ * Maximum length of the chunk. + *

+ * + * @throws \FireHub\Runtime\Exception\StringSplitLengthException If the $length parameter is less than 1. + * + * @return list If the optional $length parameter is specified, the returned array will be broken + * down into chunks with each being $length in length, except the final chunk which may be shorter if the string + * doesn't divide evenly. + * + * The default $length is 1, meaning every chunk will be one byte in size. + */ + public static function split (string $string, int $length = 1):array { + + return $length >= 1 + ? str_split($string, $length) + : throw new StringSplitLengthException( + 'The split length must be greater than zero.', + [ + 'string' => $string, + 'length' => $length, + 'minimum' => 1, + ] + ); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Casing.php b/src/Str/SB/Casing.php new file mode 100644 index 0000000..6fba48a --- /dev/null +++ b/src/Str/SB/Casing.php @@ -0,0 +1,119 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function lcfirst; +use function strtolower; +use function strtoupper; +use function ucfirst; +use function ucwords; + +/** + * ### PHP Single-Byte String Runtime Wrapper Utility - Casing + * + * Provides runtime wrappers for changing the letter case of single-byte string data using native PHP casing + * operations while preserving native behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for single-byte string case + * transformation operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Casing extends NativeRuntime { + + /** + * ### Make string lowercase + * @since 1.0.0 + * + * @param string $string

+ * The string being lowercased. + *

+ * + * @return ($string is empty ? '' : lowercase-string) String with all alphabetic characters converted to lowercase. + */ + public static function toLower (string $string):string { + + return strtolower($string); + + } + + /** + * ### Make string uppercase + * @since 1.0.0 + * + * @param string $string

+ * The string being uppercased. + *

+ * + * @return ($string is empty ? '' : uppercase-string) String with all alphabetic characters converted to uppercase. + */ + public static function toUpper (string $string):string { + + return strtoupper($string); + + } + + /** + * ### Make a string title-cased + * @since 1.0.0 + * + * @param string $string

+ * The string being title cased. + *

+ * + * @return ($string is empty ? '' : non-falsy-string) String with title-cased conversion. + */ + public static function toTitle (string $string):string { + + return ucwords($string); + + } + + /** + * ### Make the first character of a string uppercased + * @since 1.0.0 + * + * @param string $string

+ * The string being converted. + *

+ * + * @return ($string is empty ? '' : non-falsy-string) String with the first character uppercased. + */ + public static function capitalize (string $string):string { + + return ucfirst($string); + + } + + /** + * ### Make the first character of string lowercased + * + * Returns a string with the first character of $string lowercased if that character is an ASCII character in the + * range "A" (0x41) to "Z" (0x5a). + * @since 1.0.0 + * + * @param string $string

+ * The string being converted. + *

+ * + * @return ($string is empty ? '' : non-falsy-string) String with the first character lowercased. + */ + public static function uncapitalize (string $string):string { + + return lcfirst($string); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Compare.php b/src/Str/SB/Compare.php new file mode 100644 index 0000000..e60663a --- /dev/null +++ b/src/Str/SB/Compare.php @@ -0,0 +1,123 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function strcasecmp; +use function strcmp; +use function strncmp; +use function substr_compare; + +/** + * ### PHP Single-Byte String Runtime Wrapper Utility - Compare + * + * Provides runtime wrappers for comparing single-byte string data, including binary, lexical, and segment-based + * comparison operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for byte-oriented string + * comparison operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Compare extends NativeRuntime { + + /** + * ### String comparison + * @since 1.0.0 + * + * @param string $string_1

+ * String to compare against. + *

+ * @param string $string_2

+ * String to compare with. + *

+ * @param bool $case_sensitive [optional]

+ * Is comparison case-sensitive or not. + *

+ * + * @return int<-1,1> -1 if string1 is less than string2; 1 if string1 is greater than string2, and 0 if they are + * equal. + */ + public static function lexical (string $string_1, string $string_2, bool $case_sensitive = true):int { + + $cmp = $case_sensitive + ? strcmp($string_1, $string_2) + : strcasecmp($string_1, $string_2); + + return $cmp < 0 ? -1 : ($cmp > 0 ? 1 : 0); + + } + + /** + * ### String comparison of the first n characters + * @since 1.0.0 + * + * @param string $string_1

+ * String to compare against. + *

+ * @param string $string_2

+ * String to compare with. + *

+ * @param int $length

+ * Number of characters to use in the comparison. + *

+ * + * @return ($length is negative-int ? false : int<-1, 1>) -1 if string1 is less than string2; 1 if string1 is greater than + * string2, and 0 if they are equal, or false if the length is less than 0. + */ + public static function firstN (string $string_1, string $string_2, int $length):int|false { + + if ($length < 0) return false; + + return strncmp($string_1, $string_2, $length) <=> 0; + + } + + /** + * ### Comparison of two strings from an offset, up-to-length characters + * @since 1.0.0 + * + * @param string $string_1

+ * String to compare against. + *

+ * @param string $string_2

+ * String to compare with. + *

+ * @param int $offset

+ * The start position for the comparison. + * + * If negative, it starts counting from the end of the string. + *

+ * @param null|int $length [optional]

+ * The length of the comparison. + * + * The default value is the largest of the length for the needle compared to the length of haystack minus the + * offset. + *

+ * @param bool $case_sensitive [optional]

+ * If case_sensitive is true, the comparison is case-sensitive. + *

+ * + * @return ($length is negative-int ? false : int<-1, 1>) -1 if string1 is less than string2, 1 if string1 is + * greater than string2, and zero if they're equal. + */ + public static function part (string $string_1, string $string_2, int $offset, ?int $length = null, bool $case_sensitive = true):int|false { + + if ($length < 0) return false; + + return substr_compare($string_1, $string_2, $offset, $length, !$case_sensitive) <=> 0; + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Delimiter.php b/src/Str/SB/Delimiter.php new file mode 100644 index 0000000..16418fa --- /dev/null +++ b/src/Str/SB/Delimiter.php @@ -0,0 +1,93 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Foundation\Constant\Numeric\IntegerLimits; +use FireHub\Runtime\Exception\EmptySeparatorException; + +use function explode; +use function implode; + +/** + * ### PHP String Runtime Wrapper Utility - Delimiter + * + * Provides runtime wrappers for splitting strings into arrays and joining arrays of strings into a single string + * using delimiter-based operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for string segmentation and + * concatenation operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Delimiter extends NativeRuntime { + + /** + * ### Join array elements with a string + * + * Join array elements with a $separator string. + * @since 1.0.0 + * + * @param array $array

+ * The array of strings to implode. + *

+ * @param string $separator [optional]

+ * The boundary string. + *

+ * + * @return string Returns a string containing a string representation of all the array elements in the same order, + * with the separator string between each element. + */ + public static function implode (array $array, string $separator = ''):string { + + return implode($separator, $array); + + } + + /** + * ### Split a string by a string + * + * Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries + * formed by the string separator. + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * @param non-empty-string $separator

+ * The boundary string. + *

+ * @param int $limit [optional]

+ * If the limit is set and positive, the returned array will contain a maximum of limit elements with the last + * element containing the rest of the string. + * + * If the limit parameter is negative, all components except the last – limit are returned. + * + * If the limit parameter is zero, then this is treated as 1. + *

+ * + * @throws \FireHub\Runtime\Exception\EmptySeparatorException If the separator is an empty string. + * + * @return ($string is empty ? list : non-empty-list) If a delimiter contains a value not contained + * in string, and a negative limit is used, then an empty array will be returned. For any other limit, an array + * containing a string will be returned. + */ + public static function explode (string $string, string $separator, int $limit = IntegerLimits::MAX):array { + + if ($separator === '') throw new EmptySeparatorException; + + return explode($separator, $string, $limit); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Escape.php b/src/Str/SB/Escape.php new file mode 100644 index 0000000..95d0870 --- /dev/null +++ b/src/Str/SB/Escape.php @@ -0,0 +1,167 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function addcslashes; +use function addslashes; +use function quotemeta; +use function strip_tags; +use function stripcslashes; +use function stripslashes; + +/** + * ### PHP Single-Byte String Runtime Wrapper Utility - Escape + * + * Provides runtime wrappers for escaping, quoting, and removing escape sequences from single-byte string data using + * native PHP string escaping operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for single-byte string escape + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Escape extends NativeRuntime { + + /** + * ### Quote string with slashes + * + * Backslashes are added before characters that need to be escaped: (single quote, double quote, backslash, NUL). + * @since 1.0.0 + * + * @param string $string

+ * The string to be escaped. + *

+ * + * @return ($string is empty ? '' : non-falsy-string) The escaped string. + * + * @caution The Escape:addSlashes() is sometimes incorrectly used to try to prevent SQL Injection. Instead, + * database-specific escaping functions and/or prepared statements should be used. + */ + public static function addSlashes (string $string):string { + + return addslashes($string); + + } + + /** + * ### Quote string with slashes in a C style + * + * Returns a string with backslashes before characters that are listed in characters' parameter. + * @since 1.0.0 + * + * @param string $string

+ * The string to be escaped. + *

+ * @param string $characters

+ * The list of characters to be escaped. + * + * Non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation. + *

+ * + * @return string The escaped string. + */ + public static function addCSlashes (string $string, string $characters):string { + + return addcslashes($string, $characters); + + } + + /** + * ### Unquotes a quoted string + * + * Backslashes are removed: (backslashes become single quote, double backslashes are made into a single backslash). + * @since 1.0.0 + * + * @param string $string

+ * The string to be unquoted. + *

+ * + * @return string String with backslashes stripped off. + * + * @note SB::stripSlashes() is not recursive. If you want to apply this function to a multidimensional array, + * you need to use a recursive function. + * @tip SB::stripSlashes() can be used if you aren't inserting this data into a place (such as a database) + * that requires escaping. For example, if you're simply outputting data straight from an HTML form. + */ + public static function stripSlashes (string $string):string { + + return stripslashes($string); + + } + + /** + * ### Unquote string quoted with Escape::addCSlashes + * + * Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal, and hexadecimal + * representation. + * @since 1.0.0 + * + * @param string $string

+ * The string to be unquoted. + *

+ * + * @return string The unescaped string. + */ + public static function stripCSlashes (string $string):string { + + return stripcslashes($string); + + } + + /** + * ### Quote meta-characters + * + * Returns a version of str with a backslash character (\) before every character that is among these: .\+*?[^]($). + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * + * @return ($string is empty ? '' : non-empty-string) The string with meta-characters quoted. + */ + public static function quoteMeta (string $string):string { + + return quotemeta($string); + + } + + /** + * ### Strip HTML and PHP tags from a string + * + * This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given string. + * + * It uses the same tag-stripping state machine as the fgetss() function. + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * @param null|string|array $allowed_tags

+ * You can use the optional second parameter to specify tags which shouldn't be stripped. + *

+ * + * @return string the Stripped string. + * + * @note Self-closing XHTML tags are ignored, and only non-self-closing tags should be used in allowed_tags. For + * example, to allow both ```
``` and ```
```, you should use: ```
```. + */ + public static function stripTags (string $string, null|string|array $allowed_tags = null):string { + + return strip_tags($string, $allowed_tags); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Inspection.php b/src/Str/SB/Inspection.php new file mode 100644 index 0000000..8acdedc --- /dev/null +++ b/src/Str/SB/Inspection.php @@ -0,0 +1,67 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function crc32; +use function strlen; + +/** + * ### PHP Byte-Oriented String Runtime Wrapper Utility - Inspection + * + * Provides runtime wrappers for inspecting byte-oriented string data, including string length, checksum calculation, + * and other string metadata operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for byte-oriented string + * inspection operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Inspection extends NativeRuntime { + + /** + * ### Get string length + * @since 1.0.0 + * + * @param string $string

+ * The string being measured for length. + *

+ * + * @return non-negative-int String length. + * + * @note The function returns the number of bytes rather than the number of characters in a string. + */ + public static function length (string $string):int { + + return strlen($string); + + } + + /** + * ### Calculates the crc32 polynomial of a string + * @since 1.0.0 + * + * @param string $string

+ * The data. + *

+ * + * @return int crc32 checksum of string as an integer. + */ + public static function crc32 (string $string):int { + + return crc32($string); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Regex.php b/src/Str/SB/Regex.php new file mode 100644 index 0000000..31f3f52 --- /dev/null +++ b/src/Str/SB/Regex.php @@ -0,0 +1,212 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\InvalidPatternException; + +use function preg_match; +use function preg_match_all; +use function preg_replace; +use function preg_replace_callback; +use function preg_split; +use function preg_quote; + +/** + * ### Regular Expression Utilities + * + * Provides low-level wrappers for matching, replacing, splitting, and escaping strings using PHP's native PCRE + * regular expression engine while preserving native runtime behavior. + * @since 1.0.0 + */ +final class Regex extends NativeRuntime { + + /** + * ### Perform a regular expression match + * + * Searches subject for a match to the regular expression given in a pattern. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param string $string

+ * The string being evaluated. + *

+ * @param int $offset [optional]

+ * Normally, the search starts from the beginning of the subject string. + * + * The optional parameter offset can be used to specify the alternate place from which to start the search (in + * bytes). + *

+ * @param bool $all [optional]

+ * If true, search subject for a match to the regular expression given in a pattern. + *

+ * @param null|string[] &$result [optional]

+ * Regular expressions match the result. + *

+ * @param-out array|array> $result + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If the regular expression pattern is invalid. + * + * @return bool True if the string matches the regular expression pattern, false if not. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * Read the section on Booleans for more information. + * Use the === operator for testing the return value of this function. + */ + public static function match (string $pattern, string $string, int $offset = 0, bool $all = false, ?array &$result = null):bool { + + $match = $all + ? preg_match_all($pattern, $string, $result, offset: $offset) + : preg_match($pattern, $string, $result, offset: $offset); + + return $match === false + ? throw new InvalidPatternException + : $match !== 0; + + } + + /** + * ### Perform a regular expression search and replace + * + * Searches $subject for matches to $pattern and replaces them with $replacement. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param string $replacement

+ * The string to replace. + *

+ * @param string $string

+ * The string being evaluated. + *

+ * @param int $limit [optional]

+ * The maximum possible replacements for each pattern in each subject string. + * + * Defaults to -1 (no limit). + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If error while performing a regular expression, + * search and replace. + * + * @return string Replaced string. + */ + public static function replace (string $pattern, string $replacement, string $string, int $limit = -1):string { + + return preg_replace($pattern, $replacement, $string, $limit) + ?? throw new InvalidPatternException; + + } + + /** + * ### Perform a regular expression search and replace using a callback + * + * Searches $subject for matches to $pattern and replaces them with $replacement. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param callable(array $matches):string $callback

+ * A callback that will be called and passed an array of matched elements in the subject string. + * + * The callback should return the replacement string. + * + * This is the callback signature. + *

+ * @param string $string

+ * The string being evaluated. + *

+ * @param int $limit [optional]

+ * The maximum possible replacements for each pattern in each subject string. + * + * Defaults to -1 (no limit). + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If error while performing a regular expression, + * search and replace. + * + * @return string Replaced string. + */ + public static function replaceUsing (string $pattern, callable $callback, string $string, int $limit = -1):string { + + return preg_replace_callback($pattern, $callback, $string, $limit) + ?? throw new InvalidPatternException; + + } + + /** + * ### Split string by a regular expression + * + * Split the given string by a regular expression. + * @since 1.0.0 + * + * @param string $pattern

+ * The regular expression pattern. + *

+ * @param string $string

+ * The input string. + *

+ * @param int $limit [optional]

+ * The maximum possible replacements for each pattern in each subject string. + * + * Defaults to -1 (no limit). + *

+ * @param bool $remove_empty [optional]

+ * If true, only non-empty pieces will be returned. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidPatternException If error while performing a regular expression split. + * + * @return list Array containing substrings of $string split along boundaries matched by $pattern. + */ + public static function split (string $pattern, string $string, int $limit = -1, bool $remove_empty = false):array { + + return preg_split($pattern, $string, $limit, $remove_empty ? PREG_SPLIT_NO_EMPTY : 0) + ?: throw new InvalidPatternException; + + } + + /** + * ### Quote regular expression characters + * + * Method takes string and puts a backslash in front of every character that is part of the regular expression + * syntax. + * + * This is useful if you have a runtime string that you need to match in some text and the string may contain + * special regex characters. + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * @param null|string $delimiter [optional]

+ * If the optional delimiter is specified, it will also be escaped. + * + * This is useful for escaping the delimiter required by the PCRE functions. + * + * The / is the most commonly used delimiter. + *

+ * + * @return string The quoted (escaped) string. + */ + public static function quote (string $string, ?string $delimiter = null):string { + + return preg_quote($string, $delimiter); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Replace.php b/src/Str/SB/Replace.php new file mode 100644 index 0000000..a3126ec --- /dev/null +++ b/src/Str/SB/Replace.php @@ -0,0 +1,132 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function str_ireplace; +use function str_replace; +use function strtr; +use function substr_replace; + +/** + * ### PHP Single-Byte String Runtime Wrapper Utility - Replace + * + * Provides runtime wrappers for replacing, substituting, and transforming portions of single-byte string data using + * direct character and substring replacement operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for single-byte string replacement + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Replace extends NativeRuntime { + + /** + * ### Replace all occurrences of the search string with the replacement string + * + * This function returns a string or an array with all occurrences of search in a subject replaced with the given + * replacement value. + * @since 1.0.0 + * + * @param string|list $search

+ * The string being searched and replaced on. + *

+ * @param string|list $replace

+ * The replacement value that replaces found search values. + * + * An array may be used to designate multiple replacements. + *

+ * @param string $string

+ * The value being searched for. + *

+ * @param bool $case_sensitive [optional]

+ * Searched values are case-sensitive. + *

+ * @param null|int &$count [optional]

+ * If passed, this will hold the number of matched and replaced needles. + *

+ * @param-out int $count + * + * @return string String with the replaced values. + * + * @note Because the method replaces left to right, it might replace a previously inserted value when doing + * multiple replacements. + * @tip To replace text based on a pattern rather than a fixed string, use preg_replace(). + */ + public static function replace (string|array $search, string|array $replace, string $string, bool $case_sensitive = true, ?int &$count = null):string { + + if ($case_sensitive) return str_replace($search, $replace, $string, $count); + + return str_ireplace($search, $replace, $string, $count); + + } + + /** + * ### Replace text within a portion of a string + * + * Replaces a copy of string delimited by the $offset and (optionally) $length parameters with the string given + * in $replace parameter. + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * @param string $replace

+ * The replacement string. + *

+ * @param int $offset

+ * If the offset is non-negative, the replacing will begin at the into string. + * + * If offset is negative, the replacing will begin at the character from the end of the string. + *

+ * @param null|int $length [optional]

+ * If given and is positive, it represents the length of the portion of string which is to be replaced. + * + * If it is negative, it represents the number of characters from the end of the string at which to stop replacing. + * + * If it is not given, then it will default to SB::length(string); in other words, end the replacing at the + * end of the string. + * + * Of course, if the length is zero, then this function will have the effect of inserting $replace into string + * at the given offset. + *

+ * + * @return string String with the replaced values. + */ + public static function part (string $string, string $replace, int $offset, ?int $length = null):string { + + return substr_replace($string, $replace, $offset, $length); + + } + + /** + * ### Translate characters or replace substrings + * @since 1.0.0 + * + * @param string $string

+ * The string being translated to. + *

+ * @param array $replace_pairs

+ * An array of key-value pairs for translation. + *

+ * + * @return string The translated string. + */ + public static function translate (string $string, array $replace_pairs):string { + + return strtr($string, $replace_pairs); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Search.php b/src/Str/SB/Search.php new file mode 100644 index 0000000..31b1999 --- /dev/null +++ b/src/Str/SB/Search.php @@ -0,0 +1,260 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function str_contains; +use function str_ends_with; +use function str_starts_with; +use function stripos; +use function strpos; +use function strripos; +use function strrpos; +use function strcspn; +use function strspn; + +/** + * ### PHP Single-Byte String Runtime Wrapper Utility - Search + * + * Provides runtime wrappers for searching within single-byte string data, including substring lookup, character + * occurrence detection, position retrieval, and string matching operations while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for byte-oriented string search + * operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Search extends NativeRuntime { + + /** + * ### Checks if a string contains a value + * + * Performs a case-sensitive check indicating if $string is contained in $string. + * @since 1.0.0 + * + * @param string $value

+ * The value to search for. + *

+ * @param string $string

+ * The string to search in. + *

+ * + * @return bool True if a string contains a value, false otherwise. + */ + public static function contains (string $value, string $string):bool { + + return str_contains($string, $value); + + } + + /** + * ### Checks if a string starts with a given value + * + * Performs a case-sensitive check indicating if $string begins with $value. + * @since 1.0.0 + * + * @param string $value

+ * The value to search for. + *

+ * @param string $string

+ * The string to search in. + *

+ * + * @return bool True if the string starts with value, false otherwise. + */ + public static function startsWith (string $value, string $string):bool { + + return str_starts_with($string, $value); + + } + + /** + * ### Checks if a string ends with a given value + * + * Performs a case-sensitive check indicating if $string ends with $value. + * @since 1.0.0 + * + * @param string $value

+ * The value to search for. + *

+ * @param string $string

+ * The string to search in. + *

+ * + * @return bool True if the string ends with value, false otherwise. + */ + public static function endsWith (string $value, string $string):bool { + + return str_ends_with($string, $value); + + } + + /** + * ### Find the position of the first occurrence of a substring in a string + * @since 1.0.0 + * + * @param string $search

+ * A string to find position. + *

+ * @param string $string

+ * The string to search in. + *

+ * @param bool $case_sensitive [optional]

+ * Search case-sensitive position. + *

+ * @param int $offset [optional]

+ * If specified, search will start this number of characters counted from the beginning of the string. + *

+ * + * @return non-negative-int|false Numeric position of the first occurrence or false if none exist. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * Read the section on Booleans for more information. + * Use the === operator for testing the return value of this function. + */ + public static function firstPosition (string $search, string $string, bool $case_sensitive = true, int $offset = 0):int|false { + + if ($case_sensitive) return strpos($string, $search, $offset); + + return stripos($string, $search, $offset); + + } + + /** + * ### Find the position of the last occurrence of a substring in a string + * @since 1.0.0 + * + * @param string $search

+ * A string to find position. + *

+ * @param string $string

+ * The string to search in. + *

+ * @param bool $case_sensitive [optional]

+ * Search case-sensitive position. + *

+ * @param int $offset [optional]

+ * If specified, search will start this number of characters counted from the beginning of the string. + *

+ * + * @return non-negative-int|false Numeric position of the last occurrence or false if none exist. + * + * @warning This function may return Boolean false but may also return a non-Boolean value which evaluates to false. + * Read the section on Booleans for more information. + * Use the === operator for testing the return value of this function. + */ + public static function lastPosition (string $search, string $string, bool $case_sensitive = true, int $offset = 0):int|false { + + if ($case_sensitive) + /** @var non-negative-int|false */ + return strrpos($string, $search, $offset); + + /** @var non-negative-int|false */ + return strripos($string, $search, $offset); + + } + + /** + * ### Length of the initial segment for a string consisting entirely of characters contained within a given mask + * + * Finds the length of the initial segment for $string that contains only characters from $characters. + * @since 1.0.0 + * + * @param string $string

+ * The string to examine. + *

+ * @param string $characters

+ * The list of allowable characters. + *

+ * @param int $offset [optional]

+ * The position in a subject to start searching. + * + * If start is given and is non-negative, then Seach::segmentMatching() will begin examining the subject at + * the start position. + * + * For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', + * and so forth. + * + * If start is given and is negative, then Seach::segmentMatching() will begin examining the subject at the start + * position from the end of a subject. + *

+ * @param int|null $length [optional]

+ * The length of the segment from the subject to examine. + * + * If length is given and is non-negative, then the subject will be examined for length characters after the + * starting position. + * + * If length is given and is negative, then the subject will be examined from the starting position up-to-length + * characters from the end of the subject. + *

+ * + * @return non-negative-int The length of the initial segment for string which consists entirely of characters in + * characters. + * + * @note When the offset parameter is set, the returned length is counted starting from this position, not from + * beginning of the string. + */ + public static function segmentLength (string $string, string $characters, int $offset = 0, ?int $length = null):int { + + return strspn($string, $characters, $offset, $length); + + } + + /** + * ### Find length of the initial segment not matching mask + * + * Returns the length of the initial segment for $string which doesn't contain any of the characters in $characters. + * @since 1.0.0 + * + * @param string $string

+ * The string to examine. + *

+ * @param string $characters

+ * The string containing every disallowed character. + *

+ * @param int $offset [optional]

+ * The position in a subject to start searching. + * + * If start is given and is non-negative, then Seach::segmentNotMatching() will begin examining the subject at + * the start position. + * + * For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', + * and so forth. + * + * If start is given and is negative, then Search::segmentNotMatching() will begin examining the subject at the + * start position from the end of a subject. + *

+ * @param null|int $length [optional]

+ * The length of the segment from the subject to examine + * + * If length is given and is non-negative, then the subject will be examined for length characters after the + * starting position. + * + * If length is given and is negative, then the subject will be examined from the starting position up-to-length + * characters from the end of the subject. + *

+ * + * @return non-negative-int The length of the initial segment from string which consists entirely of characters not + * in characters. + * + * @note When the offset parameter is set, the returned length is counted starting from this position, not from + * beginning of the string. + */ + public static function segmentNotLength (string $string, string $characters, int $offset = 0, ?int $length = null):int { + + return strcspn($string, $characters, $offset, $length); + + } + +} \ No newline at end of file diff --git a/src/Str/SB/Transform.php b/src/Str/SB/Transform.php new file mode 100644 index 0000000..24b429e --- /dev/null +++ b/src/Str/SB/Transform.php @@ -0,0 +1,304 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Str\SB; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Meta\Enum\Side; +use FireHub\Runtime\Exception\ { + EmptyPadException, InvalidChunkLengthException +}; + +use const STR_PAD_BOTH; +use const STR_PAD_LEFT; +use const STR_PAD_RIGHT; + +use function chunk_split; +use function ltrim; +use function rtrim; +use function sprintf; +use function str_pad; +use function str_repeat; +use function str_shuffle; +use function strrev; +use function trim; +use function wordwrap; + +/** + * ### PHP Single-Byte String Runtime Wrapper Utility - Transform + * + * Provides runtime wrappers for transforming single-byte string data using native PHP string manipulation operations + * while preserving native PHP behavior. + * + * This component is part of the FireHub Runtime layer and provides a consistent API for single-byte string + * transformation operations without introducing domain logic, framework coupling, or additional abstraction overhead. + * @since 1.0.0 + */ +final class Transform extends NativeRuntime { + + /** + * ### Repeat a string + * + * Returns string repeated with $times parameter. + * @since 1.0.0 + * + * @param string $string

+ * The string is to be repeated. + *

+ * @param int $times

+ * Number of times the input string should be repeated. + * + * Multiplier has to be greater than or equal to 0. + * + * If the $times are set to 0 or less, the function will return an empty string. + *

+ * @param string $separator [optional]

+ * Separator in between any repeated string. + *

+ * + * @return string Repeated string. + * + * @note If $times is less than 1, an empty string will be returned. + */ + public static function repeat (string $string, int $times, string $separator = ''):string { + + return $times < 1 ? '' : str_repeat($string.$separator, $times - 1).$string; + + } + + /** + * ### Pad a string to a certain length with another string + * + * This method returns the $string padded on the left, the right, or both sides to the specified padding length. + * + * If the optional argument $pad is not supplied, the $string is padded with spaces; otherwise it is padded with + * characters from $pad up to the limit. + * @since 1.0.0 + * + * @uses \FireHub\Core\Meta\Enum\Side::RIGHT If padding string to the right. + * @uses \FireHub\Core\Meta\Enum\Side::LEFT If padding string to the left. + * @uses \FireHub\Core\Meta\Enum\Side::BOTH If padding string on the both sides. + * + * @param string $string

+ * The string being padded. + *

+ * @param int $length

+ * If the value of $length is negative, less than, or equal to the length of the input string, no padding takes + * place. + *

+ * @param non-empty-string $pad [optional]

+ * The pad may be truncated if the required number of padding characters can't be evenly divided by the pad's + * length. + *

+ * @param \FireHub\Core\Meta\Enum\Side $side [optional]

+ * Pad side. + *

+ * + * @throws \FireHub\Runtime\Exception\EmptyPadException If the pad is empty. + * + * @return string Padded string. + */ + public static function pad (string $string, int $length, string $pad = ' ', Side $side = Side::RIGHT):string { + + if ($pad === '') throw new EmptyPadException; + + return str_pad( + $string, + $length, + $pad, + match ($side) { + Side::LEFT => STR_PAD_LEFT, + Side::RIGHT => STR_PAD_RIGHT, + Side::BOTH => STR_PAD_BOTH, + } + ); + + } + + /** + * ### Reverse a string + * @since 1.0.0 + * + * @param string $string

+ * The string to be reversed. + *

+ * + * @return ($string is empty ? '' : non-empty-string) The reversed string. + */ + public static function reverse (string $string):string { + + return strrev($string); + + } + + /** + * ### Randomly shuffles a string + * @since 1.0.0 + * + * @param string $string

+ * The input string. + *

+ * + * @return ($string is empty ? '' : non-empty-string) The shuffled string. + * + * @caution This function doesn't generate cryptographically secure values and mustn't be used for cryptographic + * purposes, or purposes that require returned values to be unguessable. + */ + public static function shuffle (string $string):string { + + return str_shuffle($string); + + } + + /** + * ### Split a string into smaller chunks + * + * Can be used to split a string into smaller chunks, which is useful, for example, converting base64_encode() + * output to match RFC 2045 semantics. + * + * It inserts $separator every $length characters. + * @since 1.0.0 + * + * @param string $string

+ * The string to be chunked. + *

+ * @param positive-int $length [optional]

+ * The chunk length. + *

+ * @param string $separator [optional]

+ * The line-ending sequence. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidChunkLengthException If the length is less than 1. + * + * @return string The chunked string. + */ + public static function chunkSplit (string $string, int $length = 76, string $separator = "\r\n"):string { + + if ($length < 1) { + throw new InvalidChunkLengthException( + 'The length of each chunk must be a positive integer.', + [ + 'length' => $length, + 'minimum' => 1, + ] + ); + } + + return chunk_split($string, $length, $separator); + + } + + /** + * ### Wraps a string to a given number of characters + * + * Wraps a string to a given number of characters using a string break character. + * @since 1.0.0 + * + * @param string $string

+ * The string to warp. + *

+ * @param int $width [optional]

+ * The column width. + *

+ * @param string $break [optional]

+ * The line is broken using the optional break parameter. + *

+ * @param bool $cut_long_words [optional]

+ * If the cut is set to true, the string is always wrapped at or before the specified width. + * + * So if you have a word that is larger than the given width, it is broken apart. + *

+ * + * @return string The given string wrapped at the specified column. + */ + public static function wrap (string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false):string { + + return wordwrap($string, $width, $break, $cut_long_words); + + } + + /** + * ### Return a formatted string + * + * Returns a string produced according to the formatting string $format. + * @since 1.0.0 + * + * @param string $format

+ * String is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to + * the result and conversion specifications, each of which results in fetching its own parameter. + * + * A conversion specification follows this prototype: %[argnum$][flags][width][.precision]specifier. + *

+ * @param null|scalar ...$values

+ * The values to insert into the formatted string. + *

+ * + * @return string string produced according to the formatting string $format. + */ + public static function format (string $format, null|bool|float|int|string ...$values):string { + + return sprintf($format, ...$values); + + } + + /** + * ### Strip whitespace (or other characters) from the beginning and end of a string + * + * This function returns a string with whitespace stripped from the beginning and end of the string. + * + * Without the second parameter, SB::trim() will strip these characters. + * + * - " " (ASCII 32 (0x20)), an ordinary space. + * - "\t" (ASCII 9 (0x09)), a tab. + * - "\n" (ASCII 10 (0x0A)), a new line (line feed). + * - "\r" (ASCII 13 (0x0D)), a carriage return. + * - "\0" (ASCII 0 (0x00)), the NUL-byte. + * - "\v" (ASCII 11 (0x0B)), a vertical tab. + * @since 1.0.0 + * + * @uses \FireHub\Core\Meta\Enum\Side::BOTH If trimming string on the both sides. + * @uses \FireHub\Core\Meta\Enum\Side::LEFT If trimming string on the left side. + * @uses \FireHub\Core\Meta\Enum\Side::RIGHT If trimming string on the right side. + * + * @param string $string

+ * The string that will be trimmed. + *

+ * @param \FireHub\Core\Meta\Enum\Side $side [optional]

+ * Side to trim string. + *

+ * @param string $characters [optional]

+ * The stripped characters can also be specified using the char-list parameter. + * + * List all characters that you want to be stripped. With '..', you can specify a range of characters. + *

+ * + * @return string The trimmed string. + * + * @note Because SB::trim trims characters from the beginning and end of a string, it may be confusing when + * characters are (or aren't) removed from the middle. + * SB::trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to + * also be trimmed. + * So, this is why it "works" whereas SB::trim('abc', 'b') seemingly doesn't. + */ + public static function trim (string $string, Side $side = Side::BOTH, string $characters = " \n\r\t\v\x00"):string { + + return match($side) { + Side::LEFT => ltrim($string, $characters), + Side::RIGHT => rtrim($string, $characters), + Side::BOTH => trim($string, $characters) + }; + + } + +} \ No newline at end of file diff --git a/src/System/Clock.php b/src/System/Clock.php new file mode 100644 index 0000000..ed5ce4f --- /dev/null +++ b/src/System/Clock.php @@ -0,0 +1,84 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function hrtime; +use function microtime; +use function time; + +/** + * ### PHP Runtime Clock Utilities + * + * Provides low-level wrappers for retrieving high-resolution and system clock values, including Unix timestamps, + * microsecond precision time measurements, and monotonic timers while preserving native PHP behavior. + * + * This component exposes PHP clock and time measurement capabilities through a consistent FireHub Runtime API + * without altering native runtime semantics. + * @since 1.0.0 + */ +final class Clock extends NativeRuntime { + + /** + * ### Return current Unix timestamp + * + * Returns the current time measured in the number of seconds since the Unix Epoch (January, 1 1970 00:00:00 GMT). + * @since 1.0.0 + * + * @return positive-int The current timestamp. + * + * @tip The timestamp of the start for the request is available in $_SERVER['REQUEST_TIME']. + */ + public static function time ():int { + + return time(); + + } + + /** + * ### Get current Unix microseconds + * + * Method returns the current Unix timestamp with microseconds. + * + * This function is only available on operating systems that support the gettimeofday() system call. + * @since 1.0.0 + * + * @return float The current timestamp with microseconds. + * + * @tip For performance measurements, using hrtime() is recommended. + */ + public static function microtime ():float { + + return microtime(true); + + } + + /** + * ### Get the system's high-resolution time + * + * Returns the system's high-resolution time, counted from an arbitrary point in time. The delivered timestamp is + * monotonic and cannot be adjusted. + * @since 1.0.0 + * + * @return array{0: int<0, max>, 1: int<0, 999999999>} Returns an array of integers in the form [seconds, + * nanoseconds]. + */ + public static function highResolution ():array { + + return hrtime(); + + } + +} \ No newline at end of file diff --git a/src/System/Configuration.php b/src/System/Configuration.php new file mode 100644 index 0000000..37786e8 --- /dev/null +++ b/src/System/Configuration.php @@ -0,0 +1,218 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Php\Ini\AccessLevel; +use FireHub\Runtime\Str; +use FireHub\Runtime\Exception\ { + ConfigurationOptionNotFoundException, ConfigurationRetrievalException, ExtensionNotFoundException, + FailedToSetConfigurationOptionException, InvalidConfigurationQuantityException +}; + +use function ini_get; +use function ini_get_all; +use function ini_restore; +use function ini_parse_quantity; +use function ini_set; +use function php_ini_loaded_file; + +/** + * ### PHP Runtime Configuration Utilities + * + * Provides low-level access to PHP runtime configuration values, including reading, modifying, and restoring + * configuration directives while preserving native PHP behavior. + * + * This component exposes PHP configuration management capabilities through a consistent FireHub Runtime API without + * altering the underlying PHP configuration system. + * @since 1.0.0 + */ +final class Configuration extends NativeRuntime { + + /** + * ### Retrieve a path to the loaded php.ini file + * @since 1.0.0 + * + * @return non-empty-string|false The loaded php.ini path, or false if one is not loaded. + */ + public static function getPath ():string|false { + + return php_ini_loaded_file(); + + } + + /** + * ### Gets the value of a configuration option + * @since 1.0.0 + * + * @param non-empty-string $option

+ * The configuration option name. + *

+ * + * @throws \FireHub\Runtime\Exception\ConfigurationOptionNotFoundException If configuration option is not valid. + * + * @return string Value of the configuration option as a string on success, or an empty string for null + * values. + * + * @note A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on + * will be returned as "1". + * The function can also return the literal string of INI value. + * @note Method can't read array ini options such as pdo.dsn.*, and returns false in this case. + */ + public static function get (string $option):string { + + return ($value = ini_get($option)) !== false + ? $value + : throw new ConfigurationOptionNotFoundException; + + } + + /** + * ### Gets all configuration options + * @since 1.0.0 + * + * @uses \FireHub\Core\Type\Php\Ini\AccessLevel To set an access level. + * @uses \FireHub\Runtime\System\Extension::hasExtension() To check if the extension is loaded. + * + * @param null|non-empty-string $extension

+ * An optional extension name. + * + * If not null or the string core, the function returns only options specific for that extension. + *

+ * + * @throws \FireHub\Runtime\Exception\ExtensionNotFoundException If the extension is not valid. + * @throws \FireHub\Runtime\Exception\ConfigurationRetrievalException If failed to retrieve configuration. + * + * @return array + * Associative array with a directive name as the array key. + * + * @note Method ignores "array" ini options such as pdo.dsn.*. + */ + public static function getAll (?string $extension = null):array { + + if ($extension !== null && Extension::hasExtension($extension) === false) + throw new ExtensionNotFoundException; + + /** @var array|false $options + */ + $options = ini_get_all($extension); + + if ($options === false) + throw new ConfigurationRetrievalException; + + foreach ($options as $option => $values) + $options[$option]['access'] = AccessLevel::from($values['access']); + + return $options; + + } + + /** + * ### Sets the value of a configuration option + * + * Sets the value of the given configuration option. + * + * The configuration option will keep this new value during the script's execution and will be restored at the + * script's ending. + * @since 1.0.0 + * + * @param non-empty-string $option

+ * The configuration option name. + *

+ * @param null|scalar $value

+ * The new value for the option. + *

+ * + * @throws \FireHub\Runtime\Exception\FailedToSetConfigurationOptionException If failed to set configuration option. + * + * @return True Always true. + * + * @note A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on + * will be returned as "1". + * The function can also return the literal string of INI value. + * @note Method can't read array ini options such as pdo.dsn.*, and returns false in this case. + */ + public static function set (string $option, null|int|float|string|bool $value):true { + + return ini_set($option, $value) !== false + ? true : throw new FailedToSetConfigurationOptionException; + + } + + /** + * ### Restores the value of a configuration option to its original value + * @since 1.0.0 + * + * @uses self::get() To get the original value. + * + * @param non-empty-string $option

+ * The configuration option name. + *

+ * + * @throws \FireHub\Runtime\Exception\ConfigurationOptionNotFoundException If configuration option is not valid. + * + * @return string Value of the configuration option as a string on success, or an empty string for null + * values. + * + * @note A boolean ini value of off will be returned as an empty string or "0" while a boolean ini value of on + * will be returned as "1". + * The function can also return the literal string of INI value. + * @note Method can't read array ini options such as pdo.dsn.*, and returns false in this case. + */ + public static function restore (string $option):string { + + ini_restore($option); + + return self::get($option); + + } + + /** + * ### Get interpreted size from ini shorthand syntax + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Str\SB\Transform::trim() To trim the input string. + * @uses \FireHub\Runtime\Str\SB\Regex::match() To validate the input string. + * + * @param non-empty-string $shorthand

+ * Ini shorthand to parse, there must be a number followed by an optional multiplier. + * + * The following multipliers are supported: k/K (1024), m/M (1048576), g/G (1073741824). + * + * The number can be a decimal, hex (prefixed with 0x or 0X), octal (prefixed with 0o, 0O, or 0) or binary + * (prefixed with 0b or 0B). + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidConfigurationQuantityException If shorthand is not valid. + * @throws \FireHub\Runtime\Exception\InvalidPatternException If shorthand is not valid. + * + * @return non-negative-int Interpreted size in bytes on success from ini shorthand. + */ + public static function parseQuantity (string $shorthand):int { + + /** @var non-negative-int */ + return Str\SB\Regex::match( + '/^(?:0x[0-9a-fA-F]+|0b[01]+|0o[0-7]+|\d+)[KMG]?$/x', + Str\SB\Transform::trim($shorthand) + ) === false + ? throw new InvalidConfigurationQuantityException + : ini_parse_quantity($shorthand); + + } + +} \ No newline at end of file diff --git a/src/System/Environment.php b/src/System/Environment.php new file mode 100644 index 0000000..7a7cd57 --- /dev/null +++ b/src/System/Environment.php @@ -0,0 +1,100 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function getenv; +use function get_current_user; +use function putenv; +use function sys_get_temp_dir; + +/** + * ### PHP Runtime Environment Utilities + * + * Provides low-level wrappers for accessing and managing the current PHP process environment, including environment + * variables, execution user information, and temporary directory locations while preserving native runtime behavior. + * + * This component exposes PHP environment capabilities through a consistent FireHub Runtime API without altering + * operating system or process environment semantics. + * @since 1.0.0 + */ +final class Environment extends NativeRuntime { + + /** + * ### Gets the value of a single or all the environment variables + * @since 1.0.0 + * + * @param null|string $name [optional]

+ * The variable name as a string or null. + *

+ * + * @return ($name is null ? array : string|false) Returns the value of the environment variable + * name, or false if the environment variable name doesn't exist. + * If the name is null, all environment variables are returned as an associative array. + */ + public static function getVariable (?string $name = null):array|string|false { + + return getenv($name); + + } + + /** + * ### Sets the value of an environment variable + * + * Adds assignment to the server environment. + * + * The environment variable will only exist for the duration of the current request. + * + * At the end of the request, the environment is restored to its original state. + * @since 1.0.0 + * + * @param non-empty-string $assignment

+ * The setting, like "FOO=BAR". + *

+ * + * @return bool True on success or false on failure. + */ + public static function setVariable (string $assignment):bool { + + return putenv($assignment); + + } + + /** + * ### Gets the owner of the current PHP script file + * @since 1.0.0 + * + * @return string Username as a string. + */ + public static function scriptOwner ():string { + + return get_current_user(); + + } + + /** + * ### Gets a directory path used for temporary files + * @since 1.0.0 + * + * @return non-empty-string Path of the temporary directory. + */ + public static function tempFolder ():string { + + /** @var non-empty-string */ + return sys_get_temp_dir(); + + } + +} \ No newline at end of file diff --git a/src/System/Extension.php b/src/System/Extension.php new file mode 100644 index 0000000..1d43fe2 --- /dev/null +++ b/src/System/Extension.php @@ -0,0 +1,86 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ExtensionNotFoundException; + +use function extension_loaded; +use function get_extension_funcs; +use function get_loaded_extensions; + +/** + * ### PHP Extension Management Utilities + * + * Provides low-level wrappers for inspecting PHP extensions, including checking loaded extensions, retrieving + * extension functions, and listing available modules while preserving native runtime behavior. + * + * This component exposes PHP extension discovery capabilities through a consistent FireHub Runtime API without + * altering extension loading or execution semantics. + * @since 1.0.0 + */ +final class Extension extends NativeRuntime { + + /** + * ### Check if a PHP extension is loaded + * @since 1.0.0 + * + * @param non-empty-string $name

+ * Extension name or verified extension enum. + * + * This parameter is case-insensitive for strings. + *

+ * + * @return bool True if the extension is loaded, false otherwise. + */ + public static function hasExtension (string $name):bool { + + return extension_loaded($name); + + } + + /** + * ### Array with the names of all modules compiled and loaded + * @since 1.0.0 + * + * @return list Indexed array of all the module names. + */ + public static function loadedExtensions ():array { + + /** @var list */ + return get_loaded_extensions(); + + } + + /** + * ### Array with the names of the functions for a module + * @since 1.0.0 + * + * @param string $extension

+ * The module name. This parameter is case-insensitive. + *

+ * + * @throws \FireHub\Runtime\Exception\ExtensionNotFoundException If the extension is not valid or does not have + * functions. + * + * @return list Array with all the functions. + */ + public static function extensionFunctions (string $extension):array { + + return ($functions = get_extension_funcs($extension)) !== false + ? $functions : throw new ExtensionNotFoundException('Extension not found or does not have functions.'); + + } + +} \ No newline at end of file diff --git a/src/System/FileSystem.php b/src/System/FileSystem.php new file mode 100644 index 0000000..43c321e --- /dev/null +++ b/src/System/FileSystem.php @@ -0,0 +1,46 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Str; + +use function get_included_files; + +/** + * ### PHP Runtime File System Utilities + * + * Provides low-level wrappers for interacting with the file system, including files, directories, paths, + * permissions, and file metadata while preserving native PHP behavior. + * + * This component exposes PHP file system capabilities through a consistent FireHub Runtime API without altering + * native runtime behavior. + * @since 1.0.0 + */ +final class FileSystem extends NativeRuntime { + + /** + * ### Array with the names of included or required files + * @since 1.0.0 + * + * @return list Array of the names for all files referenced by include and family. + */ + public static function includedFiles ():array { + + /** @var list */ + return get_included_files(); + + } + +} \ No newline at end of file diff --git a/src/System/Memory.php b/src/System/Memory.php new file mode 100644 index 0000000..6f9e167 --- /dev/null +++ b/src/System/Memory.php @@ -0,0 +1,71 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Str; + +use function memory_get_usage; +use function memory_get_peak_usage; +use function memory_reset_peak_usage; + +/** + * ### PHP Runtime Memory Utilities + * + * Provides low-level wrappers for inspecting and managing PHP runtime memory usage, including current allocation, + * peak memory consumption, and memory-related runtime operations while preserving native PHP behavior. + * + * This component exposes PHP memory management capabilities through a consistent FireHub Runtime API without + * altering native runtime behavior. + * @since 1.0.0 + */ +final class Memory extends NativeRuntime { + + /** + * ### Gets the amount of memory allocated to PHP + * @since 1.0.0 + * + * @return non-negative-int The memory amount in bytes. + */ + public static function getUsage ():int { + + return memory_get_usage(); + + } + + /** + * ### Gets the peak of memory allocated by PHP + * @since 1.0.0 + * + * @return non-negative-int The memory peak in bytes. + */ + public static function getPeakUsage ():int { + + return memory_get_peak_usage(); + + } + + /** + * ### Reset the peak memory usage + * @since 1.0.0 + * + * @return void + */ + public static function resetPeakUsage ():void { + + memory_reset_peak_usage(); + + } + +} \ No newline at end of file diff --git a/src/System/Platform.php b/src/System/Platform.php new file mode 100644 index 0000000..fab1450 --- /dev/null +++ b/src/System/Platform.php @@ -0,0 +1,55 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; + +use function php_uname; + +/** + * ### PHP Platform Utilities + * + * Provides low-level wrappers for inspecting the underlying operating system and hardware platform where PHP is + * running, including system name, hostname, release, version, and machine architecture while preserving native + * runtime behavior. + * + * This component exposes PHP platform information through a consistent FireHub Runtime API without altering + * operating system detection semantics. + * @since 1.0.0 + */ +final class Platform extends NativeRuntime { + + /** + * ### Gets OS information + * + * Information about the operating system PHP is running one "cli" whereas with Apache it may have several different + * values depending on the exact SAPI used. + * @since 1.0.0 + * + * @return array{name: string, hostname: string, release: string, version: string, machine: string} Operating system + * information. + */ + public static function osInfo ():array { + + return [ + 'name' => php_uname('s'), + 'hostname' => php_uname('n'), + 'release' => php_uname('r'), + 'version' => php_uname('v'), + 'machine' => php_uname('m') + ]; + + } + +} \ No newline at end of file diff --git a/src/System/Process.php b/src/System/Process.php new file mode 100644 index 0000000..6a4d88b --- /dev/null +++ b/src/System/Process.php @@ -0,0 +1,52 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\ProcessIdUnavailableException; + +use function getmypid; + +/** + * ### PHP Process Utilities + * + * Provides low-level wrappers for inspecting the current PHP process environment, including retrieving process + * identifiers and process-related runtime information while preserving native runtime behavior. + * + * This component exposes PHP process capabilities through a consistent FireHub Runtime API without altering + * operating system process semantics. + * @since 1.0.0 + */ +final class Process extends NativeRuntime { + + /** + * ### Gets PHP's process ID + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\ProcessIdUnavailableException If failed to get a process ID. + * + * @return positive-int Current PHP process ID. + * + * @warning Process IDs aren't unique, thus they're a weak entropy source. + * We recommend against relying on pids in security-dependent contexts. + */ + public static function ID ():int { + + /** @var positive-int */ + return ($process_id = getmypid()) !== false + ? $process_id : throw new ProcessIdUnavailableException; + + } + +} \ No newline at end of file diff --git a/src/System/Runtime.php b/src/System/Runtime.php new file mode 100644 index 0000000..e1d5e34 --- /dev/null +++ b/src/System/Runtime.php @@ -0,0 +1,126 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Core\Type\Version\Constraint; +use FireHub\Runtime\Exception\SapiUnavailableException; + +use function phpversion; +use function php_sapi_name; +use function version_compare; +use function zend_version; + +/** + * ### PHP Runtime Introspection Utilities + * + * Provides low-level wrappers for inspecting the current PHP runtime environment, including PHP version, + * Zend Engine version, and Server API (SAPI) information while preserving native runtime behavior. + * + * This component exposes PHP runtime metadata through a consistent FireHub Runtime API without altering native + * runtime detection semantics. + * @since 1.0.0 + */ +final class Runtime extends NativeRuntime { + + /** + * ### Type of interface between web server and PHP + * + * Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. + * + * For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values + * depending on the exact SAPI used. + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\SapiUnavailableException If failed to get server + * API. + * + * @return non-empty-string Interface type. + */ + public static function serverAPI ():string { + + return ($sapi_name = php_sapi_name()) !== false + ? $sapi_name : throw new SapiUnavailableException; + + } + + /** + * ### Gets the current PHP or extension version + * @since 1.0.0 + * + * @param null|non-empty-string $extension

+ * An optional extension name. + *

+ * + * @return string|false The current PHP version as a string. + * If a string argument is provided for an extension parameter, phpversion() returns the version of that extension, + * or false if there is no version information associated or the extension isn't enabled. + */ + public static function phpVersion (?string $extension = null):string|false { + + return phpversion($extension); //@phpstan-ignore argument.type + + } + + /** + * ### Gets the version of the current Zend engine + * @since 1.0.0 + * + * @return non-empty-string Zend Engine version number, as a string. + */ + public static function zendVersion ():string { + + /** @var non-empty-string */ + return zend_version(); + + } + + /** + * ### Compares two "PHP-standardized" version number strings + * @since 1.0.0 + * + * @param string $first

+ * First version number. + *

+ * @param string $second

+ * Second version number. + *

+ * @param null|\FireHub\Core\Type\Version\Constraint $comparison [optional]

+ * Comparison constraint. + *

+ * + * @return ($comparison is null + * ? int-mask<-1, 0, 1> + * : bool + * ) Returns -1 if the first version is lower than the second, 0 if they're equal, and 1 if the second is lower. + */ + public static function compareVersion (string $first, string $second, ?Constraint $comparison = null):int|bool { + + /** + * @var ($comparison is null + * ? int-mask<-1, 0, 1> + * : bool + * ) + * + * @phpstan-ignore-next-line + */ + return version_compare( + $first, + $second, + $comparison?->value + ); + + } + +} \ No newline at end of file diff --git a/src/System/Time.php b/src/System/Time.php new file mode 100644 index 0000000..d004851 --- /dev/null +++ b/src/System/Time.php @@ -0,0 +1,122 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime\System; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Str; +use FireHub\Runtime\Exception\InvalidSleepDurationException; + +use function sleep; +use function time_nanosleep; +use function time_sleep_until; +use function usleep; + +/** + * ### PHP Runtime Time Utilities + * + * Provides low-level wrappers for working with time-related runtime operations, including timestamps, + * delays, sleeping, and time measurement while preserving native PHP behavior. + * + * This component exposes PHP time management capabilities through a consistent FireHub Runtime API without + * altering native runtime behavior. + * @since 1.0.0 + */ +final class Time extends NativeRuntime { + + /** + * ### Delay execution + * @since 1.0.0 + * + * @param non-negative-int $seconds

+ * Halt time in seconds. + *

+ * @param non-negative-int $nanoseconds [optional]

+ * Halt time in nanoseconds. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidSleepDurationException If the sleep time is invalid. + * + * @return ($nanoseconds is positive-int ? bool|array{seconds: int<0, max>, nanoseconds: int<0, max>} : bool) + * True on success, false if the call was interrupted by a signal or if nanoseconds are used, an associative + * array will be returned with the components: + * - seconds - number of seconds remaining in the delay + * - nanoseconds - number of nanoseconds remaining in the delay + * + * @phpstan-ignore return.unusedType + */ + public static function sleep (int $seconds, int $nanoseconds = 0):bool|array { + + if ($seconds < 0) + throw new InvalidSleepDurationException( + 'The sleep time must be at least 0.', + [ + 'time' => $seconds, + 'minimum' => 0, + ] + ); + + return $nanoseconds > 0 + ? time_nanosleep($seconds, $nanoseconds) + : sleep($seconds) === 0; + + } + + /** + * ### Delays program execution for the given number of microseconds + * @since 1.0.0 + * + * @param int<0, 999999> $microseconds

+ * Halt time in microseconds. + *

+ * + * @throws \FireHub\Runtime\Exception\InvalidSleepDurationException If the number of microseconds is less than 0 or + * more than 999_999. + * + * @return void + */ + public static function sleepMicroseconds (int $microseconds):void { + + if ($microseconds < 0 || $microseconds > 999_999) + throw new InvalidSleepDurationException( + 'The microsleep time must be between 0 and 999999 microseconds.', + [ + 'time' => $microseconds, + 'minimum' => 0, + 'maximum' => 999_999, + ] + ); + + usleep($microseconds); + + } + + /** + * ### Delays program execution until the given timestamp + * @since 1.0.0 + * + * @uses \FireHub\Runtime\System\Clock::time() To get the current timestamp. + * + * @param int $timestamp

+ * The timestamp when the script should wake. + *

+ * + * @return bool Returns true on success or false on failure. + */ + public static function sleepUntil (int $timestamp):bool { + + return $timestamp <= Clock::time() || time_sleep_until($timestamp); + + } + +} \ No newline at end of file diff --git a/src/Tick.php b/src/Tick.php new file mode 100644 index 0000000..a6dc730 --- /dev/null +++ b/src/Tick.php @@ -0,0 +1,76 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime + */ + +namespace FireHub\Runtime; + +use FireHub\Core\Boundary\Runtime\NativeRuntime; +use FireHub\Runtime\Exception\RegisterTickFailedException; + +use function register_tick_function; +use function unregister_tick_function; + +/** + * ### PHP Runtime Tick Utilities + * + * Provides low-level wrappers for registering and removing tick callbacks using native PHP tick handling while + * preserving runtime behavior. + * + * This component exposes execution tick hooks through a consistent FireHub Runtime API without changing PHP tick + * semantics. + * @since 1.0.0 + */ +final class Tick extends NativeRuntime { + + /** + * ### Register a function for execution on each tick + * + * Registers the given callback to be executed when a tick is called. + * @since 1.0.0 + * + * @param callable $callback

+ * The function to register. + *

+ * @param mixed ...$arguments

+ * Parameters for a callback function. + *

+ * + * @throws \FireHub\Runtime\Exception\RegisterTickFailedException If failed to register tick function. + * + * @return true True on success. + */ + public static function register (callable $callback, mixed ...$arguments):true { + + return register_tick_function($callback, ...$arguments) + ?: throw new RegisterTickFailedException; + + } + + /** + * ### De-register a function for execution on each tick + * + * De-registers the function, so it is no longer executed when a tick is called. + * @since 1.0.0 + * + * @param callable $callback

+ * The function to deregister. + *

+ * + * @return void + */ + public static function unregister (callable $callback):void { + + unregister_tick_function($callback); + + } + +} \ No newline at end of file diff --git a/src/Type/Arr/KeyCase.php b/src/Type/Arr/KeyCase.php new file mode 100644 index 0000000..8603569 --- /dev/null +++ b/src/Type/Arr/KeyCase.php @@ -0,0 +1,52 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Arr; + +use const CASE_LOWER; +use const CASE_UPPER; + +/** + * ### Array Key Case Style + * + * Defines the casing style applied to array string keys during transformation operations. + * + * This type represents the supported key casing modes used by runtime utilities when normalizing array keys while + * preserving PHP native array behavior. + * @since 1.0.0 + */ +enum KeyCase:int { + + /** + * ### Lower case + * + * Converts all characters in a string to the lower case. + * + * "Hello World" → "hello world" + * + * @since 1.0.0 + */ + case LOWER = CASE_LOWER; + + /** + * ### Upper case + * + * Converts all characters in a string to the upper case. + * + * "Hello World" → "HELLO WORLD" + * + * @since 1.0.0 + */ + case UPPER = CASE_UPPER; + +} \ No newline at end of file diff --git a/src/Type/Arr/SortFlag.php b/src/Type/Arr/SortFlag.php new file mode 100644 index 0000000..c77d02c --- /dev/null +++ b/src/Type/Arr/SortFlag.php @@ -0,0 +1,38 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Arr; + +use const SORT_FLAG_CASE; + +/** + * ### Array Sorting Flag + * + * Defines optional modifiers applied to array sorting comparison behavior. + * + * Sorting flags can be combined with sorting types using bitwise operations. + * + * @since 1.0.0 + */ +enum SortFlag:int { + + /** + * ### Case insensitive comparison + * + * Can be combined with SORT_STRING or SORT_NATURAL to compare strings without case sensitivity. + * + * @since 1.0.0 + */ + case CASE_INSENSITIVE = SORT_FLAG_CASE; + +} \ No newline at end of file diff --git a/src/Type/Arr/SortType.php b/src/Type/Arr/SortType.php new file mode 100644 index 0000000..c7529f9 --- /dev/null +++ b/src/Type/Arr/SortType.php @@ -0,0 +1,74 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Arr; + +use const SORT_LOCALE_STRING; +use const SORT_NATURAL; +use const SORT_NUMERIC; +use const SORT_REGULAR; +use const SORT_STRING; + +/** + * ### Array Sorting Type + * + * Defines the comparison type used by array sorting functions. + * + * This enum represents PHP sorting comparison modes and provides a type-safe way to specify how array values are + * compared during sorting operations. + * + * @since 1.0.0 + */ +enum SortType:int { + + /** + * ### Regular comparison + * + * Compare items normally. + * @since 1.0.0 + */ + case REGULAR = SORT_REGULAR; + + /** + * ### Numeric comparison + * + * Compare items numerically. + * @since 1.0.0 + */ + case NUMERIC = SORT_NUMERIC; + + /** + * ### String comparison + * + * Compare items as strings. + * @since 1.0.0 + */ + case STRING = SORT_STRING; + + /** + * ### Locale string comparison + * + * Compare items as strings, based on the current locale. + * @since 1.0.0 + */ + case LOCALE_STRING = SORT_LOCALE_STRING; + + /** + * ### Natural string comparison + * + * Compare items as strings using natural ordering like natsort(). + * @since 1.0.0 + */ + case NATURAL = SORT_NATURAL; + +} \ No newline at end of file diff --git a/src/Type/Arr/UniqueMode.php b/src/Type/Arr/UniqueMode.php new file mode 100644 index 0000000..95ca0ff --- /dev/null +++ b/src/Type/Arr/UniqueMode.php @@ -0,0 +1,68 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Arr; + +use const SORT_LOCALE_STRING; +use const SORT_NUMERIC; +use const SORT_REGULAR; +use const SORT_STRING; + +/** + * ### Array Unique Comparison Mode + * + * Defines the comparison mode used when removing duplicate values from an array. + * + * This enum represents the supported comparison modes of PHP's array_unique() function. + * + * @since 1.0.0 + */ +enum UniqueMode:int { + + /** + * ### Regular comparison + * + * Compare items normally. + * + * @since 1.0.0 + */ + case REGULAR = SORT_REGULAR; + + /** + * ### Numeric comparison + * + * Compare items numerically. + * + * @since 1.0.0 + */ + case NUMERIC = SORT_NUMERIC; + + /** + * ### String comparison + * + * Compare items as strings. + * + * @since 1.0.0 + */ + case STRING = SORT_STRING; + + /** + * ### Locale string comparison + * + * Compare items as strings, based on the current locale. + * + * @since 1.0.0 + */ + case LOCALE_STRING = SORT_LOCALE_STRING; + +} \ No newline at end of file diff --git a/src/Type/Data/Category.php b/src/Type/Data/Category.php new file mode 100644 index 0000000..c17ad16 --- /dev/null +++ b/src/Type/Data/Category.php @@ -0,0 +1,54 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Data; + +/** + * ### PHP Runtime Data Category + * + * Represents the category classification of native PHP runtime data types. + * + * This enum groups PHP data types by their value structure and runtime behavior, allowing consistent + * classification of values across the FireHub Runtime layer. + * @since 1.0.0 + */ +enum Category { + + /** + * ### Scalar data category + * + * Represents data types that contain a single value: + * booleans, integers, floats, and strings. + * @since 1.0.0 + */ + case SCALAR; + + /** + * ### Compound data category + * + * Represents data types that can contain multiple values or structures: + * arrays and objects. + * @since 1.0.0 + */ + case COMPOUND; + + /** + * ### Special data category + * + * Represents data types with special runtime behavior: + * null and resources. + * @since 1.0.0 + */ + case SPECIAL; + +} \ No newline at end of file diff --git a/src/Type/Data/Type.php b/src/Type/Data/Type.php new file mode 100644 index 0000000..b761e2e --- /dev/null +++ b/src/Type/Data/Type.php @@ -0,0 +1,147 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Data; + +/** + * ### PHP Runtime Data Type + * + * Represents the native data types supported by the PHP runtime. + * + * This enum provides a type-safe representation of PHP runtime value types for use throughout the FireHub Runtime + * layer when inspecting, validating, or classifying values without relying on string literals returned by native + * PHP functions. + * @since 1.0.0 + */ +enum Type:string { + + /** + * ### A bool expresses a truth value, it can be either true or false + * @since 1.0.0 + */ + case BOOL = 'boolean'; + + /** + * ### An int is a number of the set Z = {..., -2, -1, 0, 1, 2, ...} + * @since 1.0.0 + */ + case INT = 'integer'; + + /** + * ### A floating-point number is represented approximately with a fixed number of significant digits + * @since 1.0.0 + */ + case FLOAT = 'double'; + + /** + * ### A string is a series of characters, where a character is the same as a byte + * @since 1.0.0 + */ + case STRING = 'string'; + + /** + * ### An ordered map where map is a type that associates values to keys + * @since 1.0.0 + */ + case ARRAY = 'array'; + + /** + * ### An object is an individual instance of the data structure defined by a class + * @since 1.0.0 + */ + case OBJECT = 'object'; + + /** + * ### The special null value represents a variable with no value + * @since 1.0.0 + */ + case NULL = 'NULL'; + + /** + * ### The special resource type is used to store references to some function call or to external PHP resources + * @since 1.0.0 + */ + case RESOURCE = 'resource'; + + /** + * ### A closed resource represents a previously valid PHP resource that has been closed + * @since 1.0.0 + */ + case CLOSED_RESOURCE = 'resource (closed)'; + + /** + * ## Gets the data type category + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Data\Category::SCALAR To check if this enum is a scalar type category. + * @uses \FireHub\Runtime\Type\Data\Category::COMPOUND To check if this enum is a compound type category. + * @uses \FireHub\Runtime\Type\Data\Category::SPECIAL To check if this enum is a special type category. + * + * @return \FireHub\Runtime\Type\Data\Category::* Data type category. + */ + public function category ():Category { + + return match ($this) { + self::BOOL, self::INT, self::FLOAT, self::STRING => Category::SCALAR, + self::ARRAY, self::OBJECT => Category::COMPOUND, + self::NULL, self::RESOURCE, self::CLOSED_RESOURCE => Category::SPECIAL + }; + + } + + /** + * ### Checks if this enum is a scalar type category + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Data\Category::category() To get the data type category. + * @uses \FireHub\Runtime\Type\Data\Category::SCALAR To check if this enum is a scalar type category. + * + * @return bool True if this enum is a scalar type category. + */ + public function isScalar ():bool { + + return $this->category() === Category::SCALAR; + + } + + /** + * ### Checks if this enum is a compound type category + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Data\Category::category() To get the data type category. + * @uses \FireHub\Runtime\Type\Data\Category::COMPOUND To check if this enum is a compound type category. + * + * @return bool True if this enum is a compound type category. + */ + public function isCompound ():bool { + + return $this->category() === Category::COMPOUND; + + } + + /** + * ### Checks if this enum is a special type category + * @since 1.0.0 + * + * @uses \FireHub\Runtime\Type\Data\Category::category() To get the data type category. + * @uses \FireHub\Runtime\Type\Data\Category::SPECIAL To check if this enum is a special type category. + * + * @return bool True if this enum is a special type category. + */ + public function isSpecial ():bool { + + return $this->category() === Category::SPECIAL; + + } + +} \ No newline at end of file diff --git a/src/Type/Resource.php b/src/Type/Resource.php new file mode 100644 index 0000000..f7d3954 --- /dev/null +++ b/src/Type/Resource.php @@ -0,0 +1,55 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type; + +/** + * ### Supported PHP runtime resource types + * + * Represents resource types exposed by PHP native runtime functions. + * + * This enumeration contains stable resource identifiers returned by PHP resource inspection APIs while preserving + * native runtime behavior. + * + * Extension-specific resources should be defined by their corresponding FireHub Capability modules. + * @since 1.0.0 + */ +enum Resource:string { + + /** + * ### Stream resource + * @since 1.0.0 + */ + case STREAM = 'stream'; + + /** + * ### Stream context resource + * @since 1.0.0 + */ + case STREAM_CONTEXT = 'stream-context'; + + /** + * ### Process resource + * @since 1.0.0 + */ + case PROCESS = 'process'; + + /** + * ### Unknown resource type + * + * Represents an unsupported or unidentified native resource type. + * @since 1.0.0 + */ + case UNKNOWN = 'unknown'; + +} \ No newline at end of file diff --git a/src/Type/Str/CaseMode.php b/src/Type/Str/CaseMode.php new file mode 100644 index 0000000..94cdd5c --- /dev/null +++ b/src/Type/Str/CaseMode.php @@ -0,0 +1,54 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime + */ + +namespace FireHub\Runtime\Type\Str; + +use const MB_CASE_LOWER; +use const MB_CASE_TITLE; +use const MB_CASE_UPPER; + +/** + * ### String Case Conversion Mode + * + * Defines the character case conversion mode supported by PHP string transformation functions. + * + * This enum represents the supported conversion modes of PHP's multibyte string case conversion operations. + * @since 1.0.0 + */ +enum CaseMode:int { + + /** + * ### Lowercase conversion + * + * Converts all characters in a string to lowercase. + * @since 1.0.0 + */ + case LOWER = MB_CASE_LOWER; + + /** + * ### Uppercase conversion + * + * Converts all characters in a string to uppercase. + * @since 1.0.0 + */ + case UPPER = MB_CASE_UPPER; + + /** + * ### Title case conversion + * + * Converts the first character of each word to uppercase. + * @since 1.0.0 + */ + case TITLE = MB_CASE_TITLE; + +} \ No newline at end of file diff --git a/tests/DataProviders/ArrDataProvider.php b/tests/DataProviders/ArrDataProvider.php new file mode 100644 index 0000000..132b9c6 --- /dev/null +++ b/tests/DataProviders/ArrDataProvider.php @@ -0,0 +1,67 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; + +/** + * ### Array data provider + * @since 1.0.0 + */ +final class ArrDataProvider { + + /** + * @since 1.0.0 + * + * @return array + */ + public static function list ():array { + + return [ + [[1, 2, 3]], + [[10.2, 200, -3]], + [['x', 'y', 'z']], + [[]] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array + */ + public static function associative ():array { + + return [ + [['one' => 1, 'two' => 2, 'three' => 3]], + [['ONE' => 1, 'TWO' => 2, 'THREE' => 3]], + [[2 => '', 'x' => null, 5 => false]] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array + */ + public static function multidimensional ():array { + + return [ + [['one' => [1, 2, 3], 'two' => [4, 5, 6], 'three' => [7, 8, 9]]], + [[1 => [1 => null, 2 => false], 2 => [1 => true, 'x' => false]]] + ]; + + } + +} \ No newline at end of file diff --git a/tests/DataProviders/ConstantDataProvider.php b/tests/DataProviders/ConstantDataProvider.php new file mode 100644 index 0000000..9763b39 --- /dev/null +++ b/tests/DataProviders/ConstantDataProvider.php @@ -0,0 +1,39 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; + +/** + * ### Constant data provider + * @since 1.0.0 + */ +final class ConstantDataProvider { + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function types ():array { + + return [ + ['testString', 'test'], + ['testInt', 10], + ['testBool', false], + ['testNull', null], + ['testArray', ['x']] + ]; + + } + +} \ No newline at end of file diff --git a/tests/DataProviders/DataDataProvider.php b/tests/DataProviders/DataDataProvider.php new file mode 100644 index 0000000..687ab57 --- /dev/null +++ b/tests/DataProviders/DataDataProvider.php @@ -0,0 +1,163 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; +use Countable; + +/** + * ### Data data provider + * @since 1.0.0 + */ +final class DataDataProvider { + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function string ():array { + + return [ + ['firehub'], + [''] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function int ():array { + + return [ + [10], + [-5], + [0] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function float ():array { + + return [ + [10.5], + [-2.3] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function array ():array { + + return [ + [[1, 2, 3]], + [[1 => 'one', 2 => 'two', 3 => 'three']] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function null ():array { + + return [ + [null] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function bool ():array { + + return [ + [true], + [false] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function callable ():array { + + return [ + [fn() => true], + [new class {public function __invoke () {}}] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function countable ():array { + + return [ + [new class implements Countable {public function count ():int {return 10;}}] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function resource ():array { + + return [ + [fopen('php://stdout', 'wb')] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function closedResource ():array { + + $resource = fopen('php://stdout', 'wb'); + fclose($resource); + + return [ + [$resource] + ]; + + } + +} \ No newline at end of file diff --git a/tests/DataProviders/DateDataProvider.php b/tests/DataProviders/DateDataProvider.php new file mode 100644 index 0000000..c90abe7 --- /dev/null +++ b/tests/DataProviders/DateDataProvider.php @@ -0,0 +1,88 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; + +use FireHub\Core\Type\Date\Zone; + +/** + * ### Date data provider + * @since 1.0.0 + */ +final class DateDataProvider { + + /** + * @since 1.0.0 + * + * @return array + */ + public static function validDates ():array { + + return [ + [1, 1, 1], + [2024, 12, 31], + [1000, 10, 6] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array + */ + public static function invalidDates ():array { + + return [ + [0, -1, -1], + [1, 1, 32], + [1, 13, 12] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array + */ + public static function stringToTime ():array { + + return [ + ['now'], + ['10 September 2000'], + ['+1 day'], + ['+1 week'], + ['+1 week 2 days 4 hours 2 seconds'], + ['next Thursday'], + ['last Monday'] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array<\FireHub\Core\Type\Date\Zone[]> + */ + public static function timezones ():array { + + $zones = []; + foreach (Zone::cases() as $zone) + $zones[][] = $zone; + + return $zones; + + } + +} \ No newline at end of file diff --git a/tests/DataProviders/NumDataProvider.php b/tests/DataProviders/NumDataProvider.php new file mode 100644 index 0000000..bc98eef --- /dev/null +++ b/tests/DataProviders/NumDataProvider.php @@ -0,0 +1,88 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; + +/** + * ### Numeric data provider + * @since 1.0.0 + */ +final class NumDataProvider { + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function positiveInt ():array { + + return [[10], [45874], [INF]]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function negativeInt ():array { + + return [[-1], [-4568], [-INF]]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function positiveFloat ():array { + + return [[0.435435], [45.223], [43253.43543]]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function negativeFloat ():array { + + return [[-0.3532545], [-1.2], [-10.567]]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function null ():array { + + return [[0], [-0], [0.0000], [-0.00]]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function nan ():array { + + return [[NAN]]; + + } + +} \ No newline at end of file diff --git a/tests/DataProviders/ResourceDataProvider.php b/tests/DataProviders/ResourceDataProvider.php new file mode 100644 index 0000000..150b80c --- /dev/null +++ b/tests/DataProviders/ResourceDataProvider.php @@ -0,0 +1,35 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; + +/** + * ### Resource data provider + * @since 1.0.0 + */ +final class ResourceDataProvider { + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function stream ():array { + + return [ + [fopen('php://stdout', 'wb')] + ]; + + } + +} \ No newline at end of file diff --git a/tests/DataProviders/StrDataProvider.php b/tests/DataProviders/StrDataProvider.php new file mode 100644 index 0000000..ad916b8 --- /dev/null +++ b/tests/DataProviders/StrDataProvider.php @@ -0,0 +1,48 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\DataProviders; + +/** + * ### String data provider + * @since 1.0.0 + */ +final class StrDataProvider { + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function stringsSB ():array { + + return [ + ['The lazy fox jumped over the fence.'] + ]; + + } + + /** + * @since 1.0.0 + * + * @return array> + */ + public static function stringsMB ():array { + + return [ + ['đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'] + ]; + + } + +} \ No newline at end of file diff --git a/tests/Stubs/CountableClass.php b/tests/Stubs/CountableClass.php new file mode 100644 index 0000000..9a8e7a4 --- /dev/null +++ b/tests/Stubs/CountableClass.php @@ -0,0 +1,35 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Stubs; + +use Countable; + +/** + * ### Countable class + * @since 1.0.0 + */ +class CountableClass implements Countable { + + /** + * @since 1.0.0 + * + * @return int + */ + public function count ():int { + + return 10; + + } + +} \ No newline at end of file diff --git a/tests/Stubs/EmptyClass.php b/tests/Stubs/EmptyClass.php new file mode 100644 index 0000000..6e22b52 --- /dev/null +++ b/tests/Stubs/EmptyClass.php @@ -0,0 +1,20 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Stubs; + +/** + * ### Normal class + * @since 1.0.0 + */ +class EmptyClass {} \ No newline at end of file diff --git a/tests/Stubs/EmptyEnum.php b/tests/Stubs/EmptyEnum.php new file mode 100644 index 0000000..d6e86e5 --- /dev/null +++ b/tests/Stubs/EmptyEnum.php @@ -0,0 +1,20 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Stubs; + +/** + * ### Normal enum + * @since 1.0.0 + */ +enum EmptyEnum {} \ No newline at end of file diff --git a/tests/Stubs/EmptyInterface.php b/tests/Stubs/EmptyInterface.php new file mode 100644 index 0000000..846d9b5 --- /dev/null +++ b/tests/Stubs/EmptyInterface.php @@ -0,0 +1,20 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Stubs; + +/** + * ### Normal interface + * @since 1.0.0 + */ +interface EmptyInterface {} \ No newline at end of file diff --git a/tests/Stubs/EmptyTrait.php b/tests/Stubs/EmptyTrait.php new file mode 100644 index 0000000..cca8f07 --- /dev/null +++ b/tests/Stubs/EmptyTrait.php @@ -0,0 +1,20 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Stubs; + +/** + * ### Normal trait + * @since 1.0.0 + */ +trait EmptyTrait {} \ No newline at end of file diff --git a/tests/Stubs/FilledClass.php b/tests/Stubs/FilledClass.php new file mode 100644 index 0000000..a1df086 --- /dev/null +++ b/tests/Stubs/FilledClass.php @@ -0,0 +1,39 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Stubs; + +/** + * ### Filled class + * @since 1.0.0 + */ +class FilledClass extends EmptyClass implements EmptyInterface { + + /** + * @since 1.0.0 + */ + use EmptyTrait; + + /** + * @since 1.0.0 + */ + public string $publicVar = 'foo'; + + /** + * @since 1.0.0 + * + * @return void + */ + public function publicMethod ():void {} + +} \ No newline at end of file diff --git a/tests/Unit/Arr/AccessTest.php b/tests/Unit/Arr/AccessTest.php new file mode 100644 index 0000000..6d7cf24 --- /dev/null +++ b/tests/Unit/Arr/AccessTest.php @@ -0,0 +1,297 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use FireHub\Runtime\Exception\ { + EmptyArrayException, InvalidRandomKeyCountException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Access + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Access::class)] +final class AccessTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param array-key $key + * @param array $array + * + * @return void + */ + #[TestWith([true, 2, [1, 2, 3]])] + #[TestWith([false, 3, [1, 2, 3]])] + #[TestWith([false, 'x', [null, 2, 3]])] + public function testKeyExists (bool $expected, int|string $key, array $array):void { + + self::assertSame($expected, Arr\Access::keyExists($array, $key)); + + } + + /** + * @since 1.0.0 + * + * @param int|string|false $expected + * @param array $array + * @param mixed $value + * + * @return void + */ + #[TestWith(['two', ['one' => 1, 'two' => 2, 'three' => 3], 2])] + #[TestWith([false, ['one' => 1, 'two' => 2, 'three' => 3], 5])] + public function testSearch (int|string|false $expected, array $array, mixed $value):void { + + self::assertSame($expected, Arr\Access::search($array, $value)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array-key $key + * @param null|array-key $index + * + * @return void + */ + #[TestWith([[3 => 2, 6 => 5, 9 => 8], ['one' => [1, 2, 3], 'two' => [4, 5, 6], 'three' => [7, 8, 9]], 1, 2])] + public function testColumn (array $expected, array $array, int|string $key, null|int|string $index = null):void { + + self::assertSame($expected, Arr\Access::column($array, $key, $index)); + + } + + /** + * @since 1.0.0 + * + * @param null|array-key $expected + * @param array $array + * + * @return void + */ + #[TestWith([1, ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testFirst (mixed $expected, array $array):void { + + self::assertSame($expected, Arr\Access::first($array)); + + } + + /** + * @since 1.0.0 + * + * @param null|array-key $expected + * @param array $array + * + * @return void + */ + #[TestWith([3, ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testLast (mixed $expected, array $array):void { + + self::assertSame($expected, Arr\Access::last($array)); + + } + + /** + * @since 1.0.0 + * + * @param null|array-key $expected + * @param array $array + * + * @return void + */ + #[TestWith(['one', ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testFirstKey (null|int|string $expected, array $array):void { + + self::assertSame($expected, Arr\Access::firstKey($array)); + + } + + /** + * @since 1.0.0 + * + * @param null|array-key $expected + * @param array $array + * + * @return void + */ + #[TestWith(['three', ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testLastKey (null|int|string $expected, array $array):void { + + self::assertSame($expected, Arr\Access::lastKey($array)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param mixed $filter + * + * @return void + */ + #[TestWith([['one', 'two', 'three'], ['one' => 1, 'two' => 2, 'three' => 3], null])] + #[TestWith([[''], ['' => 3], null])] + #[TestWith([['two'], ['one' => 1, 'two' => 2, 'three' => 3], 2])] + public function testKeys (array $expected, array $array, mixed $filter):void { + + self::assertSame($expected, Arr\Access::keys($array, $filter)); + + } + + /** + * @since 1.0.0 + * + * @param list[] $expected + * @param array $array + * + * @return void + */ + #[TestWith([[1, 2, 3], ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testValues (array $expected, array $array):void { + + self::assertSame($expected, Arr\Access::values($array)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $expected + * @param array $array + * + * @return void + */ + #[TestWith([2, ['one' => 1, 'two' => 2, 'three' => 3]])] + #[TestWith([null, ['one' => 1, 'three' => 3]])] + public function testFind (mixed $expected, array $array):void { + + self::assertSame( + $expected, + Arr\Access::find($array, static fn($value, $key) => $value === 2) + ); + + } + + /** + * @since 1.0.0 + * + * @param null|array-key $expected + * @param array $array + * + * @return void + */ + #[TestWith(['two', ['one' => 1, 'two' => 2, 'three' => 3]])] + #[TestWith([null, ['one' => 1, 'three' => 3]])] + public function testFindKey (mixed $expected, array $array):void { + + self::assertSame( + $expected, + Arr\Access::findKey($array, static fn($value, $key) => $value === 2) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * + * @throws \FireHub\Runtime\Exception\EmptyArrayException + * @throws \FireHub\Runtime\Exception\InvalidRandomKeyCountException + * + * @return void + */ + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3]])] + public function testRandom (array $array):void { + + self::assertArrayHasKey(Arr\Access::random($array), $array); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * @param positive-int $number + * + * @throws \FireHub\Runtime\Exception\EmptyArrayException + * @throws \FireHub\Runtime\Exception\InvalidRandomKeyCountException + * + * @return void + */ + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3], 2])] + public function testRandomMultiple (array $array, int $number):void { + + $expected = Arr\Access::random($array, $number); + + self::assertIsArray($expected); + self::assertCount($number, $expected); + + foreach ($expected as $key) + self::assertArrayHasKey($key, $array); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * @param positive-int $number + * + * @throws \FireHub\Runtime\Exception\InvalidRandomKeyCountException + * + * @return void + */ + #[TestWith([[], 1])] + public function testRandomEmptyArray (array $array, int $number):void { + + $this->expectException(EmptyArrayException::class); + + Arr\Access::random($array, $number); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * @param positive-int $number + * + * @throws \FireHub\Runtime\Exception\EmptyArrayException + * + * @return void + */ + #[TestWith([[1, 1, 1, 2, 3], 0])] + #[TestWith([[1, 1, 1, 2, 3], 10])] + public function testRandomInvalidRange (array $array, int $number):void { + + $this->expectException(InvalidRandomKeyCountException::class); + + Arr\Access::random($array, $number); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/CompositionTest.php b/tests/Unit/Arr/CompositionTest.php new file mode 100644 index 0000000..3315a49 --- /dev/null +++ b/tests/Unit/Arr/CompositionTest.php @@ -0,0 +1,146 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use FireHub\Runtime\Exception\ArrayKeysAndValuesCountMismatchException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Composition + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Composition::class)] +final class CompositionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $keys + * @param array $values + * + * @throws \FireHub\Runtime\Exception\ArrayKeysAndValuesCountMismatchException + * + * @return void + */ + #[TestWith([[1 => 1, 2 => 2, 3 => 3], [1, 2, 3], ['one' => 1, 'two' => 2, 'three' => 3]])] + #[TestWith([['' => 3], [2 => '', 'x' => null, 5 => false], ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testCombine (array $expected, array $keys, array $values):void { + + self::assertSame($expected, Arr\Composition::combine($keys, $values)); + + } + + /** + * @since 1.0.0 + * + * @param array $keys + * @param array $values + * + * @return void + */ + #[TestWith([[], ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testCombineDiffElementNumber (array $keys, array $values):void { + + $this->expectException(ArrayKeysAndValuesCountMismatchException::class); + + Arr\Composition::combine($keys, $values); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array ...$array + * + * @return void + */ + #[TestWith([ + [1, 2, 3, 'one' => 1, 'two' => 2, 'three' => 3], + [1, 2, 3], + ['one' => 1, 'two' => 2, 'three' => 3] + ])] + public function testMerge (array $expected, array ...$array):void { + + self::assertSame($expected, Arr\Composition::merge(...$array)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array ...$arrays + * + * @return void + */ + #[TestWith([ + ['one' => [1, 1], 'two' => [2, 2], 'three' => [3, 3]], + ['one' => 1, 'two' => 2, 'three' => 3], + ['one' => 1, 'two' => 2, 'three' => 3] + ])] + public function testMergeRecursive (array $expected, array ...$arrays):void { + + self::assertSame($expected, Arr\Composition::mergeRecursive(...$arrays)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$replacements + * + * @return void + */ + #[TestWith([ + ['one' => 6, 'two' => 7, 'three' => 3], + ['one' => 1, 'two' => 2, 'three' => 3], + ['one' => 6, 'two' => 7] + ])] + public function testReplace (array $expected, array $array, array ...$replacements):void { + + self::assertSame($expected, Arr\Composition::replace($array, ...$replacements)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$replacements + * + * @return void + */ + #[TestWith([ + ['one' => [4, 2, 3], 'two' => [4, 5, 6], 'three' => [7, 8, 9]], + ['one' => [1, 2, 3], 'two' => [4, 5, 6], 'three' => [7, 8, 9]], + ['one' => [4]] + ])] + public function testReplaceRecursive (array $expected, array $array, array ...$replacements):void { + + self::assertSame($expected, Arr\Composition::replaceRecursive($array, ...$replacements)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/InspectionTest.php b/tests/Unit/Arr/InspectionTest.php new file mode 100644 index 0000000..546886f --- /dev/null +++ b/tests/Unit/Arr/InspectionTest.php @@ -0,0 +1,163 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use FireHub\Tests\Runtime\DataProviders\ArrDataProvider; +use FireHub\Tests\Runtime\Stubs\CountableClass; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small, TestWith +}; +use Countable; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Inspection + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Inspection::class)] +final class InspectionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param array $array + * @param mixed $result + * + * @return void + */ + #[TestWith([true, [1, 2, 3], 0.5])] + #[TestWith([true, ['x', 'y', 'z'], 'e'])] + #[TestWith([false, ['x', 'y', 'z'], 'y'])] + public function testAll (bool $expected, array $array, mixed $result):void { + + self::assertSame($expected, Arr\Inspection::all($array, static fn($value) => $value >= $result)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param array $array + * @param mixed $result + * + * @return void + */ + #[TestWith([true, [1, 2, 3], 2])] + #[TestWith([false, [1, 2, 3], 2.5])] + #[TestWith([true, ['x', 'y', 'z'], 'y'])] + #[TestWith([false, ['x', 'y', 'z'], 'e'])] + public function testAny (bool $expected, array $array, mixed $result):void { + + self::assertSame($expected, Arr\Inspection::any($array, static fn($value) => $value === $result)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param array $array + * @param mixed $value + * + * @return void + */ + #[TestWith([true, [1, 2, 3], 2])] + #[TestWith([false, [1, 2, 3], 4])] + #[TestWith([true, [null, 2, 3], null])] + public function testInArray (bool $expected, array $array, mixed $value):void { + + self::assertSame($expected, Arr\Inspection::inArray($array, $value)); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * + * @return void + */ + #[DataProviderExternal(ArrDataProvider::class, 'list')] + public function testIsList (array $array):void { + + self::assertTrue(Arr\Inspection::isList($array)); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * + * @return void + */ + #[DataProviderExternal(ArrDataProvider::class, 'associative')] + #[DataProviderExternal(ArrDataProvider::class, 'multidimensional')] + public function testIsNotList (array $array):void { + + self::assertFalse(Arr\Inspection::isList($array)); + + } + + /** + * @since 1.0.0 + * + * @param int $expected + * @param array|Countable $value + * @param bool $recursive + * + * @return void + */ + #[TestWith([2, [1, 2]])] + #[TestWith([0, []])] + #[TestWith([5, [1, 2, [1, 1]], true])] + public function testCount (int $expected, array|Countable $value, bool $recursive = false):void { + + self::assertSame($expected, Arr\Inspection::count($value, $recursive)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testCountWithCountable ():void { + + self::assertSame(10, Arr\Inspection::count(new CountableClass())); + + } + + /** + * @since 1.0.0 + * + * @param positive-int[] $expected + * @param array $array + * + * @return void + */ + #[TestWith([[1 => 1, 2 => 1], [1, 2]])] + #[TestWith([[], []])] + public function testCountValues (array $expected, array $array):void { + + self::assertSame($expected, Arr\Inspection::countValues($array)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/MathTest.php b/tests/Unit/Arr/MathTest.php new file mode 100644 index 0000000..8aa287d --- /dev/null +++ b/tests/Unit/Arr/MathTest.php @@ -0,0 +1,61 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Math + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Math::class)] +final class MathTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param int|float $expected + * @param array $array + * + * @return void + */ + #[TestWith([6, ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testProduct (int|float $expected, array $array):void { + + self::assertSame($expected, Arr\Math::product($array)); + + } + + /** + * @since 1.0.0 + * + * @param int|float $expected + * @param array $array + * + * @return void + */ + #[TestWith([6, ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testSum (int|float $expected, array $array):void { + + self::assertSame($expected, Arr\Math::sum($array)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/MutationTest.php b/tests/Unit/Arr/MutationTest.php new file mode 100644 index 0000000..089baac --- /dev/null +++ b/tests/Unit/Arr/MutationTest.php @@ -0,0 +1,101 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Mutation + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Mutation::class)] +final class MutationTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * + * @return void + */ + #[TestWith([[1, 2], [1, 2, 3]])] + public function testPop (array $expected, array $actual):void { + + Arr\Mutation::pop($actual); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * @param mixed ...$values + * + * @return void + */ + #[TestWith([[1, 2, 3, 4], [1, 2, 3], 4])] + public function testPush (array $expected, array $actual, mixed ...$values):void { + + Arr\Mutation::push($actual, ...$values); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * + * @return void + */ + #[TestWith([[2, 3], [1, 2, 3]])] + public function testShift (array $expected, array $actual):void { + + Arr\Mutation::shift($actual); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * @param mixed ...$values + * + * @return void + */ + #[TestWith([[0, 1, 2, 3], [1, 2, 3], 0])] + public function testUnshift (array $expected, array $actual, mixed ...$values):void { + + Arr\Mutation::unshift($actual, ...$values); + + self::assertSame($expected, $actual); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/OrderingTest.php b/tests/Unit/Arr/OrderingTest.php new file mode 100644 index 0000000..b6f7b2b --- /dev/null +++ b/tests/Unit/Arr/OrderingTest.php @@ -0,0 +1,205 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use FireHub\Core\Meta\Enum\Order; +use FireHub\Runtime\Type\Arr\ { + SortFlag, SortType +}; +use FireHub\Tests\Runtime\DataProviders\ArrDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Ordering + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Ordering::class)] +final class OrderingTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * @param bool $preserve_keys + * @param \FireHub\Core\Meta\Enum\Order $order + * @param \FireHub\Runtime\Type\Arr\SortType $type + * @param \FireHub\Runtime\Type\Arr\SortFlag ...$flags + * + * @return void + */ + #[TestWith([ + ['Orange1', 'orange2', 'Orange3', 'orange20'], + [1 => 'Orange1', 2 => 'orange2', 3 => 'Orange3', 4 => 'orange20'], + false, + Order::ASC, + SortType::NATURAL, + SortFlag::CASE_INSENSITIVE + ])] + #[TestWith([ + [1 => 'Orange1', 2 => 'orange2', 3 => 'Orange3', 4 => 'orange20'], + [1 => 'Orange1', 4 => 'orange20', 2 => 'orange2', 3 => 'Orange3'], + true, + Order::ASC, + SortType::NATURAL, + SortFlag::CASE_INSENSITIVE + ])] + #[TestWith([ + ['orange20', 'Orange3', 'orange2', 'Orange1'], + [1 => 'Orange1', 2 => 'orange2', 3 => 'Orange3', 4 => 'orange20'], + false, + Order::DESC, + SortType::NATURAL, + SortFlag::CASE_INSENSITIVE + ])] + #[TestWith([ + [4 => 'orange20', 3 => 'Orange3', 2 => 'orange2', 1 => 'Orange1'], + [1 => 'Orange1', 4 => 'orange20', 2 => 'orange2', 3 => 'Orange3'], + true, + Order::DESC, + SortType::NATURAL, + SortFlag::CASE_INSENSITIVE + ])] + public function testSort (array $expected, array $actual, bool $preserve_keys = false, Order $order = Order::ASC, SortType $type = SortType::REGULAR, SortFlag ...$flags):void { + + Arr\Ordering::sort($actual, $preserve_keys, $order, $type, ...$flags); + + self::assertSame($expected, $actual); + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * @param \FireHub\Core\Meta\Enum\Order $order + * @param \FireHub\Runtime\Type\Arr\SortType $type + * @param \FireHub\Runtime\Type\Arr\SortFlag ...$flags + * + * @return void + */ + #[TestWith([ + ['age' => 25, 'firstname' => 'John', 'gender' => 'male', 'height' => '190cm', 'lastname' => 'Doe'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm', 'gender' => 'male'] + ])] + #[TestWith([ + ['lastname' => 'Doe', 'height' => '190cm', 'gender' => 'male', 'firstname' => 'John', 'age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm', 'gender' => 'male'], + Order::DESC, + SortType::STRING + ])] + public function testSortByKeys (array $expected, array $actual, Order $order = Order::ASC, SortType $type = SortType::REGULAR, SortFlag ...$flags):void { + + Arr\Ordering::sortByKeys($actual, $order, $type, ...$flags); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * @param bool $preserve_keys + * + * @return void + */ + #[TestWith([ + ['190cm', 25, 'Doe', 'John', 'male'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm', 'gender' => 'male'] + ])] + #[TestWith([ + ['height' => '190cm', 'age' => 25, 'lastname' => 'Doe', 'firstname' => 'John', 'gender' => 'male'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm', 'gender' => 'male'], + true + ])] + public function testSortBy (array $expected, array $actual, bool $preserve_keys = false):void { + + Arr\Ordering::sortBy($actual, static function ($current, $next) { + if ($current === $next) return 0; + return ($current < $next) ? -1 : 1; + }, $preserve_keys); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * + * @return void + */ + #[TestWith([ + ['age' => 25, 'firstname' => 'John', 'gender' => 'male', 'height' => '190cm', 'lastname' => 'Doe'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm', 'gender' => 'male'] + ])] + public function testSortKeysBy (array $expected, array $actual):void { + + Arr\Ordering::sortKeysBy($actual, static function ($current, $next) { + if ($current === $next) return 0; + return ($current < $next) ? -1 : 1; + }); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * + * @return void + */ + #[TestWith([ + [[0, 10, 100, 100], [4, 1, 2, 3]], + [[10, 100, 100, 0], [1, 3, 2, 4]]] + )] + public function testMultiSort (array $expected, array $actual):void { + + Arr\Ordering::multiSort(...$actual); + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $actual + * + * @return void + */ + #[DataProviderExternal(ArrDataProvider::class, 'list')] + public function testShuffle (array $actual):void { + + $expected = $actual; + + Arr\Ordering::shuffle($actual); + + self::assertEqualsCanonicalizing($expected, $actual); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/PointerTest.php b/tests/Unit/Arr/PointerTest.php new file mode 100644 index 0000000..60f1ee8 --- /dev/null +++ b/tests/Unit/Arr/PointerTest.php @@ -0,0 +1,55 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Pointer + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Pointer::class)] +final class PointerTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param array $array + * + * @return void + */ + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3]])] + public function testInternalPointers (array $array):void { + + Arr\Pointer::reset($array); + + self::assertSame(1, Arr\Pointer::current($array)); + + self::assertSame(2, Arr\Pointer::next($array)); + + self::assertSame(1, Arr\Pointer::prev($array)); + + self::assertSame(3, Arr\Pointer::end($array)); + + self::assertSame('three', Arr\Pointer::key($array)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/SetOperationTest.php b/tests/Unit/Arr/SetOperationTest.php new file mode 100644 index 0000000..76caab4 --- /dev/null +++ b/tests/Unit/Arr/SetOperationTest.php @@ -0,0 +1,437 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - SetOperation + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\SetOperation::class)] +final class SetOperationTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testDifference (array $expected, array $array, array ...$excludes):void { + + self::assertSame($expected, Arr\SetOperation::difference($array, ...$excludes)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testDifferenceUsing (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::differenceUsing($array, $excludes, + static function ($value_a, $value_b) { + if ($value_a === $value_b && $value_a !== 'two') return 0; + return ($value_a > $value_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$excludes + * + * @return void + */ + #[TestWith([ + ['age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['firstname' => 'Jane', 'lastname' => 'Doe', 'height' => '160cm'] + ])] + public function testDifferenceKey (array $expected, array $array, array ...$excludes):void { + + self::assertSame($expected, Arr\SetOperation::differenceKey($array, ...$excludes)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'lastname' => 'Doe', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testDifferenceUsingKey (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::differenceUsingKey($array, $excludes, + static function ($key_a, $key_b) { + if ($key_a === $key_b && $key_a !== 'lastname') return 0; + return ($key_a > $key_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testDifferenceAssoc (array $expected, array $array, array ...$excludes):void { + + self::assertSame($expected, Arr\SetOperation::differenceAssoc($array, ...$excludes)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'lastname' => 'Doe', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['age' => 25] + ])] + public function testDifferenceAssocUsingValue (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::differenceAssocUsingValue($array, $excludes, + static function ($value_a, $value_b) { + if ($value_a === $value_b && $value_a !== 'Doe') return 0; + return ($value_a > $value_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'lastname' => 'Doe', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testDifferenceAssocUsingKey (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::differenceAssocUsingKey($array, $excludes, + static function ($key_a, $key_b) { + if ($key_a === $key_b && $key_a !== 'lastname') return 0; + return ($key_a > $key_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'lastname' => 'Doe', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testDifferenceAssocUsingKeyValue (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::differenceAssocUsingKeyValue($array, $excludes, + static function ($value_a, $value_b) { + if ($value_a === $value_b && $value_a !== 'Doe') return 0; + return ($value_a > $value_b) ? 1 : -1; + }, static function ($key_a, $key_b) { + if ($key_a === $key_b && $key_a !== 'lastname') return 0; + return ($key_a > $key_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$excludes + * + * @return void + */ + #[TestWith([ + ['lastname' => 'Doe', 'age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testIntersect (array $expected, array $array, array ...$excludes):void { + + self::assertSame($expected, Arr\SetOperation::intersect($array, ...$excludes)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['lastname' => 'Doe', 'age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testIntersectUsing (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::intersectUsing($array, $excludes, + static function ($value_a, $value_b) { + if ($value_a === $value_b && $value_a !== 'two') return 0; + return ($value_a > $value_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['firstname' => 'Jane', 'lastname' => 'Doe', 'height' => '160cm'] + ])] + public function testIntersectUsingKey (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::intersectUsingKey($array, $excludes, + static function ($key_a, $key_b) { + if ($key_a === $key_b && $key_a !== 'lastname') return 0; + return ($key_a > $key_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$excludes + * + * @return void + */ + #[TestWith([ + ['firstname' => 'John', 'lastname' => 'Doe', 'height' => '190cm'], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['firstname' => 'Jane', 'lastname' => 'Doe', 'height' => '160cm'] + ])] + public function testIntersectKey (array $expected, array $array, array ...$excludes):void { + + self::assertSame($expected, Arr\SetOperation::intersectKey($array, ...$excludes)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array ...$excludes + * + * @return void + */ + #[TestWith([ + ['lastname' => 'Doe', 'age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testIntersectAssoc (array $expected, array $array, array ...$excludes):void { + + self::assertSame($expected, Arr\SetOperation::intersectAssoc($array, ...$excludes)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testIntersectAssocUsingValue (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::intersectAssocUsingValue($array, $excludes, + static function ($value_a, $value_b) { + if ($value_a === $value_b && $value_a !== 'Doe') return 0; + return ($value_a > $value_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testIntersectAssocUsingKey (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::intersectAssocUsingKey($array, $excludes, + static function ($key_a, $key_b) { + if ($key_a === $key_b && $key_a !== 'lastname') return 0; + return ($key_a > $key_b) ? 1 : -1; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param array $excludes + * + * @return void + */ + #[TestWith([ + ['age' => 25], + ['firstname' => 'John', 'lastname' => 'Doe', 'age' => 25, 'height' => '190cm'], + ['lastname' => 'Doe', 'age' => 25] + ])] + public function testIntersectAssocUsingKeyValue (array $expected, array $array, array $excludes):void { + + self::assertSame( + $expected, + Arr\SetOperation::intersectAssocUsingKeyValue($array, $excludes, + static function ($value_a, $value_b) { + if ($value_a === $value_b && $value_a !== 'Doe') return 0; + return ($value_a > $value_b) ? 1 : -1; + }, static function ($key_a, $key_b) { + if ($key_a === $key_b && $key_a !== 'lastname') return 0; + return ($key_a > $key_b) ? 1 : -1; + } + ) + ); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/StructureTest.php b/tests/Unit/Arr/StructureTest.php new file mode 100644 index 0000000..29913fd --- /dev/null +++ b/tests/Unit/Arr/StructureTest.php @@ -0,0 +1,227 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use FireHub\Runtime\Exception\ { + InvalidArrayLengthException, InvalidChunkLengthException, InvalidRangeStepException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Structure + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Structure::class)] +final class StructureTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param positive-int $length + * @param bool $preserve_keys + * + * @throws \FireHub\Runtime\Exception\InvalidChunkLengthException + * + * @return void + */ + #[TestWith([[[1, 2], [3]], ['one' => 1, 'two' => 2, 'three' => 3], 2])] + #[TestWith([[['one' => 1], ['two' => 2], ['three' => 3]], ['one' => 1, 'two' => 2, 'three' => 3], 1, true])] + public function testChunk (array $expected, array $array, int $length, bool $preserve_keys = false):void { + + self::assertSame($expected, Arr\Structure::chunk($array, $length, $preserve_keys)); + + } + + /** + * @since 1.0.0 + * + * @param array $array + * @param positive-int $length + * @param bool $preserve_keys + * + * @return void + */ + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3], 0])] + public function testChunkLengthLessThenZero (array $array, int $length, bool $preserve_keys = false):void { + + $this->expectException(InvalidChunkLengthException::class); + + Arr\Structure::chunk($array, $length, $preserve_keys); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param mixed $value + * @param int $start_index + * @param positive-int $length + * + * @throws \FireHub\Runtime\Exception\InvalidArrayLengthException + * + * @return void + */ + #[TestWith([[1, 1, 1, 1, 1], 1, 0, 5])] + #[TestWith([[-2 => 1, -1 => 1, 0 => 1], 1, -2, 3])] + public function testFill (array $expected, mixed $value, int $start_index, int $length):void { + + self::assertSame($expected, Arr\Structure::fill($value, $start_index, $length)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * @param int $start_index + * @param positive-int $length + * + * @return void + */ + #[TestWith([1, 0, -5])] + public function testFillOutOfRangeWithNegativeNumber (mixed $value, int $start_index, int $length):void { + + $this->expectException(InvalidArrayLengthException::class); + + Arr\Structure::fill($value, $start_index, $length); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $keys + * @param mixed $value + * + * @return void + */ + #[TestWith([[1 => 1, 2 => 1, 3 => 1, '' => 1], [1, 2, 3, null], 1])] + public function testFillKeys (array $expected, array $keys, mixed $value):void { + + self::assertSame($expected, Arr\Structure::fillKeys($keys, $value)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param int $length + * @param mixed $value + * + * @return void + */ + #[TestWith([[1, 2, 3, 'x', 'x'], [1, 2, 3], 5, 'x'])] + #[TestWith([['x', 'x', 1, 2, 3], [1, 2, 3], -5, 'x'])] + #[TestWith([[1, 2, 3], [1, 2, 3], 2, 'x'])] + public function testPad (array $expected, array $array, int $length, mixed $value):void { + + self::assertSame($expected, Arr\Structure::pad($array, $length, $value)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param int $offset + * @param null|int $length + * @param bool $preserve_keys + * + * @return void + */ + #[TestWith([[2, 3], [1, 2, 3], 1])] + #[TestWith([[1 => 2, 2 => 3], [1, 2, 3], 1, null, true])] + #[TestWith([[0 => 3], [1, 2, 3], -1])] + public function testSlice (array $expected, array $array, int $offset, ?int $length = null, bool $preserve_keys = + false):void { + + self::assertSame($expected, Arr\Structure::slice($array, $offset, $length, $preserve_keys)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param int $offset + * @param null|int $length + * @param array $replacement + * + * @return void + */ + #[TestWith([[3], [1, 2, 3], 0, 2, []])] + #[TestWith([[5, 3], [1, 2, 3], 0, 2, [5]])] + #[TestWith([[1, 3], [1, 2, 3], -2, 1, []])] + #[TestWith([[1, 3], [1, 2, 3], -2, 1, []])] + public function testSplice (array $expected, array $array, int $offset, ?int $length = null, mixed $replacement = []):void { + + Arr\Structure::splice($array, $offset, $length, $replacement); + + self::assertSame($expected, $array); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param int|float|string $start + * @param int|float|string $end + * @param positive-int|float $step + * + * @throws \FireHub\Runtime\Exception\InvalidRangeStepException + * + * @return void + */ + #[TestWith([[1, 3, 5, 7, 9], 1, 10, 2])] + public function testRange (array $expected, int|float|string $start, int|float|string $end, int|float $step = 1):void { + + self::assertSame($expected, Arr\Structure::range($start, $end, $step)); + + } + + /** + * @since 1.0.0 + * + * @param int|float|string $start + * @param int|float|string $end + * @param positive-int|float $step + * + * @return void + */ + #[TestWith([1, 10, 0])] + #[TestWith([1, 10, -2])] + public function testInvalidRange (int|float|string $start, int|float|string $end, int|float $step):void { + + $this->expectException(InvalidRangeStepException::class); + + Arr\Structure::range($start, $end, $step); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Arr/TransformTest.php b/tests/Unit/Arr/TransformTest.php new file mode 100644 index 0000000..4ea7389 --- /dev/null +++ b/tests/Unit/Arr/TransformTest.php @@ -0,0 +1,202 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Arr; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Arr; +use FireHub\Runtime\Type\Arr\KeyCase; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Array Runtime Wrapper Utility - Transform + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Arr\Transform::class)] +final class TransformTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param mixed $expected + * @param array $array + * @param mixed $initial + * + * @return void + */ + #[TestWith([6, [1, 2, 3]])] + #[TestWith([9, [1, 2, 3], 3])] + public function testReduce (mixed $expected, array $array, mixed $initial = null):void { + + if ($initial === null) + self::assertSame($expected, Arr\Transform::reduce($array, static fn($carry, $item) => $carry + $item)); + else + self::assertSame($expected, Arr\Transform::reduce($array, static fn($carry, $item) => $carry + $item, $initial)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param \FireHub\Runtime\Type\Arr\KeyCase $style + * + * @return void + */ + #[TestWith([['ONE' => 1, 'TWO' => 2, 'THREE' => 3], ['one' => 1, 'two' => 2, 'three' => 3], KeyCase::UPPER])] + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3], ['ONE' => 1, 'TWO' => 2, 'THREE' => 3], KeyCase::LOWER])] + public function testFoldKeys (array $expected, array $array, KeyCase $style):void { + + self::assertSame($expected, Arr\Transform::keyCase($array, $style)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * + * @return void + */ + #[TestWith([['three' => 3], ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testFilter (array $expected, array $array):void { + + self::assertSame( + $expected, + Arr\Transform::filter($array, static function ($value, $key) { + return $key !== 'one' && $value > 2; + } + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * + * @return void + */ + #[TestWith([[0 => 'foo', 2 => -1], [0 => 'foo', 1 => false, 2 => -1, 3 => null, 4 => '', 5 => '0', 6 => 0]])] + public function testFilterWithoutCallback (array $expected, array $array):void { + + self::assertSame($expected, Arr\Transform::filter($array)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * + * @return void + */ + #[TestWith([[1 => 'one', 2 => 'two', 3 => 'three'], ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testFlip (array $expected, array $array):void { + + self::assertSame($expected, Arr\Transform::flip($array)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * + * @return void + */ + #[TestWith([['one' => '1-x', 'two' => '2-x', 'three' => '3-x'], ['one' => 1, 'two' => 2, 'three' => 3]])] + public function testMap (array $expected, array $array):void { + + self::assertSame($expected, Arr\Transform::map($array, static fn($value) => $value.'-x')); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * + * @return void + */ + #[TestWith([['0-x', '1-x', '2-x'], [0, 1, 2]])] + public function testWalk (array $expected, array $actual):void { + + Arr\Transform::walk($actual, static fn(&$value, $key) => $value = $key.'-x'); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $actual + * + * @return void + */ + #[TestWith([[['a' => 'a-x', 'b' => 'b-x'], '1-x', '2-x'], [['a' => 'r','b' => 'g'], '1' => 'b', '2' => 'y']])] + public function testWalkRecursive (array $expected, array $actual):void { + + Arr\Transform::walkRecursive($actual, static fn(&$value, $key) => $value = $key.'-x'); + + self::assertSame($expected, $actual); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * @param bool $preserve_keys + * + * @return void + */ + #[TestWith([[3, 2, 1], [1, 2, 3]])] + #[TestWith([[2 => 3, 1 => 2, 0 => 1], [1, 2, 3], true])] + public function testReverse (array $expected, array $array, bool $preserve_keys = false):void { + + self::assertSame($expected, Arr\Transform::reverse($array, $preserve_keys)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param array $array + * + * @return void + */ + #[TestWith([[0 => 1, 3 => 2, 4 => 3], [1, 1, 1, 2, 3]])] + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3], ['one' => 1, 'one2' => 1, 'two' => 2, 'three' => 3]])] + public function testUnique (array $expected, array $array):void { + + self::assertSame($expected, Arr\Transform::unique($array)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Char/MBTest.php b/tests/Unit/Char/MBTest.php new file mode 100644 index 0000000..68608e0 --- /dev/null +++ b/tests/Unit/Char/MBTest.php @@ -0,0 +1,70 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Char; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Char; +use FireHub\Core\Type\Str\Encoding; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Multibyte Character Runtime Wrapper Utility - MB + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Char\MB::class)] +final class MBTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param int $codepoint + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['A', 65, Encoding::UTF_8])] + #[TestWith(['?', 63])] + #[TestWith(['€', 0x20AC])] + #[TestWith(['🐘', 128024])] + public function testChr (string $expected, int $codepoint, ?Encoding $encoding = null):void { + + self::assertSame($expected, Char\MB::chr($codepoint, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param int $expected + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['A', 65, Encoding::UTF_8])] + #[TestWith(['?', 63])] + #[TestWith(['€', 0x20AC])] + #[TestWith(['🐘', 128024])] + public function testOrd (string $string, int $expected, ?Encoding $encoding = null):void { + + self::assertSame($expected, Char\MB::ord($string, $encoding)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Char/SBTest.php b/tests/Unit/Char/SBTest.php new file mode 100644 index 0000000..1210026 --- /dev/null +++ b/tests/Unit/Char/SBTest.php @@ -0,0 +1,86 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Char; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Char; +use FireHub\Runtime\Exception\InvalidCharacterCodepointException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte Character Runtime Wrapper Utility - SB + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Char\SB::class)] +final class SBTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $string + * @param int<0, 255> $codepoint + * + * @throws \FireHub\Runtime\Exception\InvalidCharacterCodepointException + * + * @return void + */ + #[TestWith(['!', 33])] + #[TestWith(['@', 64])] + #[TestWith(['a', 97])] + public function testChr (string $string, int $codepoint):void { + + self::assertSame($string, Char\SB::chr($codepoint)); + + } + + /** + * @since 1.0.0 + * + * @param int<0, 255> $codepoint + * + * @return void + */ + #[TestWith([-1])] + #[TestWith([256])] + public function testChrOutsideValidRange (int $codepoint):void { + + $this->expectException(InvalidCharacterCodepointException::class); + + Char\SB::chr($codepoint); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param int<0, 255> $codepoint + * + * @return void + */ + #[TestWith(['!', 33])] + #[TestWith(['@', 64])] + #[TestWith(['a', 97])] + #[TestWith(['', 0])] + public function testOrd (string $string, int $codepoint):void { + + self::assertSame($codepoint, Char\SB::ord($string)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ConstantTest.php b/tests/Unit/ConstantTest.php new file mode 100644 index 0000000..caee1aa --- /dev/null +++ b/tests/Unit/ConstantTest.php @@ -0,0 +1,123 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Constant; +use FireHub\Runtime\Exception\{ + CannotDefineConstantException, ConstantAlreadyDefinedException, UndefinedConstantException +}; +use FireHub\Tests\Runtime\DataProviders\ConstantDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Depends, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Constant + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Constant::class)] +final class ConstantTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * @param null|array|scalar $value + * + * @return void + */ + #[Depends('testDefine')] + #[DataProviderExternal(ConstantDataProvider::class, 'types')] + public function testDefined (string $name, null|array|bool|float|int|string $value):void { + + self::assertTrue( Constant::defined($name)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * @param null|array|scalar $value + * + * @throws \FireHub\Runtime\Exception\ConstantAlreadyDefinedException + * @throws \FireHub\Runtime\Exception\CannotDefineConstantException + * + * @return void + */ + #[DataProviderExternal(ConstantDataProvider::class, 'types')] + public function testDefine (string $name, null|array|bool|float|int|string $value):void { + + self::assertTrue( Constant::define($name, $value)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * @param null|array|scalar $value + * + * @throws \FireHub\Runtime\Exception\CannotDefineConstantException + * + * @return void + */ + #[DataProviderExternal(ConstantDataProvider::class, 'types')] + public function testDefineAlreadyExist (string $name, null|array|bool|float|int|string $value):void { + + $this->expectException(ConstantAlreadyDefinedException::class); + + self::assertTrue( Constant::define($name, $value)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * @param null|array|scalar $value + * + * @@throws \FireHub\Runtime\Exception\UndefinedConstantException + * + * @return void + */ + #[Depends('testDefine')] + #[DataProviderExternal(ConstantDataProvider::class, 'types')] + public function testValue (string $name, null|array|bool|float|int|string $value):void { + + self::assertSame($value, Constant::value($name)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * + * @return void + */ + #[Depends('testDefine')] + #[TestWith(['NotDefined'])] + public function testValueNotFound (string $name):void { + + $this->expectException(UndefinedConstantException::class); + + Constant::value($name); + + } + +} \ No newline at end of file diff --git a/tests/Unit/DataTest.php b/tests/Unit/DataTest.php new file mode 100644 index 0000000..285bdea --- /dev/null +++ b/tests/Unit/DataTest.php @@ -0,0 +1,880 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ { + Data, DataIs +}; +use FireHub\Runtime\Type\Data\Type; +use FireHub\Runtime\Exception\{ + ArrayToStringConversionException, CannotSerializeException, CannotUnserializeException, + ResourceTypeConversionException +}; +use FireHub\Tests\Runtime\DataProviders\DataDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small, TestWith +}; + +/** + * ### Test PHP Data Runtime Utility + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Data::class)] +#[CoversClass(DataIs::class)] +final class DataTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'array')] + public function testArray (mixed $value):void { + + self::assertTrue(DataIs::array($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotArray (mixed $value):void { + + self::assertFalse(DataIs::array($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testBool (mixed $value):void { + + self::assertTrue(DataIs::bool($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotBool (mixed $value):void { + + self::assertFalse(DataIs::bool($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'callable')] + public function testCallable (mixed $value):void { + + self::assertTrue(DataIs::callable($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotCallable (mixed $value):void { + + self::assertFalse(DataIs::callable($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + public function testCountable (mixed $value):void { + + self::assertTrue(DataIs::countable($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotCountable (mixed $value):void { + + self::assertFalse(DataIs::countable($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'float')] + public function testFloat (mixed $value):void { + + self::assertTrue(DataIs::float($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotFloat (mixed $value):void { + + self::assertFalse(DataIs::float($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'int')] + public function testInt (mixed $value):void { + + self::assertTrue(DataIs::int($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotInt (mixed $value):void { + + self::assertFalse(DataIs::int($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'array')] + public function testIterable (mixed $value):void { + + self::assertTrue(DataIs::iterable($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotIterable (mixed $value):void { + + self::assertFalse(DataIs::iterable($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'null')] + public function testNull (mixed $value):void { + + self::assertTrue(DataIs::null($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotNull (mixed $value):void { + + self::assertFalse(DataIs::null($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + public function testNumeric (mixed $value):void { + + self::assertTrue(DataIs::numeric($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotNumeric (mixed $value):void { + + self::assertFalse(DataIs::numeric($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + public function testObject (mixed $value):void { + + self::assertTrue(DataIs::object($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotObject (mixed $value):void { + + self::assertFalse(DataIs::object($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testResource (mixed $value):void { + + self::assertTrue(DataIs::resource($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + public function testNotResource (mixed $value):void { + + self::assertFalse(DataIs::resource($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testScalar (mixed $value):void { + + self::assertTrue(DataIs::scalar($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotsScalar (mixed $value):void { + + self::assertFalse(DataIs::scalar($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + public function testString (mixed $value):void { + + self::assertTrue(DataIs::string($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testNotString (mixed $value):void { + + self::assertFalse(DataIs::string($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + public function testGetDebugType (mixed $value):void { + + self::assertSame('string', Data::getDebugType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + public function testGetTypeString (mixed $value):void { + + self::assertSame(Type::STRING, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'int')] + public function testGetTypeInt (mixed $value):void { + + self::assertSame(Type::INT, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'float')] + public function testGetTypeFloat (mixed $value):void { + + self::assertSame(Type::FLOAT, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'array')] + public function testGetTypeArray (mixed $value):void { + + self::assertSame(Type::ARRAY, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'null')] + public function testGetTypeNull (mixed $value):void { + + self::assertSame(Type::NULL, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testGetTypeBool (mixed $value):void { + + self::assertSame(Type::BOOL, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'callable')] + #[DataProviderExternal(DataDataProvider::class, 'countable')] + public function testGetTypeObject (mixed $value):void { + + self::assertSame(Type::OBJECT, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'resource')] + public function testGetTypeResource (mixed $value):void { + + self::assertSame(Type::RESOURCE, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'closedResource')] + public function testGetTypeClosedResource (mixed $value):void { + + self::assertSame(Type::CLOSED_RESOURCE, Data::getType($value)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testSetTypeString (mixed $value):void { + + self::assertSame(Type::STRING, Data::getType(Data::setType($value, Type::STRING))); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testSetTypeInt (mixed $value):void { + + self::assertSame(Type::INT, Data::getType(Data::setType($value, Type::INT))); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testSetTypeFloat (mixed $value):void { + + self::assertSame(Type::FLOAT, Data::getType(Data::setType($value, Type::FLOAT))); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testSetTypeArray (mixed $value):void { + + self::assertSame(Type::ARRAY, Data::getType(Data::setType($value, Type::ARRAY))); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testSetTypeNull (mixed $value):void { + + self::assertSame(Type::NULL, Data::getType(Data::setType($value, Type::NULL))); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + #[DataProviderExternal(DataDataProvider::class, 'int')] + #[DataProviderExternal(DataDataProvider::class, 'float')] + #[DataProviderExternal(DataDataProvider::class, 'array')] + #[DataProviderExternal(DataDataProvider::class, 'null')] + #[DataProviderExternal(DataDataProvider::class, 'bool')] + public function testSetTypeBool (mixed $value):void { + + self::assertSame(Type::BOOL, Data::getType(Data::setType($value, Type::BOOL))); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ResourceTypeConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'array')] + public function testSetTypeStringFromArray (mixed $value):void { + + $this->expectException(ArrayToStringConversionException::class); + + Data::setType($value, Type::STRING); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * + * @throws \FireHub\Runtime\Exception\ArrayToStringConversionException + * @throws \FireHub\Runtime\Exception\FailedToConvertTypeException + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'string')] + public function testSetTypeFromResource (mixed $value):void { + + $this->expectException(ResourceTypeConversionException::class); + + Data::setType($value, Type::RESOURCE); + + } + + /** + * @since 1.0.0 + * + * @param null|scalar|array|object $value + * @param string $result + * + * @throws \FireHub\Runtime\Exception\CannotSerializeException + * + * @return void + */ + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3], 'a:3:{s:3:"one";i:1;s:3:"two";i:2;s:5:"three";i:3;}'])] + #[TestWith(['This is long string.', 's:20:"This is long string.";'])] + public function testSerialize (null|string|int|float|bool|array|object $value, string $result):void { + + self::assertSame($result, Data::serialize($value)); + + } + + /** + * @since 1.0.0 + * + * @param null|scalar|array|object $value + * + * @return void + */ + #[DataProviderExternal(DataDataProvider::class, 'countable')] + public function testSerializeAnonymousClasses (null|string|int|float|bool|array|object $value):void { + + $this->expectException(CannotSerializeException::class); + + Data::serialize($value); + + } + + /** + * @since 1.0.0 + * + * @param null|scalar|array|object $result + * @param string $value + * + * @throws \FireHub\Runtime\Exception\CannotUnserializeException + * + * @return void + */ + #[TestWith([['one' => 1, 'two' => 2, 'three' => 3], 'a:3:{s:3:"one";i:1;s:3:"two";i:2;s:5:"three";i:3;}'])] + #[TestWith(['This is long string.', 's:20:"This is long string.";'])] + public function testUnserialize (null|string|int|float|bool|array|object $result, string $value):void { + + self::assertSame($result, Data::unserialize($value)); + + } + + /** + * @since 1.0.0 + * + * @param string $value + * + * @return void + */ + #[TestWith(['b:0;'])] + #[TestWith(['N;'])] + public function testUnserializeFalse (string $value):void { + + $this->expectException(CannotUnserializeException::class); + + Data::unserialize($value); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Date/CalendarTest.php b/tests/Unit/Date/CalendarTest.php new file mode 100644 index 0000000..d183ab7 --- /dev/null +++ b/tests/Unit/Date/CalendarTest.php @@ -0,0 +1,74 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Date; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Date; +use FireHub\Tests\Runtime\DataProviders\DateDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small, TestWith +}; + +/** + * ### Test Calendar Date Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Date\Calendar::class)] +final class CalendarTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param int<1, 32767> $year + * @param int<1, 12> $month + * @param int<1, 31> $day + * + * @return void + */ + #[DataProviderExternal(DateDataProvider::class, 'validDates')] + public function testCheckValid (int $year, int $month, int $day):void { + + self::assertTrue(Date\Calendar::check($year, $month, $day)); + + } + + /** + * @since 1.0.0 + * + * @param string $info + * @param mixed $expected + * @param null|int $timestamp + * + * @return void + */ + #[TestWith(['seconds', 0, 0])] + #[TestWith(['minutes', 0, 0])] + #[TestWith(['mday', 1, 0])] + #[TestWith(['wday', 4, 0])] + #[TestWith(['mon', 1, 0])] + #[TestWith(['year', 1970, 0])] + #[TestWith(['yday', 0, 0])] + #[TestWith(['weekday', 'Thursday', 0])] + #[TestWith(['month', 'January', 0])] + #[TestWith(['timestamp', 0, 0])] + #[TestWith(['timestamp', 0, 0])] + public function testInfo (string $info, mixed $expected, ?int $timestamp):void { + + self::assertSame($expected, Date\Calendar::info($timestamp)[$info]); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Date/FormatTest.php b/tests/Unit/Date/FormatTest.php new file mode 100644 index 0000000..209d695 --- /dev/null +++ b/tests/Unit/Date/FormatTest.php @@ -0,0 +1,78 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Date; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Date; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Date Formatting Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Date\Format::class)] +final class FormatTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $format + * @param null|int $timestamp + * @param bool $gmt + * + * @return void + */ + #[TestWith(['1970-01-01T00:00:00+00:00', DATE_ATOM, 0, true])] + #[TestWith(['Thursday, 01-Jan-1970 00:00:00 GMT', DATE_COOKIE, 0, true])] + #[TestWith(['Thu, 01 Jan 1970 00:00:00 +0000', DATE_RSS, 0, true])] + public function testString (string $expected, string $format, ?int $timestamp, bool $gmt):void { + + self::assertSame($expected, Date\Format::string($format, $timestamp, $gmt)); + + } + + /** + * @since 1.0.0 + * + * @param int $expected + * @param string $format + * @param null|int $timestamp + * + * @throws \FireHub\Runtime\Exception\FailedToFormatTimestampAsIntException + * + * @return void + */ + #[TestWith([70, 'y', 0])] + #[TestWith([1970, 'Y', 0])] + #[TestWith([1, 'd', 0])] + #[TestWith([0, 'z', 0])] + #[TestWith([1, 'W', 0])] + #[TestWith([4, 'w', 0])] + #[TestWith([0, 'U', 0])] + #[TestWith([31, 't', 0])] + #[TestWith([0, 's', 0])] + #[TestWith([1, 'm', 0])] + #[TestWith([0, 'i', 0])] + public function testInteger (int $expected, string $format, ?int $timestamp):void { + + self::assertSame($expected, Date\Format::integer($format, $timestamp)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Date/ParseTest.php b/tests/Unit/Date/ParseTest.php new file mode 100644 index 0000000..337efe8 --- /dev/null +++ b/tests/Unit/Date/ParseTest.php @@ -0,0 +1,115 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Date; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Date; +use FireHub\Runtime\Exception\{ + CannotParseTimestampException, ParseFromFormatException +}; +use FireHub\Tests\Runtime\DataProviders\DateDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small, TestWith +}; + +/** + * ### Test Date Parsing Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Date\Parse::class)] +final class ParseTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-empty-string $datetime + * + * @return void + */ + #[DataProviderExternal(DateDataProvider::class, 'stringToTime')] + public function testDate (string $datetime):void { + + self::assertEmpty(Date\Parse::date($datetime)['errors']); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $format + * @param non-empty-string $datetime + * + * @throws \FireHub\Runtime\Exception\ParseFromFormatException + * + * @return void + */ + #[TestWith(['j.n.Y H:iP', '6.1.2009 13:00+01:00'])] + public function testDateFromFormat (string $format, string $datetime):void { + + self::assertEmpty(Date\Parse::dateFromFormat($format, $datetime)['errors']); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $format + * @param non-empty-string $datetime + * + * @return void + */ + #[TestWith(['Y', "\0"])] + public function testParseFromFormatContainsNulByte (string $format, string $datetime):void { + + $this->expectException(ParseFromFormatException::class); + + Date\Parse::dateFromFormat($format, $datetime); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $datetime + * + * @throws \FireHub\Runtime\Exception\CannotParseTimestampException + * + * @return void + */ + #[DataProviderExternal(DateDataProvider::class, 'stringToTime')] + public function testTimestamp (string $datetime):void { + + self::assertIsInt(Date\Parse::timestamp($datetime)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $datetime + * + * @return void + */ + #[TestWith(['NotTime'])] + public function testTimestampNotTime (string $datetime):void { + + $this->expectException(CannotParseTimestampException::class); + + Date\Parse::timestamp($datetime); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Date/SolarTest.php b/tests/Unit/Date/SolarTest.php new file mode 100644 index 0000000..7b46a8f --- /dev/null +++ b/tests/Unit/Date/SolarTest.php @@ -0,0 +1,57 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Date; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Date; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Solar Calculation Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Date\Solar::class)] +final class SolarTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param int $timestamp + * @param float $latitude + * @param float $longitude + * + * @return void + */ + #[TestWith([0, 40.730610, -73.935242])] + public function testInfo (int $timestamp, float $latitude, float $longitude):void { + + $get = Date\Solar::info($timestamp, $latitude, $longitude); + + self::assertIsInt($get['sunrise']); + self::assertIsInt($get['sunset']); + self::assertIsInt($get['transit']); + self::assertIsInt($get['civil_twilight_begin']); + self::assertIsInt($get['civil_twilight_end']); + self::assertIsInt($get['nautical_twilight_begin']); + self::assertIsInt($get['nautical_twilight_end']); + self::assertIsInt($get['astronomical_twilight_begin']); + self::assertIsInt($get['astronomical_twilight_end']); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Date/TimestampTest.php b/tests/Unit/Date/TimestampTest.php new file mode 100644 index 0000000..5ee75e3 --- /dev/null +++ b/tests/Unit/Date/TimestampTest.php @@ -0,0 +1,55 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Date; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Date; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Unix Timestamp Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Date\Timestamp::class)] +final class TimestampTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param int<0, 24> $hour + * @param null|int<0, 59> $minute + * @param null|int<0, 59> $second + * @param null|int $year + * @param null|int<0, 12> $month + * @param null|int<0, 31> $day + * @param bool $gmt + * + * @throws \FireHub\Runtime\Exception\CannotCreateTimestampException + * + * @return void + */ + #[TestWith([0, 0, 0, 1970, 1, 1])] + #[TestWith([0, 0, 0, 1970, 1, 1, true])] + public function testCreate (int $hour, ?int $minute = null, ?int $second = null, ?int $year = null, ?int $month = + null, ?int $day = null, bool $gmt = false):void { + + self::assertIsInt(Date\Timestamp::create($hour, $minute, $second, $year, $month, $day, $gmt)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Date/TimezoneTest.php b/tests/Unit/Date/TimezoneTest.php new file mode 100644 index 0000000..1d0c41a --- /dev/null +++ b/tests/Unit/Date/TimezoneTest.php @@ -0,0 +1,62 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Date; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Date; +use FireHub\Core\Type\Date\Zone; +use FireHub\Tests\Runtime\DataProviders\DateDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small +}; + +/** + * ### Test Time Zone Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Date\Timezone::class)] +final class TimezoneTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param \FireHub\Core\Type\Date\Zone $expected + * + * @throws \FireHub\Runtime\Exception\FailedToGetTimezoneException + * @throws \FireHub\Runtime\Exception\FailedToSetTimezoneException + * + * @return void + */ + #[DataProviderExternal(DateDataProvider::class, 'timezones')] + public function testSetAndGetDefaultTimezone (Zone $expected):void { + + self::assertTrue(Date\Timezone::setDefault($expected)); + self::assertSame($expected, Date\Timezone::getDefault()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testAbbreviationList ():void { + + self::assertIsArray(Date\Timezone::abbreviationList()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/FileTest.php b/tests/Unit/FileSystem/FileTest.php new file mode 100644 index 0000000..7870b58 --- /dev/null +++ b/tests/Unit/FileSystem/FileTest.php @@ -0,0 +1,335 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.2 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use FireHub\Runtime\Exception\ { + CopyFileException, DeleteFileException, EmptyPathException, ReadFileException, RenameFileException, + UploadedFileMoveException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Depends, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime File Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\File::class)] +final class FileTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith([true, '/test.txt'])] + #[TestWith([false, '/test_unknown.txt'])] + public function testExist (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\File::exist($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith([true, '/test.txt'])] + #[TestWith([false, '/test_unknown.txt'])] + public function testIsFile (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\File::isFile($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith([false, '/test.txt'])] + #[TestWith([false, '/test_unknown.txt'])] + public function testIsUploaded (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\File::isUploaded($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $to + * + * @throws \FireHub\Runtime\Exception\CopyFileException + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith(['/test.txt', '/test2.txt'])] + public function testCopy (string $path, string $to):void { + + self::assertTrue(FileSystem\File::copy($this->temp_folder.$path, $this->temp_folder.$to)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $to + * + * @return void + */ + #[TestWith(['/test_x.txt', '/test_y.txt'])] + public function testCopyFailed (string $path, string $to):void { + + $this->expectException(CopyFileException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\File::copy($this->temp_folder.$path, $this->temp_folder.$to) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $to + * + * @throws \FireHub\Runtime\Exception\RenameFileException + * + * @return void + */ + #[Depends('testCopy')] + #[TestWith(['/test2.txt', '/test3.txt'])] + public function testRename (string $path, string $to):void { + + self::assertTrue(FileSystem\File::rename($this->temp_folder.$path, $this->temp_folder.$to)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $to + * + * @return void + */ + #[TestWith(['/test_x.txt', '/test_y.txt'])] + public function testRenameFailed (string $path, string $to):void { + + $this->expectException(RenameFileException::class); + + $this->suppressPhpErrors( + fn() => self::assertTrue(FileSystem\File::rename($this->temp_folder.$path, $this->temp_folder.$to)) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @throws \FireHub\Runtime\Exception\DeleteFileException + * + * @return void + */ + #[Depends('testRename')] + #[TestWith(['/test3.txt'])] + public function testDelete (string $path):void { + + self::assertTrue(FileSystem\File::delete($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_x.txt'])] + public function testDeleteFailed (string $path):void { + + $this->expectException(DeleteFileException::class); + + $this->suppressPhpErrors( + fn() => self::assertTrue(FileSystem\File::delete($this->temp_folder.$path)) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $to + * + * @return void + */ + #[TestWith(['/test.txt', '/test2.txt'])] + public function testMoveUploadedFailed (string $path, string $to):void { + + $this->expectException(UploadedFileMoveException::class); + + FileSystem\File::moveUploaded($this->temp_folder.$path, $this->temp_folder.$to); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $path + * @param string $output + * + * @throws \FireHub\Runtime\Exception\ReadFileException + * @throws \FireHub\Runtime\Exception\EmptyPathException + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith([5, '/test.txt', 'hallo'])] + public function testRead (int $expected, string $path, string $output):void { + + ob_start(); + + $bytes = FileSystem\File::read($this->temp_folder.$path); + + $output = ob_get_clean(); + + self::assertSame($expected, $bytes); + self::assertSame($output, $output); + + } + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\ReadFileException + * + * @return void + */ + public function testReadEmptyPath ():void { + + $this->expectException(EmptyPathException::class); + + FileSystem\File::read(''); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $path + * @param int $offset + * @param null|int $length + * + * @throws \FireHub\Runtime\Exception\ReadFileException + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith(['hallo', '/test.txt'])] + #[TestWith(['llo', '/test.txt', 2])] + #[TestWith(['ha', '/test.txt', 0, 2])] + public function testGetContent (string $expected, string $path, int $offset = 0, ?int $length = null):void { + + self::assertSame($expected, FileSystem\File::getContent($this->temp_folder.$path, $offset, $length)); + + } + + /** + * @since 1.0.0 + * + * @param list $expected + * @param string $path + * @param bool $skip_empty_lines + * @param bool $ignore_new_lines + * + * @throws \FireHub\Runtime\Exception\ReadFileException + * + * @return void + */ + #[Depends('testPutContent')] + #[TestWith([ + ['hallo'], + '/test.txt' + ])] + public function testGetContentAsArray (array $expected, string $path, bool $skip_empty_lines = false, bool $ignore_new_lines = false):void { + + self::assertSame( + $expected, + FileSystem\File::getContentArray($this->temp_folder.$path, $skip_empty_lines, $ignore_new_lines) + ); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testGetContentException ():void { + + $this->expectException(ReadFileException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\File::getContent($this->temp_folder.'x') + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string|string[] $data + * + * @throws \FireHub\Runtime\Exception\FileNotFoundException + * @throws \FireHub\Runtime\Exception\FileWriteException + * + * @return void + */ + #[TestWith(['/test.txt', 'hallo'])] + public function testPutContent (string $path, array|string $data):void { + + self::assertGreaterThan(0, FileSystem\File::putContent($this->temp_folder.$path, $data)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/FolderTest.php b/tests/Unit/FileSystem/FolderTest.php new file mode 100644 index 0000000..e0271e0 --- /dev/null +++ b/tests/Unit/FileSystem/FolderTest.php @@ -0,0 +1,186 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use FireHub\Core\Type\FileSystem\PermissionMode; +use FireHub\Core\Meta\Enum\Order; +use FireHub\Core\Meta\Enum\FileSystem\ { + PathSearchFlag, Permission +}; +use FireHub\Runtime\Exception\ { + CannotListFolderException, DeleteFolderException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Depends, DependsExternal, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Folder Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\Folder::class)] +final class FolderTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith([true, ''])] + #[TestWith([false, 'unknown'])] + public function testExists (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\Folder::exists($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @throws \FireHub\Runtime\Exception\CreateFolderException + * + * @return void + */ + #[TestWith([true, 'test_folder'])] + public function testCreate (bool $expected, string $path):void { + + $mode = new PermissionMode( + Permission::NONE, + Permission::ALL, + Permission::ALL + ); + + self::assertSame( + $expected, + FileSystem\Folder::create($this->temp_folder.$path, $mode) + ); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @throws \FireHub\Runtime\Exception\DeleteFolderException + * + * @return void + */ + #[Depends('testCreate')] + #[TestWith([true, 'test_folder'])] + public function testDelete (bool $expected, string $path):void { + + self::assertSame( + $expected, + FileSystem\Folder::delete($this->temp_folder.$path) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['unknown_folder'])] + public function testDeleteException (string $path):void { + + $this->expectException(DeleteFolderException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Folder::delete($this->temp_folder.$path) + ); + + } + + /** + * @since 1.0.0 + * + * @param \FireHub\Core\Meta\Enum\FileSystem\PathSearchFlag ...$flags + * + * @throws \FireHub\Runtime\Exception\MatchInFolderException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + public function testMatch (PathSearchFlag ...$flags):void { + + self::assertSame( + [ + $this->temp_folder.'/test.txt' + ], + FileSystem\Folder::match($this->temp_folder.'/*', ...$flags) + ); + + self::assertSame( + [], + FileSystem\Folder::match($this->temp_folder.'/unknown/*.txt', ...$flags) + ); + + } + + /** + * @since 1.0.0 + * + * @param null|\FireHub\Core\Meta\Enum\FileSystem\PathSearchFlag ...$flags + * + * @throws \FireHub\Runtime\Exception\CannotListFolderException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + public function testList (?Order $order = null):void { + + self::assertSame( + [ + '.', + '..', + 'test.txt' + ], + FileSystem\Folder::list($this->temp_folder, $order) + ); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + public function testListException ():void { + + $this->expectException(CannotListFolderException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Folder::list($this->temp_folder.'/unknown') + ); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/LinkTest.php b/tests/Unit/FileSystem/LinkTest.php new file mode 100644 index 0000000..a7e7efd --- /dev/null +++ b/tests/Unit/FileSystem/LinkTest.php @@ -0,0 +1,88 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use FireHub\Runtime\Exception\CreateLinkException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Depends, DependsExternal, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime File Link Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\Link::class)] +final class LinkTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $link + * + * @throws \FireHub\Runtime\Exception\CreateLinkException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt', 'hardLink'])] + public function testHard (string $path, string $link):void { + + self::assertTrue(FileSystem\Link::hard($this->temp_folder.$path, $this->temp_folder.$link)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * @param string $link + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['', 'hardLink'])] + #[TestWith(['/test.txt', ''])] + public function testHardException (string $path, string $link):void { + + $this->expectException(CreateLinkException::class); + + $this->suppressPhpErrors( + fn() => self::assertTrue(FileSystem\Link::hard($this->temp_folder.$path, $this->temp_folder.$link)) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @throws \FireHub\Runtime\Exception\DeleteFileException + * + * @return void + */ + #[Depends('testHard')] + #[TestWith(['hardLink'])] + public function testUnlink (string $path):void { + + self::assertTrue(FileSystem\File::delete($this->temp_folder.$path)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/MetaDataTest.php b/tests/Unit/FileSystem/MetaDataTest.php new file mode 100644 index 0000000..7eda1c4 --- /dev/null +++ b/tests/Unit/FileSystem/MetaDataTest.php @@ -0,0 +1,542 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use FireHub\Core\Type\FileSystem\PermissionMode; +use FireHub\Core\Meta\Enum\FileSystem\Permission; +use FireHub\Runtime\Exception\ { + PathGroupException, PathInodeException, PathOwnerException, PathPermissionsException, PathSizeException, + PathStatisticsException, PathTimestampException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, DependsExternal, Group, RequiresOperatingSystemFamily, Small, TestWith +}; + +/** + * ### Test PHP Runtime File Metadata Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\Metadata::class)] +final class MetaDataTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathSizeException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testSize (string $path):void { + + self::assertIsInt(FileSystem\Metadata::size($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testSizeException (string $path):void { + + $this->expectException(PathSizeException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::size($this->temp_folder.$path) + ); + + } + + /** + * @param string $path + * + * @return void + *@throws \FireHub\Runtime\Exception\PathTimestampException + * + * @since 1.0.0 + * + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testLastAccessed (string $path):void { + + self::assertIsInt(FileSystem\Metadata::lastAccessed($this->temp_folder.$path)); + + } + + /** + * @param string $path + * + * @return void + *@throws \FireHub\Runtime\Exception\PathTimestampException + * + * @since 1.0.0 + * + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testLastAModified (string $path):void { + + self::assertIsInt(FileSystem\Metadata::lastModified($this->temp_folder.$path)); + + } + + /** + * @param string $path + * + * @return void + *@throws \FireHub\Runtime\Exception\PathTimestampException + * + * @since 1.0.0 + * + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testLastChanged (string $path):void { + + self::assertIsInt(FileSystem\Metadata::lastChanged($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testLastAccessedChangedModifiedException (string $path):void { + + $this->expectException(PathTimestampException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::lastAccessed($this->temp_folder.$path) + ); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::lastChanged($this->temp_folder.$path) + ); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::lastModified($this->temp_folder.$path) + ); + + } + + /** + * @param string $path + * + * @return void + *@throws \FireHub\Runtime\Exception\PathInodeException + * + * @since 1.0.0 + * + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testInode (string $path):void { + + self::assertIsInt(FileSystem\Metadata::inode($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testInodeException (string $path):void { + + $this->expectException(PathInodeException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::inode($this->temp_folder.$path) + ); + + } + + /** + * @param bool $expected + * @param string $path + * @param null|int $last_accessed + * @param null|int $last_modified + * + * @return void + *@throws \FireHub\Runtime\Exception\PathTimestampException + * + * @since 1.0.0 + * + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith([true, '/test.txt', 3600, 3600])] + public function testSetTimestamps (bool $expected, string $path, ?int $last_accessed = null, ?int $last_modified = null):void { + + self::assertSame($expected, FileSystem\Metadata::setTimestamps($this->temp_folder.$path, $last_accessed, $last_modified)); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathGroupException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testGetGroup (string $path):void { + + $group = FileSystem\Metadata::getGroup($this->temp_folder.$path); + + self::assertGreaterThanOrEqual(0, $group); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testGetGroupException (string $path):void { + + $this->expectException(PathGroupException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::getGroup($this->temp_folder.$path) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathGroupException + * + * @return void + */ + #[RequiresOperatingSystemFamily('Linux')] + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testSetGroupLinux (string $path):void { + + self::assertTrue( + FileSystem\Metadata::setGroup( + $this->temp_folder.$path, + FileSystem\Metadata::getGroup($this->temp_folder.$path) + ) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathGroupException + * + * @return void + */ + #[RequiresOperatingSystemFamily('Darwin')] + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testSetGroupDarwin (string $path):void { + + self::assertTrue( + FileSystem\Metadata::setGroup( + $this->temp_folder.$path, + FileSystem\Metadata::getGroup($this->temp_folder.$path) + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testSetGroupException (string $path):void { + + $this->expectException(PathGroupException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::setGroup($this->temp_folder.$path, 0) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathOwnerException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testGetOwner (string $path):void { + + $group = FileSystem\Metadata::getOwner($this->temp_folder.$path); + + self::assertGreaterThanOrEqual(0, $group); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testGetOwnerException (string $path):void { + + $this->expectException(PathOwnerException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::getOwner($this->temp_folder.$path) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathOwnerException + * + * @return void + */ + #[RequiresOperatingSystemFamily('Linux')] + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testSetOwnerLinux (string $path):void { + + self::assertTrue( + FileSystem\Metadata::setOwner( + $this->temp_folder.$path, + FileSystem\Metadata::getOwner($this->temp_folder.$path) + ) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathOwnerException + * + * @return void + */ + #[RequiresOperatingSystemFamily('Darwin')] + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testSetOwnerDarwin (string $path):void { + + self::assertTrue( + FileSystem\Metadata::setOwner( + $this->temp_folder.$path, + FileSystem\Metadata::getOwner($this->temp_folder.$path) + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testSetOwnerException (string $path):void { + + $this->expectException(PathOwnerException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::setOwner($this->temp_folder.$path, 0) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathPermissionsException + * @throws \FireHub\Runtime\Exception\InvalidNumberBaseException + * + * @return void + */ + #[RequiresOperatingSystemFamily('Linux')] + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testPermissionsLinux (string $path):void { + + $expected = new PermissionMode( + Permission::READ_WRITE, + Permission::READ, + Permission::NONE + ); + + FileSystem\Metadata::setPermissions($this->temp_folder.$path, $expected); + + self::assertSame( + $expected->value(), + FileSystem\Metadata::getPermissions($this->temp_folder.$path)->value() + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathPermissionsException + * @throws \FireHub\Runtime\Exception\InvalidNumberBaseException + * + * @return void + */ + #[RequiresOperatingSystemFamily('Darwin')] + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testPermissionsDarwin (string $path):void { + + $expected = new PermissionMode( + Permission::READ_WRITE, + Permission::READ, + Permission::NONE + ); + + FileSystem\Metadata::setPermissions($this->temp_folder.$path, $expected); + + self::assertSame( + $expected->value(), + FileSystem\Metadata::getPermissions($this->temp_folder.$path)->value() + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @throws \FireHub\Runtime\Exception\InvalidNumberBaseException + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testGetPermissionsException (string $path):void { + + $this->expectException(PathPermissionsException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::getPermissions($this->temp_folder.$path) + ); + + } + + /** + * @param string $path + * + * @throws \FireHub\Runtime\Exception\PathStatisticsException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith(['/test.txt'])] + public function testStatistics (string $path):void { + + $statistics = FileSystem\Metadata::statistics($this->temp_folder.$path); + + self::assertIsArray($statistics); + + self::assertArrayHasKey('dev', $statistics); + self::assertArrayHasKey('ino', $statistics); + self::assertArrayHasKey('mode', $statistics); + self::assertArrayHasKey('nlink', $statistics); + self::assertArrayHasKey('uid', $statistics); + self::assertArrayHasKey('gid', $statistics); + self::assertArrayHasKey('rdev', $statistics); + self::assertArrayHasKey('size', $statistics); + self::assertArrayHasKey('atime', $statistics); + self::assertArrayHasKey('mtime', $statistics); + self::assertArrayHasKey('ctime', $statistics); + self::assertArrayHasKey('blksize', $statistics); + self::assertArrayHasKey('blocks', $statistics); + + self::assertSame( + 5, + $statistics['size'] + ); + + } + + /** + * @since 1.0.0 + * + * @param string $path + * + * @return void + */ + #[TestWith(['/test_unknown.txt'])] + public function testStatisticsException (string $path):void { + + $this->expectException(PathStatisticsException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Metadata::statistics($this->temp_folder.$path) + ); + + } + + /** + * @since 1.0.0 + * + * @param bool $clear_realpath_cache + * @param string $path + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith([false, '/test.txt'])] + public function testClearCache (bool $clear_realpath_cache = false, string $path = ''):void { + + FileSystem\Metadata::clearCache($clear_realpath_cache, $this->temp_folder.$path); + + self::assertFileExists($this->temp_folder.$path); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/PathTest.php b/tests/Unit/FileSystem/PathTest.php new file mode 100644 index 0000000..28e08d5 --- /dev/null +++ b/tests/Unit/FileSystem/PathTest.php @@ -0,0 +1,126 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use FireHub\Runtime\Exception\PathResolutionException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime File System Path Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\Path::class)] +final class PathTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param non-empty-string $path + * @param string $suffix + * + * @return void + */ + #[TestWith(['file.txt', '/var/www/file.txt'])] + #[TestWith(['file', '/var/www/file.txt', '.txt'])] + public function testBasename (string $expected, string $path, string $suffix = ''):void { + + self::assertSame($expected, FileSystem\Path::basename($path, $suffix)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $path + * @param positive-int $levels + * + * @throws \FireHub\Runtime\Exception\InvalidPathParentLevelException + * + * @return void + */ + #[TestWith(['/var/www/html', '/var/www/html/index.php'])] + #[TestWith(['/var/www', '/var/www/html/index.php', 2])] + public function testParent (string $expected, string $path, int $levels = 1):void { + + self::assertSame($expected, FileSystem\Path::parent($path, $levels)); + + } + + /** + * @since 1.0.0 + * + * @param array $expected + * @param string $path + * + * @return void + */ + #[TestWith([ + [ + 'dirname' => '/var/www', + 'basename' => 'index.php', + 'extension' => 'php', + 'filename' => 'index' + ], + '/var/www/index.php' + ])] + #[TestWith([ + [ + 'dirname' => '.', + 'basename' => 'README', + 'extension' => null, + 'filename' => 'README' + ], + 'README' + ])] + public function testInfo (array $expected, string $path):void { + + self::assertSame($expected, FileSystem\Path::info($path)); + + } + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\PathResolutionException + * + * @return void + */ + public function testAbsolute ():void { + + self::assertIsString(FileSystem\Path::absolute($this->temp_folder)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testAbsoluteInvalidPath ():void { + + $this->expectException(PathResolutionException::class); + + self::assertIsString(FileSystem\Path::absolute('unknown')); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/PermissionTest.php b/tests/Unit/FileSystem/PermissionTest.php new file mode 100644 index 0000000..383b241 --- /dev/null +++ b/tests/Unit/FileSystem/PermissionTest.php @@ -0,0 +1,82 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use PHPUnit\Framework\Attributes\ { + CoversClass, DependsExternal, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime File System Permission Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\Permission::class)] +final class PermissionTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith([false, '/test.txt'])] + #[TestWith([false, '/test_unknown.txt'])] + public function testSize (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\Permission::isExecutable($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith([true, '/test.txt'])] + #[TestWith([false, '/test_unknown.txt'])] + public function testIsReadable (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\Permission::isReadable($this->temp_folder.$path)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $path + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + #[TestWith([true, '/test.txt'])] + #[TestWith([false, '/test_unknown.txt'])] + public function testIsWritable (bool $expected, string $path):void { + + self::assertSame($expected, FileSystem\Permission::isWritable($this->temp_folder.$path)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FileSystem/StorageTest.php b/tests/Unit/FileSystem/StorageTest.php new file mode 100644 index 0000000..7c01667 --- /dev/null +++ b/tests/Unit/FileSystem/StorageTest.php @@ -0,0 +1,90 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\FileSystem; + +use FireHub\Testing\FileSystemTestCase; +use FireHub\Runtime\FileSystem; +use FireHub\Runtime\Exception\DiskSpaceException; +use PHPUnit\Framework\Attributes\ { + CoversClass, DependsExternal, Group, Small +}; + +/** + * ### Test PHP Runtime File System Storage Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(FileSystem\Storage::class)] +final class StorageTest extends FileSystemTestCase { + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\DiskSpaceException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + public function testTotalSpace ():void { + + self::assertGreaterThanOrEqual(0, FileSystem\Storage::totalSpace($this->temp_folder)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testTotalSpaceException ():void { + + $this->expectException(DiskSpaceException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Storage::totalSpace($this->temp_folder.'-') + ); + + } + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\DiskSpaceException + * + * @return void + */ + #[DependsExternal(FileTest::class, 'testPutContent')] + public function testFreeSpace ():void { + + self::assertGreaterThanOrEqual(0, FileSystem\Storage::freeSpace($this->temp_folder)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testTotalFreeException ():void { + + $this->expectException(DiskSpaceException::class); + + $this->suppressPhpErrors( + fn() => FileSystem\Storage::freeSpace($this->temp_folder.'-') + ); + + } + +} \ No newline at end of file diff --git a/tests/Unit/FuncTest.php b/tests/Unit/FuncTest.php new file mode 100644 index 0000000..16298fc --- /dev/null +++ b/tests/Unit/FuncTest.php @@ -0,0 +1,75 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Func; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Function Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Func::class)] +final class FuncTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * @param bool $expected + * + * @return void + */ + #[TestWith(['array_sum', true])] + #[TestWith(['i_am_not_a_function', false])] + public function testIsFunction (string $name, bool $expected):void { + + self::assertSame($expected, Func::isFunction($name)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $expected + * + * @return void + */ + #[TestWith(['Hi!'])] + public function testCall (mixed $expected):void { + + self::assertSame($expected, Func::call(static fn() => $expected)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $expected + * + * @return void + */ + #[TestWith(['Hi!'])] + public function testCallWithArray (mixed $expected):void { + + self::assertSame($expected, Func::callWithArray(static fn() => $expected, [])); + + } + +} \ No newline at end of file diff --git a/tests/Unit/IntrospectionTest.php b/tests/Unit/IntrospectionTest.php new file mode 100644 index 0000000..e9849bd --- /dev/null +++ b/tests/Unit/IntrospectionTest.php @@ -0,0 +1,86 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Introspection; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test PHP Runtime Introspection Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Introspection::class)] +final class IntrospectionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testClasses ():void { + + self::assertIsList(Introspection::classes()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testInterfaces ():void { + + self::assertIsList(Introspection::interfaces()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testTraits ():void { + + self::assertIsList(Introspection::traits()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testDefinedConstants ():void { + + self::assertIsArray(Introspection::definedConstants()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testDefinedFunctions ():void { + + self::assertIsArray(Introspection::definedFunctions()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/IteratorTest.php b/tests/Unit/IteratorTest.php new file mode 100644 index 0000000..057b9d6 --- /dev/null +++ b/tests/Unit/IteratorTest.php @@ -0,0 +1,97 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Iterator; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; +use SplFixedArray; + +/** + * ### Test PHP Runtime Iterator Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Iterator::class)] +final class IteratorTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @var SplFixedArray + */ + private SplFixedArray $iterator; + + /** + * @inheritDoc + * + * @since 1.0.0 + * + * @return void + */ + public function setUp ():void { + + $this->iterator = new SplFixedArray(3); + $this->iterator[0] = 'one'; + $this->iterator[1] = 'two'; + $this->iterator[2] = 'three'; + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testToArray ():void { + + self::assertSame([0 => 'one', 1 => 'two', 2 => 'three'], Iterator::toArray($this->iterator)); + self::assertSame(['one', 'two', 'three'], Iterator::toArray($this->iterator, false)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testCount ():void { + + self::assertSame(3, Iterator::count($this->iterator)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testApply ():void { + + Iterator::apply($this->iterator, function (...$param) { + foreach ($param as $key => $value) { + $this->iterator[$key] = $value.'-'; + } + return true; + + },$this->iterator->toArray()); + + self::assertSame(['one-', 'two-', 'three-'], $this->iterator->toArray()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/JsonTest.php b/tests/Unit/JsonTest.php new file mode 100644 index 0000000..3adadaf --- /dev/null +++ b/tests/Unit/JsonTest.php @@ -0,0 +1,142 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Json; +use FireHub\Runtime\Json\ { + Flag, Flag\Decode, Flag\Encode, Flag\Validate +}; +use FireHub\Runtime\Exception\ { + JsonDecodeException, JsonEncodeException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime JSON Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Json::class)] +final class JsonTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param mixed $value + * @param positive-int $depth + * @param \FireHub\Runtime\Json\Flag|\FireHub\Runtime\Json\Flag\Encode ...$flags + * + * @throws \FireHub\Runtime\Exception\JsonEncodeException + * + * @return void + */ + #[TestWith(['"firehub"', 'firehub'])] + #[TestWith(['[1,2,3]', [1,2,3]])] + #[TestWith(['{"a":1,"b":2,"c":3,"d":4,"e":5}', ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]])] + #[TestWith(['12', 12.0])] + #[TestWith(['12.0', 12.0, 512, Encode::PRESERVE_ZERO_FRACTION])] + public function testEncode (string $expected, mixed $value, int $depth = 512, Flag|Encode ...$flags):void { + + self::assertSame($expected, JSON::encode($value, $depth, ...$flags)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $value + * @param positive-int $depth + * @param \FireHub\Runtime\Json\Flag|\FireHub\Runtime\Json\Flag\Encode ...$flags + * + * @return void + */ + #[TestWith(["\xB1\x31"])] + public function testEncodeException (mixed $value, int $depth = 512, Flag|Encode ...$flags):void { + + $this->expectException(JsonEncodeException::class); + + JSON::encode($value, $depth, ...$flags); + + } + + /** + * @since 1.0.0 + * + * @param mixed $expected + * @param string $json + * @param bool $as_array + * @param positive-int $depth + * @param \FireHub\Runtime\Json\Flag|\FireHub\Runtime\Json\Flag\Decode ...$flags + * + * @throws \FireHub\Runtime\Exception\JsonDecodeException + * + * @return void + */ + #[TestWith(['firehub', '"firehub"'])] + #[TestWith([[1,2,3], '[1,2,3]'])] + #[TestWith([['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5], '{"a":1,"b":2,"c":3,"d":4,"e":5}', true])] + #[TestWith([12.0, '12.0'])] + #[TestWith([1.2345678901234567E+19, "12345678901234567890"])] + #[TestWith(['12345678901234567890', "12345678901234567890", false, 512, Decode::BIGINT_AS_STRING])] + public function testDecode (mixed $expected, string $json, bool $as_array = false, int $depth = 512, Flag|Decode ...$flags):void { + + self::assertSame($expected, JSON::decode($json, $as_array, $depth, ...$flags)); + + } + + /** + * @since 1.0.0 + * + * @param string $json + * @param bool $as_array + * @param positive-int $depth + * @param \FireHub\Runtime\Json\Flag|\FireHub\Runtime\Json\Flag\Decode ...$flags + * + * @return void + */ + #[TestWith(["\xB1\x31"])] + public function testDecodeException (string $json, bool $as_array = false, int $depth = 512, Flag|Decode ...$flags):void { + + $this->expectException(JsonDecodeException::class); + + JSON::decode($json, $as_array, $depth, ...$flags); + + } + + /** + * @since 1.0.0 + * + * @param string $json + * @param positive-int $depth + * @param \FireHub\Runtime\Json\Flag\Validate ...$flags + * + * @return void + */ + #[TestWith(['"firehub"'])] + #[TestWith(['[1,2,3]'])] + #[TestWith(['{"a":1,"b":2,"c":3,"d":4,"e":5}'])] + #[TestWith(['12.0'])] + #[TestWith(["12345678901234567890"])] + public function testValidate (string $json, int $depth = 512, Validate ...$flags):void { + + self::assertTrue(JSON::validate($json, $depth, ...$flags)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Math/LogBaseTest.php b/tests/Unit/Math/LogBaseTest.php new file mode 100644 index 0000000..61ac278 --- /dev/null +++ b/tests/Unit/Math/LogBaseTest.php @@ -0,0 +1,65 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Math; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Math\LogBase; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test PHP Runtime Logarithmic Bases + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(LogBase::class)] +final class LogBaseTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testValue ():void { + + self::assertSame( + M_E, + LogBase::E->value() + ); + + self::assertSame( + M_LOG2E, + LogBase::LOG2E->value() + ); + + self::assertSame( + M_LOG10E, + LogBase::LOG10E->value() + ); + + self::assertSame( + M_LN2, + LogBase::LN2->value() + ); + + self::assertSame( + M_LN10, + LogBase::LN10->value() + ); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Math/RoundModeTest.php b/tests/Unit/Math/RoundModeTest.php new file mode 100644 index 0000000..1f7cf9c --- /dev/null +++ b/tests/Unit/Math/RoundModeTest.php @@ -0,0 +1,81 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Math; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Math\RoundMode; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; +use RoundingMode; + +/** + * ### Test PHP Runtime Number Rounding Modes + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(RoundMode::class)] +final class RoundModeTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testToNative ():void { + + self::assertSame( + RoundingMode::HalfAwayFromZero, + RoundMode::HALF_AWAY_FROM_ZERO->toNative() + ); + + self::assertSame( + RoundingMode::HalfTowardsZero, + RoundMode::HALF_TOWARDS_ZERO->toNative() + ); + + self::assertSame( + RoundingMode::HalfEven, + RoundMode::HALF_EVEN->toNative() + ); + + self::assertSame( + RoundingMode::HalfOdd, + RoundMode::HALF_ODD->toNative() + ); + + self::assertSame( + RoundingMode::TowardsZero, + RoundMode::TOWARDS_ZERO->toNative() + ); + + self::assertSame( + RoundingMode::AwayFromZero, + RoundMode::AWAY_FROM_ZERO->toNative() + ); + + self::assertSame( + RoundingMode::NegativeInfinity, + RoundMode::NEGATIVE_INFINITY->toNative() + ); + + self::assertSame( + RoundingMode::PositiveInfinity, + RoundMode::POSITIVE_INFINITY->toNative() + ); + + } + +} \ No newline at end of file diff --git a/tests/Unit/MathTest.php b/tests/Unit/MathTest.php new file mode 100644 index 0000000..8c6a92d --- /dev/null +++ b/tests/Unit/MathTest.php @@ -0,0 +1,664 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Math; +use FireHub\Runtime\Math\ { + LogBase, RoundMode +}; +use FireHub\Tests\Runtime\DataProviders\NumDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Depends, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Math Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Math::class)] +final class MathTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $excepted + * @param float $number + * + * @return void + */ + #[TestWith([true, 10])] + #[TestWith([false, NAN])] + #[TestWith([false, INF])] + public function testIsFinite (bool $excepted, float $number):void { + + self::assertSame($excepted, Math::isFinite($number)); + + } + + /** + * @since 1.0.0 + * + * @param bool $excepted + * @param float $number + * + * @return void + */ + #[TestWith([true, INF])] + #[TestWith([false, 10.5])] + public function testIsInfinite (bool $excepted, float $number):void { + + self::assertSame($excepted, Math::isInfinite($number)); + + } + + /** + * @since 1.0.0 + * + * @param bool $excepted + * @param float $number + * + * @return void + */ + #[TestWith([true, NAN])] + #[TestWith([false, 10.5])] + #[TestWith([false, INF])] + public function testIsNan (bool $excepted, float $number):void { + + self::assertSame($excepted, Math::isNan($number)); + + } + + /** + * @since 1.0.0 + * + * @param int $expected + * @param int $dividend + * @param non-zero-int $divisor + * + * @return void + */ + #[TestWith([1, 3, 2])] + #[TestWith([-1, -3, 2])] + #[TestWith([-1, 3, -2])] + #[TestWith([1, -3, -2])] + #[TestWith([0, PHP_INT_MAX, PHP_INT_MIN])] + #[TestWith([-1, PHP_INT_MIN, PHP_INT_MAX])] + public function testDivideInt (int $expected, int $dividend, int $divisor):void { + + self::assertSame($expected, Math::divideInt($dividend, $divisor)); + + } + + /** + * @since 1.0.0 + * + * @param float $result + * @param float $dividend + * @param float $divisor + * + * @return void + */ + #[TestWith([2.0, 4, 2])] + #[TestWith([INF, 1.0, 0.0])] + #[TestWith([-INF, -1.0, 0.0])] + #[TestWith([4.384615384615385, 5.7, 1.3])] + #[Depends('testRound')] + public function testDivideFloats (float $result, float $dividend, float $divisor):void { + + self::assertSame(Math::round($result, 5), Math::round(Math::divideFloat($dividend, $divisor), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $dividend + * @param float $divisor + * + * @return void + */ + #[TestWith([0.5, 5.7, 1.3])] + public function testRemainder (float $expected, float $dividend, float $divisor):void { + + self::assertSame($expected, Math::remainder($dividend, $divisor)); + + } + + /** + * @since 1.0.0 + * + * @param float|int $float + * + * @return void + */ + #[DataProviderExternal(NumDataProvider::class, 'positiveInt')] + #[DataProviderExternal(NumDataProvider::class, 'negativeInt')] + #[DataProviderExternal(NumDataProvider::class, 'positiveFloat')] + #[DataProviderExternal(NumDataProvider::class, 'negativeFloat')] + #[DataProviderExternal(NumDataProvider::class, 'null')] + public function testAbs (float|int $float):void { + + self::assertTrue(Math::abs($float) >= 0); + + } + + /** + * @since 1.0.0 + * + * @param int $expected + * @param float|int $number + * + * @return void + */ + #[TestWith([5, 4.3])] + #[TestWith([10, 9.999])] + #[TestWith([-3, -3.14])] + public function testCeil (int $expected, float|int $number):void { + + self::assertSame($expected, Math::ceil($number)); + + } + + /** + * @since 1.0.0 + * + * @param int $expected + * @param float|int $number + * + * @return void + */ + #[TestWith([4, 4.3])] + #[TestWith([9, 9.999])] + #[TestWith([-4, -3.14])] + public function testFloor (int $expected, float|int $number):void { + + self::assertSame($expected, Math::floor($number)); + + } + + /** + * @since 1.0.0 + * + * @param int|float $expected + * @param int|float $number + * @param int $precision + * @param \FireHub\Runtime\Math\RoundMode $mode + * + * @return void + */ + #[TestWith([2, 1.5, 0, RoundMode::HALF_AWAY_FROM_ZERO])] + #[TestWith([1, 0.5, 0, RoundMode::HALF_AWAY_FROM_ZERO])] + #[TestWith([0, 0.49, 0, RoundMode::HALF_AWAY_FROM_ZERO])] + #[TestWith([-0.4, -0.35, 1, RoundMode::HALF_AWAY_FROM_ZERO])] + #[TestWith([0.46, 0.455, 2, RoundMode::HALF_AWAY_FROM_ZERO])] + #[TestWith([1, 1.5, 0, RoundMode::HALF_TOWARDS_ZERO])] + #[TestWith([0, 0.5, 0, RoundMode::HALF_TOWARDS_ZERO])] + #[TestWith([0, 0.49, 0, RoundMode::HALF_TOWARDS_ZERO])] + #[TestWith([-0.3, -0.35, 1, RoundMode::HALF_TOWARDS_ZERO])] + #[TestWith([0.45, 0.455, 2, RoundMode::HALF_TOWARDS_ZERO])] + #[TestWith([1, 1.5, 0, RoundMode::HALF_ODD])] + #[TestWith([1, 0.5, 0, RoundMode::HALF_ODD])] + #[TestWith([0, 0.49, 0, RoundMode::HALF_ODD])] + #[TestWith([-0.3, -0.35, 1, RoundMode::HALF_ODD])] + #[TestWith([0.45, 0.455, 2, RoundMode::HALF_ODD])] + #[TestWith([2, 1.5, 0, RoundMode::HALF_EVEN])] + #[TestWith([0, 0.5, 0, RoundMode::HALF_EVEN])] + #[TestWith([0, 0.49, 0, RoundMode::HALF_EVEN])] + #[TestWith([-0.4, -0.35, 1, RoundMode::HALF_EVEN])] + #[TestWith([0.46, 0.455, 2, RoundMode::HALF_EVEN])] + #[TestWith([1, 1.5, 0, RoundMode::TOWARDS_ZERO])] + #[TestWith([0, 0.5, 0, RoundMode::TOWARDS_ZERO])] + #[TestWith([0, 0.49, 0, RoundMode::TOWARDS_ZERO])] + #[TestWith([-0.3, -0.35, 1, RoundMode::TOWARDS_ZERO])] + #[TestWith([0.45, 0.455, 2, RoundMode::TOWARDS_ZERO])] + #[TestWith([2, 1.5, 0, RoundMode::AWAY_FROM_ZERO])] + #[TestWith([1, 0.5, 0, RoundMode::AWAY_FROM_ZERO])] + #[TestWith([1, 0.49, 0, RoundMode::AWAY_FROM_ZERO])] + #[TestWith([-0.4, -0.35, 1, RoundMode::AWAY_FROM_ZERO])] + #[TestWith([0.46, 0.455, 2, RoundMode::AWAY_FROM_ZERO])] + #[TestWith([1, 1.5, 0, RoundMode::NEGATIVE_INFINITY])] + #[TestWith([0, 0.5, 0, RoundMode::NEGATIVE_INFINITY])] + #[TestWith([0, 0.49, 0, RoundMode::NEGATIVE_INFINITY])] + #[TestWith([-0.4, -0.35, 1, RoundMode::NEGATIVE_INFINITY])] + #[TestWith([0.45, 0.455, 2, RoundMode::NEGATIVE_INFINITY])] + public function testRound (int|float $expected, float|int $number, int $precision = 0, RoundMode $mode = RoundMode::HALF_AWAY_FROM_ZERO):void { + + self::assertSame($expected, Math::round($number, $precision, $mode)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float|int $number + * @param float|\FireHub\Runtime\Math\LogBase $base + * + * @return void + */ + #[TestWith([2.302585092994046, 10, LogBase::E])] + #[TestWith([6.282411788757109, 10, LogBase::LOG2E])] + #[TestWith([-2.7607859935346917, 10, LogBase::LOG10E])] + #[TestWith([-6.282411788757108, 10, LogBase::LN2])] + #[TestWith([2.7607859935346912, 10, LogBase::LN10])] + #[TestWith([0.28893129185221283, 1.335, LogBase::E])] + #[TestWith([0.788324982905575, 1.335, LogBase::LOG2E])] + #[TestWith([-0.34642692079720505, 1.335, LogBase::LOG10E])] + #[TestWith([-0.7883249829055747, 1.335, LogBase::LN2])] + #[TestWith([0.346426920797205, 1.335, LogBase::LN10])] + #[Depends('testRound')] + public function testLog (float $expected, float|int $number, float|LogBase $base = LogBase::E):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::log($number, $base), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float|int $number + * + * @return void + */ + #[TestWith([2.3978952727983707, 10])] + #[TestWith([0.8480118911208606, 1.335])] + #[Depends('testRound')] + public function testLog1p (float $expected, float|int $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::log1p($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float|int $number + * + * @return void + */ + #[TestWith([1.0, 10])] + #[TestWith([0.125481265700594, 1.335])] + #[Depends('testRound')] + public function testLog10 (float $expected, float|int $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::log10($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $expected + * @param array $values + * + * @return void + */ + #[TestWith([8, [2, 6, 8]])] + #[TestWith([4.23544, [2.345, 4.23544, 4.1214]])] + public function testMax (mixed $expected, array $values):void { + + self::assertSame($expected, Math::max(...$values)); + + } + + /** + * @since 1.0.0 + * + * @param mixed $expected + * @param array $values + * + * @return void + */ + #[TestWith([2, [2, 6, 8]])] + #[TestWith([2.345, [2.345, 4.23544, 4.1214]])] + public function testMin (mixed $expected, array $values):void { + + self::assertSame($expected, Math::min(...$values)); + + } + + /** + * @since 1.0.0 + * + * @param float|int $expected + * @param float|int $base + * @param float|int $exponent + * + * @return void + */ + #[TestWith([256, 2, 8])] + #[TestWith([0.1, 10, -1])] + public function testPow (float|int $expected, float|int $base, float|int $exponent):void { + + self::assertSame($expected, Math::pow($base, $exponent)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param int|float $number + * + * @return void + */ + #[TestWith([0.4031710572106902, 23.1])] + #[TestWith([0.7853981633974483, 45])] + #[Depends('testRound')] + public function testDeg2rad (float $expected, int|float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::deg2rad($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param int|float $number + * + * @return void + */ + #[TestWith([23.099939426289396, 0.40317])] + #[TestWith([45.0, 0.7853981633974483])] + #[Depends('testRound')] + public function testRad2deg (float $expected, int|float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::rad2deg($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param int|float $number + * + * @return void + */ + #[TestWith([298.8674009670603, 5.7])] + #[TestWith([9744803446.2489, 23])] + #[Depends('testRound')] + public function testExp (float $expected, int|float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::exp($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param int|float $number + * + * @return void + */ + #[TestWith([4839126178.743089, 22.3])] + #[TestWith([9744803445.248903, 23])] + #[Depends('testRound')] + public function testExpm1 (float $expected, int|float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::expm1($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param int|float $x + * @param int|float $y + * + * @return void + */ + #[TestWith([2.6832815729997477, 1.2, 2.4])] + #[TestWith([2.23606797749979, 1, 2])] + #[Depends('testRound')] + public function testHypot (float $expected, int|float $x, int|float $y):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::hypot($x, $y), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param int|float $number + * + * @return void + */ + #[TestWith([3.03315017762062, 9.2])] + #[TestWith([3.0, 9])] + #[Depends('testRound')] + public function testSqrt (float $expected, int|float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::sqrt($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([-1.0, M_PI])] + public function testCos (float $expected, float $number):void { + + self::assertSame($expected, Math::cos($number)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([1.0471975511965979, 0.5])] + #[Depends('testRound')] + public function testAcos (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::acos($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([1.1276259652063807, 0.5])] + #[Depends('testRound')] + public function testCosh (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::cosh($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([0.4435682543851153, 1.1])] + #[Depends('testRound')] + public function testAcosh (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::acosh($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([0.479425538604203, 0.5])] + #[Depends('testRound')] + public function testSin (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::sin($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([1.5707963267948966, 1])] + #[Depends('testRound')] + public function testAsin (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::asin($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([1.1752011936438014, 1])] + #[Depends('testRound')] + public function testSinh (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::sinh($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([0.881373587019543, 1])] + #[Depends('testRound')] + public function testAsinh (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::asinh($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([1.5574077246549023, 1])] + #[Depends('testRound')] + public function testTan (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::tan($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([0.7853981633974483, 1])] + #[Depends('testRound')] + public function testAtan (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::atan($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $x + * @param float $y + * + * @return void + */ + #[TestWith([0.7853981633974483, 1, 1])] + public function testAtan2 (float $expected, float $x, float $y):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::atan2($x, $y), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([0.7615941559557649, 1])] + #[Depends('testRound')] + public function testTanh (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::tanh($number), 5)); + + } + + /** + * @since 1.0.0 + * + * @param float $expected + * @param float $number + * + * @return void + */ + #[TestWith([0.5493061443340549, 0.5])] + #[Depends('testRound')] + public function testAtanh (float $expected, float $number):void { + + self::assertSame(Math::round($expected, 5), Math::round(Math::atanh($number), 5)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/NumberTest.php b/tests/Unit/NumberTest.php new file mode 100644 index 0000000..9c196e5 --- /dev/null +++ b/tests/Unit/NumberTest.php @@ -0,0 +1,51 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Number; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Number Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Number::class)] +final class NumberTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param int|float $number + * @param non-negative-int $decimals + * @param string $decimal_separator + * @param string $thousands_separator + * + * @return void + */ + #[TestWith(['5,000', 5000, 0, '.', ','])] + #[TestWith(['456', 456, 0, ',', '.'])] + #[TestWith(['45656,560', 45656.56, 3, ',', ''])] + public function testFormat (string $expected, int|float $number, int $decimals, string $decimal_separator = '.', string $thousands_separator = ','):void { + + self::assertSame($expected, Number::format($number, $decimals, $decimal_separator, $thousands_separator)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ObjectModel/IdentityTest.php b/tests/Unit/ObjectModel/IdentityTest.php new file mode 100644 index 0000000..64d1498 --- /dev/null +++ b/tests/Unit/ObjectModel/IdentityTest.php @@ -0,0 +1,60 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ObjectModel; +use FireHub\Tests\Runtime\Stubs\EmptyClass; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Object Identity Management + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(ObjectModel\Identity::class)] +final class IdentityTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param class-string $class + * + * @return void + */ + #[TestWith([EmptyClass::class])] + public function testID (string $class):void { + + self::assertIsInt(ObjectModel\Identity::id(new $class)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $class + * + * @return void + */ + #[TestWith([EmptyClass::class])] + public function testHash (string $class):void { + + self::assertIsString(ObjectModel\Identity::hash(new $class)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ObjectModel/InspectionTest.php b/tests/Unit/ObjectModel/InspectionTest.php new file mode 100644 index 0000000..c5a6a4e --- /dev/null +++ b/tests/Unit/ObjectModel/InspectionTest.php @@ -0,0 +1,142 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ObjectModel; +use FireHub\Tests\Runtime\Stubs\ { + EmptyClass, EmptyEnum, EmptyInterface, EmptyTrait, FilledClass +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Object and Class Inspection + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(ObjectModel\Inspection::class)] +final class InspectionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param class-string $name + * @param bool $excepted + * + * @return void + */ + #[TestWith([EmptyClass::class, true])] + #[TestWith([EmptyInterface::class, false])] + #[TestWith([EmptyTrait::class, false])] + #[TestWith([EmptyEnum::class, false])] + public function testIsClass (string $name, bool $excepted):void { + + self::assertSame($excepted, ObjectModel\Inspection::isClass($name)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $name + * @param bool $excepted + * + * @return void + */ + #[TestWith([EmptyClass::class, false])] + #[TestWith([EmptyInterface::class, true])] + #[TestWith([EmptyTrait::class, false])] + #[TestWith([EmptyEnum::class, false])] + public function testIsInterface (string $name, bool $excepted):void { + + self::assertSame($excepted, ObjectModel\Inspection::isInterface($name)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $name + * @param bool $excepted + * + * @return void + */ + #[TestWith([EmptyClass::class, false])] + #[TestWith([EmptyInterface::class, false])] + #[TestWith([EmptyTrait::class, true])] + #[TestWith([EmptyEnum::class, false])] + public function testIsTrait (string $name, bool $excepted):void { + + self::assertSame($excepted, ObjectModel\Inspection::isTrait($name)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $name + * @param bool $excepted + * + * @return void + */ + #[TestWith([EmptyClass::class, false])] + #[TestWith([EmptyInterface::class, false])] + #[TestWith([EmptyTrait::class, false])] + #[TestWith([EmptyEnum::class, true])] + public function testIsEnum (string $name, bool $excepted):void { + + self::assertSame($excepted, ObjectModel\Inspection::isEnum($name)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param class-string $class + * @param non-empty-string $method + * + * @return void + */ + #[TestWith([true, FilledClass::class, 'publicMethod'])] + #[TestWith([false, FilledClass::class, 'xxx'])] + public function testMethodExists (bool $expected, string $class, string $method):void { + + self::assertSame($expected, ObjectModel\Inspection::methodExists($class, $method)); + self::assertSame($expected, ObjectModel\Inspection::methodExists(new $class, $method)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param class-string $class + * @param non-empty-string $property + * + * @return void + */ + #[TestWith([true, FilledClass::class, 'publicVar'])] + #[TestWith([false, FilledClass::class, 'xxx'])] + public function testPropertyExists (bool $expected, string $class, string $property):void { + + self::assertSame($expected, ObjectModel\Inspection::propertyExists($class, $property)); + self::assertSame($expected, ObjectModel\Inspection::propertyExists(new $class, $property)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ObjectModel/MetadataTest.php b/tests/Unit/ObjectModel/MetadataTest.php new file mode 100644 index 0000000..d3ff313 --- /dev/null +++ b/tests/Unit/ObjectModel/MetadataTest.php @@ -0,0 +1,100 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ObjectModel; +use FireHub\Tests\Runtime\Stubs\ { + EmptyClass, FilledClass +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Object and Class Metadata + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(ObjectModel\Metadata::class)] +final class MetadataTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param class-string $class + * @param class-string $alias + * + * @throws \FireHub\Runtime\Exception\ClassAliasException + * + * @return void + */ + #[TestWith([EmptyClass::class, 'NewTestClass'])] + public function testAlias (string $class, string $alias):void { + + ObjectModel\Metadata::alias($class, $alias); + + self::assertInstanceOf(\NewTestClass::class, new $class); + + } + + /** + * @since 1.0.0 + * + * @param class-string $class + * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException + * + * @return void + */ + #[TestWith([FilledClass::class])] + public function testProperties (string $class):void { + + self::assertSame(['publicVar' => 'foo'], ObjectModel\Metadata::properties($class)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testMangledProperties ():void { + + $vars = ObjectModel\Metadata::mangledProperties(new FilledClass()); + + self::assertArrayHasKey('publicVar', $vars); + + self::assertArraysHaveIdenticalValues(['foo'], $vars); + + } + + /** + * @since 1.0.0 + * + * @param class-string $class + * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException + * + * @return void + */ + #[TestWith([FilledClass::class])] + public function testMethods (string $class):void { + + self::assertSame(['publicMethod'], ObjectModel\Metadata::methods($class)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ObjectModel/RelationTest.php b/tests/Unit/ObjectModel/RelationTest.php new file mode 100644 index 0000000..a1489c2 --- /dev/null +++ b/tests/Unit/ObjectModel/RelationTest.php @@ -0,0 +1,142 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ObjectModel; +use FireHub\Tests\Runtime\Stubs\ { + EmptyClass, EmptyInterface, EmptyTrait, FilledClass +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Object and Class Relations + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(ObjectModel\Relation::class)] +final class RelationTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param class-string $class + * @param class-string $class1 + * + * @return void + */ + #[TestWith([true, FilledClass::class, EmptyInterface::class])] + #[TestWith([false, FilledClass::class, 'xxx'])] + public function testInstanceOf (bool $expected, string $class, string $class1):void { + + self::assertSame($expected, ObjectModel\Relation::instanceOf($class, $class1)); + self::assertSame($expected, ObjectModel\Relation::instanceOf(new $class, $class1)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param class-string $object_or_class + * @param class-string $class + * + * @return void + */ + #[TestWith([true, FilledClass::class, EmptyClass::class])] + #[TestWith([false, FilledClass::class, 'xxx'])] + public function testIsSubClassOf (bool $expected, string|object $object_or_class, string $class):void { + + self::assertSame($expected, ObjectModel\Relation::isSubClassOf($object_or_class, $class)); + self::assertSame($expected, ObjectModel\Relation::isSubClassOf(new $object_or_class, $class)); + + } + + /** + * @since 1.0.0 + * + * @param class-string|object $object_or_class + * @param class-string $class + * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException + * + * @return void + */ + #[TestWith([FilledClass::class, EmptyClass::class])] + public function testParentClass (string|object $object_or_class, string $class):void { + + self::assertSame($class, ObjectModel\Relation::parentClass($object_or_class)); + self::assertSame($class, ObjectModel\Relation::parentClass(new $object_or_class)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $expected + * @param class-string $object_or_class + * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException + * + * @return void + */ + #[TestWith([EmptyClass::class, FilledClass::class])] + public function testParents (string $expected, string|object $object_or_class):void { + + self::assertSame([$expected => $expected], ObjectModel\Relation::parents($object_or_class)); + self::assertSame([$expected => $expected], ObjectModel\Relation::parents(new $object_or_class)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $expected + * @param class-string $object_or_class + * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException + * + * @return void + */ + #[TestWith([EmptyInterface::class, FilledClass::class])] + public function testImplements (string $expected, string|object $object_or_class):void { + + self::assertSame([$expected => $expected], ObjectModel\Relation::implements($object_or_class)); + self::assertSame([$expected => $expected], ObjectModel\Relation::implements(new $object_or_class)); + + } + + /** + * @since 1.0.0 + * + * @param class-string $expected + * @param class-string $object_or_class + * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException + * + * @return void + */ + #[TestWith([EmptyTrait::class, FilledClass::class])] + public function testUses (string $expected, string|object $object_or_class):void { + + self::assertSame([$expected => $expected], ObjectModel\Relation::uses($object_or_class)); + self::assertSame([$expected => $expected], ObjectModel\Relation::uses(new $object_or_class)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/RandomTest.php b/tests/Unit/RandomTest.php new file mode 100644 index 0000000..a715de9 --- /dev/null +++ b/tests/Unit/RandomTest.php @@ -0,0 +1,193 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Random; +use FireHub\Runtime\Exception\ { + RandomByteLengthTooSmallException, RandomMaximumBelowMinimumException, RandomNumberAboveGeneratorMaximumException, + RandomNumberBelowMinimumException, SecureRandomBytesException, SecureNumberException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Random Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Random::class)] +final class RandomTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-negative-int $min + * @param null|non-negative-int $max + * + * @throws \FireHub\Runtime\Exception\RandomNumberBelowMinimumException + * @throws \FireHub\Runtime\Exception\RandomMaximumBelowMinimumException + * @throws \FireHub\Runtime\Exception\RandomNumberAboveGeneratorMaximumException + * + * @return void + */ + #[TestWith([0, 100])] + public function testNumber (int $min = 0, ?int $max = null):void { + + $actual = Random::number($min, $max); + + self::assertIsInt($actual); + self::assertGreaterThanOrEqual($min, $actual); + + } + + /** + * @since 1.0.0 + * + * @param int $min + * @param null|int $max + * + * @throws \FireHub\Runtime\Exception\RandomMaximumBelowMinimumException + * @throws \FireHub\Runtime\Exception\RandomNumberAboveGeneratorMaximumException + * + * @return void + */ + #[TestWith([-1])] + public function testNumberLessThenMin (int $min = 0, ?int $max = null):void { + + $this->expectException(RandomNumberBelowMinimumException::class); + + Random::number($min, $max); + + } + + /** + * @since 1.0.0 + * + * @param int $min + * @param null|int $max + * + * @throws \FireHub\Runtime\Exception\RandomNumberBelowMinimumException + * @throws \FireHub\Runtime\Exception\RandomNumberAboveGeneratorMaximumException + * + * @return void + */ + #[TestWith([10, 5])] + public function testNumberMaxLessThenMin (int $min = 0, ?int $max = null):void { + + $this->expectException(RandomMaximumBelowMinimumException::class); + + Random::number($min, $max); + + } + + /** + * @since 1.0.0 + * + * @param int $min + * @param null|int $max + * + * @throws \FireHub\Runtime\Exception\RandomNumberBelowMinimumException + * @throws \FireHub\Runtime\Exception\RandomMaximumBelowMinimumException + * + * @return void + */ + #[TestWith([0, PHP_INT_MAX])] + public function testNumberGreaterThenMax (int $min = 0, ?int $max = null):void { + + $this->expectException(RandomNumberAboveGeneratorMaximumException::class); + + Random::number($min, $max); + + } + /** + * @since 1.0.0 + * + * @param int $min + * @param int $max + * + * @throws \FireHub\Runtime\Exception\RandomMaximumBelowMinimumException + * @throws \FireHub\Runtime\Exception\SecureNumberException + * + * @return void + */ + #[TestWith([0, 100])] + public function testSecureNumber (int $min, int $max):void { + + $actual = Random::secureNumber($min, $max); + + self::assertIsInt($actual); + self::assertGreaterThanOrEqual($min, $actual); + + } + + /** + * @since 1.0.0 + * + * @param int $min + * @param int $max + * + * @throws \FireHub\Runtime\Exception\SecureNumberException + * + * @return void + */ + #[TestWith([10, 5])] + public function testSecureNumberMaxLessThenMin (int $min, int $max):void { + + $this->expectException(RandomMaximumBelowMinimumException::class); + + Random::secureNumber($min, $max); + + } + + /** + * @since 1.0.0 + * + * @param int $length + * + * @throws \FireHub\Runtime\Exception\RandomByteLengthTooSmallException + * @throws \FireHub\Runtime\Exception\SecureRandomBytesException + * + * @return void + */ + #[TestWith([20])] + public function testBytes (int $length):void { + + $actual = Random::bytes($length); + + self::assertIsString($actual); + + } + + /** + * @since 1.0.0 + * + * @param int $length + * + * @throws \FireHub\Runtime\Exception\SecureRandomBytesException + * + * @return void + */ + #[TestWith([0])] + public function testBytesLengthLessThenMin (int $length):void { + + $this->expectException(RandomByteLengthTooSmallException::class); + + Random::bytes($length); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ResourceManagerTest.php b/tests/Unit/ResourceManagerTest.php new file mode 100644 index 0000000..83c8005 --- /dev/null +++ b/tests/Unit/ResourceManagerTest.php @@ -0,0 +1,80 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ResourceManager; +use FireHub\Runtime\Type\Resource; +use FireHub\Tests\Runtime\DataProviders\ResourceDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Depends, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Resource Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(ResourceManager::class)] +final class ResourceManagerTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param resource $resource + * + * @return void + */ + #[DataProviderExternal(ResourceDataProvider::class, 'stream')] + public function testID (mixed $resource):void { + + $id = ResourceManager::id($resource); + + self::assertIsInt($id); + self::assertTrue($id > 0); + + } + + /** + * @since 1.0.0 + * + * @param resource $resource + * + * @return void + */ + #[DataProviderExternal(ResourceDataProvider::class, 'stream')] + public function testType (mixed $resource):void { + + self::assertSame(Resource::STREAM, ResourceManager::type($resource)); + + } + + /** + * @since 1.0.0 + * + * @param null|\FireHub\Runtime\Type\Resource $type + * + * @return void + */ + #[Depends('testType')] + #[TestWith([null])] + #[TestWith([Resource::STREAM])] + public function testActive (?Resource $type = null):void { + + self::assertIsArray(ResourceManager::active($type)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/ShutdownTickTest.php b/tests/Unit/ShutdownTickTest.php new file mode 100644 index 0000000..753db76 --- /dev/null +++ b/tests/Unit/ShutdownTickTest.php @@ -0,0 +1,53 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\ { + Shutdown, Tick +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test PHP Runtime Shutdown and Tick Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Shutdown::class)] +#[CoversClass(Tick::class)] +final class ShutdownTickTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\RegisterTickFailedException + * + * @return void + */ + public function testRegisterFunctions ():void { + + $func = static fn() => 'x'; + + self::assertTrue(Tick::register($func)); + + Tick::unregister($func); + + Shutdown::register($func); + + } + +} \ No newline at end of file diff --git a/tests/Unit/SplAutoloadTest.php b/tests/Unit/SplAutoloadTest.php new file mode 100644 index 0000000..2986be7 --- /dev/null +++ b/tests/Unit/SplAutoloadTest.php @@ -0,0 +1,107 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\SplAutoload; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; +use Closure; + +/** + * ### Test PHP Runtime Autoloading Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(SplAutoload::class)] +final class SplAutoloadTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @var Closure + */ + private Closure $callback = static function ($string) {}; + + /** + * @since 1.0.0 + * + * @param bool $prepend + * + * @throws \FireHub\Runtime\Exception\RegisterAutoloadFailedException + * + * @return void + */ + #[TestWith([])] + public function testRegister (bool $prepend = false):void { + + self::assertTrue(SplAutoload::register($this->callback, $prepend)); + + } + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\UnregisterAutoloadFailedException + * + * @return void + */ + #[Depends('testRegister')] + public function testUnregister ():void { + + self::assertTrue(SplAutoload::unregister($this->callback)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testFunctions ():void { + + self::assertIsList(SplAutoload::functions()); + + } + + /** + * @since 1.0.0 + * + * @param class-string $class + * + * @return void + */ + #[TestWith(['SplAutoload'])] + public function testLoad (string $class):void { + + SplAutoload::load($class); + + self::assertTrue(true); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testExtensions ():void { + + self::assertIsString(SplAutoload::extensions()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/AccessTest.php b/tests/Unit/Str/MB/AccessTest.php new file mode 100644 index 0000000..051ada8 --- /dev/null +++ b/tests/Unit/Str/MB/AccessTest.php @@ -0,0 +1,162 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Exception\StringSplitLengthException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Multibyte String Runtime Wrapper Utility - Access + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Access::class)] +final class AccessTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param int $start + * @param null|int $length + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 6])] + #[TestWith(['ЛЙ È', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 11, 4])] + #[TestWith(['カタカ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', -4, 3])] + public function testPart (string $expected, string $string, int $start, ?int $length = null, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Access::part($string, $start, $length, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $string + * @param string $search + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith([2, 'ЛЙ ÈßÁ ЛЙ ÈßÁ', 'ЛЙ'])] + public function testPartCount (int $expected, string $string, string $search, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Access::partCount($string, $search, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $character + * @param string $string + * @param bool $before_needle + * @param bool $case_sensitive + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['诶杰艾玛 ЛЙ ÈßÁ カタカナ', '诶杰艾玛', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + #[TestWith(['đščćž 诶杰艾玛', ' ЛЙ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', true])] + #[TestWith(['čćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'Č', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false, false])] + public function testLastCharacter (string $expected, string $character, string $string, bool $before_needle = false, bool $case_sensitive = true, ?Encoding $encoding = null):void { + + self::assertSame( + $expected, + Str\MB\Access::lastCharacter($string, $character, $before_needle, $case_sensitive, $encoding) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param string $find + * @param bool $before_needle + * @param bool $case_sensitive + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', '诶杰艾玛'])] + #[TestWith(['đščćž 诶杰艾玛', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', ' ЛЙ', true])] + #[TestWith(['čćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'Č', false, false])] + public function testFirstOccurrence (string $expected, string $string, string $find, bool $before_needle = false, bool $case_sensitive = true, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Access::firstOccurrence($string, $find, $before_needle, $case_sensitive, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param list $expected + * @param non-empty-string $string + * @param positive-int $length + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @throws \FireHub\Runtime\Exception\StringSplitLengthException + * + * @return void + */ + #[TestWith([ + [ + 0 => 'đščćž', + 1 => ' 诶杰艾玛', + 2 => ' ЛЙ È', + 3 => 'ßÁ カタ', + 4 => 'カナ' + ], + 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', + 5 + ])] + public function testSplit (array $expected, string $string, int $length = 1, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Access::split($string, $length, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $string + * @param positive-int $length + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['The lazy fox jumped over the fence', 0])] + public function testSplitLengthLessThanOne (string $string, int $length = 1, ?Encoding $encoding = null):void { + + $this->expectException(StringSplitLengthException::class); + + Str\MB\Access::split($string, $length, $encoding); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/CasingTest.php b/tests/Unit/Str/MB/CasingTest.php new file mode 100644 index 0000000..d5b4c19 --- /dev/null +++ b/tests/Unit/Str/MB/CasingTest.php @@ -0,0 +1,82 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Type\Str\CaseMode; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Multibyte String Runtime Wrapper Utility - Casing + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Casing::class)] +final class CasingTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param \FireHub\Runtime\Type\Str\CaseMode $case_mode + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith(['ĐŠČĆŽ 诶杰艾玛 ЛЙ ÈSSÁ カタカナ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', CaseMode::UPPER])] + #[TestWith(['đščćž 诶杰艾玛 лй èssá カタカナ', 'ĐŠČĆŽ 诶杰艾玛 ЛЙ ÈSSÁ カタカナ', CaseMode::LOWER])] + #[TestWith(['Đščćž 诶杰艾玛 Лй Èßá カタカナ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', CaseMode::TITLE])] + public function testConvert (string $expected, string $string, CaseMode $case_mode, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Casing::convert($string, $case_mode, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['Đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + public function testCapitalize (string $expected, string $string):void { + + self::assertSame($expected, Str\MB\Casing::capitalize($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', 'Đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + public function testUncapitalize (string $expected, string $string):void { + + self::assertSame($expected, Str\MB\Casing::uncapitalize($string)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/ConfigurationTest.php b/tests/Unit/Str/MB/ConfigurationTest.php new file mode 100644 index 0000000..58edcde --- /dev/null +++ b/tests/Unit/Str/MB/ConfigurationTest.php @@ -0,0 +1,50 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### PHP Multibyte String Runtime Wrapper Utility - Configuration + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Configuration::class)] +final class ConfigurationTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith([Encoding::UTF_8])] + public function testEncoding (?Encoding $encoding):void { + + self::assertTrue(Str\MB\Configuration::encoding($encoding)); + + self::assertSame($encoding, Str\MB\Configuration::encoding()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/InspectionTest.php b/tests/Unit/Str/MB/InspectionTest.php new file mode 100644 index 0000000..9721301 --- /dev/null +++ b/tests/Unit/Str/MB/InspectionTest.php @@ -0,0 +1,112 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Multibyte String Runtime Wrapper Utility - Inspection + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Inspection::class)] +final class InspectionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $string + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith([22, 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + public function testLength (int $expected, string $string, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Inspection::length($string, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $string + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith([true, 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + #[TestWith([false, 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', Encoding::ASCII])] + public function testCheckEncoding (bool $expected, string $string, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Inspection::checkEncoding($string, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param \FireHub\Core\Type\Str\Encoding $expected + * @param string $string + * + * @return void + */ + #[TestWith([Encoding::UTF_8, 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + public function testDetectEncoding (Encoding $expected, string $string):void { + + self::assertSame($expected, Str\MB\Inspection::detectEncoding($string)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testListEncoding ():void { + + self::assertIsArray(Str\MB\Inspection::listEncodings()); + + self::assertNotEmpty(Str\MB\Inspection::listEncodings()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testEncodingEnumContainsOnlySupportedEncodings ():void { + + $supported = Str\MB\Inspection::listEncodings(); + + foreach (Encoding::cases() as $encoding) { + self::assertContains( + $encoding->value, + $supported, + sprintf('Encoding "%s" is not supported by this PHP runtime.', $encoding->value), + ); + } + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/RegexTest.php b/tests/Unit/Str/MB/RegexTest.php new file mode 100644 index 0000000..036cf43 --- /dev/null +++ b/tests/Unit/Str/MB/RegexTest.php @@ -0,0 +1,228 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Runtime\Exception\InvalidPatternException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Depends, Group, Small, TestWith +}; + +/** + * ### Test Multibyte Regular Expression Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Regex::class)] +final class RegexTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $pattern + * @param string $string + * @param bool $case_sensitive + * @param mixed &$result_out + * + * @return void + */ + #[TestWith([true, 'danži', 'Danži is a boy.', false, [0 => 'Danži']])] + #[TestWith([false, 'danži', 'Danži is a boy.', true, []])] + public function testMatch (bool $expected, string $pattern, string $string, bool $case_sensitive = true, mixed $result_out = null):void { + + self::assertSame($expected, Str\MB\Regex::match($pattern, $string, $case_sensitive, $result)); + self::assertSame($result_out, $result); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $pattern + * @param string $replacement + * @param string $string + * @param bool $case_sensitive + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith(['PhP, ça marche !', '[é]', 'P', 'éhé, ça marche !'])] + #[TestWith(['PhP, ça marche !', '[P]', 'P', 'Php, ça marche !', false])] + public function testReplace (string $expected, string $pattern, string $replacement, string $string, bool $case_sensitive = true):void { + + self::assertSame($expected, Str\MB\Regex::replace($pattern, $replacement, $string, $case_sensitive)); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $replacement + * @param string $string + * @param bool $case_sensitive + * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith(['(', '', ''])] + public function testReplaceInvalidPattern (string $pattern, string $replacement, string $string, bool $case_sensitive = true):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\MB\Regex::replace($pattern, $replacement, $string, $case_sensitive) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $pattern + * @param string $string + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith([ + 'April fools day is 04/01/2003 and last christmas was 12/24/2002.', + '(\d{2}/\d{2}/)(\d{4})', + 'April fools day is 04/01/2002 and last christmas was 12/24/2001.', + ])] + public function testReplaceUsing (string $expected, string $pattern, string $string):void { + + self::assertSame( + $expected, + Str\MB\Regex::replaceUsing( + $pattern, + static fn($matches) => $matches[1].($matches[2]+1), + $string + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $string + * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith([ + ')', + 'April fools day is 04/01/2002 and last christmas was 12/24/2001.' + ])] + public function testReplaceUsingInvalidPattern (string $pattern, string $string):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\MB\Regex::replaceUsing( + $pattern, + static fn($matches) => $matches[1].($matches[2]+1), + $string + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param list $expected + * @param string $pattern + * @param string $string + * @param int $limit + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith([['', 'h', ''], 'é', 'éhé'])] + public function testSplit (array $expected, string $pattern, string $string, int $limit = -1):void { + + self::assertSame($expected, Str\MB\Regex::split($pattern, $string, $limit)); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $string + * @param int $limit + * + * @return void + */ + #[TestWith(['(', ''])] + public function testSplitInvalidPattern (string $pattern, string $string, int $limit = -1):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\MB\Regex::split($pattern, $string, $limit) + ); + + } + + /** + * @since 1.0.0 + * + * @param \FireHub\Core\Type\Str\Encoding $encoding + * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith([Encoding::UTF_8])] + public function testSetEncoding (Encoding $encoding):void { + + self::assertTrue(Str\MB\Regex::encoding($encoding)); + + } + + /** + * @since 1.0.0 + * + * @param \FireHub\Core\Type\Str\Encoding $encoding + * + * @throws \FireHub\Runtime\Exception\InvalidEncodingException + * + * @return void + */ + #[TestWith([Encoding::UTF_8])] + #[Depends('testSetEncoding')] + public function testGetEncoding (Encoding $encoding):void { + + self::assertSame($encoding, Str\MB\Regex::encoding()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/SearchTest.php b/tests/Unit/Str/MB/SearchTest.php new file mode 100644 index 0000000..5c7a72f --- /dev/null +++ b/tests/Unit/Str/MB/SearchTest.php @@ -0,0 +1,78 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Multibyte String Runtime Wrapper Utility - Searc + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Search::class)] +final class SearchTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-negative-int|false $expected + * @param string $search + * @param string $string + * @param bool $case_sensitive + * @param int $offset + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith([false, 'лй', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + #[TestWith([11, 'лй', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false])] + #[TestWith([11, 'ЛЙ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false, 9])] + #[TestWith([0, 'đ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + #[TestWith([false, 'ЛЙ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false, 20])] + public function testFirstPosition (int|false $expected, string $search, string $string, bool $case_sensitive = true, int $offset = 0, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Search::firstPosition($search, $string, $case_sensitive, $offset, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int|false $expected + * @param string $search + * @param string $string + * @param bool $case_sensitive + * @param int $offset + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith([false, 'лй', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + #[TestWith([11, 'лй', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false])] + #[TestWith([11, 'ЛЙ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false, 9])] + #[TestWith([0, 'đ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ'])] + #[TestWith([false, 'ЛЙ', 'đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', false, 20])] + public function testLastPosition (int|false $expected, string $search, string $string, bool $case_sensitive = true, int $offset = 0, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Search::lastPosition($search, $string, $case_sensitive, $offset, $encoding)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/MB/TransformTest.php b/tests/Unit/Str/MB/TransformTest.php new file mode 100644 index 0000000..1fa27f4 --- /dev/null +++ b/tests/Unit/Str/MB/TransformTest.php @@ -0,0 +1,148 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\MB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Type\Str\Encoding; +use FireHub\Core\Meta\Enum\Side; +use FireHub\Runtime\Exception\EmptyPadException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Multibyte String Runtime Wrapper Utility - Transform + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\MB\Transform::class)] +final class TransformTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param int $length + * @param non-empty-string $pad + * @param \FireHub\Core\Meta\Enum\Side $side + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @throws \FireHub\Runtime\Exception\EmptyPadException + * + * @return void + */ + #[TestWith([ + '❤❓❇❤▶▶', + '▶▶', + 6, + '❤❓❇', + Side::LEFT + ])] + #[TestWith([ + '▶▶❤❓❇❤', + '▶▶', + 6, + '❤❓❇' + ])] + #[TestWith([ + '❤❓▶▶❤❓', + '▶▶', + 6, + '❤❓❇', + Side::BOTH + ])] + public function testPad (string $expected, string $string, int $length, string $pad = ' ', Side $side = Side::RIGHT, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Transform::pad($string, $length, $pad, $side, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param int $length + * @param non-empty-string $pad + * @param \FireHub\Core\Meta\Enum\Side $side + * + * @return void + */ + #[TestWith([ + 'The lazy fox jumped over the fence', + 50, + '', + Side::BOTH + ])] + public function testPadIsEmpty (string $string, int $length, string $pad = ' ', Side $side = Side::RIGHT):void { + + $this->expectException(EmptyPadException::class); + + Str\MB\Transform::pad($string, $length, $pad, $side); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param \FireHub\Core\Meta\Enum\Side $side + * @param null|string $characters + * @param null|\FireHub\Core\Type\Str\Encoding $encoding + * + * @return void + */ + #[TestWith([ + "ÈßÁ カタカナЙÈßÁ カタカナ :) ... \n\r", + "\t\tÈßÁ カタカナЙÈßÁ カタカナ :) ... \n\r", + Side::LEFT, + " \n\r\t\v\x00" + ])] + #[TestWith([ + "\t\tÈßÁ カタカナЙÈßÁ カタカナ :) ...", + "\t\tÈßÁ カタカナЙÈßÁ カタカナ :) ...", + Side::RIGHT, + " \n\r\t\v\x00" + ])] + #[TestWith([ + "ÈßÁ カタカナЙÈßÁ カタカナ :) ...", + "\t\tÈßÁ カタカナЙÈßÁ カタカナ :) ... \n\r", + Side::BOTH, + " \n\r\t\v\x00" + ])] + public function testTrim (string $expected, string $string, Side $side = Side::BOTH, ?string $characters = null, ?Encoding $encoding = null):void { + + self::assertSame($expected, Str\MB\Transform::trim($string, $side, $characters, $encoding)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param \FireHub\Core\Type\Str\Encoding $to + * @param null|\FireHub\Core\Type\Str\Encoding $from + * + * @return void + */ + #[TestWith(['đščćž 诶杰艾玛 ЛЙ ÈßÁ カタカナ', Encoding::UTF_8, Encoding::UTF_8])] + public function testConvertEncoding (string $string, Encoding $to, ?Encoding $from = null):void { + + self::assertSame($string, Str\MB\Transform::convertEncoding($string, $to, $from)); + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/AccessTest.php b/tests/Unit/Str/SB/AccessTest.php new file mode 100644 index 0000000..9a28855 --- /dev/null +++ b/tests/Unit/Str/SB/AccessTest.php @@ -0,0 +1,173 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Runtime\Exception\StringSplitLengthException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Byte-Oriented String Runtime Wrapper Utility - Access + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Access::class)] +final class AccessTest extends FireHubTestCase { + + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param int $start + * @param null|int $length + * + * @return void + */ + #[TestWith(['azy fox jumped over the fence', 'The lazy fox jumped over the fence', 5])] + #[TestWith(['ox j', 'The lazy fox jumped over the fence', 10, 4])] + #[TestWith(['fen', 'The lazy fox jumped over the fence', -5, 3])] + public function testPart (string $expected, string $string, int $start, ?int $length = null):void { + + self::assertSame($expected, Str\SB\Access::part($string, $start, $length)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $string + * @param string $search + * @param int $start + * @param null|int $length + * + * @return void + */ + #[TestWith([2, 'This is a test', 'is'])] + #[TestWith([1, 'This is a test', 'is', 3])] + #[TestWith([0, 'This is a test', 'is', 3, 3])] + public function testPartCount (int $expected, string $string, string $search, int $start = 0, ?int $length = null):void { + + self::assertSame($expected, Str\SB\Access::partCount($string, $search, $start, $length)); + + } + + /** + * @since 1.0.0 + * + * @param string|false $expected + * @param string $characters + * @param string $string + * + * @return void + */ + #[TestWith(['ox jumped over the fence', 'xov', 'The lazy fox jumped over the fence'])] + #[TestWith([false, 'bqg', 'The lazy fox jumped over the fence'])] + public function testPartFrom (string|false $expected, string $characters, string $string):void { + + self::assertSame($expected, Str\SB\Access::firstCharacterFrom($characters, $string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param string $character + * @param bool $before_needle + * + * @return void + */ + #[TestWith(['jumped over the fence', 'jumped', 'The lazy fox jumped over the fence'])] + public function testLastCharacter (string $expected, string $character, string $string, bool $before_needle = false):void { + + self::assertSame($expected, Str\SB\Access::lastCharacter($string, $character, $before_needle)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param string $find + * @param bool $before_needle + * @param bool $case_sensitive + * + * @return void + */ + #[TestWith(['fox jumped over the fence', 'The lazy fox jumped over the fence', 'fox'])] + #[TestWith(['The lazy', 'The lazy fox jumped over the fence', ' fox', true])] + #[TestWith([' fox jumped over the fence', 'The lazy fox jumped over the fence', ' Fox', false, false])] + public function testFirstOccurrence (string $expected, string $string, string $find, bool $before_needle = false, bool $case_sensitive = true):void { + + self::assertSame($expected, Str\SB\Access::firstOccurrence($string, $find, $before_needle, $case_sensitive)); + + } + + /** + * @since 1.0.0 + * + * @param list $expected + * @param non-empty-string $string + * @param positive-int $length + * + * @throws \FireHub\Runtime\Exception\StringSplitLengthException + * + * @return void + */ + #[TestWith([ + [ + 0 => 'The l', + 1 => 'azy f', + 2 => 'ox ju', + 3 => 'mped ', + 4 => 'over ', + 5 => 'the f', + 6 => 'ence' + ], + 'The lazy fox jumped over the fence', + 5 + ])] + public function testSplit (array $expected, string $string, int $length = 1):void { + + self::assertSame($expected, Str\SB\Access::split($string, $length)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $string + * @param positive-int $length + * + * @return void + */ + #[TestWith(['The lazy fox jumped over the fence', 0])] + public function testSplitLengthLessThanOne (string $string, int $length = 1):void { + + $this->expectException(StringSplitLengthException::class); + + Str\SB\Access::split($string, $length); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/CasingTest.php b/tests/Unit/Str/SB/CasingTest.php new file mode 100644 index 0000000..c454352 --- /dev/null +++ b/tests/Unit/Str/SB/CasingTest.php @@ -0,0 +1,106 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte String Runtime Wrapper Utility - Casing + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Casing::class)] +final class CasingTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['the lazy fox jumped over the fence', 'The lazy fox jumped over the fence'])] + public function testToLower (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Casing::toLower($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['THE LAZY FOX JUMPED OVER THE FENCE', 'The lazy fox jumped over the fence'])] + public function testToUpper (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Casing::toUpper($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['The Lazy Fox Jumped Over The Fence', 'The lazy fox jumped over the fence'])] + public function testToTitle (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Casing::toTitle($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['The lazy fox jumped over the fence', 'the lazy fox jumped over the fence'])] + public function testCapitalize (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Casing::capitalize($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['the lazy fox jumped over the fence', 'The lazy fox jumped over the fence'])] + public function testUncapitalize (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Casing::uncapitalize($string)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/CompareTest.php b/tests/Unit/Str/SB/CompareTest.php new file mode 100644 index 0000000..bfb8cea --- /dev/null +++ b/tests/Unit/Str/SB/CompareTest.php @@ -0,0 +1,91 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte String Runtime Wrapper Utility - Compare + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Compare::class)] +final class CompareTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param int<-1, 1> $expected + * @param string $string_1 + * @param string $string_2 + * @param bool $case_sensitive + * + * @return void + */ + #[TestWith([-1, 'a', 'z'])] + #[TestWith([1, 'hello', 'Hello'])] + #[TestWith([0, 'Hello', 'Hello'])] + #[TestWith([1, 'a', 'A'])] + #[TestWith([0, 'a', 'A', false])] + public function testLexical (int $expected, string $string_1, string $string_2, bool $case_sensitive = true):void { + + self::assertSame($expected, Str\SB\Compare::lexical($string_1, $string_2, $case_sensitive)); + + } + + /** + * @since 1.0.0 + * + * @param int<-1, 1> $expected + * @param string $string_1 + * @param string $string_2 + * @param int $length + * + * @return void + */ + #[TestWith([1, 'Hello John', 'Hello Doe', 50])] + #[TestWith([0, 'Hello John', 'Hello Doe', 5])] + public function testFirstN (int $expected, string $string_1, string $string_2, int $length):void { + + self::assertSame($expected, Str\SB\Compare::firstN($string_1, $string_2, $length)); + + } + + /** + * @since 1.0.0 + * + * @param int<-1, 1> $expected + * @param string $string_1 + * @param string $string_2 + * @param int $offset + * @param null|int $length + * @param bool $case_sensitive + * + * @return void + */ + #[TestWith([0, 'abcde', 'BC', 1, 2, false])] + #[TestWith([1, 'abcde', 'BC', 1, 3])] + #[TestWith([-1, 'abcde', 'cd', 1, 2])] + public function testPart (int $expected, string $string_1, string $string_2, int $offset, ?int $length = null, bool $case_sensitive = true):void { + + self::assertSame($expected, Str\SB\Compare::part($string_1, $string_2, $offset, $length, $case_sensitive)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/DelimiterTest.php b/tests/Unit/Str/SB/DelimiterTest.php new file mode 100644 index 0000000..5e3bbeb --- /dev/null +++ b/tests/Unit/Str/SB/DelimiterTest.php @@ -0,0 +1,70 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Runtime\Exception\EmptySeparatorException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP String Runtime Wrapper Utility - Delimiter + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Delimiter::class)] +final class DelimiterTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param array $array + * @param string $separator + * + * @throws \FireHub\Runtime\Exception\EmptySeparatorException + * + * @return void + */ + #[TestWith([' ', ['', ''], ' '])] + #[TestWith(['The lazy fox jumped over the fence', ['The', 'lazy', 'fox', 'jumped', 'over', 'the', 'fence'], ' '])] + #[TestWith(['The lazy fox - over the fence', ['The lazy fox ', ' over the fence'], '-'])] + public function testImplodeExplode (string $expected, array $array, string $separator = ''):void { + + self::assertSame($expected, Str\SB\Delimiter::implode($array, $separator)); + self::assertSame($array, Str\SB\Delimiter::explode($expected, $separator)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param string $separator + * + * @return void + */ + #[TestWith(['The lazy fox jumped over the fence', ''])] + public function testExplodeEmptyString (string $string, string $separator):void { + + $this->expectException(EmptySeparatorException::class); + + Str\SB\Delimiter::explode($string, $separator); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/EscapeTest.php b/tests/Unit/Str/SB/EscapeTest.php new file mode 100644 index 0000000..eeec1aa --- /dev/null +++ b/tests/Unit/Str/SB/EscapeTest.php @@ -0,0 +1,112 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte String Runtime Wrapper Utility - Escape + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Escape::class)] +final class EscapeTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(["O\\\\\\'Reilly", "O\'Reilly"])] + #[TestWith(["O\'Reilly", "O'Reilly"])] + #[TestWith(["O\\\\\\\"Reilly", 'O\"Reilly'])] + #[TestWith(["O\\\\\\\"Reilly", 'O\"Reilly'])] + #[TestWith(["O\\\\Reilly", 'O\\Reilly'])] + #[TestWith(["O\\\\Reilly", 'O\Reilly'])] + public function testAddStripSlashes (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Escape::addSlashes($string)); + self::assertSame($string, Str\SB\Escape::stripSlashes($expected)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param null|string $characters + * + * @return void + */ + #[TestWith(["\\O\\\\Reilly", 'O\Reilly', 'A..Z'])] + #[TestWith(["OR\\e\\i\\l\\l\\y", 'OReilly', 'a..z'])] + public function testAddCStripSlashes (string $expected, string $string, ?string $characters = null):void { + + self::assertSame($expected, Str\SB\Escape::addCSlashes($string, $characters)); + self::assertSame($string, Str\SB\Escape::stripCSlashes($expected)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith([ + "PHP is a popular scripting language\. Fast, flexible, and pragmatic\.", + 'PHP is a popular scripting language. Fast, flexible, and pragmatic.' + ])] + public function testQuoteMeta (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Escape::quoteMeta($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param null|string|array $allowed_tags + * + * @return void + */ + #[TestWith([ + 'Test paragraph. Other text', + '

Test paragraph.

Other text' + ])] + #[TestWith([ + '

Test paragraph.

Other text', + '

Test paragraph.

Other text', + ['p', 'a'] + ])] + public function testStripTags (string $expected, string $string, null|string|array $allowed_tags = null):void { + + self::assertSame($expected, Str\SB\Escape::stripTags($string, $allowed_tags)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/InspectionTest.php b/tests/Unit/Str/SB/InspectionTest.php new file mode 100644 index 0000000..9bc41ce --- /dev/null +++ b/tests/Unit/Str/SB/InspectionTest.php @@ -0,0 +1,62 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Byte-Oriented String Runtime Wrapper Utility - Inspection + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Inspection::class)] +final class InspectionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $string + * + * @return void + */ + #[TestWith([34, 'The lazy fox jumped over the fence'])] + #[TestWith([0, ''])] + public function testLength (int $expected, string $string):void { + + self::assertSame($expected, Str\SB\Inspection::length($string)); + + } + + /** + * @since 1.0.0 + * + * @param int $expected + * @param string $string + * + * @return void + */ + #[TestWith([2191738434, 'The quick brown fox jumped over the lazy dog.'])] + public function testCrc32 (int $expected, string $string):void { + + self::assertSame($expected, Str\SB\Inspection::crc32($string)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/RegexTest.php b/tests/Unit/Str/SB/RegexTest.php new file mode 100644 index 0000000..9e2c486 --- /dev/null +++ b/tests/Unit/Str/SB/RegexTest.php @@ -0,0 +1,232 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Runtime\Exception\InvalidPatternException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test Regular Expression Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Regex::class)] +final class RegexTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $pattern + * @param string $string + * @param int $offset + * @param bool $all + * @param null|string[] &$result_out + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith([true, '/php/i', 'PHP is the web scripting language of choice.', 0, false, [0 => 'PHP']])] + #[TestWith([false, '/php/i', 'PHP is the web scripting language of choice.', 10, false, []])] + #[TestWith([true, '/\bweb\b/i', 'PHP is the web scripting language of choice.', 0, false, [0 => 'web']])] + #[TestWith([true, '/Web/','FireHub Web App FireHub Web App', 0, true, [0 => [0 => 'Web', 1 => 'Web']]])] + public function testMatch (bool $expected, string $pattern, string $string, int $offset = 0, bool $all = false, ?array $result_out = null):void { + + self::assertSame($expected, Str\SB\Regex::match($pattern, $string, $offset, $all, $result)); + self::assertSame($result_out, $result); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $string + * @param int $offset + * @param bool $all + * @param null|string[] &$result + * + * @return void + */ + #[TestWith(['-1', ''])] + public function testMatchInvalidPattern (string $pattern, string $string, int $offset = 0, bool $all = false, ?array &$result = null):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\SB\Regex::match($pattern, $string, $offset, $all, $result) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $pattern + * @param string $replacement + * @param string $string + * @param int $limit + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith(['April1,2003', '/(\w+) (\d+), (\d+)/i', '${1}1,$3', 'April 15, 2003'])] + public function testReplace (string $expected, string $pattern, string $replacement, string $string, int $limit = -1):void { + + self::assertSame($expected, Str\SB\Regex::replace($pattern, $replacement, $string, $limit)); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $replacement + * @param string $string + * @param int $limit + * + * @return void + */ + #[TestWith(['-1', '', ''])] + public function testReplaceInvalidPattern (string $pattern, string $replacement, string $string, int $limit = -1):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\SB\Regex::replace($pattern, $replacement, $string, $limit) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $pattern + * @param string $string + * @param int $limit + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith([ + 'April fools day is 04/01/2003 and last christmas was 12/24/2002.', + '|(\d{2}/\d{2}/)(\d{4})|', + 'April fools day is 04/01/2002 and last christmas was 12/24/2001.' + ])] + public function testReplaceUsing (string $expected, string $pattern, string $string, int $limit = -1):void { + + self::assertSame( + $expected, + Str\SB\Regex::replaceUsing($pattern, static fn($matches) => $matches[1].($matches[2]+1), + $string, + $limit + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $string + * @param int $limit + * + * @return void + */ + #[TestWith([ + '-1', + 'April fools day is 04/01/2002 and last christmas was 12/24/2001.' + ])] + public function testReplaceUsingInvalidPattern (string $pattern, string $string, int $limit = -1):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\SB\Regex::replaceUsing($pattern, static fn($matches) => $matches[1].($matches[2]+1), + $string, + $limit + ) + ); + + } + + /** + * @since 1.0.0 + * + * @param list $expected + * @param string $pattern + * @param string $string + * @param int $limit + * @param bool $remove_empty + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith([['Fire', 'ub'], '/H/', 'FireHub'])] + public function testSplit (array $expected, string $pattern, string $string, int $limit = -1, bool $remove_empty = false):void { + + self::assertSame($expected, Str\SB\Regex::split($pattern, $string, $limit, $remove_empty)); + + } + + /** + * @since 1.0.0 + * + * @param string $pattern + * @param string $string + * @param int $limit + * @param bool $remove_empty + * + * @return void + */ + #[TestWith(['-1', 'FireHub'])] + public function testSplitInvalidPattern (string $pattern, string $string, int $limit = -1, bool $remove_empty = false):void { + + $this->expectException(InvalidPatternException::class); + + $this->suppressPhpErrors( + fn() => Str\SB\Regex::split($pattern, $string, $limit, $remove_empty) + ); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param null|string $delimiter + * + * @return void + */ + #[TestWith(['Fire\Hub', 'FireHub', 'H'])] + public function testQuote (string $expected, string $string, ?string $delimiter = null):void { + + self::assertSame($expected, Str\SB\Regex::quote($string, $delimiter)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/ReplaceTest.php b/tests/Unit/Str/SB/ReplaceTest.php new file mode 100644 index 0000000..ef29a54 --- /dev/null +++ b/tests/Unit/Str/SB/ReplaceTest.php @@ -0,0 +1,137 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte String Runtime Wrapper Utility - Replace + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Replace::class)] +final class ReplaceTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string|list $search + * @param string|list $replace + * @param string $string + * @param bool $case_sensitive + * @param int $count_replaced + * + * @return void + */ + #[TestWith([ + 'The lazy mouse jumped over the fence', + 'fox', + 'mouse', + 'The lazy fox jumped over the fence', + true, + 1 + ])] + #[TestWith([ + 'The lazy fox jumped over the fence', + 'Fox', + 'mouse', + 'The lazy fox jumped over the fence', + true, + 0 + ])] + #[TestWith([ + 'The lazy fox, the lazy fox, the lazy fox', + 'mouse', + 'fox', + 'The lazy mouse, the lazy mouse, the lazy mouse', + true, + 3 + ])] + #[TestWith([ + 'The lazy mouse jumped over the fence', + 'Fox', + 'mouse', + 'The lazy fox jumped over the fence', + false, + 1 + ])] + #[TestWith([ + 'An lazy mouse jumped over the fence', + ['The', 'fox'], + ['An', 'mouse'], + 'The lazy fox jumped over the fence', + true, + 2 + ])] + public function testReplace (string $expected, string|array $search, string|array $replace, string $string, bool $case_sensitive, int $count_replaced):void { + + self::assertSame($expected, Str\SB\Replace::replace($search, $replace, $string, $case_sensitive, $count)); + self::assertSame($count, $count_replaced); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param string $replace + * @param int $offset + * @param null|int $length + * + * @return void + */ + #[TestWith([ + 'An lazy fox jumped over the fence', + 'The lazy fox jumped over the fence', + 'An', + 0, + 3 + ])] + #[TestWith([ + 'The lazy fox jumped over the bush', + 'The lazy fox jumped over the fence', + 'bush', + -5, + 5 + ])] + public function testPart (string $expected, string $string, string $replace, int $offset, ?int $length = null):void { + + self::assertSame($expected, Str\SB\Replace::part($string, $replace, $offset, $length)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param array $replace_pairs + * + * @return void + */ + #[TestWith(['Hello World', 'Hillo Warld', ['il' => 'el', 'ar' => 'or']])] + public function testTranslate (string $expected, string $string, array $replace_pairs):void { + + self::assertSame($expected, Str\SB\Replace::translate($string, $replace_pairs)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/SearchTest.php b/tests/Unit/Str/SB/SearchTest.php new file mode 100644 index 0000000..b89a3ab --- /dev/null +++ b/tests/Unit/Str/SB/SearchTest.php @@ -0,0 +1,166 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte String Runtime Wrapper Utility - Search + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Search::class)] +final class SearchTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $value + * @param string $string + * + * @return void + */ + #[TestWith([false, 'j', ''])] + #[TestWith([true, 'j', 'ijk'])] + public function testContains (bool $expected, string $value, string $string):void { + + self::assertSame($expected, Str\SB\Search::contains($value, $string)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $value + * @param string $string + * + * @return void + */ + #[TestWith([false, 'j', ''])] + #[TestWith([true, 'i', 'ijk'])] + public function testStartsWith (bool $expected, string $value, string $string):void { + + self::assertSame($expected, Str\SB\Search::startsWith($value, $string)); + + } + + /** + * @since 1.0.0 + * + * @param bool $expected + * @param string $value + * @param string $string + * + * @return void + */ + #[TestWith([false, 'j', ''])] + #[TestWith([true, 'k', 'ijk'])] + public function testEndsWith (bool $expected, string $value, string $string):void { + + self::assertSame($expected, Str\SB\Search::endsWith($value, $string)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int|false $expected + * @param string $search + * @param string $string + * @param bool $case_sensitive + * @param int $offset + * + * @return void + */ + #[TestWith([false, 'Fox', 'The lazy fox jumped over the fence'])] + #[TestWith([9, 'Fox', 'The lazy fox jumped over the fence', false])] + #[TestWith([9, 'Fox', 'The lazy fox jumped over the fence', false, 9])] + #[TestWith([0, 'T', 'The lazy fox jumped over the fence'])] + #[TestWith([false, 'Fox', 'The lazy fox jumped over the fence', false, 10])] + public function testFirstPosition (int|false $expected, string $search, string $string, bool $case_sensitive = true, int $offset = 0):void { + + self::assertSame($expected, Str\SB\Search::firstPosition($search, $string, $case_sensitive, $offset)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int|false $expected + * @param string $search + * @param string $string + * @param bool $case_sensitive + * @param int $offset + * + * @return void + */ + #[TestWith([false, 'Fox', 'The lazy fox jumped over the fence'])] + #[TestWith([9, 'Fox', 'The lazy fox jumped over the fence', false])] + #[TestWith([9, 'Fox', 'The lazy fox jumped over the fence', false, 9])] + #[TestWith([0, 'T', 'The lazy fox jumped over the fence'])] + #[TestWith([false, 'Fox', 'The lazy fox jumped over the fence', false, 10])] + public function testLastPosition (int|false $expected, string $search, string $string, bool $case_sensitive = true, int $offset = 0):void { + + self::assertSame($expected, Str\SB\Search::lastPosition($search, $string, $case_sensitive, $offset)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $string + * @param string $characters + * @param int $offset + * @param null|int $length + * + * @return void + */ + #[TestWith([0, 'The lazy fox jumped over the fence', 'lazy'])] + #[TestWith([4, 'The lazy fox jumped over the fence', 'lazy',4])] + #[TestWith([3, 'The lazy fox jumped over the fence', 'lazy',4, 3])] + public function testSegmentLength (int $expected, string $string, string $characters, int $offset = 0, ?int $length = null):void { + + self::assertSame($expected, Str\SB\Search::segmentLength($string, $characters, $offset, $length)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param string $string + * @param string $characters + * @param int $offset + * @param null|int $length + * + * @return void + */ + #[TestWith([4, 'The lazy fox jumped over the fence', 'lazy', 0])] + #[TestWith([0, 'The lazy fox jumped over the fence', 'lazy', 4])] + #[TestWith([2, 'The lazy fox jumped over the fence', 'lazy', 2, 4])] + public function testSegmentNotLength (int $expected, string $string, string $characters, int $offset = 0, ?int $length = null):void { + + self::assertSame($expected, Str\SB\Search::segmentNotLength($string, $characters, $offset, $length)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Str/SB/TransformTest.php b/tests/Unit/Str/SB/TransformTest.php new file mode 100644 index 0000000..b01b786 --- /dev/null +++ b/tests/Unit/Str/SB/TransformTest.php @@ -0,0 +1,260 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Str\SB; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Str; +use FireHub\Core\Meta\Enum\Side; +use FireHub\Runtime\Exception\ { + EmptyPadException, InvalidChunkLengthException +}; +use FireHub\Tests\Runtime\DataProviders\StrDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, DependsExternal, Group, Small, TestWith +}; + +/** + * ### Test PHP Single-Byte String Runtime Wrapper Utility - Transform + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Str\SB\Transform::class)] +final class TransformTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param int $times + * @param string $separator + * + * @return void + */ + #[TestWith(['fox-fox', 'fox', 2, '-'])] + public function testRepeat (string $expected, string $string, int $times, string $separator = ''):void { + + self::assertSame($expected, Str\SB\Transform::repeat($string, $times, $separator)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param int $length + * @param non-empty-string $pad + * @param \FireHub\Core\Meta\Enum\Side $side + * + * @throws \FireHub\Runtime\Exception\EmptyPadException + * + * @return void + */ + #[TestWith([ + '----------------The lazy fox jumped over the fence', + 'The lazy fox jumped over the fence', + 50, + '-', + Side::LEFT + ])] + #[TestWith([ + 'The lazy fox jumped over the fence----------------', + 'The lazy fox jumped over the fence', + 50, + '-' + ])] + #[TestWith([ + '--------The lazy fox jumped over the fence--------', + 'The lazy fox jumped over the fence', + 50, + '-', + Side::BOTH + ])] + public function testPad (string $expected, string $string, int $length, string $pad = ' ', Side $side = Side::RIGHT):void { + + self::assertSame($expected, Str\SB\Transform::pad($string, $length, $pad, $side)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param int $length + * @param non-empty-string $pad + * @param \FireHub\Core\Meta\Enum\Side $side + * + * @return void + */ + #[TestWith([ + 'The lazy fox jumped over the fence', + 50, + '', + Side::BOTH + ])] + public function testPadIsEmpty (string $string, int $length, string $pad = ' ', Side $side = Side::RIGHT):void { + + $this->expectException(EmptyPadException::class); + + Str\SB\Transform::pad($string, $length, $pad, $side); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * + * @return void + */ + #[TestWith(['ecnef eht revo depmuj xof yzal ehT', 'The lazy fox jumped over the fence'])] + public function testReverse (string $expected, string $string):void { + + self::assertSame($expected, Str\SB\Transform::reverse($string)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * + * @throws \FireHub\Runtime\Exception\StringSplitLengthException + * + * @return void + */ + #[DependsExternal(InspectionTest::class, 'testLength')] + #[DependsExternal(AccessTest::class, 'testSplit')] + #[DataProviderExternal(StrDataProvider::class, 'stringsSB')] + public function testShuffle (string $string):void { + + $shuffled = Str\SB\Transform::shuffle($string); + + self::assertSame(Str\SB\Inspection::length($string), Str\SB\Inspection::length($shuffled)); + + self::assertEqualsCanonicalizing(Str\SB\Access::split($string), Str\SB\Access::split($shuffled)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param positive-int $length + * @param string $separator + * + * @throws \FireHub\Runtime\Exception\InvalidChunkLengthException + * + * @return void + */ + #[TestWith([ + 'The lazy f-ox jumped -over the f-ence-', + 'The lazy fox jumped over the fence', + 10, + '-' + ])] + public function testChunkSplit (string $expected, string $string, int $length = 76, string $separator = "\r\n"):void { + + self::assertSame($expected, Str\SB\Transform::chunkSplit($string, $length, $separator)); + + } + + /** + * @since 1.0.0 + * + * @param string $string + * @param positive-int $length + * @param string $separator + * + * @return void + */ + #[TestWith(['The lazy fox jumped over the fence', 0, '-'])] + public function testChunkSplitLengthLessThanOne (string $string, int $length = 76, string $separator = "\r\n"):void { + + $this->expectException(InvalidChunkLengthException::class); + + Str\SB\Transform::chunkSplit($string, $length, $separator); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param int $width + * @param string $break + * @param bool $cut_long_words + * + * @return void + */ + #[TestWith(['The lazy fox jumped
over the fence', 'The lazy fox jumped over the fence', 20, '
', true])] + #[TestWith(['A very
long
wooooooo
ooooord', 'A very long woooooooooooord', 8, '
', true])] + public function testWrap (string $expected, string $string, int $width = 75, string $break = "\n", bool $cut_long_words = false):void { + + self::assertSame($expected, Str\SB\Transform::wrap($string, $width, $break, $cut_long_words)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $format + * @param null|scalar...$values + * + * @return void + */ + #[TestWith(['There are 5 monkeys in the tree', 'There are %d monkeys in the %s', 5, 'tree'])] + public function testFormat (string $expected, string $format, null|bool|float|int|string ...$values):void { + + self::assertSame($expected, Str\SB\Transform::format($format, ...$values)); + + } + + /** + * @since 1.0.0 + * + * @param string $expected + * @param string $string + * @param \FireHub\Core\Meta\Enum\Side $side + * @param string $characters + * + * @return void + */ + #[TestWith([ + "These are a few words :) ... \n\r", + "\t\tThese are a few words :) ... \n\r", + Side::LEFT + ])] + #[TestWith([ + "\t\tThese are a few words :) ...", + "\t\tThese are a few words :) ...", + Side::RIGHT + ])] + #[TestWith([ + "These are a few words :) ...", + "\t\tThese are a few words :) ... \n\r" + ])] + public function testTrim (string $expected, string $string, Side $side = Side::BOTH, string $characters = " \n\r\t\v\x00"):void { + + self::assertSame($expected, Str\SB\Transform::trim($string, $side, $characters)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/ClockTest.php b/tests/Unit/System/ClockTest.php new file mode 100644 index 0000000..0226e0b --- /dev/null +++ b/tests/Unit/System/ClockTest.php @@ -0,0 +1,93 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test Runtime Clock Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Clock::class)] +final class ClockTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testTime ():void { + + $before = time(); + + $result = System\Clock::time(); + + $after = time(); + + self::assertIsInt($result); + self::assertGreaterThan(0, $result); + + self::assertGreaterThanOrEqual($before, $result); + self::assertLessThanOrEqual($after, $result); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testMicrotime ():void { + + $before = microtime(true); + + $result = System\Clock::microtime(); + + $after = microtime(true); + + self::assertIsFloat($result); + self::assertGreaterThan(0, $result); + + self::assertGreaterThanOrEqual($before, $result); + self::assertLessThanOrEqual($after, $result); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testHighResolution ():void { + + $time = System\Clock::highResolution(); + + self::assertIsArray($time); + self::assertCount(2, $time); + + self::assertIsInt($time[0]); + self::assertIsInt($time[1]); + + self::assertGreaterThanOrEqual(0, $time[0]); + self::assertGreaterThanOrEqual(0, $time[1]); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/ConfigurationTest.php b/tests/Unit/System/ConfigurationTest.php new file mode 100644 index 0000000..9323729 --- /dev/null +++ b/tests/Unit/System/ConfigurationTest.php @@ -0,0 +1,233 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use FireHub\Runtime\Exception\{ + ConfigurationOptionNotFoundException, ExtensionNotFoundException, FailedToSetConfigurationOptionException, + InvalidConfigurationQuantityException +}; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Configuration Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Configuration::class)] +final class ConfigurationTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testGetPath ():void { + + self::assertIsString(System\Configuration::getPath()); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $option + * + * @throws \FireHub\Runtime\Exception\ConfigurationOptionNotFoundException + * + * @return void + */ + #[TestWith(['post_max_size'])] + public function testGet (string $option):void { + + self::assertIsString(System\Configuration::get($option)); + + } + + /** + * @since 1.0.0 + * + * @param string $name + * + * @return void + */ + #[TestWith(['NotValidConfigurationOption'])] + public function testGetConfigurationOptionNotValid (string $name):void { + + $this->expectException(ConfigurationOptionNotFoundException::class); + + System\Configuration::get($name); + + } + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\ExtensionNotFoundException + * @throws \FireHub\Runtime\Exception\ConfigurationRetrievalException + * + * @return void + */ + public function testGetAll ():void { + + self::assertIsArray(System\Configuration::getAll()); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $extension + * + * @throws \FireHub\Runtime\Exception\ExtensionNotFoundException + * @throws \FireHub\Runtime\Exception\ConfigurationRetrievalException + * + * @return void + */ + #[TestWith(['pcre'])] + public function testGetAllWithName (string $extension):void { + + self::assertIsArray(System\Configuration::getAll($extension)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $extension + * + * @throws \FireHub\Runtime\Exception\ConfigurationRetrievalException + * + * @return void + */ + #[TestWith(['NotValidExtension'])] + public function testGetAllWithNameNotValid (string $extension):void { + + $this->expectException(ExtensionNotFoundException::class); + + System\Configuration::getAll($extension); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $option + * @param null|scalar $value + * + * @throws \FireHub\Runtime\Exception\FailedToSetConfigurationOptionException + * + * @return void + */ + #[TestWith(['display_errors', '0'])] + public function testSet (string $option, null|int|float|string|bool $value):void { + + self::assertTrue(System\Configuration::set($option, $value)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $option + * @param null|scalar $value + * + * @return void + */ + #[TestWith(['test', '0'])] + public function testSetFailed (string $option, null|int|float|string|bool $value):void { + + $this->expectException(FailedToSetConfigurationOptionException::class); + + System\Configuration::set($option, $value); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $option + * + * @throws \FireHub\Runtime\Exception\ConfigurationOptionNotFoundException + * + * @return void + */ + #[TestWith(['max_memory_limit'])] + public function testRestore (string $option):void { + + self::assertIsString(System\Configuration::restore($option)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $option + * + * @return void + */ + #[TestWith([''])] + public function testRestoreWithEmptyOption (string $option):void { + + $this->expectException(ConfigurationOptionNotFoundException::class); + + System\Configuration::restore($option); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $expected + * @param non-empty-string $shorthand + * + * @throws \FireHub\Runtime\Exception\InvalidConfigurationQuantityException + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith([1024, '1024'])] + #[TestWith([1073741824, '1024M'])] + #[TestWith([524288, '512K'])] + #[TestWith([532, '0o1024'])] + #[TestWith([532, '01024'])] + public function testParseQuantity (int $expected, string $shorthand):void { + + self::assertSame($expected, System\Configuration::parseQuantity($shorthand)); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $shorthand + * + * @throws \FireHub\Runtime\Exception\InvalidPatternException + * + * @return void + */ + #[TestWith(['xxx'])] + public function testParseQuantityWithInvalidShorthand (string $shorthand):void { + + $this->expectException(InvalidConfigurationQuantityException::class); + + System\Configuration::parseQuantity($shorthand); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/EnvironmentTest.php b/tests/Unit/System/EnvironmentTest.php new file mode 100644 index 0000000..7f267c4 --- /dev/null +++ b/tests/Unit/System/EnvironmentTest.php @@ -0,0 +1,93 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.0 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use PHPUnit\Framework\Attributes\ { + CoversClass, Depends, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Environment Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Environment::class)] +final class EnvironmentTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-empty-string $assignment + * + * @return void + */ + #[TestWith(['FOO=BAR'])] + public function testSetVariables (string $assignment):void { + + self::assertTrue(System\Environment::setVariable($assignment)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testGetVariables ():void { + + self::assertIsArray(System\Environment::getVariable()); + + } + + /** + * @since 1.0.0 + * + * @param non-empty-string $name + * + * @return void + */ + #[TestWith(['FOO'])] + #[Depends('testSetVariables')] + public function testGetVariablesWithName (string $name):void { + + self::assertSame('BAR', System\Environment::getVariable($name)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testScriptOwner ():void { + + self::assertIsString(System\Environment::scriptOwner()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testTempFolder ():void { + + self::assertIsString(System\Environment::tempFolder()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/ExtensionTest.php b/tests/Unit/System/ExtensionTest.php new file mode 100644 index 0000000..d3f3b70 --- /dev/null +++ b/tests/Unit/System/ExtensionTest.php @@ -0,0 +1,89 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use FireHub\Runtime\Exception\ExtensionNotFoundException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Extension Management Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Extension::class)] +final class ExtensionTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param string $name + * + * @return void + */ + #[TestWith(['Core'])] + public function testHasExtension (string $name):void { + + self::assertTrue(System\Extension::hasExtension($name)); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testLoadedExtensions ():void { + + self::assertIsList(System\Extension::loadedExtensions()); + + } + + /** + * @since 1.0.0 + * + * @param string $extension + * + * @throws \FireHub\Runtime\Exception\ExtensionNotFoundException + * + * @return void + */ + #[TestWith(['Core'])] + public function testIsExtensionFunctions (string $extension):void { + + self::assertIsList(System\Extension::extensionFunctions($extension)); + + } + + /** + * @since 1.0.0 + * + * @param string $extension + * + * @return void + */ + #[TestWith(['NotValidExtension'])] + public function testIsExtensionFunctionsNotValid (string $extension):void { + + $this->expectException(ExtensionNotFoundException::class); + + System\Extension::extensionFunctions($extension); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/FileSystemTest.php b/tests/Unit/System/FileSystemTest.php new file mode 100644 index 0000000..28c1e2c --- /dev/null +++ b/tests/Unit/System/FileSystemTest.php @@ -0,0 +1,42 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test PHP Runtime File System Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\FileSystem::class)] +final class FileSystemTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testIncludedFiles ():void { + + self::assertIsList(System\FileSystem::includedFiles()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/MemoryTest.php b/tests/Unit/System/MemoryTest.php new file mode 100644 index 0000000..9543f2a --- /dev/null +++ b/tests/Unit/System/MemoryTest.php @@ -0,0 +1,68 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test PHP Runtime Memory Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Memory::class)] +final class MemoryTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testGetUsage ():void { + + self::assertIsInt(System\Memory::getUsage()); + self::assertTrue(System\Memory::getUsage() > 0); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testGetPeakUsage ():void { + + self::assertIsInt(System\Memory::getPeakUsage()); + self::assertTrue(System\Memory::getPeakUsage() > 0); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testResetPeakUsage ():void { + + System\Memory::resetPeakUsage(); + + self::assertTrue(true); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/PlatformTest.php b/tests/Unit/System/PlatformTest.php new file mode 100644 index 0000000..67a54cf --- /dev/null +++ b/tests/Unit/System/PlatformTest.php @@ -0,0 +1,49 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Platform Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Platform::class)] +final class PlatformTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-empty-string $key + * + * @return void + */ + #[TestWith(['name'])] + #[TestWith(['hostname'])] + #[TestWith(['release'])] + #[TestWith(['version'])] + #[TestWith(['machine'])] + public function testOsInfo (string $key):void { + + self::assertArrayHasKey($key, System\Platform::osInfo()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/ProcessTest.php b/tests/Unit/System/ProcessTest.php new file mode 100644 index 0000000..d7ba1b8 --- /dev/null +++ b/tests/Unit/System/ProcessTest.php @@ -0,0 +1,44 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small +}; + +/** + * ### Test PHP Process Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Process::class)] +final class ProcessTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\ProcessIdUnavailableException + * + * @return void + */ + public function testID ():void { + + self::assertIsInt(System\Process::ID()); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/RuntimeTest.php b/tests/Unit/System/RuntimeTest.php new file mode 100644 index 0000000..dc2e852 --- /dev/null +++ b/tests/Unit/System/RuntimeTest.php @@ -0,0 +1,88 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use FireHub\Core\Type\Version\Constraint; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Introspection Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Runtime::class)] +final class RuntimeTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @throws \FireHub\Runtime\Exception\SapiUnavailableException + * + * @return void + */ + public function testServerAPI ():void { + + self::assertIsString(System\Runtime::serverAPI()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testPhpVersion ():void { + + self::assertSame(System\Runtime::phpVersion(), System\Runtime::phpVersion('Core')); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testZendVersion ():void { + + self::assertIsString(System\Runtime::zendVersion()); + + } + + /** + * @since 1.0.0 + * + * @param int-mask<-1, 0, 1>|bool $excepted + * @param string $first + * @param string $second + * @param null|\FireHub\Core\Type\Version\Constraint $comparison + * + * @return void + */ + #[TestWith([-1, '1.0.0', '1.0.1'])] + #[TestWith([0, '1.0.0', '1.0.0'])] + #[TestWith([1, '2.0.0', '1.0.0'])] + #[TestWith([true, '2.0.0', '1.0.0', Constraint::GREATER])] + #[TestWith([false, '2.0.0', '3.0.0', Constraint::GREATER])] + public function testCompareVersion (int|bool $excepted, string $first, string $second, ?Constraint $comparison = null):void { + + self::assertSame($excepted, System\Runtime::compareVersion($first, $second, $comparison)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/System/TimeTest.php b/tests/Unit/System/TimeTest.php new file mode 100644 index 0000000..3dce4b4 --- /dev/null +++ b/tests/Unit/System/TimeTest.php @@ -0,0 +1,114 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=7.4 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\System; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\System; +use FireHub\Runtime\Exception\InvalidSleepDurationException; +use PHPUnit\Framework\Attributes\ { + CoversClass, Group, Small, TestWith +}; + +/** + * ### Test PHP Runtime Time Utilities + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(System\Time::class)] +final class TimeTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @param non-negative-int $seconds + * @param non-negative-int $nanoseconds + * + * @throws \FireHub\Runtime\Exception\InvalidSleepDurationException + * + * @return void + */ + #[TestWith([0])] + #[TestWith([0, 2])] + public function testSleep (int $seconds, int $nanoseconds = 0):void { + + self::assertTrue(System\Time::sleep($seconds, $nanoseconds)); + + } + + /** + * @since 1.0.0 + * + * @param non-negative-int $seconds + * + * @throws \FireHub\Runtime\Exception\InvalidSleepDurationException + * + * @return void + */ + #[TestWith([-1])] + public function testSleepInvalidSeconds (int $seconds):void { + + $this->expectException(InvalidSleepDurationException::class); + + System\Time::sleep($seconds); + + } + + /** + * @since 1.0.0 + * + * @param int<0, 999999> $microseconds + * + * @throws \FireHub\Runtime\Exception\InvalidSleepDurationException + * + * @return void + */ + #[TestWith([1])] + public function testSleepMicroseconds (int $microseconds):void { + + System\Time::sleepMicroseconds($microseconds); + + self::assertTrue(true); + + } + + /** + * @since 1.0.0 + * + * @param int $value + * + * @return void + */ + #[TestWith([-1])] + #[TestWith([1_000_000])] + public function testSleepMicrosecondsInvalidMicroseconds (int $value):void { + + $this->expectException(InvalidSleepDurationException::class); + + System\Time::sleepMicroseconds($value); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testSleepUntil ():void { + + self::assertTrue(System\Time::sleepUntil(time() - 10)); + + } + +} \ No newline at end of file diff --git a/tests/Unit/Type/Data/TypeTest.php b/tests/Unit/Type/Data/TypeTest.php new file mode 100644 index 0000000..5f6e4e2 --- /dev/null +++ b/tests/Unit/Type/Data/TypeTest.php @@ -0,0 +1,100 @@ + + * @copyright 2026-present The FireHub Project - All rights reserved + * @license https://opensource.org/license/Apache-2-0 Apache License, Version 2.0 + * + * @php-version >=8.1 + * @package Runtime\Tests + */ + +namespace FireHub\Tests\Runtime\Unit\Type\Data; + +use FireHub\Testing\FireHubTestCase; +use FireHub\Runtime\Type\Data\ { + Category, Type +}; +use FireHub\Tests\Runtime\DataProviders\DataDataProvider; +use PHPUnit\Framework\Attributes\ { + CoversClass, DataProviderExternal, Group, Small +}; + +/** + * ### Test PHP Runtime Data Type + * @since 1.0.0 + */ +#[Small] +#[Group('src')] +#[CoversClass(Type::class)] +final class TypeTest extends FireHubTestCase { + + /** + * @since 1.0.0 + * + * @return void + */ + public function testCategory ():void { + + self::assertSame(Category::SCALAR, Type::BOOL->category()); + self::assertSame(Category::SCALAR, Type::INT->category()); + self::assertSame(Category::SCALAR, Type::FLOAT->category()); + self::assertSame(Category::SCALAR, Type::STRING->category()); + + self::assertSame(Category::COMPOUND, Type::ARRAY->category()); + self::assertSame(Category::COMPOUND, Type::OBJECT->category()); + + self::assertSame(Category::SPECIAL, Type::NULL->category()); + self::assertSame(Category::SPECIAL, Type::RESOURCE->category()); + self::assertSame(Category::SPECIAL, Type::CLOSED_RESOURCE->category()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testIsScalar():void { + + self::assertTrue(Type::BOOL->isScalar()); + self::assertTrue(Type::INT->isScalar()); + self::assertTrue(Type::FLOAT->isScalar()); + self::assertTrue(Type::STRING->isScalar()); + + self::assertFalse(Type::ARRAY->isScalar()); + self::assertFalse(Type::OBJECT->isScalar()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testIsCompound ():void { + + self::assertTrue(Type::ARRAY->isCompound()); + self::assertTrue(Type::OBJECT->isCompound()); + + self::assertFalse(Type::STRING->isCompound()); + + } + + /** + * @since 1.0.0 + * + * @return void + */ + public function testIsSpecial ():void { + + self::assertTrue(Type::NULL->isSpecial()); + self::assertTrue(Type::RESOURCE->isSpecial()); + + self::assertFalse(Type::BOOL->isSpecial()); + + } + +} \ No newline at end of file