index/src/Http/Content/FormContent.php

59 lines
1.7 KiB
PHP

<?php
// FormContent.php
// Created: 2022-02-10
// Updated: 2023-08-21
namespace Index\Http\Content;
use RuntimeException;
use Index\Http\HttpUploadedFile;
class FormContent implements IHttpContent {
private array $postFields;
private array $uploadedFiles;
public function __construct(array $postFields, array $uploadedFiles) {
$this->postFields = $postFields;
$this->uploadedFiles = $uploadedFiles;
}
public function getParam(string $name, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed {
if(!isset($this->postFields[$name]))
return null;
return filter_var($this->postFields[$name] ?? null, $filter, $options);
}
public function hasParam(string $name): bool {
return isset($this->postFields[$name]);
}
public function getParams(): array {
return $this->postFields;
}
public function getParamString(bool $spacesAsPlus = false): string {
return http_build_query($this->postFields, '', '&', $spacesAsPlus ? PHP_QUERY_RFC1738 : PHP_QUERY_RFC3986);
}
public function getUploadedFile(string $name): HttpUploadedFile {
if(!isset($this->uploadedFiles[$name]))
throw new RuntimeException('No file with name $name present.');
return $this->uploadedFiles[$name];
}
public static function fromRaw(array $post, array $files): FormContent {
return new FormContent(
$post,
HttpUploadedFile::createFromFILES($files)
);
}
public static function fromRequest(): FormContent {
return self::fromRaw($_POST, $_FILES);
}
public function __toString(): string {
return $this->getParamString();
}
}