<?php

declare(strict_types=1);

namespace Drupal\Tests\netforum\xWeb;

/**
 * An array that is backed by a JSON file on disk.
 *
 * @implements \ArrayAccess<string, mixed>
 */
class JsonStateStore implements \ArrayAccess {

  private ?array $state = NULL;

  public function __construct(private readonly string $file) {}

  public function offsetExists(mixed $offset): bool {
    $this->load();

    return isset($this->state[$offset]);
  }

  private function load(): void {
    if ($this->state === NULL) {
      $file = file_get_contents($this->file);
      if ($file === FALSE) {
        throw new \RuntimeException('Could not read state file.');
      }

      $this->state = json_decode($file, TRUE) ?? [];
    }
  }

  public function offsetGet(mixed $offset): mixed {
    $this->load();

    return $this->state[$offset] ?? NULL;
  }

  public function offsetSet(mixed $offset, mixed $value): void {
    $this->load();

    $this->state[$offset] = $value;

    $this->save();
  }

  private function save(): void {
    file_put_contents($this->file, json_encode($this->state));
  }

  public function offsetUnset(mixed $offset): void {
    $this->load();

    unset($this->state[$offset]);

    $this->save();
  }

}
