Oihana PHP System

StatusTrait uses trait:short, trait:short, trait:short, trait:short

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)]);

Table of Contents

Constants

LOGGABLE  : string = 'loggable'
The 'loggable' parameter constant.
LOGGER  : string = 'logger'
The 'logger' parameter constant.

Properties

$baseUrl  : string
The application's base URL.
$cborSerializeOptions  : array<string|int, mixed>
Temporary serialization options.
$jsonOptions  : int
The default json options used in the controller.
$jsonSerializeOptions  : array<string|int, mixed>
Temporary serialization options passed to JsonSerializer.
$loggable  : bool
The loggable flag.

Methods

alert()  : void
Action must be taken immediately.
cborResponse()  : ResponseInterface
Return a cbor response
critical()  : void
Critical conditions.
debug()  : void
Detailed debug information.
emergency()  : void
System is unusable.
error()  : void
Runtime errors that do not require immediate action but should typically be logged and monitored.
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.
getLogger()  : LoggerInterface|null
Returns the logger reference.
getPath()  : string
Generates a path based on the base URL and a provided relative path.
info()  : void
Interesting events.
initializeBaseUrl()  : static
Initializes the internal `baseUrl` property.
initializeCborOptions()  : static
Initialize the internal $cborSerializeOptions property.
initializeJsonOptions()  : static
Initialize the internal $jsonOptions property.
initializeLoggable()  : static
Initialize the loggable flag.
initializeLogger()  : static
Initializes the logger reference for the current instance.
jsonResponse()  : ResponseInterface
Return a JSON response
log()  : void
Logs with an arbitrary level.
notice()  : void
Normal but significant events.
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.
warning()  : void
Exceptional occurrences that are not errors.
withFreshBody()  : ResponseInterface|null
Returns the same response with a fresh, empty body stream.

Constants

LOGGABLE

The 'loggable' parameter constant.

public string LOGGABLE = 'loggable'

LOGGER

The 'logger' parameter constant.

public string LOGGER = 'logger'

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.

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

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

$jsonOptions

The default json options used in the controller.

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

$jsonSerializeOptions

Temporary serialization options passed to JsonSerializer.

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

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

$loggable

The loggable flag.

public bool $loggable = false

Methods

alert()

Action must be taken immediately.

public alert(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Entire website down, database unavailable, etc. This should trigger the SMS alerts and wake you up.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

cborResponse()

Return a cbor response

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

critical()

Critical conditions.

public critical(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Application component unavailable, unexpected exception.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

debug()

Detailed debug information.

public debug(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

emergency()

System is unusable.

public emergency(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

error()

Runtime errors that do not require immediate action but should typically be logged and monitored.

public error(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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

getLogger()

Returns the logger reference.

public getLogger() : LoggerInterface|null
Return values
LoggerInterface|null

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

info()

Interesting events.

public info(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: User logs in, SQL logs.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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 during access

NotFoundExceptionInterface

If the ControllerParam::BASE_URL key is not found in the container

Return values
static

Returns the current instance for method chaining

initializeCborOptions()

Initialize the internal $cborSerializeOptions property.

public initializeCborOptions([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
Parameters
$init : array<string|int, mixed> = []
$container : ContainerInterface|null = null
Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Return values
static

initializeJsonOptions()

Initialize the internal $jsonOptions property.

public initializeJsonOptions([array<string|int, mixed> $init = [] ][, ContainerInterface|null $container = null ]) : static
Parameters
$init : array<string|int, mixed> = []
$container : ContainerInterface|null = null
Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Return values
static

initializeLoggable()

Initialize the loggable flag.

public initializeLoggable([bool|array<string|int, mixed>|null $init = null ][, ContainerInterface|null $container = null ][, bool|array<string|int, mixed>|null $defaultValue = false ]) : static
Parameters
$init : bool|array<string|int, mixed>|null = null

The definition to initialize the loggable property.

$container : ContainerInterface|null = null
$defaultValue : bool|array<string|int, mixed>|null = false

The default value if the $init argument is not defined.

Tags
throws
ContainerExceptionInterface
NotFoundExceptionInterface
Return values
static

initializeLogger()

Initializes the logger reference for the current instance.

public initializeLogger([array<string|int, mixed>|LoggerInterface|string|null $init = null ][, ContainerInterface|null $container = null ][, bool $useDefault = true ]) : static

This method accepts either:

  • A LoggerInterface instance
  • An associative array containing a logger reference under the static::LOGGER key
  • A string representing a service ID or class name resolvable by the container
  • null or an empty value, which will default to LoggerInterface::class depending on the $useDefault parameter.

If a dependency injection container is provided, the method will attempt to resolve the logger service from it. If no valid logger can be resolved, the $this->logger property will be set to null.

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

Logger initialization data. May be an instance, an array with a logger entry, a string service ID/class name, or null.

$container : ContainerInterface|null = null

Optional dependency injection container used to resolve the logger service.

$useDefault : bool = true

Whether to use LoggerInterface::class as a fallback if $init does not provide a valid logger string. Defaults to true.

Tags
throws
DependencyException

If there is a dependency resolution error.

NotFoundException

If the specified service is not found in the container.

NotFoundExceptionInterface

If the specified service is not found in the container.

ContainerExceptionInterface

If the container encounters a general error.

Return values
static

Returns the current instance for method chaining.

jsonResponse()

Return a JSON response

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

log()

Logs with an arbitrary level.

public log(mixed $level, string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$level : mixed
$message : string|Stringable
$context : array<string|int, mixed> = []

notice()

Normal but significant events.

public notice(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void
Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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

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().

warning()

Exceptional occurrences that are not errors.

public warning(string|Stringable $message[, array<string|int, mixed> $context = [] ]) : void

Example: Use of deprecated APIs, poor use of an API, undesirable things that are not necessarily wrong.

Parameters
$message : string|Stringable
$context : array<string|int, mixed> = []

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