HEX
Server: nginx
System: Linux pool195-106-36.bur.atomicsites.net 6.12.57+deb12-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.12.57-1~bpo12+1 (2025-11-17) x86_64
User: (0)
PHP: 8.3.32
Disabled: pcntl_fork
Upload Files
File: /wordpress/plugins/wp-cloud-client/1.1.8/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 );
	}
}