VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/3.4-data-transformation-utilities

⇱ Data Transformation Utilities | friendsofhyperf/components | DeepWiki


Loading...
Last indexed: 14 February 2026 (15d5ca)
Menu

Data Transformation Utilities

This document covers the data transformation utility functions and macros provided by the helpers and macros components. These utilities enable concise data manipulation, type coercion, conditional transformations, and object/array operations commonly needed in application code.

For general helper functions beyond data transformation (container access, logging, caching), see Global Helper Functions. For request-specific data extraction and validation, see Request Macros and Extensions.

Overview

The data transformation utilities provide two primary categories of functionality:

  1. Standalone helper functions - Global functions available throughout the application for value transformation, type coercion, and object manipulation
  2. Request macro methods - Methods added to RequestInterface for transforming HTTP input data into typed values

These utilities follow Laravel's convention of providing fluent, expressive APIs for common data manipulation tasks while maintaining type safety where possible.

Key Design Patterns:

  • Functions handle null and empty values gracefully, returning appropriate defaults
  • Type coercion methods accept default values when keys are missing
  • Transformation functions use callbacks for custom logic
  • Enum support leverages PHP 8.1+ enum features

Sources: src/helpers/src/Functions.php1-682 src/macros/src/RequestMixin.php1-387

Value Transformation Functions

transform()

The transform() function applies a callback to a value only if the value is "filled" (non-empty). If the value is blank, it returns a default value instead.


Function signature:


Behavior:

  • Returns $callback($value) if value is filled
  • Returns $default($value) if default is callable
  • Returns $default directly if not callable
  • Uses filled() check (see Emptiness Detection)

Example use cases:

  • Normalizing optional input values
  • Converting strings to uppercase only when present
  • Applying transformations with fallback values

Sources: src/helpers/src/Functions.php622-645 tests/Helpers/HelpersTest.php112-132

rescue()

The rescue() function executes a callback and returns a default value if an exception is thrown. It provides an exception handler for logging or other side effects.


Function signature:


Parameters:

  • $callback - The operation to attempt
  • $rescue - Default value or callable that receives the exception
  • $exceptionHandler - Optional closure for exception logging/handling

Example use case:


Sources: src/helpers/src/Functions.php509-531 tests/Helpers/HelpersTest.php154-191

enum_value()

The enum_value() function extracts scalar values from PHP 8.1+ enums, handling both backed and unit enums.

Function signature:


Extraction logic:

  • BackedEnum → returns $value->value
  • UnitEnum → returns $value->name
  • Non-enum → returns value unchanged
  • Empty string → returns empty string (special case)
  • Blank value → returns default

Supported enum types:

  • BackedEnum with integer backing: enum Status: int { case Active = 1; }
  • BackedEnum with string backing: enum Role: string { case Admin = 'admin'; }
  • UnitEnum without backing: enum Color { case Red; }

Sources: src/helpers/src/Functions.php243-267 tests/Helpers/HelpersTest.php134-152

when()

The when() function conditionally returns one of two values based on an expression evaluation.

Function signature:


Behavior:

  • Evaluates $expr using value() helper
  • Returns $value if expression is truthy
  • Returns $default if expression is falsy
  • If result is a Closure, calls it with $expr as argument

Sources: src/helpers/src/Functions.php671-681

Type Coercion Methods

The request macros provide type-safe methods for coercing input values to specific types with default value support.


Primitive Type Coercion

MethodReturn TypeImplementationDefault Value
boolean()boolfilter_var(..., FILTER_VALIDATE_BOOLEAN)false
integer()int(int) cast0
float()float(float) castnull
string()StringableStr::of()null

Boolean conversion behavior:

  • "1", "true", "on", "yes"true
  • All other values → false

Sources: src/macros/src/RequestMixin.php58-61 src/macros/src/RequestMixin.php145-148 src/macros/src/RequestMixin.php225-228 src/macros/src/RequestMixin.php316-324

Date Transformation

The date() method transforms input strings into Carbon datetime instances with optional format parsing and timezone support.

Method signature:


Behavior:

  • Returns null if key is not filled
  • Uses Carbon::parse() if format is null
  • Uses Carbon::createFromFormat() if format is specified
  • Accepts optional timezone parameter

Example usage:


Sources: src/macros/src/RequestMixin.php76-89

Enum Transformation

The enum() method converts input values to typed enum instances using the enum's tryFrom() method.

Method signature:


Requirements:

  • PHP 8.1+ with enum_exists() function
  • $enumClass must be a BackedEnum with tryFrom() method
  • Returns null if key is not filled or enum conversion fails

Example usage:


Sources: src/macros/src/RequestMixin.php92-106

Collection and Fluent Transformations

fluent()

The fluent() function and request macro create Hyperf\Support\Fluent instances, which provide object-style access to array data with dynamic property access.


Function signature:


Request macro signature:


Features:

  • Dynamic property access: $fluent->name
  • Array access: $fluent['name']
  • Method chaining for mutations
  • Supports nested data structures
  • Accepts objects or arrays as input

Request macro behavior:

  • If $key is null, returns Fluent wrapping all input
  • If $key is an array, returns Fluent with only those keys
  • If $key is a string, returns Fluent wrapping that input value

Sources: src/helpers/src/Functions.php293-301 src/macros/src/RequestMixin.php150-155

collect()

The request collect() macro transforms input data into a Hyperf\Collection\Collection instance for functional operations.

Method signature:


Behavior:

  • If $key is null, returns collection of all input
  • If $key is an array, returns collection with only those keys
  • If $key is a string, wraps that input value in a collection

Use cases:

  • Functional data manipulation (map, filter, reduce)
  • Pipeline transformations
  • Aggregation operations

Sources: src/macros/src/RequestMixin.php64-74

literal()

The literal() function creates anonymous objects using named arguments, providing a concise syntax for ad-hoc data structures.

Function signature:


Behavior:

  • If single argument and is a list array, returns that argument
  • Otherwise, converts named arguments to stdClass object

Example usage:


Sources: src/helpers/src/Functions.php326-338 tests/Helpers/HelpersTest.php106-110

Object Manipulation

object_get()

The object_get() function retrieves nested object properties using dot notation, similar to array dot notation access.


Function signature:


Behavior:

  • Returns object itself if key is null or empty
  • Splits key by . delimiter
  • Traverses object properties for each segment
  • Returns default if any segment is missing
  • Uses value() helper for callable defaults

Example usage:


Sources: src/helpers/src/Functions.php399-424 tests/Helpers/HelpersTest.php31-37

String Manipulation

preg_replace_array()

The preg_replace_array() function performs sequential pattern replacement, consuming replacement values in order for each match.


Function signature:


Behavior:

  • Uses preg_replace_callback() internally
  • Shifts one replacement value for each match
  • Maintains replacement array pointer automatically
  • Empty replacements for remaining matches become empty strings

Example usage:


Sources: src/helpers/src/Functions.php427-436 tests/Helpers/HelpersTest.php39-62

Emptiness Detection: blank() and filled()

The blank() and filled() functions provide comprehensive emptiness checking across various types.

blank()

Returns true if a value is considered "blank" (empty or whitespace).

Type-specific behavior:

TypeCondition for Blank
nullAlways blank
stringTrimmed string is empty
numericNever blank
boolNever blank
ModelNever blank
CountableCount is zero
StringableTrimmed string is empty
Otherempty() check

filled()

Returns true if a value is not blank: !blank($value)


Special cases:

  • Model instances are never blank, even if empty
  • 0 and 0.0 are considered filled (not blank)
  • false is considered filled (not blank)
  • Whitespace-only strings are blank

Sources: src/helpers/src/Functions.php86-101 src/helpers/src/Functions.php284-291 tests/Helpers/HelpersTest.php73-104

Request Data Filtering

The request macros provide methods for filtering and extracting subsets of input data.

only()

Returns a subset of input data containing only the specified keys, supporting dot notation for nested values.

Method signature:


Behavior:

  • Accepts array of keys or variadic arguments
  • Supports dot notation: 'user.name'
  • Uses placeholder object to detect missing keys
  • Reconstructs nested arrays with Arr::set()

except()

Returns all input data except the specified keys.

Method signature:


Behavior:

  • Accepts array of keys or variadic arguments
  • Uses Arr::forget() to remove keys
  • Supports dot notation for nested removal

Conditional Filtering

MethodPurpose
filled($key)Check if key has non-empty value
isNotFilled($key)Check if key has empty value
exists($key)Alias for has($key)
missing($key)Check if key is absent
anyFilled($keys)Check if any key is filled
hasAny($keys)Check if any key exists

Sources: src/macros/src/RequestMixin.php108-118 src/macros/src/RequestMixin.php287-304 src/macros/src/RequestMixin.php43-56 src/macros/src/RequestMixin.php130-143 src/macros/src/RequestMixin.php157-160 src/macros/src/RequestMixin.php282-285

Conditional Transformations

whenFilled()

Executes a callback when a key has a filled (non-empty) value.

Method signature:


Behavior:

  • Returns callback result if key is filled
  • Returns $this (request) if callback returns falsy
  • Calls optional default callback if key is not filled
  • Enables fluent chaining

Example usage:


whenHas()

Executes a callback when a key exists, regardless of value.

Method signature:


Difference from whenFilled():

  • whenHas() - triggers if key exists (even if value is empty)
  • whenFilled() - triggers only if value is non-empty

Sources: src/macros/src/RequestMixin.php335-363

Data Merging

merge()

Merges new input data into the request's parsed data, overriding existing keys.

Method signature:


Implementation:

  • Uses Context::override() to update parsed data
  • Performs array_replace() to merge values
  • Returns $this for fluent chaining

mergeIfMissing()

Merges input data only for keys that don't already exist in the request.

Method signature:


Behavior:

  • Filters input to only missing keys
  • Uses collect() and filter() with missing() check
  • Calls merge() with filtered array

Sources: src/macros/src/RequestMixin.php264-280

Integration with Validation

The data transformation utilities integrate seamlessly with Hyperf's validation system:


Validation methods:

  • validate(array $rules, ...) - Validates and returns data
  • validateWithBag(string $errorBag, array $rules, ...) - Named error bag

Workflow pattern:

  1. Extract and transform input: $status = $request->enum('status', Status::class)
  2. Validate transformed data: $request->validate(['email' => 'required|email'])
  3. Create type-safe DTOs with validated, transformed values

For comprehensive validation and DTO creation, see Validated DTOs and Type Casting.

Sources: src/macros/src/RequestMixin.php365-385