nur-ture/src/php/access/KeyAccess.php

76 lines
1.9 KiB
PHP

<?php
namespace nur\sery\wip\php\access;
use ArrayAccess;
use nulib\cl;
/**
* Class KeyAccess: accès à une valeur d'une clé dans un tableau
*/
class KeyAccess extends AbstractAccess {
function __construct(&$array, $key, ?array $params=null) {
parent::__construct($params);
$this->array =& $array;
$this->key = $key;
$this->allowNull = $params["allow_null"] ?? true;
$this->allowFalse = $params["allow_false"] ?? false;
}
/** @var array|ArrayAccess */
protected $array;
/** @var int|string|array */
protected $key;
protected bool $allowNull;
protected bool $allowFalse;
function reset(&$array): self {
$this->array =& $array;
return $this;
}
function exists(): bool {
$key = $this->key;
if ($key === null) return false;
return cl::phas($this->array, $key);
}
function available(): bool {
if (!$this->exists()) return false;
$value = cl::pget($this->array, $this->key);
if ($value === "") return $this->allowEmpty;
if ($value === null) return $this->allowNull;
if ($value === false) return $this->allowFalse;
return true;
}
function get($default=null) {
if ($this->key === null) return $default;
$value = cl::pget($this->array, $this->key, $default);
if ($value === "" && !$this->allowEmpty) return $default;
if ($value === null && !$this->allowNull) return $default;
if ($value === false && !$this->allowFalse) return $default;
return $value;
}
function set($value): void {
if ($this->key === null) return;
cl::pset($this->array, $this->key, $value);
}
function del(): void {
if ($this->key === null) return;
cl::pdel($this->array, $this->key);
}
function addKey($key): self {
return new KeyAccess($this->array, cl::merge($this->key, $key), [
"allow_empty" => $this->allowEmpty,
"allow_null" => $this->allowNull,
"allow_false" => $this->allowFalse,
]);
}
}