83 lines
2.7 KiB
PHP
83 lines
2.7 KiB
PHP
<?php
|
|
namespace Patchouli\Http;
|
|
|
|
class HttpRequest {
|
|
private string $method;
|
|
private string $path;
|
|
|
|
private array $serverParams;
|
|
private array $queryParams;
|
|
private array $postParams;
|
|
|
|
public function __construct(array $server, array $query, array $post) {
|
|
$this->method = $server['REQUEST_METHOD'];
|
|
$this->path = '/' . trim(parse_url($server['REQUEST_URI'], PHP_URL_PATH), '/');
|
|
$this->serverParams = $server;
|
|
$this->queryParams = $query;
|
|
$this->postParams = $post;
|
|
}
|
|
|
|
public static function create(): self {
|
|
return new static($_SERVER, $_GET, $_POST);
|
|
}
|
|
|
|
public function getMethod(): string {
|
|
return $this->method;
|
|
}
|
|
public function isMethod(string|array $method): bool {
|
|
if(is_string($method))
|
|
return $this->method === $method;
|
|
return in_array($this->method, $method);
|
|
}
|
|
|
|
public function getPath(): string {
|
|
return $this->path;
|
|
}
|
|
public function isPath(string $path): bool {
|
|
return $this->path === $path;
|
|
}
|
|
public function matchPath(string $regex, ?array &$args = null): bool {
|
|
if(!preg_match($regex, $this->path, $matches))
|
|
return false;
|
|
$args = array_slice($matches, 1);
|
|
return true;
|
|
}
|
|
|
|
public function match(string|array $method, string $path, ?array &$args = null): bool {
|
|
if(!$this->isMethod($method))
|
|
return false;
|
|
if($path[0] === '/')
|
|
return $this->isPath($path);
|
|
return $this->matchPath($path, $args);
|
|
}
|
|
|
|
public function getHeader($name): string {
|
|
$name = strtr(strtoupper($name), '-', '_');
|
|
if($name === 'CONTENT_LENGTH' || $name === 'CONTENT_LENGTH')
|
|
return $this->serverParams[$name];
|
|
return $this->serverParams['HTTP_' . $name] ?? '';
|
|
}
|
|
|
|
public function getServerParam(string $name): string {
|
|
return $this->serverParams[$name] ?? '';
|
|
}
|
|
|
|
public function getBody(): string {
|
|
return file_get_contents('php://input');
|
|
}
|
|
|
|
public function getQueryParams(): array {
|
|
return $this->queryParams;
|
|
}
|
|
public function getQueryParam(string $name, int $filter = FILTER_DEFAULT, mixed $options = null): mixed {
|
|
return filter_var($this->queryParams[$name] ?? null, $filter, $options);
|
|
}
|
|
|
|
public function getPostParams(): array {
|
|
return $this->postParams;
|
|
}
|
|
public function getPostParam(string $name, int $filter = FILTER_DEFAULT, mixed $options = null): mixed {
|
|
return filter_var($this->postParams[$name] ?? null, $filter, $options);
|
|
}
|
|
}
|