VOOZH about

URL: https://deepwiki.com/hypervel/components/3.5-response-transformation

⇱ Response Transformation | hypervel/components | DeepWiki


Loading...
Last indexed: 7 March 2026 (96fbab)
Menu

Response Transformation

Purpose and Scope

This document explains how Hypervel's HTTP layer converts various return types from route handlers and controllers into standard PSR-7 HTTP responses. Response transformation enables developers to return intuitive data types (strings, arrays, objects) from their handlers without manually constructing HTTP response objects.

For information about the complete request processing pipeline, see Request Lifecycle and Processing. For details on view rendering, see View Factory and Events.


Overview

Response transformation occurs in the CoreMiddleware after a route handler executes. The transferToResponse() method inspects the return value and converts it into a ResponsePlusInterface object, automatically setting appropriate content-type headers and serializing data as needed.

This design allows handlers to return domain objects, collections, or primitives while maintaining clean separation between business logic and HTTP concerns.

Sources: src/http/src/CoreMiddleware.php46-91


Transformation Architecture


Sources: src/http/src/CoreMiddleware.php50-91 src/http/src/CoreMiddleware.php154-176


Request Processing Flow


Sources: src/http/src/CoreMiddleware.php154-176 src/http/src/CoreMiddleware.php123-148


Supported Return Types

Renderable Interface

Objects implementing Hypervel\Support\Contracts\Renderable have their render() method called to produce HTML content.

PropertyValue
Type Check$response instanceof Renderable
Transformation$response->render()
Content-Typetext/html
Body StreamSwooleStream
Primary Use CaseView objects from Blade templates

Example:


Sources: src/http/src/CoreMiddleware.php52-56 src/support/src/Contracts/Renderable.php


Htmlable Interface

Objects implementing Hypervel\Support\Contracts\Htmlable are cast to strings to produce HTML content.

PropertyValue
Type Check$response instanceof Htmlable
Transformation(string) $response
Content-Typetext/html
Body StreamSwooleStream
Primary Use CaseCustom HTML objects, Blade component strings

Example:


Sources: src/http/src/CoreMiddleware.php58-62 src/support/src/Contracts/Htmlable.php


String Responses

Plain strings are returned as text/plain responses.

PropertyValue
Type Checkis_string($response)
TransformationDirect pass-through
Content-Typetext/plain
Body StreamSwooleStream
Primary Use CaseSimple text responses, debugging output

Example:


Sources: src/http/src/CoreMiddleware.php64-66


PSR-7 ResponseInterface

Objects already implementing ResponseInterface are wrapped in a ResponsePlusProxy without modification.

PropertyValue
Type Check$response instanceof ResponseInterface
Transformationnew ResponsePlusProxy($response)
Content-TypePreserved from original response
Body StreamPreserved from original response
Primary Use CaseManual response construction, response modification

Example:


Sources: src/http/src/CoreMiddleware.php68-70


Arrays and Arrayable Objects

Arrays and objects implementing Arrayable are JSON-encoded automatically.

PropertyValue
Type Checkis_array($response) or $response instanceof Arrayable
TransformationJson::encode($response)
Content-Typeapplication/json
Body StreamSwooleStream
Primary Use CaseAPI responses, data collections

Example:


Sources: src/http/src/CoreMiddleware.php72-76


Jsonable Interface

Objects implementing Jsonable are cast to strings (already JSON-serialized).

PropertyValue
Type Check$response instanceof Jsonable
Transformation(string) $response
Content-Typeapplication/json
Body StreamSwooleStream
Primary Use CaseCustom JSON serialization logic

Example:


Sources: src/http/src/CoreMiddleware.php78-82


Fallback Transformations

The transformation logic includes two fallback cases:

Existing Content-Type Header

If the response context already has a content-type header set (from middleware or other sources), the return value is cast to string and used as the body.

Sources: src/http/src/CoreMiddleware.php84-86

Default Transformation

If no other conditions match, the value is cast to string and returned as text/plain.

Sources: src/http/src/CoreMiddleware.php88-90


Response Context

The transferToResponse() method retrieves the current response object from ResponseContext, which maintains per-request response state in coroutine-safe context storage.


Sources: src/http/src/CoreMiddleware.php96-99 src/context/src/ResponseContext.php


Type Checking Order

The transformation logic checks types in a specific order to ensure correct handling:

PriorityType CheckRationale
1RenderableView objects must render before string conversion
2HtmlableHTML objects before generic string check
3stringPlain strings as text/plain
4ResponseInterfacePre-constructed responses preserved
5array or ArrayableCollections and arrays as JSON
6JsonablePre-serialized JSON objects
7Existing header checkUse developer-set content-type
8DefaultCast to string as text/plain

This ordering ensures that more specific types are handled before more general conversions.

Sources: src/http/src/CoreMiddleware.php50-91


Integration with CoreMiddleware

Response transformation is invoked within the CoreMiddleware::process() method after route execution:


Sources: src/http/src/CoreMiddleware.php154-176


Handler Execution

Before transformation occurs, the handleFound() method executes the route handler with dependency-injected parameters:


The mixed return value from this method is then passed to transferToResponse().

Sources: src/http/src/CoreMiddleware.php123-148


Content-Type Header Management

Return TypeContent-TypeMethod
Renderabletext/htmladdHeader('content-type', 'text/html')
Htmlabletext/htmladdHeader('content-type', 'text/html')
stringtext/plainaddHeader('content-type', 'text/plain')
ResponseInterfacePreservedNo modification
array/Arrayableapplication/jsonaddHeader('content-type', 'application/json')
Jsonableapplication/jsonaddHeader('content-type', 'application/json')
With existing headerPreservedNo modification
Defaulttext/plainaddHeader('content-type', 'text/plain')

Sources: src/http/src/CoreMiddleware.php50-91


Body Stream Creation

All transformed responses use SwooleStream to wrap the serialized body content:


SwooleStream is a PSR-7 stream implementation optimized for Swoole's coroutine environment, supporting efficient memory management and non-blocking I/O operations.

Sources: src/http/src/CoreMiddleware.php55 src/http/src/CoreMiddleware.php61 src/http/src/CoreMiddleware.php65 src/http/src/CoreMiddleware.php75 src/http/src/CoreMiddleware.php81 src/http/src/CoreMiddleware.php85 src/http/src/CoreMiddleware.php90


Response Plus Proxy

When a handler returns a pre-constructed ResponseInterface, it's wrapped in ResponsePlusProxy to ensure compatibility with Swoole's response handling:


ResponsePlusProxy adapts standard PSR-7 responses to the ResponsePlusInterface required by Hyperf's HTTP server.

Sources: src/http/src/CoreMiddleware.php68-70


Server Header Injection

After transformation, the CoreMiddleware adds a server identification header to all responses:


This occurs regardless of the transformation path, ensuring consistent server identification in HTTP responses.

Sources: src/http/src/CoreMiddleware.php175


Form Request Validation Integration

Form requests implementing ValidatesWhenResolved are validated during dependency resolution before the handler executes. If validation fails, a validation exception is thrown and caught by the exception handler, bypassing normal response transformation.

The FormRequestServiceProvider registers an after-resolving callback with RouteDependency:


Sources: src/foundation/src/Providers/FormRequestServiceProvider.php16-22


Relationship to View System

View objects returned from view() helper functions implement the Renderable interface, making them compatible with response transformation:


The view is rendered by calling its render() method, which compiles Blade templates and returns the generated HTML.

Sources: src/http/src/CoreMiddleware.php52-56 src/view/src/Contracts/View.php


JSON Encoding

JSON transformation uses Hyperf's Json::encode() utility, which provides consistent JSON serialization with error handling:


This encoder handles special cases like encoding options, Unicode handling, and error reporting for invalid JSON structures.

Sources: src/http/src/CoreMiddleware.php75


Error Handling

If transformation fails (e.g., invalid JSON encoding), exceptions propagate to the exception handler. The framework's exception handler then renders appropriate error responses based on the request's expected content type (JSON for API requests, HTML for browser requests).

For details on exception rendering, see Exception Handling.

Sources: src/http/src/CoreMiddleware.php46-91