Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
2 / 2
CRAP
100.00% covered (success)
100.00%
1 / 1
Client
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
2 / 2
5
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
12 / 12
100.00% covered (success)
100.00%
1 / 1
2
 buildGuzzleClient
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
3
1<?php
2
3declare(strict_types=1);
4
5namespace ForgeDashboard;
6
7use ForgeDashboard\Generated\Api\AuthApi;
8use ForgeDashboard\Generated\Api\DashboardApi;
9use ForgeDashboard\Generated\Api\HealthApi;
10use ForgeDashboard\Generated\Api\PullRequestsApi;
11use ForgeDashboard\Generated\Api\SettingsApi;
12use ForgeDashboard\Generated\Api\TokensApi;
13use ForgeDashboard\Generated\Api\WebhooksApi;
14use ForgeDashboard\Generated\Configuration;
15use ForgeDashboard\Retry\RetryMiddleware;
16use GuzzleHttp\Client as GuzzleClient;
17use GuzzleHttp\ClientInterface;
18use GuzzleHttp\Handler\MockHandler;
19use GuzzleHttp\HandlerStack;
20use GuzzleHttp\Middleware;
21use Psr\Http\Message\RequestInterface;
22
23/**
24 * A forge-dashboard API client (github.com/alrayyes/forge-dashboard).
25 *
26 * Every operation except {@see HealthApi::health()}, {@see HealthApi::getVersion()}
27 * and the two webhook receivers ({@see WebhooksApi}) requires an
28 * authenticated session. forge-dashboard accepts either a browser's
29 * passkey session cookie or a personal API token
30 * (`Authorization: Bearer <token>`, minted via `POST /api/tokens`) -- this
31 * client only speaks the token half, the headless-friendly one. Pass it
32 * to the constructor or set {@see self::API_TOKEN_ENV_VAR}. See the
33 * README for the full explanation and an example.
34 *
35 * Each generated Api class is exposed as a public, readonly property
36 * ({@see self::$dashboard}, {@see self::$tokens}, ...) for direct,
37 * one-response-at-a-time calls -- forge-dashboard's spec has no
38 * pagination to wrap.
39 */
40final readonly class Client
41{
42    /**
43     * Environment variable the constructor falls back to when no API
44     * token is passed explicitly.
45     */
46    public const API_TOKEN_ENV_VAR = 'FORGE_DASHBOARD_API_TOKEN';
47
48    public HealthApi $health;
49
50    public DashboardApi $dashboard;
51
52    public AuthApi $auth;
53
54    public SettingsApi $settings;
55
56    public TokensApi $tokens;
57
58    public WebhooksApi $webhooks;
59
60    public PullRequestsApi $pullRequests;
61
62    /**
63     * @param  string  $baseUrl  the forge-dashboard instance's origin, e.g.
64     *                           "https://forge-dashboard.example.com"
65     * @param  string|null  $apiToken  overrides
66     *                                 {@see self::API_TOKEN_ENV_VAR} when given
67     * @param  ClientInterface|null  $httpClient  replaces the underlying Guzzle
68     *                                            client entirely (a test double, usually); when given, the retry
69     *                                            and auth-injection middleware below are *not* applied, and
70     *                                            $handlerStack/$maxRetries/$retryBaseDelaySeconds are ignored --
71     *                                            the caller owns that behaviour instead
72     * @param  HandlerStack|null  $handlerStack  the base handler stack the
73     *                                           retry and auth-injection middleware get pushed onto -- pass a
74     *                                           stack built around a {@see MockHandler} in a
75     *                                           test to exercise both against a fake transport. Defaults to a
76     *                                           fresh {@see HandlerStack::create()} (the real cURL/stream
77     *                                           handler). Ignored when $httpClient is given.
78     * @param  int  $maxRetries  additional attempts after the first, for a
79     *                           429/5xx or network failure
80     * @param  float  $retryBaseDelaySeconds  the starting backoff before
81     *                                        jitter and any server-sent Retry-After
82     */
83    public function __construct(
84        string $baseUrl,
85        ?string $apiToken = null,
86        ?ClientInterface $httpClient = null,
87        ?HandlerStack $handlerStack = null,
88        int $maxRetries = 3,
89        float $retryBaseDelaySeconds = 0.25,
90    ) {
91        $token = $apiToken ?? (getenv(self::API_TOKEN_ENV_VAR) ?: null);
92
93        $guzzle = $httpClient ?? $this->buildGuzzleClient($handlerStack ?? HandlerStack::create(), $token, $maxRetries, $retryBaseDelaySeconds);
94
95        $config = new Configuration;
96        $config->setHost(rtrim($baseUrl, '/'));
97        // The generator sends a boolean query parameter as 1 or 0 by default;
98        // the API and its mock accept only true or false. Its serializer reads
99        // the process-wide default Configuration, not the instance above, so
100        // that is the one to set. Setting it again on every Client is harmless.
101        Configuration::getDefaultConfiguration()->setBooleanFormatForQueryString(Configuration::BOOLEAN_FORMAT_STRING);
102
103        $this->health = new HealthApi($guzzle, $config);
104        $this->dashboard = new DashboardApi($guzzle, $config);
105        $this->auth = new AuthApi($guzzle, $config);
106        $this->settings = new SettingsApi($guzzle, $config);
107        $this->tokens = new TokensApi($guzzle, $config);
108        $this->webhooks = new WebhooksApi($guzzle, $config);
109        $this->pullRequests = new PullRequestsApi($guzzle, $config);
110    }
111
112    private function buildGuzzleClient(HandlerStack $stack, ?string $token, int $maxRetries, float $baseDelaySeconds): GuzzleClient
113    {
114        $stack->push(Middleware::mapRequest(
115            static function (RequestInterface $request) use ($token): RequestInterface {
116                if ($token === null || $token === '') {
117                    return $request;
118                }
119
120                return $request->withHeader('Authorization', 'Bearer '.$token);
121            },
122        ), 'bearer_auth');
123
124        $retry = new RetryMiddleware($maxRetries, $baseDelaySeconds);
125        $stack->push(Middleware::retry($retry->decider(), $retry->delay()), 'retry');
126
127        return new GuzzleClient(['handler' => $stack]);
128    }
129}