Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
94.20% covered (success)
94.20%
65 / 69
70.00% covered (warning)
70.00%
7 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
ZeusClient
94.20% covered (success)
94.20%
65 / 69
70.00% covered (warning)
70.00%
7 / 10
34.23
0.00% covered (danger)
0.00%
0 / 1
 token
95.45% covered (success)
95.45%
21 / 22
0.00% covered (danger)
0.00%
0 / 1
8
 postMultipart
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 postJson
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 get
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 send
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 request
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
1
 url
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 attachFiles
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
7.03
 flatten
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
7
 tokenTtl
71.43% covered (warning)
71.43%
5 / 7
0.00% covered (danger)
0.00%
0 / 1
5.58
1<?php
2
3namespace App\Services;
4
5use Illuminate\Http\Client\PendingRequest;
6use Illuminate\Http\Client\Response;
7use Illuminate\Http\UploadedFile;
8use Illuminate\Support\Carbon;
9use Illuminate\Support\Facades\Cache;
10use Illuminate\Support\Facades\Http;
11
12/**
13 * Thin HTTP client for Zeus's public API.
14 *
15 * Titan is just another third party as far as Zeus is concerned: it logs in at
16 * `POST /api/auth` with its own credentials and carries the returned bearer
17 * token. Nothing in here knows anything about Zeus internals — it only speaks
18 * the documented wire (see http://localhost:8001/api/docs).
19 *
20 * The token is cached (Zeus issues 24h tokens) and refreshed automatically: a
21 * 401 forgets the cached token and the call is retried exactly once, so a
22 * server-side session reset never costs more than one failed request.
23 *
24 * @see ZeusBridge for the routing/replay decisions
25 */
26class ZeusClient
27{
28    /**
29     * Authenticate against Zeus and return a bearer token, or null when Zeus is
30     * unreachable / the credentials are wrong. Cached until shortly before the
31     * token Zeus reports as its expiry.
32     */
33    public function token(bool $fresh = false): ?string
34    {
35        $key = (string) config('zeus.token_cache_key');
36
37        if ($fresh) {
38            Cache::forget($key);
39        } elseif (($cached = Cache::get($key)) !== null) {
40            return (string) $cached;
41        }
42
43        $email = config('zeus.email');
44        $password = config('zeus.password');
45
46        if (empty($email) || empty($password)) {
47            throw new \RuntimeException('Zeus bridge credentials are not configured (ZEUS_API_EMAIL / ZEUS_API_PASSWORD).');
48        }
49
50        $response = $this->request()
51            ->asJson()
52            ->post($this->url('/api/auth'), [
53                'email' => $email,
54                'password' => $password,
55            ]);
56
57        if (! $response->successful()) {
58            throw new \RuntimeException('Zeus auth failed with HTTP '.$response->status());
59        }
60
61        $token = $response->json('token');
62
63        if (! is_string($token) || $token === '') {
64            throw new \RuntimeException('Zeus auth returned no token.');
65        }
66
67        Cache::put($key, $token, $this->tokenTtl($response->json('token_expires_at')));
68
69        return $token;
70    }
71
72    /**
73     * POST a replayed third-party request to Zeus as multipart/form-data —
74     * the content type Zeus's createQuotation/updateQuotation declare.
75     *
76     * @param  array<string, mixed>  $fields  scalar form fields (nested arrays are flattened)
77     * @param  array<string, mixed>  $files  file fields exactly as `$request->allFiles()` returns them
78     */
79    public function postMultipart(string $path, array $fields, array $files = []): Response
80    {
81        return $this->send(
82            fn (PendingRequest $http) => $this->attachFiles($http->asMultipart(), $files)
83                ->post($this->url($path), $this->flatten($fields)),
84        );
85    }
86
87    /**
88     * POST a JSON body to Zeus (for the endpoints that declare
89     * application/json, e.g. validateEmail / listQuotations).
90     *
91     * @param  array<string, mixed>  $payload
92     */
93    public function postJson(string $path, array $payload): Response
94    {
95        return $this->send(
96            fn (PendingRequest $http) => $http->asJson()->post($this->url($path), $payload),
97        );
98    }
99
100    /**
101     * GET one of Zeus's read endpoints.
102     *
103     * `downloadFile` answers with raw bytes rather than JSON; the response is
104     * handed back untouched so the caller decides how to relay it.
105     *
106     * @param  array<string, mixed>  $query
107     */
108    public function get(string $path, array $query = []): Response
109    {
110        return $this->send(
111            fn (PendingRequest $http) => $http->get($this->url($path), $query),
112        );
113    }
114
115    /**
116     * Run an authenticated call, retrying once on 401 with a fresh token.
117     *
118     * @param  callable(PendingRequest): Response  $call
119     */
120    private function send(callable $call): Response
121    {
122        $response = $call($this->request()->withToken($this->token()));
123
124        if ($response->status() === 401) {
125            $response = $call($this->request()->withToken($this->token(true)));
126        }
127
128        return $response;
129    }
130
131    private function request(): PendingRequest
132    {
133        return Http::timeout((int) config('zeus.timeout', 10))
134            ->connectTimeout((int) config('zeus.connect_timeout', 3))
135            ->withHeaders(['Accept' => 'application/json']);
136    }
137
138    private function url(string $path): string
139    {
140        return rtrim((string) config('zeus.base_url'), '/').'/'.ltrim($path, '/');
141    }
142
143    /**
144     * Attach uploaded files under the same field names the third party used.
145     * `files[]` / `internal_files[]` arrive as arrays and must stay arrays on
146     * the wire; `coverage_contract_file` is a single binary.
147     *
148     * @param  array<string, mixed>  $files
149     */
150    private function attachFiles(PendingRequest $http, array $files): PendingRequest
151    {
152        foreach ($files as $field => $file) {
153            foreach (is_array($file) ? $file : [$file] as $one) {
154                if (! $one instanceof UploadedFile || ! $one->isValid()) {
155                    continue;
156                }
157
158                // Array fields keep the `name[]` shape Zeus's schema declares;
159                // single fields keep their bare name.
160                $wireName = is_array($file) ? $field.'[]' : $field;
161
162                $http = $http->attach(
163                    $wireName,
164                    // The temp file is still on disk at this point in the
165                    // request lifecycle; a stream avoids loading it into memory.
166                    fopen($one->getRealPath(), 'r'),
167                    $one->getClientOriginalName(),
168                    ['Content-Type' => $one->getClientMimeType()],
169                );
170            }
171        }
172
173        return $http;
174    }
175
176    /**
177     * Flatten nested arrays into PHP's form-encoding convention
178     * (`sortModel[0][colId]`) and cast scalars to string, because multipart
179     * bodies carry no types. Nulls are dropped: sending the literal string
180     * "null" would overwrite a Zeus field with garbage.
181     *
182     * @param  array<string, mixed>  $fields
183     * @return array<string, string>
184     */
185    private function flatten(array $fields, string $prefix = ''): array
186    {
187        $flat = [];
188
189        foreach ($fields as $key => $value) {
190            $name = $prefix === '' ? (string) $key : $prefix.'['.$key.']';
191
192            if (is_array($value)) {
193                $flat += $this->flatten($value, $name);
194
195                continue;
196            }
197
198            if ($value === null) {
199                continue;
200            }
201
202            $flat[$name] = is_bool($value) ? ($value ? '1' : '0') : (string) $value;
203        }
204
205        return $flat;
206    }
207
208    /**
209     * Cache the token until shortly before Zeus's own expiry. Falls back to a
210     * conservative hour when Zeus does not report one.
211     */
212    private function tokenTtl(mixed $expiresAt): int
213    {
214        $margin = (int) config('zeus.token_safety_margin', 300);
215
216        if (is_string($expiresAt) && $expiresAt !== '') {
217            try {
218                // Whole seconds from integer timestamps — a TTL is never fractional.
219                $seconds = Carbon::parse($expiresAt)->getTimestamp() - Carbon::now()->getTimestamp();
220
221                if ($seconds > $margin) {
222                    return $seconds - $margin;
223                }
224            } catch (\Throwable) {
225                // Unparseable expiry — fall through to the default below.
226            }
227        }
228
229        return 3600;
230    }
231}