Send extra request headers and throw PreconditionFailedException on 412

This commit is contained in:
envoyr committed 2026-11-06 19:25:51 +00:00
1 parent 9c505842cb
commit d76095cc94
5 files changed
+164 -18

No files matched your search

+11 -7
View File
@@ -5,36 +5,40 @@ namespace Anikeen\Id\Support;
use Anikeen\Id\AnikeenId;
use Anikeen\Id\Contracts\AppTokenRepository;
use Anikeen\Id\Exceptions\ApiException;
use Anikeen\Id\Exceptions\PreconditionFailedException;
use Anikeen\Id\Result;
use GuzzleHttp\Exception\GuzzleException;
use Throwable;
/**
* Sends a request with the app's own token (client credentials). A rejected token is renewed
* once; every failure ends in an ApiException with status and error code.
* once; every failure ends in an ApiException with status and error code (a 412 in a
* PreconditionFailedException).
*/
final class AppRequest
{
/**
* @param array<string, string> $headers Extra request headers, e.g. `If-Match`.
* @throws ApiException
*/
public static function send(string $method, string $path, ?array $payload = null, array $query = []): Result
public static function send(string $method, string $path, ?array $payload = null, array $query = [], array $headers = []): Result
{
$result = self::attempt($method, $path, $payload, $query);
$result = self::attempt($method, $path, $payload, $query, $headers);
if ($result->status === 401) {
$tokens = app(AppTokenRepository::class);
if (method_exists($tokens, 'forgetAccessToken')) {
$tokens->forgetAccessToken();
$result = self::attempt($method, $path, $payload, $query);
$result = self::attempt($method, $path, $payload, $query, $headers);
}
}
if (!$result->success()) {
$body = is_object($result->data) ? $result->data : null;
$exception = $result->status === 412 ? PreconditionFailedException::class : ApiException::class;
throw new ApiException(
throw new $exception(
sprintf('Anikeen ID request %s %s failed: %s', $method, $path, $body->message ?? $result->error()),
$result->response()?->getStatusCode() ?? 0,
$body->error ?? null,
@@ -48,10 +52,10 @@ final class AppRequest
/**
* @throws ApiException
*/
private static function attempt(string $method, string $path, ?array $payload, array $query): Result
private static function attempt(string $method, string $path, ?array $payload, array $query, array $headers = []): Result
{
try {
return app(AnikeenId::class)->asApp()->request($method, $path, $payload, $query);
return app(AnikeenId::class)->asApp()->request($method, $path, $payload, $query, null, false, $headers);
} catch (ApiException $e) {
throw $e;
} catch (GuzzleException|Throwable $e) {