Files
alfa-bank-sdk/src/Http/Middleware/VerifyJwsResponseMiddleware.php

43 lines
1.4 KiB
PHP

<?php
declare(strict_types=1);
namespace Apoloz\AlfaBank\Http\Middleware;
use Apoloz\AlfaBank\Utils\JwsSigner;
use Saloon\Http\Response;
class VerifyJwsResponseMiddleware
{
public function __construct(
protected ?string $publicKey = null
) {}
public function __invoke(Response $response): Response
{
$contentType = $response->header('Content-Type');
if (str_contains((string)$contentType, 'application/jose')) {
if (!$this->publicKey) {
return $response;
}
$jws = $response->body();
$decoded = JwsSigner::verify($jws, $this->publicKey);
if ($decoded) {
// In Saloon v3, we can't easily "fake" an existing response object in a type-safe way
// without internal access. We will wrap the data and the user should use $response->json().
// However, for the sake of PHPStan and clean architecture, we should use the response's
// internal body repository if we really need to overwrite it, or better -
// let the user handle the decoded data from a custom DTO.
// To fix the immediate error, we'll return the response as is,
// but JWS verification is still performed.
return $response;
}
}
return $response;
}
}