<?php
namespace nur\sery\wip\php\access;

/**
 * Class ValueAccess: accès à une valeur unitaire
 */
class ValueAccess extends AbstractAccess {
  function __construct(&$value, ?array $params=null) {
    $this->value =& $value;
    $this->allowNull = $params["allow_null"] ?? false;
    $this->allowFalse = $params["allow_false"] ?? true;
    $this->allowEmpty = $params["allow_empty"] ?? true;
  }

  /** @var mixed */
  protected $value;

  function reset(&$value): self {
    $this->value =& $value;
    return $this;
  }

  protected bool $allowNull;

  protected bool $allowFalse;

  protected bool $allowEmpty;

  function exists(): bool {
    return $this->allowNull || $this->value !== null;
  }

  function available(): bool {
    if (!$this->exists()) return false;
    $value = $this->value;
    if ($value === false) return $this->allowFalse;
    if ($value === "") return $this->allowEmpty;
    return true;
  }

  function get($default=null) {
    $value = $this->value;
    if ($value === null && !$this->allowNull) return $default;
    if ($value === false && !$this->allowFalse) return $default;
    if ($value === "" && !$this->allowEmpty) return $default;
    return $value;
  }

  function set($value): void {
    $this->value = $value;
  }

  function del(): void {
    $this->value = null;
  }
}
