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.3/src/Api/Controller/MailController.php
<?php

declare(strict_types=1);

namespace VPlugins\WPCloudClient\Api\Controller;

use VPlugins\WPCloudClient\Api\ApiResponse;
use VPlugins\WPCloudClient\Mail\MailTable;
use VPlugins\WPCloudClient\Support\Logger;
use WP_REST_Request;
use WP_REST_Response;

final readonly class MailController {

	/**
	 * Construct the mail controller.
	 *
	 * @param MailTable $mail_table Mail table instance.
	 * @param Logger    $logger     Logger instance.
	 */
	public function __construct(
		private MailTable $mail_table,
		private Logger $logger,
	) {}

	/**
	 * List pending (unnotified) email records.
	 *
	 * Accepts an optional `limit` query param (integer 1–100, default 10).
	 *
	 * @param WP_REST_Request $request The incoming REST request.
	 * @return WP_REST_Response
	 */
	public function list( WP_REST_Request $request ): WP_REST_Response {
		try {
			$limit = max( 1, min( (int) ( $request->get_param( 'limit' ) ?? 10 ), 100 ) );
			$mails = $this->mail_table->listUnnotified( $limit );

			return ApiResponse::success(
				[
					'mails' => $mails,
					'count' => count( $mails ),
				]
			)->toWpResponse();
		} catch ( \Exception $e ) {
			$this->logger->error( sprintf( 'Mail list failed (limit=%d)', $limit ?? -1 ), $e );
			return ApiResponse::error( 'list_failed', 'An internal error occurred while listing emails.', 500 )->toWpResponse();
		}
	}

	/**
	 * Fetch a single email record by ID.
	 *
	 * @param WP_REST_Request $request The incoming REST request.
	 * @return WP_REST_Response
	 */
	public function fetch( WP_REST_Request $request ): WP_REST_Response {
		try {
			$id   = (int) $request->get_param( 'id' );
			$mail = $this->mail_table->get( $id );

			if ( null === $mail ) {
				return ApiResponse::error( 'not_found', 'Email record not found.', 404 )->toWpResponse();
			}

			return ApiResponse::success( $mail )->toWpResponse();
		} catch ( \Throwable $e ) {
			$this->logger->error( sprintf( 'Mail fetch failed (id=%d)', (int) $request->get_param( 'id' ) ), $e );
			return ApiResponse::error( 'fetch_failed', 'An internal error occurred while fetching the email.', 500 )->toWpResponse();
		}
	}
}