Oihana PHP

StatusTrait uses trait:short, trait:short, trait:short, \oihana\logging\LoggerTrait

Provides standardized methods for outputting HTTP status messages and JSON responses.

This trait offers:

  • fail(): to generate structured error responses with logging support.
  • status(): to generate generic status messages.
  • success(): to generate success JSON responses, optionally including metadata like count, owner, URL, pagination, etc.

Relies on:

  • BaseUrlTrait: for generating current paths.
  • JsonTrait: for sending JSON responses.
  • LoggerTrait: for optional logging of error messages.

Usage example:

return $this->fail($response, 406, 'Invalid data', ['firstName' => 'required']);
return $this->status($response, 'custom message', 200);
return $this->success($request, $response, $data, [Output::COUNT => count($data)]);
Tags
author

Marc Alcaraz (ekameleon)

since
1.0.0

Table of Contents

Properties

$baseUrl  : string
The application's base URL.
$cborSerializeOptions  : array<string|int, mixed>
Temporary serialization options passed to the {@see CborSerializer}.
$jsonOptions  : int
The default JSON encoding flags used in the controller (bitmask of `JSON_*` constants).
$jsonSerializeOptions  : array<string|int, mixed>
Temporary serialization options passed to the {@see JsonSerializer}.

Methods

cborResponse()  : ResponseInterface
Builds a PSR-7 CBOR response.
fail()  : ResponseInterface|null
Generates a structured error response with an HTTP status code and optional detailed messages.
getCurrentPath()  : string
Returns the current application path relative to the base URL.
getFullPath()  : string
Returns the full application URL including the base URL and optional parameters.
getPath()  : string
Generates a path based on the base URL and a provided relative path.
initializeBaseUrl()  : static
Initializes the internal `baseUrl` property.
initializeCborOptions()  : static
Initializes the internal `$cborSerializeOptions` property.
initializeJsonOptions()  : static
Initializes the internal `$jsonOptions` and `$jsonSerializeOptions` properties.
jsonResponse()  : ResponseInterface
Builds a PSR-7 JSON response.
response()  : ResponseInterface
Return a response in the format accepted by the client : JSON by default or CBOR.
status()  : ResponseInterface|null
Outputs a generic HTTP status message in a JSON response.
success()  : mixed
Outputs a success message with optional JSON metadata.
successWithNewBody()  : mixed
Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.
withFreshBody()  : ResponseInterface|null
Returns the same response with a fresh, empty body stream.

Properties

$baseUrl

The application's base URL.

public string $baseUrl = \oihana\enums\Char::EMPTY

Used as a prefix for all generated URLs.

$cborSerializeOptions

Temporary serialization options passed to the {@see CborSerializer}.

public array<string|int, mixed> $cborSerializeOptions = [\oihana\core\options\ArrayOption::REDUCE => true]

(ex: ArrayOption::REDUCE, custom schema flags, etc.)

$jsonOptions

The default JSON encoding flags used in the controller (bitmask of `JSON_*` constants).

public int $jsonOptions = \oihana\enums\JsonParam::JSON_NONE

$jsonSerializeOptions

Temporary serialization options passed to the {@see JsonSerializer}.

public array<string|int, mixed> $jsonSerializeOptions = [\oihana\core\options\ArrayOption::REDUCE => true]

(ex: ArrayOption::REDUCE, custom schema flags, etc.)

Methods

cborResponse()

Builds a PSR-7 CBOR response.

public cborResponse(ResponseInterface $response[, mixed $data = null ][, int $status = HttpStatusCode::OK ]) : ResponseInterface

The payload is encoded with CborSerializer::encode() using the configured self::$cborSerializeOptions, any pending output buffer is cleared, and the resulting binary is written to a fresh stream advertised with the CBOR MIME type.

Parameters
$response : ResponseInterface

The PSR-7 Response object to write into.

$data : mixed = null

The data to encode as CBOR (defaults to null).

$status : int = HttpStatusCode::OK

The HTTP status code to set on the response (defaults to HttpStatusCode::OK).

Tags
example
class FeedController extends Controller
{
    use CborTrait ;

    public function index( Request $request , Response $response ) : Response
    {
        return $this->cborResponse( $response , [ 'hello' => 'world' ] ) ;
    }
}
Return values
ResponseInterface

The response carrying the CBOR-encoded body and headers.

fail()

Generates a structured error response with an HTTP status code and optional detailed messages.

public fail(ServerRequestInterface|null $request, ResponseInterface|null $response[, int|string|null $code = 400 ][, string|null $details = null ][, array<string|int, mixed> $options = [] ][, string|null $accept = null ]) : ResponseInterface|null

Automatically logs the error if logging is enabled.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

The PSR-7 Response object.

$code : int|string|null = 400

The HTTP status code (default: 400).

$details : string|null = null

Optional detailed error message to override default description.

$options : array<string|int, mixed> = []

Optional array of additional data to include (e.g., errors).

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->fail(
    $response,
    406,
    'fields validation failed',
    [
        'firstName' => 'firstName is required',
        'lastName'  => 'lastName must be a string'
    ]
);
Return values
ResponseInterface|null

Returns a PSR-7 Response object with JSON content or null if $response is not provided.

getCurrentPath()

Returns the current application path relative to the base URL.

public getCurrentPath([ServerRequestInterface|null $request = null ][, array<string|int, mixed> $params = [] ][, bool $useNow = false ]) : string

Uses the Request object if provided, otherwise falls back to $_SERVER['REQUEST_URI']. Allows adding GET parameters via $params.

Parameters
$request : ServerRequestInterface|null = null

Optional HTTP request

$params : array<string|int, mixed> = []

Optional associative array of GET parameters

$useNow : bool = false

If true, adds a _ parameter with the current timestamp to prevent caching

Return values
string

Full path including the base URL and query parameters

getFullPath()

Returns the full application URL including the base URL and optional parameters.

public getFullPath([array<string|int, mixed>|null $params = null ][, bool $useNow = false ]) : string
Parameters
$params : array<string|int, mixed>|null = null

Optional associative array of GET parameters

$useNow : bool = false

If true, adds a _ parameter with the current timestamp

Return values
string

Full URL

getPath()

Generates a path based on the base URL and a provided relative path.

public getPath([string $path = Char::EMPTY ][, array<string|int, mixed>|null $params = null ][, bool $useNow = false ]) : string
Parameters
$path : string = Char::EMPTY

Relative path to append to the base URL

$params : array<string|int, mixed>|null = null

Optional associative array of GET parameters

$useNow : bool = false

If true, adds a _ parameter with the current timestamp

Return values
string

Full path

initializeBaseUrl()

Initializes the internal `baseUrl` property.

public initializeBaseUrl([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static

The value can come from:

  • the $init array (key ControllerParam::BASE_URL),
  • the DI container if provided and contains the key ControllerParam::BASE_URL,
  • otherwise it remains an empty string.
Parameters
$init : array<string|int, mixed> = []

Optional initialization array

$container : ContainerInterface|null = null

Optional DI container to fetch the base URL

Tags
throws
ContainerExceptionInterface

If the container encounters an error while retrieving an entry.

NotFoundExceptionInterface

If no entry was found in the container for the given identifier.

Return values
static

Returns the current instance for method chaining.

initializeCborOptions()

Initializes the internal `$cborSerializeOptions` property.

public initializeCborOptions([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static

The options are taken from $init[ControllerParam::CBOR_SERIALIZE_OPTIONS] when present; otherwise, if empty, they are looked up in the DI container under the same key.

Parameters
$init : array<string|int, mixed> = []

Optional initialization array (e.g. ['cborSerializeOptions' => [ ... ]]).

$container : ContainerInterface|null = null

Optional PSR-11 container used to resolve the serialization options.

Tags
throws
ContainerExceptionInterface

If the container encounters an error while retrieving an entry.

NotFoundExceptionInterface

If no entry was found in the container for the given identifier.

Return values
static

Returns the current instance for method chaining.

initializeJsonOptions()

Initializes the internal `$jsonOptions` and `$jsonSerializeOptions` properties.

public initializeJsonOptions([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static

The JSON encode flags and the serializer options are taken from $init when present; otherwise they are looked up in the DI container under the matching ControllerParam keys. Invalid encode flags fall back to JsonParam::JSON_NONE.

Parameters
$init : array<string|int, mixed> = []

Optional initialization array (e.g. ['jsonOptions' => ..., 'jsonSerializeOptions' => [ ... ]]).

$container : ContainerInterface|null = null

Optional PSR-11 container used to resolve the JSON options.

Tags
throws
ContainerExceptionInterface

If the container encounters an error while retrieving an entry.

NotFoundExceptionInterface

If no entry was found in the container for the given identifier.

Return values
static

Returns the current instance for method chaining.

jsonResponse()

Builds a PSR-7 JSON response.

public jsonResponse(ResponseInterface $response[, mixed $data = null ][, int $status = HttpStatusCode::OK ]) : ResponseInterface

The payload is encoded with JsonSerializer::encode() using the configured self::$jsonOptions encode flags and self::$jsonSerializeOptions, then written to the response body with the JSON Content-Type header.

Parameters
$response : ResponseInterface

The PSR-7 Response object to write into.

$data : mixed = null

The data to encode as JSON (defaults to null).

$status : int = HttpStatusCode::OK

The HTTP status code to set on the response (defaults to HttpStatusCode::OK).

Tags
example
class UserController extends Controller
{
    use JsonTrait ;

    public function show( Request $request , Response $response ) : Response
    {
        return $this->jsonResponse( $response , [ 'id' => 42 , 'name' => 'Alice' ] ) ;
    }
}
Return values
ResponseInterface

The response carrying the JSON-encoded body and header.

response()

Return a response in the format accepted by the client : JSON by default or CBOR.

public response(ResponseInterface $response[, mixed $data = null ][, int $status = 200 ][, string|null $accept = null ]) : ResponseInterface

Checks the Accept header in the request to determine the preferred format.

Parameters
$response : ResponseInterface

PSR-7 Response object to write to.

$data : mixed = null

Data to send in the response.

$status : int = 200

HTTP status code (default: 200).

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
see
FileMimeType::JSON
FileMimeType::CBOR
FileMimeType::CBOR_SEQ
Return values
ResponseInterface

The response encoded as CBOR or JSON according to the negotiated format.

status()

Outputs a generic HTTP status message in a JSON response.

public status(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $message = Char::EMPTY ][, int|string|null $code = 200 ][, array<string|int, mixed>|null $options = null ][, string|null $accept = null ]) : ResponseInterface|null
Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

PSR-7 Response object to send output.

$message : mixed = Char::EMPTY

The message content.

$code : int|string|null = 200

The HTTP status code (default: 200).

$options : array<string|int, mixed>|null = null

Optional array of additional output properties.

$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->status($response, 'bad request', 405);
Return values
ResponseInterface|null

Returns a PSR-7 Response object with JSON content or null if $response is not provided.

success()

Outputs a success message with optional JSON metadata.

public success(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed

If $response is null, returns the $data directly. Supports optional initialization properties like count, limit, offset, owner, URL, status, total, position, options.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

Optional PSR-7 Response object.

$data : mixed = null

The main payload or data to return.

$init : array<string|int, mixed>|null = null

Optional associative array with keys:

  • count (int): Number of elements
  • limit (int): Pagination limit
  • offset (int): Pagination offset
  • params (array): Parameters for getCurrentPath()
  • status (int): HTTP status code
  • total (int): Total elements
  • url (string): URL to include in response
  • owner (array|object): Owner reference
  • options (array): Additional properties
  • position (int): Optional position in list
$accept : string|null = null

The header accepted by the client : 'application/cbor' or by default 'application/json'

Tags
example
return $this->success(
    $request,
    $response,
    $data,
    [Output::COUNT => count($data), Output::PARAMS => $request->getQueryParams()]
);
Return values
mixed

Returns a PSR-7 Response object with JSON if $response is provided, otherwise returns $data directly.

successWithNewBody()

Same as {@see self::success()} but guarantees a fresh response body stream before writing the envelope.

public successWithNewBody(ServerRequestInterface|null $request, ResponseInterface|null $response[, mixed $data = null ][, array<string|int, mixed>|null $init = null ][, string|null $accept = null ]) : mixed

Use this only when an upstream actor (typically a sub-controller called from the current controller method) may have already written into the shared PSR-7 body stream. Calling the plain success() in that case would concatenate two JSON envelopes — invalid JSON for any strict parser (NextJS RSC, modern fetch, etc.).

Implementation: swaps the response body for an empty stream via self::withFreshBody(), then delegates to success(). Whatever was previously written is discarded; the resulting body contains exactly one envelope.

Parameters
$request : ServerRequestInterface|null

Optional PSR-7 Request object.

$response : ResponseInterface|null

Optional PSR-7 Response object.

$data : mixed = null

The main payload or data to return.

$init : array<string|int, mixed>|null = null

Same keys as success().

$accept : string|null = null

The header accepted by the client.

Tags
example
// POST /users where dispatchAutoInvitation() writes into the shared body
public function post( ?Request $request , ?Response $response , array $args , array $init ) :mixed
{
    $result = parent::post( $request , $response , $args , $init ) ;
    $this->dispatchAutoInvitation( $request , $response , $userKey ) ;

    return $this->successWithNewBody
    (
        $request ,
        $result  ,
        $this->refetchHydratedUser( $userKey )
    ) ;
}
see
success()

Plain variant when the body has not been touched.

Return values
mixed

Same return contract as success().

withFreshBody()

Returns the same response with a fresh, empty body stream.

public withFreshBody(ResponseInterface|null $response) : ResponseInterface|null

Use to discard whatever an upstream actor (sub-controller, middleware) may have already written, then chain into any other response helper.

Parameters
$response : ResponseInterface|null

Optional PSR-7 Response object.

Tags
example
return $this->fail( $request , $this->withFreshBody( $response ) , 502 , 'zitadel_sync_failed' ) ;
Return values
ResponseInterface|null

The same response with a fresh empty body, or null if $response was null.

On this page

Search results