picea-ui/src/Method/FormContext.php
2024-06-04 13:34:31 +00:00

156 lines
3.5 KiB
PHP

<?php
namespace Picea\Ui\Method;
use Psr\Http\Message\ServerRequestInterface,
Psr\Http\Message\ResponseInterface;
class FormContext implements FormContextInterface
{
public string $method;
public string $formName;
public bool $formSent = false;
public bool $formExecuted = false;
public mixed $formExecutionStatus = null;
public array $values = [];
public array $files = [];
public array $messages = [];
public bool $skipCsrf = false;
protected array $catchedMethods = [ 'POST', 'PUT', 'PATCH', 'DELETE', ];
public ServerRequestInterface $request;
public ? ResponseInterface $response = null;
public function __construct(ServerRequestInterface $request, ? string $formName = null)
{
$this->request = $request;
if ( $formName ) {
$this->formName = $formName;
}
$this->values = $request->getParsedBody() ?: [];
$this->method = $this->request->getMethod();
if ( ! $this->values ) {
$content = mb_convert_encoding((string) $request->getBody(), 'UTF-8');
if ( $content && ( $json = json_decode($content, true) ) ) {
$this->values = $json;
}
}
$this->fillValues();
$this->files = $request->getUploadedFiles() ?: [];
}
public function valid() : bool
{
foreach($this->messages as $message) {
if ( $message->isError() ) {
return false;
}
}
return true;
}
public function executed() : bool
{
return $this->formExecuted;
}
public function formSent() : bool
{
$valid = in_array($this->method, $this->catchedMethods);
if ( ! $this->skipCsrf && ($this->formName ?? false) ) {
$token = $this->get('picea-ui-form')[$this->formName] ?? false;
if ( $token ) {
if ($this->validateCsrfToken) {
$valid = in_array($token, $_SESSION["picea-ui.form:{$this->formName}"] ?? []);
}
else {
$valid = (bool) $token;
}
}
else {
$valid = false;
}
}
return $this->formSent = $valid;
}
public function requestMethod() : string
{
return $this->method;
}
public function __set($key, $value)
{
return $this->set($key, $value);
}
public function __get($key)
{
return $this->get($key);
}
public function __isset($key)
{
return array_key_exists($key, $this->values);
}
public function __unset($key)
{
$this->delete($key);
}
public function get(string $key, $default = null)
{
return $this->has($key) ? $this->values[$key] : $default;
}
public function set(string $key, $value)
{
return $this->values[$key] = $value;
}
public function delete(string $key) : void
{
unset($this->values[$key]);
}
public function has(string $key) : bool
{
return array_key_exists($key, $this->values);
}
public function pushMessage(FormMessage $message) : void
{
$this->messages[] = $message;
}
protected function fillValues() : void
{
foreach($this->values as $property => $value) {
if (property_exists($this, $property)) {
$this->$property = $value;
}
}
}
}