File: /wordpress/plugins/wp-cloud-client/1.1.7/src/Api/ApiResponse.php
<?php
declare(strict_types=1);
namespace VPlugins\WPCloudClient\Api;
use VPlugins\WPCloudClient\Enum\ActionStatus;
use WP_REST_Response;
final readonly class ApiResponse {
/**
* Construct an API response.
*
* @param ActionStatus $status The action status.
* @param mixed $data The response data.
* @param ?string $errorCode The error code, if any.
* @param ?string $errorMessage The error message, if any.
* @param int $httpStatus The HTTP status code.
*/
private function __construct(
private ActionStatus $status,
private mixed $data,
private ?string $errorCode,
private ?string $errorMessage,
private int $httpStatus,
) {}
/**
* Create a success response.
*
* @param mixed $data The response data.
* @param int $httpStatus The HTTP status code.
* @return self The API response instance.
*/
public static function success( mixed $data = null, int $httpStatus = 200 ): self {
return new self(
status: ActionStatus::Success,
data: $data,
errorCode: null,
errorMessage: null,
httpStatus: $httpStatus,
);
}
/**
* Create an error response.
*
* @param string $code The error code.
* @param string $message The error message.
* @param int $httpStatus The HTTP status code.
* @return self The API response instance.
*/
public static function error( string $code, string $message, int $httpStatus = 400 ): self {
return new self(
status: ActionStatus::Failed,
data: null,
errorCode: $code,
errorMessage: $message,
httpStatus: $httpStatus,
);
}
/**
* Convert this API response to a WP_REST_Response.
*
* @return WP_REST_Response The WordPress REST response.
*/
public function toWpResponse(): WP_REST_Response {
$body = [
'status' => $this->status->value,
'data' => $this->data,
];
if ( null !== $this->errorCode ) {
$body['error'] = [
'code' => $this->errorCode,
'message' => $this->errorMessage,
];
}
return new WP_REST_Response( $body, $this->httpStatus );
}
}