nur-sery/wip/php/access/FormAccess.php

74 lines
1.8 KiB
PHP

<?php
namespace nur\sery\wip\php\access;
use nur\sery\cl;
/**
* Class FormAccess: accès à une valeur de $_POST puis $_GET, dans cet ordre
*/
class FormAccess extends AbstractAccess {
function __construct($key, ?array $params=null) {
$this->key = $key;
$this->allowEmpty = $params["allow_empty"] ?? false;
}
/** @var int|string */
protected $key;
protected bool $allowEmpty;
function exists(): bool {
$key = $this->key;
if ($key === null) return false;
return array_key_exists($key, $_POST) || array_key_exists($key, $_GET);
}
public function available(): bool {
$key = $this->key;
if ($key === null) return false;
if (array_key_exists($key, $_POST)) {
return $this->allowEmpty || $_POST[$key] !== "";
} elseif (array_key_exists($key, $_GET)) {
return $this->allowEmpty || $_GET[$key] !== "";
} else {
return false;
}
}
function get($default=null) {
$key = $this->key;
if ($key === null) return $default;
if (array_key_exists($key, $_POST)) {
$value = $_POST[$key];
if ($value === "" && !$this->allowEmpty) return $default;
return $value;
} elseif (array_key_exists($key, $_GET)) {
$value = $_GET[$key];
if ($value === "" && !$this->allowEmpty) return $default;
return $value;
} else {
return $default;
}
}
function set($value): void {
$key = $this->key;
if ($key === null) return;
if (!array_key_exists($key, $_POST) && array_key_exists($key, $_GET)) {
cl::set($_GET, $key, $value);
} else {
cl::set($_POST, $key, $value);
}
}
function del(): void {
$key = $this->key;
if ($key === null) return;
if (!array_key_exists($key, $_POST) && array_key_exists($key, $_GET)) {
cl::del($_GET, $key);
} else {
cl::del($_POST, $key);
}
}
}