VOOZH about

URL: https://deepwiki.com/friendsofhyperf/components/7.2-type-casting-and-transformation

⇱ Type Casting and Transformation | friendsofhyperf/components | DeepWiki


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

Type Casting and Transformation

This page documents the type casting and transformation mechanisms available in the friendsofhyperf/components ecosystem. These features enable automatic conversion of raw input data into strongly-typed PHP values, including primitives, Carbon dates, enums, collections, and fluent objects.

For information about DTO validation and rule definition, see DTO Definition and Validation.

Overview

The codebase provides two primary mechanisms for type casting and transformation:

  1. Request Type Casting - Methods added to the RequestInterface through macros that cast HTTP input values to specific types
  2. Transformation Utilities - Global helper functions for conditional transformations and enum value extraction

These mechanisms integrate with Hyperf's request handling and validation systems to provide a Laravel-compatible API for type-safe data processing.

Key Components:

  • Request type casters: boolean(), integer(), float(), date(), enum()
  • Object constructors: collect(), fluent(), str()/string()
  • Transformation functions: transform(), enum_value()

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

Request Type Casting Methods

The RequestMixin class extends Hyperf's RequestInterface with Laravel-style type casting methods. These methods retrieve input values and automatically convert them to the specified type.

Primitive Type Casters

Boolean Casting

The boolean() method retrieves an input value and casts it to a boolean using PHP's FILTER_VALIDATE_BOOLEAN filter, which treats "1", "true", "on", and "yes" as true.


Sources: src/macros/src/RequestMixin.php58-61

Integer and Float Casting

The integer() and float() methods cast input values to their respective numeric types using PHP's type coercion.

MethodImplementationExample InputResult
integer($key, $default)(int) $this->input($key, $default)"42"42
float($key, $default)(float) $this->input($key, $default)"3.14"3.14

Sources: src/macros/src/RequestMixin.php145-148 src/macros/src/RequestMixin.php225-228

Date and Time Casting

The date() method converts string inputs to Carbon instances with optional format parsing and timezone support.

Signature:


Behavior:

  • Returns null if the input key is empty
  • If $format is null, uses Carbon::parse() for flexible parsing
  • If $format is provided, uses Carbon::createFromFormat() for strict parsing

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

Enum Casting

The enum() method casts input values to PHP 8.1+ backed enum instances using the enum's tryFrom() method.

Signature:


Safety Checks:

  1. Verifies input key is filled
  2. Checks enum_exists() function exists
  3. Validates the class is an enum
  4. Confirms tryFrom() method exists

Example Usage:



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

Collection and Object Transformation

Collection Casting

The collect() method wraps request input in Hyperf's Collection class for fluent manipulation.

Behavior:

  • If $key is null, returns all request data as a collection
  • If $key is an array, returns only those keys as a collection
  • If $key is a string, returns that input value as a collection

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

Fluent Object Casting

The fluent() method creates a Fluent object from request inputs, providing object-style access to array data.

Example:


Sources: src/macros/src/RequestMixin.php150-155

Stringable Casting

The str() and string() methods wrap input values in Hyperf's Stringable class for chainable string operations.

Example:


Sources: src/macros/src/RequestMixin.php316-324

Transformation Utilities

Transform Function

The transform() function applies a callback to a value only if the value is "filled" (not blank).

Signature:


Logic Flow:


Use Cases:

  • Conditional transformations without explicit null checks
  • Default value fallbacks with optional callbacks

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

Enum Value Extraction

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

Signature:


Extraction Rules:

Input TypeOutput
BackedEnum$value->value
UnitEnum$value->name
Empty stringReturns empty string (preserved)
Other typesReturns value unchanged
All with defaultUses transform() internally for default handling

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

Value Presence Checks

Blank and Filled Functions

The blank() and filled() functions determine if a value is empty or contains data, with special handling for various types.

Blank Detection Rules:

TypeConsidered Blank When
nullAlways
stringEmpty after trim
numeric, boolNever
ModelNever
CountableCount is zero
StringableEmpty after trim and cast
OtherResult of empty()

Sources: src/helpers/src/Functions.php90-101 src/helpers/src/Functions.php288-291 tests/Helpers/HelpersTest.php73-104

Request Validation with Type Casting

Validated Method Integration

Request type casting methods are designed to work seamlessly with validation. The typical workflow combines validation rules with type casting for safe data access.

Workflow Pattern:


Sources: src/macros/src/RequestMixin.php365-386 src/macros/output/Hyperf/HttpServer/Contract/RequestInterface.php221-224

Request Macro Interface Extensions

The following table documents all type casting methods added to RequestInterface through the macro system:

MethodReturn TypePurpose
boolean($key, $default)boolCast to boolean
integer($key, $default)intCast to integer
float($key, $default)floatCast to float
date($key, $format, $tz)?CarbonParse to Carbon date
enum($key, $enumClass)?BackedEnumCast to enum instance
collect($key)CollectionWrap in collection
fluent($key)FluentWrap in fluent object
str($key, $default)StringableWrap in stringable
string($key, $default)StringableAlias for str()
filled($key)boolCheck if non-empty
isEmptyString($key)boolCheck if empty string
isNotFilled($key)boolCheck if empty

Sources: src/macros/output/Hyperf/HttpServer/Contract/RequestInterface.php19-224 src/macros/src/RequestMixin.php1-387

Type Casting in Testing

The type casting system integrates with request faking for testing purposes:


Sources: tests/Macros/HttpServerRequestTest.php154-179

Implementation Details

Macro Registration

Type casting methods are registered during application bootstrap through the RegisterMixinListener:

Registration Flow:

  1. RegisterMixinListener processes the BootApplication event
  2. Calls Request::mixin(new RequestMixin()) to register all methods
  3. Methods become available on all Request instances

Sources: tests/TestCase.php28-34

Coroutine Safety

All type casting operations respect Hyperf's coroutine context isolation:

  • Request data is stored in coroutine context via Context::set()
  • Each coroutine has isolated request state
  • No shared state between concurrent requests

Sources: tests/Macros/HttpServerRequestTest.php18-21