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.31
Disabled: pcntl_fork
Upload Files
File: /wordpress/plugins/wp-cloud-client/beta/src/Handler/WooCommerceDataHandler.php
<?php

declare(strict_types=1);

namespace VPlugins\WPCloudClient\Handler;

use VPlugins\WPCloudClient\Integration\WooCommerceHelper;
use VPlugins\WPCloudClient\Settings\SettingsRepository;

class WooCommerceDataHandler extends AbstractHandler {

	private const VALID_ENTITIES = [ 'products', 'orders' ];

	/**
	 * Class constructor.
	 *
	 * @param SettingsRepository $settings Settings repository.
	 */
	public function __construct(
		private readonly SettingsRepository $settings,
	) {}

	/**
	 * Return the action name.
	 *
	 * @return string Action name.
	 */
	public function action(): string {
		return 'woocommerce_data';
	}

	/**
	 * Fetch WooCommerce entity data.
	 *
	 * @param array<string, mixed> $params Action parameters.
	 * @return array<string, mixed> Entity data.
	 *
	 * @throws \InvalidArgumentException If entity type is unknown, offset is negative, or limit is out of range.
	 * @throws \DomainException          If WooCommerce is not active.
	 */
	public function execute( array $params ): array {
		$this->requireParams( $params, 'entity' );

		$entity = (string) $params['entity'];

		if ( ! in_array( $entity, self::VALID_ENTITIES, true ) ) {
			throw new \InvalidArgumentException(
				sprintf( 'Unknown entity type: %s. Valid types: %s', $entity, implode( ', ', self::VALID_ENTITIES ) ),
			);
		}

		if ( ! WooCommerceHelper::isActive() ) {
			throw new \DomainException( 'WooCommerce is not active' );
		}

		$offset = isset( $params['offset'] ) ? (int) $params['offset'] : 0;
		$limit  = isset( $params['limit'] ) ? (int) $params['limit'] : 10;

		if ( $offset < 0 ) {
			throw new \InvalidArgumentException( 'offset must be >= 0' );
		}
		if ( $limit < 1 ) {
			throw new \InvalidArgumentException( 'limit must be >= 1' );
		}
		if ( $limit > 100 ) {
			throw new \InvalidArgumentException( 'limit must be <= 100' );
		}

		$result = [
			'site_id'     => $this->settings->getSiteId(),
			'environment' => $this->settings->getEnvironment(),
			'entity'      => $entity,
			'offset'      => $offset,
			'limit'       => $limit,
		];

		$result[ $entity ] = match ( $entity ) {
			'products' => WooCommerceHelper::getProducts( $offset, $limit ),
			'orders' => WooCommerceHelper::getOrders( $offset, $limit ),
		};

		return $result;
	}
}