You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
57 lines
1.7 KiB
57 lines
1.7 KiB
<?php declare(strict_types=1);
|
|
|
|
namespace massivedynamic\lucidity\services;
|
|
|
|
use massivedynamic\lucidity\RequestType;
|
|
use massivedynamic\lucidity\Utils;
|
|
use massivedynamic\lucidity\services\Service;
|
|
use massivedynamic\lucidity\validators\Validator;
|
|
|
|
class Request implements Service {
|
|
public readonly RequestType $type;
|
|
public readonly string $query;
|
|
/** @var array<string, string> */
|
|
private readonly array $get;
|
|
/** @var array<string, string> */
|
|
private readonly array $post;
|
|
|
|
public function __construct() {
|
|
$queryString = parse_url("/".ltrim($_SERVER["REQUEST_URI"], '/'), PHP_URL_PATH);
|
|
assert($queryString !== false, "unreachable");
|
|
|
|
$this->type = RequestType::tryFrom($_SERVER["REQUEST_METHOD"]) ?? RequestType::GET;
|
|
$this->query = !$queryString ? "" : $queryString;
|
|
$this->get = $_GET;
|
|
$this->post = $_POST;
|
|
}
|
|
|
|
/**
|
|
* @param array<string, array<string>> $attributes
|
|
*/
|
|
public function validate(array $attributes) : bool {
|
|
$validator = new Validator($this->all(), $attributes);
|
|
|
|
return $validator->validate() === null;
|
|
}
|
|
|
|
public function match(string $pattern) : bool {
|
|
$pattern = "/^".preg_replace("/\//", "\/", $pattern)."$/";
|
|
|
|
return preg_match($pattern, $this->query) === 1;
|
|
}
|
|
|
|
/**
|
|
* @return array<string, string>
|
|
*/
|
|
public function all() : array {
|
|
return $this->type === RequestType::POST ? $this->post : $this->get;
|
|
}
|
|
|
|
public function get(string $key, ?string $defaultValue = null) : ?string {
|
|
return isset($this->get[$key]) ? $this->get[$key] : $defaultValue;
|
|
}
|
|
|
|
public function post(string $key, ?string $defaultValue = null) : ?string {
|
|
return isset($this->post[$key]) ? $this->post[$key] : $defaultValue;
|
|
}
|
|
}
|
|
|