+ * 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 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * An array containing keys to return. + *
+ * @param mixed $filter [optional]+ * If specified, then only keys containing these values are returned. + *
+ * + * @return list+ * The array. + *
+ * + * @return list+ * 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+ * 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+ * 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+ * Array of values to be used as keys. + * + * Illegal values for a key will be converted to string. + *
+ * @param array+ * 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+ * Variable list of arrays to merge. + *
+ * + * @return array+ * Variable list of arrays to recursively merge. + *
+ * + * @return array+ * The array in which elements are replaced. + *
+ * @param array+ * Arrays from which elements will be extracted. + * + * Values from later arrays overwrite the previous values. + *
+ * + * @return array+ * The array in which elements are replaced. + *
+ * @param array+ * Arrays from which elements will be extracted. + * + * Values from later arrays overwrite the previous values. + *
+ + * @return 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+ * 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+ * 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+ * The array is being evaluated. + *
+ * + * @phpstan-assert-if-true list+ * 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+ * The array of values to count. + *
+ * + * @return 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+ * 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+ * The array to get the value from. + *
+ * @phpstan-param-out TArray $array + * + * @return null|value-of+ * The input array. + *
+ * @param TPushedValue ...$values [optional]+ * The values to push onto the end of the array. + *
+ * @phpstan-param-out array+ * Array to shift. + *
+ * @phpstan-param-out TArray $array + * + * @return null|value-of+ * The input array. + *
+ * @param TUnshiftValue ...$values [optional]+ * The values to prepend. + *
+ * @phpstan-param-out 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 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+ * Array to sort. + *
+ * @param callable(value-of+ * 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 to sort. + *
+ * @param callable(key-of+ * 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+ * 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+ * 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+ * The array. + *
+ * + * @return value-of+ * The array. + *
+ * + * @return null|key-of+ * The input array. + *
+ * @phpstan-param-out TArray $array + * + * @return null|value-of+ * The array being affected. + *
+ * @phpstan-param-out TArray $array + * + * @return value-of+ * The input array. + *
+ * @phpstan-param-out TArray $array + * + * @return value-of+ * The input array. + *
+ * @phpstan-param-out TArray $array + * + * @return value-of+ * The array to compare from. + *
+ * @param array+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(value-of+ * 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+ * The array to compare from. + *
+ * @param array+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(key-of+ * 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+ * The array to compare from. + *
+ * @param array+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(value-of+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(key-of+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(value-of+ * The comparison function for value. + *
+ * @param callable(key-of+ * 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+ * The array with main values to check. + *
+ * @param array+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(value-of+ * 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+ * The array with main values to check. + *
+ * @param array+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(key-of+ * 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+ * The array with main values to check. + *
+ * @param array+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(value-of+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(key-of+ * 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+ * The array to compare from. + *
+ * @param TCompareArray $excludes+ * An array to compare against. + *
+ * @param callable(value-of+ * The comparison function for value. + *
+ * @param callable(key-of+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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 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+ * 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+ * 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+ * The array to work on. + *
+ * @param \FireHub\Runtime\Type\Arr\KeyCase $style [optional]+ * Either LOWER or UPPER key case style. + *
+ * + * @return 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+ * The array to flip. + *
+ * + * @return 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+ * 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+ * 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 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+ * The array to remove duplicates. + *
+ * + * @return array+ * 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+ * 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+ * 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 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+ * 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 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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.+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * An object instance. + *
+ * + * @return array+ * The class name or an object instance. + *
+ * + * @throws \FireHub\Runtime\Exception\ClassDoesntExistException If the class doesn't exist. + * + * @return array+ * A class name or an object instance. + *
+ * @param class-string+ * 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+ * The tested class. + * + * No error is generated if the class doesn't exist. + *
+ * @param class-string+ * 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 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 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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+ * 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