← Code-Übersicht

FallbackWetellSourceAdapter.php

Pfad: src/Infrastructure/Rechnung/FallbackWetellSourceAdapter.php

Ext: php

Größe: 1876 Bytes

Geändert: 2026-07-16T17:10:12+02:00

Frühere Version vom 2026-07-16T17:10:12+02:00 · zur aktuellen Fassung

<?php
declare(strict_types=1);

namespace Demo\Infrastructure\Rechnung;

use Demo\Domain\Rechnung\InvoiceLoggerPort;
use Demo\Domain\Rechnung\SourceInvoice;
use Demo\Domain\Rechnung\WetellSourcePort;
use Throwable;

/**
 * Waehlt beim Login genau einen aktiven WEtell-Adapter pro Session.
 */
final class FallbackWetellSourceAdapter implements WetellSourcePort
{
    private ?WetellSourcePort $active = null;

    /** Injiziert Primary, Fallback und Logger. */
    public function __construct(private readonly WetellSourcePort $primary, private readonly WetellSourcePort $fallback, private readonly InvoiceLoggerPort $logger)
    {
    }

    /** Aktiviert Primary oder nach technischem Fehler einen frisch eingeloggten Fallback. */
    public function login(string $username, string $password): void
    {
        try {
            $this->primary->login($username, $password);
            $this->active = $this->primary;
            $this->logger->logStep('portal', 'adapter', 'PRIMARY', []);
        } catch (Throwable $error) {
            $this->logger->logStep('portal', 'adapter', 'FALLBACK', ['reason' => $error::class]);
            $this->fallback->login($username, $password);
            $this->active = $this->fallback;
        }
    }

    /** @return list<SourceInvoice> Discovery ausschliesslich in aktiver Session. */
    public function discoverInvoices(): array { return $this->session()->discoverInvoices(); }

    /** Download ausschliesslich in aktiver Session. */
    public function downloadInvoicePdf(string $downloadUrl): string { return $this->session()->downloadInvoicePdf($downloadUrl); }

    /** Liefert den erfolgreich eingeloggten Adapter. */
    private function session(): WetellSourcePort
    {
        if ($this->active === null) { throw new \RuntimeException('WEtell-Session ist nicht eingeloggt'); }
        return $this->active;
    }
}