php-tenant/Concerns/HasStandardApiResponses.php
Claude 439d07c9de
refactor: standardise error response format across API controllers
Add HasStandardApiResponses trait with consistent error format:
{"success": false, "error": "Human-readable message", "code": "MACHINE_READABLE_CODE"}

Applied to EntitlementApiController, EntitlementWebhookController,
and WorkspaceController. Updated tests to assert the new format.

Fixes #20

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 13:31:58 +00:00

92 lines
2.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Core\Tenant\Concerns;
use Illuminate\Http\JsonResponse;
/**
* Standardised API response helpers for php-tenant controllers.
*
* All error responses follow the format:
* ```json
* {
* "success": false,
* "error": "Human-readable message",
* "code": "MACHINE_READABLE_CODE"
* }
* ```
*
* All success responses include `"success": true`.
*
* @see https://forge.lthn.ai/core/php-tenant/issues/20
*/
trait HasStandardApiResponses
{
/**
* Return a standardised error response.
*/
protected function errorResponse(string $message, string $code, int $status = 400, array $extra = []): JsonResponse
{
return response()->json(array_merge([
'success' => false,
'error' => $message,
'code' => $code,
], $extra), $status);
}
/**
* Return a standardised success response.
*/
protected function successResponse(array $data = [], int $status = 200): JsonResponse
{
return response()->json(array_merge([
'success' => true,
], $data), $status);
}
/**
* Return a not found error response.
*/
protected function notFoundResponse(string $resource = 'Resource'): JsonResponse
{
return $this->errorResponse("{$resource} not found", 'NOT_FOUND', 404);
}
/**
* Return an unauthenticated error response.
*/
protected function unauthenticatedResponse(): JsonResponse
{
return $this->errorResponse('Unauthenticated', 'UNAUTHENTICATED', 401);
}
/**
* Return an access denied error response.
*/
protected function accessDeniedResponse(string $message = 'Access denied.'): JsonResponse
{
return $this->errorResponse($message, 'ACCESS_DENIED', 403);
}
/**
* Return a no workspace error response.
*/
protected function noWorkspaceResponse(): JsonResponse
{
return $this->errorResponse(
'No workspace found. Please select a workspace first.',
'NO_WORKSPACE',
404
);
}
/**
* Return a validation / unprocessable entity error response.
*/
protected function unprocessableResponse(string $message, string $code = 'UNPROCESSABLE_ENTITY', array $extra = []): JsonResponse
{
return $this->errorResponse($message, $code, 422, $extra);
}
}