← Code-Übersicht

JsonInvoiceStateAdapter.php

Pfad: src/Infrastructure/Rechnung/JsonInvoiceStateAdapter.php

Ext: php

Größe: 1710 Bytes

Geändert: 2026-07-16T14:11:10+02:00

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

<?php
declare(strict_types=1);

namespace Demo\Infrastructure\Rechnung;

use Demo\Domain\Rechnung\InvoiceState;
use Demo\Domain\Rechnung\InvoiceStatePort;

/**
 * Dateibasierter Adapter fuer rechnungen.json.
 */
final class JsonInvoiceStateAdapter implements InvoiceStatePort
{
    /**
     * @param string $statePath Absoluter Dateipfad zur rechnungen.json.
     */
    public function __construct(
        private string $statePath
    ) {
    }

    /**
     * @return InvoiceState Geladener Zustand.
     */
    public function load(): InvoiceState
    {
        if (!is_file($this->statePath)) {
            return InvoiceState::empty();
        }

        $raw = (string) file_get_contents($this->statePath);
        if (trim($raw) === '') {
            return InvoiceState::empty();
        }

        $decoded = json_decode($raw, true);
        if (!is_array($decoded)) {
            return InvoiceState::empty();
        }

        return InvoiceState::fromArray($decoded);
    }

    /**
     * @param InvoiceState $state Persistenter Zustand.
     */
    public function save(InvoiceState $state): void
    {
        $baseDir = dirname($this->statePath);
        if (!is_dir($baseDir) && !mkdir($baseDir, 0775, true) && !is_dir($baseDir)) {
            throw new \RuntimeException('Zielverzeichnis fuer rechnungen.json fehlt');
        }

        $tmp = $this->statePath . '.tmp';
        $payload = json_encode($state->toArray(), JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR);
        file_put_contents($tmp, $payload . "\n", LOCK_EX);

        if (!rename($tmp, $this->statePath)) {
            throw new \RuntimeException('Persistenz: rename() fehlgeschlagen fuer rechnungen.json');
        }
    }
}