VOOZH about

URL: https://deepwiki.com/hypervel/support/9.1-helper-functions

⇱ Helper Functions | hypervel/support | DeepWiki


Loading...
Menu

Helper Functions

This page documents the global helper functions provided by the hypervel/support package. These functions provide convenient utilities for common programming tasks including value resolution, data manipulation, control flow, and type checking. All functions are defined in src/helpers.php1-420 and are globally available throughout the application.

The package provides 26 global helper functions organized into functional categories. For data manipulation using dot notation specifically, see 9.4 Data Manipulation For collection operations beyond the collect() helper, see 9.2 Collections For environment configuration details, see 9.5 Environment Configuration For control flow utilities including once(), retry(), tap(), and others, see 9.6 Control Flow Helpers


Function Categories Overview

The helper functions are organized into the following functional categories:

CategoryFunctionsPurpose
Value Resolutionvalue(), transform(), with(), optional()Resolve callables and conditionally transform values
Environmentenv(), environment()Access environment variables and application environment
Type Checkingblank(), filled()Determine if values are empty or filled
Data Encodinge()HTML entity encoding for XSS protection
Data Structurescollect()Create Collection instances from arrays
Data Accessdata_get(), data_set(), data_fill(), data_forget(), object_get()Access and modify nested arrays/objects using dot notation
Array Utilitieshead(), last()Retrieve first/last array elements
Control Flowretry(), throw_if(), throw_unless(), when()Exception handling, retry logic, and conditional operations
Function Utilitiesonce(), tap()Memoization and side-effect execution
Reflectionclass_basename(), class_uses_recursive(), trait_uses_recursive()Inspect class names, traits, and inheritance

Sources: src/helpers.php1-420


Helper Function Architecture


Diagram: Helper Function System Architecture

This diagram shows how helper functions are organized into functional groups and their dependencies on underlying systems. Most helpers delegate to Hyperf framework utilities or custom Hypervel classes.

Sources: src/helpers.php1-420


Value Resolution Functions

value()

Resolves a value, calling it if it's a callable. This is the foundational function for lazy evaluation throughout the package.

Function Signature: src/helpers.php15-23


Behavior:

  • If $value is a Closure or callable, executes it with $args and returns the result
  • Otherwise, returns $value unchanged
  • Delegates to \Hypervel\Support\value() implementation

Usage Pattern:


Sources: src/helpers.php15-23


transform()

Conditionally transforms a value if it is "filled" (not blank).

Function Signature: src/helpers.php326-342


Parameters:

  • $value - The value to potentially transform
  • $callback - Transformation function to apply if value is filled
  • $default - Default value/callback to use if value is blank

Behavior:

  • Checks if $value is filled using filled() function
  • If filled, applies $callback to the value
  • If blank and $default is callable, calls $default($value)
  • Otherwise returns $default unchanged

Usage Pattern:


Sources: src/helpers.php326-342


with()

Returns the given value, optionally passed through a callback. Useful for method chaining and inline transformations.

Function Signature: src/helpers.php344-352


Behavior:

  • Delegates to \Hyperf\Support\with()
  • If callback provided, passes value through it
  • Otherwise returns value unchanged

Usage Pattern:


Sources: src/helpers.php344-352


optional()

Provides safe access to optional/nullable objects, preventing null reference errors.

Function Signature: src/helpers.php244-252


Behavior:

  • Delegates to \Hyperf\Support\optional()
  • Returns a proxy that allows method calls on potentially null values
  • If callback provided and value not null, passes value through callback

Usage Pattern:


Sources: src/helpers.php244-252


Environment Functions

env()

Retrieves the value of an environment variable with optional default.

Function Signature: src/helpers.php25-33


Behavior:

  • Delegates to \Hypervel\Support\env()
  • Looks up environment variable by key
  • Returns default if not found
  • Typically reads from .env file via framework configuration

Usage Pattern:


Sources: src/helpers.php25-33


environment()

Gets the Environment instance or checks the current environment.

Function Signature: src/helpers.php35-52


Behavior:

  • If no arguments provided, returns Environment instance from container (or new instance)
  • If arguments provided, calls Environment::is() to check if current environment matches
  • Resolves from ApplicationContext if container available

Usage Pattern:


Sources: src/helpers.php35-52


Type Checking Functions

blank()

Determines if a value is "blank" (empty, null, whitespace, or empty countable).

Function Signature: src/helpers.php76-100


Behavior:

  • Returns true for:
    • null values
    • Empty strings or strings with only whitespace
    • Empty Countable objects (arrays, collections)
    • Empty values (per PHP's empty())
  • Returns false for:
    • Numeric values (including 0)
    • Boolean values (including false)

Truth Table:

InputResultReason
nulltrueNull is blank
''trueEmpty string
' 'trueWhitespace only
'hello'falseNon-empty string
0falseNumeric values not blank
falsefalseBooleans not blank
[]trueEmpty array
[1, 2]falseNon-empty array

Usage Pattern:


Sources: src/helpers.php76-100


filled()

Determines if a value is "filled" (inverse of blank()).

Function Signature: src/helpers.php172-180


Behavior:

  • Returns !blank($value)
  • More readable than !blank() in conditional logic

Usage Pattern:


Sources: src/helpers.php172-180


Data Encoding Functions

e()

Encodes HTML special characters in a string, providing XSS protection for view output.

Function Signature: src/helpers.php54-74


Behavior:

  • Handles DeferringDisplayableValue by resolving displayable value first
  • Handles Htmlable by calling toHtml() (no escaping)
  • Handles BackedEnum by extracting the value property
  • Applies htmlspecialchars() with UTF-8 encoding and ENT_QUOTES | ENT_SUBSTITUTE flags
  • Respects $doubleEncode parameter (default: true)

Usage Pattern:


Sources: src/helpers.php54-74


Data Structure Functions

collect()

Creates a Collection instance from the given value.

Function Signature: src/helpers.php102-110


Behavior:

  • Instantiates Hypervel\Support\Collection with provided value
  • Wraps arrays/iterables in a Collection for fluent operations

Usage Pattern:


Sources: src/helpers.php102-110


Data Access Functions

These functions provide dot notation access to nested array and object structures. For detailed documentation, see Data Manipulation.

data_get()

Retrieves an item from an array or object using dot notation.

Function Signature: src/helpers.php122-130


Behavior:

  • Delegates to \Hyperf\Collection\data_get()
  • Supports nested access via dot notation (e.g., 'user.profile.name')
  • Returns default if key not found

Usage Pattern:


Sources: src/helpers.php122-130


data_set()

Sets an item on an array or object using dot notation.

Function Signature: src/helpers.php132-140


Parameters:

  • $target - Array or object to modify (passed by reference)
  • $key - Dot notation key
  • $value - Value to set
  • $overwrite - Whether to overwrite existing values (default: true)

Behavior:

  • Delegates to \Hyperf\Collection\data_set()
  • Creates nested structures as needed
  • Respects $overwrite flag

Usage Pattern:


Sources: src/helpers.php132-140


data_fill()

Fills in missing data without overwriting existing values.

Function Signature: src/helpers.php112-120


Behavior:

  • Calls data_set() with $overwrite = false
  • Only sets value if key doesn't already exist

Usage Pattern:


Sources: src/helpers.php112-120


data_forget()

Removes/unsets an item from an array or object using dot notation.

Function Signature: src/helpers.php142-150


Behavior:

  • Delegates to \Hyperf\Collection\data_forget()
  • Removes key from nested structure
  • Modifies target by reference

Usage Pattern:


Sources: src/helpers.php142-150


object_get()

Gets an item from an object using dot notation (object-specific variant).

Function Signature: src/helpers.php202-222


Behavior:

  • Specifically for objects (not arrays)
  • Splits key by dots and accesses nested properties
  • Returns object itself if key is null or empty
  • Returns default (resolved via value()) if property not found

Implementation:


Usage Pattern:


Sources: src/helpers.php202-222


Array Utility Functions

head()

Gets the first element of an array.

Function Signature: src/helpers.php152-160


Behavior:

  • Uses PHP's reset() to get first element
  • Moves internal array pointer to first element
  • Returns false if array is empty

Usage Pattern:


Sources: src/helpers.php152-160


last()

Gets the last element of an array.

Function Signature: src/helpers.php162-170


Behavior:

  • Uses PHP's end() to get last element
  • Moves internal array pointer to last element
  • Returns false if array is empty

Usage Pattern:


Sources: src/helpers.php162-170


Control Flow Functions


Diagram: Control Flow Function Execution Paths

This diagram shows the execution flow for retry logic, conditional exceptions, and conditional value selection.

Sources: src/helpers.php254-420


retry()

Retries an operation a given number of times with optional backoff and conditional retrying.

Function Signature: src/helpers.php254-292


Parameters:

  • $times - Number of attempts (int) or backoff array (milliseconds per attempt)
  • $callback - Function to retry, receives attempt number as parameter
  • $sleepMilliseconds - Sleep duration between attempts (int or Closure returning int)
  • $when - Optional callback to determine if exception should trigger retry

Behavior:

  • Executes callback and returns result on success
  • On exception, checks if retries remain and $when condition passes
  • Sleeps for specified duration (supports backoff array for per-attempt delays)
  • Uses goto statement for retry loop
  • Throws exception if retries exhausted or $when returns false

Usage Patterns:


Sources: src/helpers.php254-292


throw_if()

Throws an exception if the given condition is true.

Function Signature: src/helpers.php354-378


Parameters:

  • $condition - Condition to test
  • $exception - Exception class name (string) or exception instance
  • $parameters - Constructor parameters if exception is class name

Behavior:

  • If condition is truthy:
    • If $exception is string and class exists, instantiates it with $parameters
    • If $exception is string but not class, wraps in RuntimeException
    • Otherwise throws $exception directly
  • Returns $condition unchanged if falsy

Usage Patterns:


Sources: src/helpers.php354-378


throw_unless()

Throws an exception unless the given condition is true (inverse of throw_if()).

Function Signature: src/helpers.php380-404


Behavior:

  • Same as throw_if() but with inverted condition logic
  • Throws if condition is falsy
  • Returns $condition if truthy

Usage Patterns:


Sources: src/helpers.php380-404


when()

Returns a value conditionally based on an expression.

Function Signature: src/helpers.php406-419


Parameters:

  • $expr - Expression to evaluate (resolved via value())
  • $value - Value to return if expression is truthy
  • $default - Value to return if expression is falsy

Behavior:

  • Resolves $expr via value() (evaluates if callable)
  • If truthy, uses $value; if falsy, uses $default
  • If result is Closure, calls it with $expr as argument
  • Otherwise returns result directly

Usage Patterns:


Sources: src/helpers.php406-419


Function Utility Functions

once()

Ensures a callable is only executed once per context, returning memoized result on subsequent calls.

Function Signature: src/helpers.php224-242


Behavior:

  • Uses debug_backtrace() to determine calling context
  • Creates Onceable instance with hashed context
  • Stores result in Once singleton via WeakMap
  • Returns cached result on subsequent calls from same context
  • Falls back to direct call if context cannot be determined

Usage Pattern:


For detailed documentation on the memoization system and control flow utilities, see 9.6 Control Flow Helpers

Sources: src/helpers.php224-242


tap()

Calls the given closure with the given value, then returns the value unchanged (tap pattern).

Function Signature: src/helpers.php294-308


Parameters:

  • $value - The value to tap into
  • $callback - Optional callback to execute with value

Behavior:

  • If callback is null, returns HigherOrderTapProxy for method chaining
  • If callback provided, executes it with $value and returns $value
  • Useful for side effects without breaking fluent chains

Usage Patterns:


Sources: src/helpers.php294-308 src/HigherOrderTapProxy.php1-11


Reflection Functions

class_basename()

Gets the class basename (name without namespace) of an object or class name.

Function Signature: src/helpers.php182-190


Behavior:

  • Delegates to \Hyperf\Support\class_basename()
  • Strips namespace prefix from fully qualified class name

Usage Pattern:


Sources: src/helpers.php182-190


class_uses_recursive()

Returns all traits used by a class, including traits used by parent classes and traits of traits.

Function Signature: src/helpers.php192-200


Behavior:

  • Delegates to \Hyperf\Support\class_uses_recursive()
  • Recursively resolves trait hierarchy
  • Returns flattened array of all trait names

Usage Pattern:


Sources: src/helpers.php192-200


trait_uses_recursive()

Returns all traits used by a trait, recursively including traits of traits.

Function Signature: src/helpers.php310-324


Implementation:

  • Gets direct traits via class_uses($trait)
  • Recursively processes each trait
  • Returns merged array of all trait names

Usage Pattern:


Sources: src/helpers.php310-324


Function Dependency Map


Diagram: Helper Function Dependencies

This diagram shows how helper functions depend on each other and delegate to underlying systems.

Sources: src/helpers.php1-420


Helper Function Usage Matrix

FunctionCommon Use CasesReturn TypeSide Effects
value()Lazy evaluation, resolve callablesmixedNone
env()Environment variablesmixedNone
environment()Environment detectionbool|EnvironmentNone
e()XSS prevention in viewsstringNone
blank()Empty checkingboolNone
filled()Non-empty checkingboolNone
collect()Create collectionsCollectionNone
data_get()Nested array accessmixedNone
data_set()Nested array mutationmixedModifies target
data_fill()Set defaultsmixedModifies target
data_forget()Remove nested keysmixedModifies target
object_get()Nested object accessmixedNone
head()First array elementmixedMoves pointer
last()Last array elementmixedMoves pointer
retry()Resilient operationsmixedSleeps, throws
throw_if()Conditional exceptionsmixedMay throw
throw_unless()Guard clausesmixedMay throw
when()Conditional valuesmixedNone
once()MemoizationmixedCaches result
tap()Side effectsmixedExecutes callback
transform()Conditional transformmixedNone
optional()Null safetymixedNone
with()Fluent chainingmixedNone

Sources: src/helpers.php1-420


Additional Utilities

ProcessUtils

The ProcessUtils class provides shell argument escaping for safe command execution across platforms.

Class Location: src/ProcessUtils.php1-72

Key Method:


Behavior:

  • Platform-aware escaping (Windows vs Unix)
  • Windows: Handles quotes, percent signs, trailing backslashes
  • Unix: Wraps in single quotes with escaped single quotes
  • Prevents command injection vulnerabilities

Usage Pattern:


Sources: src/ProcessUtils.php1-72


Best Practices

When to Use Helper Functions

ScenarioRecommended FunctionRationale
Access environment variableenv()Type-safe environment variable retrieval with defaults
Check if value is empty/whitespaceblank() / filled()Semantic alternative to empty() that handles whitespace and countables
Access nested array propertydata_get()Safe dot-notation access with default values
Set nested array propertydata_set()Creates intermediate arrays automatically
Set default values onlydata_fill()Like data_set() but only when key doesn't exist
Remove nested propertydata_forget()Remove keys using dot notation
Output user content in templatee()HTML entity encoding prevents XSS
Retry network/IO operationsretry()Exponential backoff and conditional retry logic
Memoize expensive computationonce()Context-based memoization using WeakMap
Execute side effect in chaintap()Inspect/modify value without breaking method chain
Transform non-blank valuestransform()Apply callback only to filled values
Handle nullable objectsoptional()Safe method calls on potentially null objects
Get first/last array elementhead() / last()Convenient array access for method chaining

Performance Considerations

Memoization (once()):

  • Uses WeakMap for automatic garbage collection
  • Context determined via debug_backtrace() (2 frames)
  • Minimal overhead for expensive operations
  • Falls back to direct execution if context unavailable

Retry Logic (retry()):

  • Sleep delays are blocking operations
  • Backoff arrays: [100, 200, 400] specifies per-attempt delays
  • Dynamic sleep via Closure accepts ($attempt, $exception) parameters
  • Uses goto statement for retry loop (performance-optimized)

Data Access (data_get, data_set, etc.):

  • Dot notation parsing has linear cost per segment
  • Creates intermediate arrays on write operations
  • Delegates to Hyperf framework implementations
  • Direct property access faster for hot paths

Reflection (class_basename, etc.):

  • Delegates to Hyperf framework utilities
  • Minimal overhead for class name parsing
  • Recursive trait resolution caches results

Sources: src/helpers.php1-420


Integration with Framework

Helper functions integrate with the Hypervel framework through several mechanisms:

Container Resolution:

  • environment() resolves from ApplicationContext
  • collect() creates framework Collection instances
  • All helpers available globally after package autoload

Delegation Pattern:

  • Many helpers delegate to Hyperf framework functions
  • Maintains compatibility with Hyperf ecosystem
  • Allows framework-specific optimizations

Testing Support:

  • Helpers can be mocked via namespace mocking
  • Pure functions are easily testable
  • Side-effect functions (retry, tap) support test doubles

Sources: src/helpers.php1-420