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

74 lines
1.8 KiB
PHP
Raw Normal View History

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