Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
97.78% covered (success)
97.78%
44 / 45
66.67% covered (warning)
66.67%
2 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
HTTP_Gateway
97.78% covered (success)
97.78%
44 / 45
66.67% covered (warning)
66.67%
2 / 3
13
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
2
 get_auth
100.00% covered (success)
100.00%
11 / 11
100.00% covered (success)
100.00%
1 / 1
5
 publish_content
96.30% covered (success)
96.30%
26 / 27
0.00% covered (danger)
0.00%
0 / 1
6
1<?php
2/**
3 * HTTP Gateway
4 *
5 * @package ChoctawNation\CNHSA_Federation
6 */
7
8namespace ChoctawNation\CNHSA_Federation\Transport;
9
10use Exception;
11
12/**
13 * HTTP Gateway handles communication with the CNHSA API.
14 */
15class HTTP_Gateway {
16    /**
17     * Base URL for the CNHSA API.
18     *
19     * @var string
20     */
21    public string $base_url;
22
23    /**
24     * Constructor.
25     *
26     * @param 'local'|'development'|'staging'|'production' $environment The environment type to determine the base URL.
27     */
28    public function __construct( string $environment ) {
29        $env_urls       = array(
30            'production'  => 'https://www.cnhsa.com',
31            'staging'     => 'https://healthclinstg.wpenginepowered.com',
32            'development' => 'https://healthclindev.wpenginepowered.com',
33            'local'       => get_transient( 'cnhsa_federation_local_url' ) ?: 'https://cnhsa.local', // phpcs:ignore Universal.Operators.DisallowShortTernary.Found
34        );
35        $this->base_url = ( $env_urls[ $environment ] ?? 'https://www.cnhsa.com' ) . '/wp-json/cnhsa/v1';
36    }
37
38    /**
39     * Gets credentials from options
40     *
41     * @return string Base64-encoded credentials for the target environment, or empty string if not set.
42     * @throws Exception If credentials are missing or invalid.
43     */
44    private function get_auth(): string {
45        $opts = get_option( 'cnhsa_federation_options', array() );
46        $envs = $opts['environments'] ?? array();
47        if ( empty( $envs ) ) {
48            throw new Exception( esc_html( 'No target environments configured for federation.' ) );
49        }
50        $env   = $envs[0]; // For now, just use the first
51        $creds = $opts['credentials'][ $env ] ?? null;
52        if ( ! $creds || empty( $creds['username'] ) || empty( $creds['app_password'] ) ) {
53            throw new Exception( esc_html( "Credentials for environment '{$env}' are not fully configured." ) );
54        }
55        $user = $creds['username'];
56        $pass = $creds['app_password'];
57
58        return base64_encode( $user . ':' . $pass ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
59    }
60
61    /**
62     * Publishes the given content post to the remote CNHSA API.
63     *
64     * @param string $url The endpoint URL to publish to.
65     * @param array  $payload The payload data to send.
66     * @return array The response body from the CNHSA API.
67     * @throws Exception If the request fails or returns an error.
68     */
69    public function publish_content( string $url, array $payload ): array {
70        $response      = wp_remote_post(
71            $url,
72            array(
73                'method'  => 'POST',
74                'body'    => wp_json_encode( $payload ),
75                'headers' => array(
76                    'Content-Type'  => 'application/json',
77                    'Authorization' => 'Basic ' . $this->get_auth(),
78                ),
79            )
80        );
81        $response_code = wp_remote_retrieve_response_code( $response );
82        if ( is_wp_error( $response ) || 201 !== $response_code ) {
83            if ( is_wp_error( $response ) ) {
84                throw new Exception( esc_html( $response->get_error_message() ) );
85            }
86            $body          = json_decode( wp_remote_retrieve_body( $response ), true );
87            $code          = ! empty( $body['code'] ) ? $body['code'] : $response_code;
88            $error_message = ! empty( $body['message'] ) ? $body['message'] : ( $body['error'] ?? 'Unknown error' );
89            throw new Exception(
90                sprintf(
91                    '%s error: %s',
92                    esc_textarea( $code ),
93                    esc_textarea( $error_message )
94                )
95            );
96        }
97        $body = json_decode( wp_remote_retrieve_body( $response ), true );
98        return $body;
99    }
100}