77 lines
2.0 KiB
PHP
77 lines
2.0 KiB
PHP
<?php
|
|
/**
|
|
* JSON Response Helper
|
|
*/
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Support;
|
|
|
|
use Psr\Http\Message\ResponseInterface;
|
|
|
|
class Response
|
|
{
|
|
public static function json(
|
|
ResponseInterface $response,
|
|
mixed $data,
|
|
int $status = 200
|
|
): ResponseInterface {
|
|
$response->getBody()->write(json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE));
|
|
return $response
|
|
->withStatus($status)
|
|
->withHeader('Content-Type', 'application/json');
|
|
}
|
|
|
|
public static function success(
|
|
ResponseInterface $response,
|
|
mixed $data = null,
|
|
string $message = 'OK',
|
|
int $status = 200
|
|
): ResponseInterface {
|
|
return self::json($response, [
|
|
'success' => true,
|
|
'message' => $message,
|
|
'data' => $data,
|
|
], $status);
|
|
}
|
|
|
|
public static function error(
|
|
ResponseInterface $response,
|
|
string $message,
|
|
int $status = 400,
|
|
array $errors = []
|
|
): ResponseInterface {
|
|
$body = [
|
|
'success' => false,
|
|
'message' => $message,
|
|
];
|
|
|
|
if (!empty($errors)) {
|
|
$body['errors'] = $errors;
|
|
}
|
|
|
|
return self::json($response, $body, $status);
|
|
}
|
|
|
|
public static function notFound(ResponseInterface $response, string $message = 'Not found'): ResponseInterface
|
|
{
|
|
return self::error($response, $message, 404);
|
|
}
|
|
|
|
public static function unauthorized(ResponseInterface $response, string $message = 'Unauthorized'): ResponseInterface
|
|
{
|
|
return self::error($response, $message, 401);
|
|
}
|
|
|
|
public static function forbidden(ResponseInterface $response, string $message = 'Forbidden'): ResponseInterface
|
|
{
|
|
return self::error($response, $message, 403);
|
|
}
|
|
|
|
public static function validationError(
|
|
ResponseInterface $response,
|
|
array $errors
|
|
): ResponseInterface {
|
|
return self::error($response, 'Validation failed', 422, $errors);
|
|
}
|
|
} |