refactor(core): enhance SDK structure and documentation

Co-authored-by: Qwen-Coder <qwen-coder@alibabacloud.com>
This commit is contained in:
2026-01-18 21:48:25 +03:00
parent 3da69c03e1
commit d214eecebe
378 changed files with 10514 additions and 496 deletions

View File

@@ -0,0 +1,130 @@
<?php
/*
// MODULE_CONTRACT: Defines the primary transport layer for the Alfa Bank BaaS API.
// RESPONSIBILITY: To manage mTLS configuration, authentication state, retries, and middleware for all BaaS API interactions.
// INPUTS: AlfaConfig (DTO), SignerInterface (service).
// OUTPUTS: An authenticated Saloon Connector instance capable of sending requests.
// NOTES:
// - Supports separate keys for Transport (mTLS) and Signing (JWS/CMS).
// - Uses `login` method for OAuth 2.0 Client Credentials flow.
// - Compatible with Saloon v3.
// LINKS: AlfaBankServiceProvider.php#bind_connector
*/
namespace Apoloz\AlfaBank\Core;
// <SECTION name="module_imports" intent="Import necessary contracts, services, and base framework components for the connector's operation.">
// <BELIEF_STATE "Saloon's plugin architecture requires importing traits for features like retries and timeouts. Local contracts (SignerInterface) are imported for dependency injection.">
use Apoloz\AlfaBank\Contracts\SignerInterface;
use Apoloz\AlfaBank\Http\Middleware\AlfaResponseMiddleware;
use Apoloz\AlfaBank\Http\Middleware\RequestIdMiddleware;
use Apoloz\AlfaBank\Http\Pagination\AlfaOffsetPaginator;
use Apoloz\AlfaBank\Requests\Auth\GetTokenRequest;
use Saloon\Http\Connector;
use Saloon\Http\Request;
use Saloon\PaginationPlugin\Contracts\HasPagination;
use Saloon\PaginationPlugin\OffsetPaginator;
use Saloon\Traits\RequestProperties\HasTries;
use Saloon\Traits\Plugins\HasTimeout;
class AlfaBankConnector extends Connector implements HasPagination
{
use HasTimeout;
use HasTries;
public function __construct(
protected AlfaConfig $alfaConfig,
protected ?SignerInterface $signer = null
) {
$this->tries = 3;
$this->retryInterval = 500;
}
public function resolveBaseUrl(): string
{
return $this->alfaConfig->baseUrl;
}
protected function defaultConfig(): array
{
$config = [
'cert' => $this->alfaConfig->certificatePath,
'ssl_key' => $this->alfaConfig->privateKeyPath,
'verify' => true,
];
if ($this->alfaConfig->caBundlePath) {
$config['verify'] = $this->alfaConfig->caBundlePath;
}
return $config;
}
protected function defaultMiddleware(): array
{
return [];
}
public function boot(\Saloon\Http\PendingRequest $pendingRequest): void
{
$pendingRequest->middleware()->onResponse(new AlfaResponseMiddleware());
$pendingRequest->middleware()->onRequest(new RequestIdMiddleware());
}
public function paginate(Request $request): OffsetPaginator
{
return new AlfaOffsetPaginator($this, $request);
}
public function login(?string $clientId = null, ?string $clientSecret = null): static
{
// Allow overriding config via method arguments
$clientId = $clientId ?? $this->alfaConfig->clientId;
$clientSecret = $clientSecret ?? $this->alfaConfig->clientSecret;
if (!$clientId || !$clientSecret) {
throw new \RuntimeException("Client ID/Secret not configured.");
}
$request = new GetTokenRequest(
clientId: $clientId,
clientSecret: $clientSecret,
grantType: 'client_credentials'
);
// Send request (using self to reuse cert/ssl config)
// We temporarily disable auth middleware if we had any,
// but here we are raw, so it's fine.
$response = $this->send($request);
$data = $response->dto();
$this->authenticate(new \Saloon\Http\Auth\TokenAuthenticator($data->access_token));
return $this;
}
// </SECTION>
// <SECTION name="signer_accessor" intent="Provide access to the configured signing service for requests that require a digital signature.">
// <BELIEF_STATE "Requests should not instantiate their own signing logic. The connector acts as a service locator, providing the globally-configured Signer service. This ensures that all signatures are generated consistently.">
public function getSigner(): SignerInterface
{
if (!$this->signer) {
throw new \RuntimeException("No signer configured for this connector.");
}
return $this->signer;
}
// </SECTION>
// <SECTION name="logging_mutator" intent="Allow attaching a PSR-3 logger to the connector for debugging.">
// <BELIEF_STATE "Logging should be an optional, opt-in feature. This method provides a fluent interface to attach a logging middleware, which will automatically sanitize sensitive data before output.">
public function withLogging(\Psr\Log\LoggerInterface $logger): static
{
$middleware = new \Apoloz\AlfaBank\Http\Middleware\LoggingMiddleware($logger);
$this->middleware()->onRequest([$middleware, 'onRequest']);
$this->middleware()->onResponse([$middleware, 'onResponse']);
return $this;
}
// </SECTION>
}

54
src/Core/AlfaConfig.php Normal file
View File

@@ -0,0 +1,54 @@
<?php
/*
// MODULE_CONTRACT: Defines a strongly-typed, immutable Data Transfer Object (DTO) for all connector configurations.
// RESPONSIBILITY: To hold and validate critical configuration parameters like certificate paths and API credentials.
// INPUTS: Configuration primitives (strings for paths, URLs, credentials).
// OUTPUTS: A validated, read-only configuration object.
// NOTES:
// - Stores both Transport keys (mTLS) and optional Signing keys (JWS/CMS).
// - Validates file existence upon instantiation.
// LINKS: AlfaBankConnector.php, SbpConnector.php
*/
namespace Apoloz\AlfaBank\Core;
// <SECTION name="class_definition" intent="Define an immutable DTO for connector configuration.">
// <BELIEF_STATE "Using a `readonly` class for configuration is a best practice. It prevents accidental modification of the configuration after instantiation, ensuring that the connector's behavior remains consistent throughout its lifecycle. This pattern is superior to passing around raw arrays.">
readonly class AlfaConfig
{
// <SECTION name="constructor" intent="Inject and validate all configuration properties upon creation.">
// <BELIEF_STATE "The constructor acts as a validation gate. By checking for the existence of certificate and key files here, we enforce a fail-fast policy. It's better to throw an exception immediately upon configuration creation than to fail unexpectedly during an API call later.">
public function __construct(
// <BELIEF_STATE "The base URL for the API endpoint.">
public string $baseUrl,
// <BELIEF_STATE "The file system path to the client's mTLS certificate.">
public string $certificatePath,
// <BELIEF_STATE "The file system path to the client's mTLS private key.">
public string $privateKeyPath,
// <BELIEF_STATE "Optional: The path to a custom Certificate Authority bundle, required for some environments (e.g., Russian Trusted CA).">
public ?string $caBundlePath = null,
// <BELIEF_STATE "Optional: The OAuth client ID, required for token-based authentication.">
public ?string $clientId = null,
// <BELIEF_STATE "Optional: The OAuth client secret, required for token-based authentication.">
public ?string $clientSecret = null,
// <BELIEF_STATE "Optional: Path to the certificate used specifically for signing requests (JWS/CMS), if different from the transport certificate.">
public ?string $signingCertificatePath = null,
// <BELIEF_STATE "Optional: Path to the private key used specifically for signing requests (JWS/CMS), if different from the transport key.">
public ?string $signingPrivateKeyPath = null,
) {
// <BELIEF_STATE "This runtime check ensures that the provided certificate and key paths are not just valid strings, but point to actual, accessible files on the filesystem. This prevents configuration errors that would otherwise only surface during an HTTP request.">
if (!file_exists($this->certificatePath)) {
throw new \InvalidArgumentException("Certificate not found: {$this->certificatePath}");
}
if (!file_exists($this->privateKeyPath)) {
throw new \InvalidArgumentException("Private key not found: {$this->privateKeyPath}");
}
if ($this->signingCertificatePath && !file_exists($this->signingCertificatePath)) {
throw new \InvalidArgumentException("Signing certificate not found: {$this->signingCertificatePath}");
}
if ($this->signingPrivateKeyPath && !file_exists($this->signingPrivateKeyPath)) {
throw new \InvalidArgumentException("Signing private key not found: {$this->signingPrivateKeyPath}");
}
}
// </SECTION>
}