<?php
namespace nur\sery\wip\schema\_assoc;

use nulib\ValueException;
use nur\sery\wip\schema\Result;

class AssocResult extends Result {
  function __construct(Result $arrayResult, array &$keyResults) {
    $this->arrayResult = $arrayResult;
    $this->keyResults =& $keyResults;
    $this->result =& $this->arrayResult;
    parent::__construct();
  }

  function isAssoc(?AssocResult &$result=null): bool { $result = $this; return true;}

  protected Result $arrayResult;

  /** @var Result[] */
  protected array $keyResults;

  function getKeys(): array {
    return array_keys($this->keyResults);
  }

  protected Result $result;

  function select($key): Result {
    if ($key === null) {
      $this->result =& $this->arrayResult;
    } elseif (array_key_exists($key, $this->keyResults)) {
      $this->result =& $this->keyResults[$key];
    } else {
      throw ValueException::invalid_key($key);
    }
    return $this;
  }

  function reset(): void {
    $this->arrayResult->reset();
    foreach ($this->keyResults as $result) {
      $result->reset();
    }
  }

  function __get(string $name) {
    return $this->result[$name];
  }

  function __set(string $name, $value): void {
    $this->result[$name] = $value;
  }
}
