Neuron-PHP

ApiResponseTrait

Trait providing RFC 9457 Problem Details response methods for API controllers.

This trait adds convenient methods to API controllers for returning standardized error responses following RFC 9457. It provides both generic and specific error response methods, making it easy to maintain consistency across all API endpoints.

The trait integrates with the existing Neuron MVC controller structure, allowing controllers to return both success responses (using existing methods) and error responses (using Problem Details format).

Tags
example
class UserApiController extends Base {
    use ApiResponseTrait;

    public function create(Request $request): string {
        $errors = $this->validator->validate($request->getData());

        if ($errors) {
            // Use the trait method for validation errors
            return $this->validationProblem($errors);
        }

        try {
            $user = $this->userService->create($data);
            return $this->renderJson(HttpResponseStatus::CREATED, ['data' => $user]);
        } catch (Exception $e) {
            // Use generic problem response
            return $this->problemResponse(
                ProblemType::INTERNAL_ERROR,
                detail: 'An error occurred while creating the user'
            );
        }
    }
}

Table of Contents

Methods

authenticationProblem()  : string
Create an authentication required error response.
badRequestProblem()  : string
Create a bad request error response.
conflictProblem()  : string
Create a conflict error response.
internalErrorProblem()  : string
Create an internal error response.
methodNotAllowedProblem()  : string
Create a method not allowed error response.
notFoundProblem()  : string
Create a not found error response.
permissionProblem()  : string
Create a permission denied error response.
problemDetailsResponse()  : string
Create a problem response from a ProblemDetails instance.
problemResponse()  : string
Create a problem response using individual parameters.
rateLimitProblem()  : string
Create a rate limit exceeded error response.
serviceUnavailableProblem()  : string
Create a service unavailable error response.
unsupportedMediaTypeProblem()  : string
Create an unsupported media type error response.
validationProblem()  : string
Create a validation error response.

Methods

authenticationProblem()

Create an authentication required error response.

protected authenticationProblem([string|null $detail = null ][, string|null $realm = null ]) : string
Parameters
$detail : string|null = null

Specific authentication failure details

$realm : string|null = null

Authentication realm (for WWW-Authenticate header)

Return values
string

JSON response

badRequestProblem()

Create a bad request error response.

protected badRequestProblem([string|null $detail = null ][, array<string|int, mixed> $errors = [] ]) : string
Parameters
$detail : string|null = null

Specific error details

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

Optional field-specific errors

Return values
string

JSON response

conflictProblem()

Create a conflict error response.

protected conflictProblem([string|null $detail = null ][, string|null $conflictingResource = null ]) : string
Parameters
$detail : string|null = null

Specific conflict details

$conflictingResource : string|null = null

The resource causing the conflict

Return values
string

JSON response

internalErrorProblem()

Create an internal error response.

protected internalErrorProblem([string|null $detail = null ][, bool $includeDebug = false ][, Exception|null $exception = null ]) : string

This should be used for unexpected errors. In production, avoid exposing internal details that could be security sensitive.

Parameters
$detail : string|null = null

Error details (be careful in production)

$includeDebug : bool = false

Include debug information (only in development)

$exception : Exception|null = null

The exception that occurred

Return values
string

JSON response

methodNotAllowedProblem()

Create a method not allowed error response.

protected methodNotAllowedProblem(array<string|int, mixed> $allowedMethods[, string|null $detail = null ]) : string
Parameters
$allowedMethods : array<string|int, mixed>

List of allowed HTTP methods

$detail : string|null = null

Specific error details

Return values
string

JSON response

notFoundProblem()

Create a not found error response.

protected notFoundProblem(string $resource[, string|int|null $identifier = null ]) : string
Parameters
$resource : string

Resource type (e.g., 'User', 'Order')

$identifier : string|int|null = null

Resource identifier

Return values
string

JSON response

permissionProblem()

Create a permission denied error response.

protected permissionProblem([string|null $detail = null ][, array<string|int, mixed>|null $requiredPermissions = null ]) : string
Parameters
$detail : string|null = null

Specific permission failure details

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

List of required permissions

Return values
string

JSON response

problemDetailsResponse()

Create a problem response from a ProblemDetails instance.

protected problemDetailsResponse(ProblemDetails $problem[, array<string|int, mixed> $headers = [] ]) : string
Parameters
$problem : ProblemDetails

The problem details

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

Additional HTTP headers

Return values
string

JSON response

problemResponse()

Create a problem response using individual parameters.

protected problemResponse(ProblemType|string $type[, string|null $title = null ][, int|null $status = null ][, string|null $detail = null ][, string|null $instance = null ][, array<string|int, mixed> $extensions = [] ][, array<string|int, mixed> $headers = [] ]) : string
Parameters
$type : ProblemType|string

Problem type enum or URI string

$title : string|null = null

Problem title (uses default if not provided)

$status : int|null = null

HTTP status code (uses type default if not provided)

$detail : string|null = null

Specific error details

$instance : string|null = null

URI for this specific occurrence

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

Additional fields

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

Additional HTTP headers

Return values
string

JSON response

rateLimitProblem()

Create a rate limit exceeded error response.

protected rateLimitProblem(int $retryAfter[, string|null $detail = null ][, int|null $limit = null ][, int|null $remaining = null ]) : string
Parameters
$retryAfter : int

Seconds until the client can retry

$detail : string|null = null

Specific rate limit details

$limit : int|null = null

The rate limit that was exceeded

$remaining : int|null = null

Remaining requests in the current window

Return values
string

JSON response

serviceUnavailableProblem()

Create a service unavailable error response.

protected serviceUnavailableProblem([string|null $detail = null ][, int|null $retryAfter = null ]) : string
Parameters
$detail : string|null = null

Specific unavailability details

$retryAfter : int|null = null

Optional seconds until service is available

Return values
string

JSON response

unsupportedMediaTypeProblem()

Create an unsupported media type error response.

protected unsupportedMediaTypeProblem(array<string|int, mixed> $supportedTypes[, string|null $detail = null ]) : string
Parameters
$supportedTypes : array<string|int, mixed>

List of supported content types

$detail : string|null = null

Specific error details

Return values
string

JSON response

validationProblem()

Create a validation error response.

protected validationProblem(array<string|int, mixed> $errors[, string|null $detail = null ]) : string
Parameters
$errors : array<string|int, mixed>

Validation errors (field => message)

$detail : string|null = null

Overall validation error message

Return values
string

JSON response


        
On this page

Search results