Files
madar/app/Http/Request.php
T
2026-09-05 15:54:33 +03:30

64 lines
2.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Http;
final class Request
{
public function __construct(private readonly array $server)
{
}
public static function capture(): self
{
return new self($_SERVER);
}
public function isHttps(): bool
{
return (!empty($this->server['HTTPS']) && $this->server['HTTPS'] !== 'off')
|| ($this->server['SERVER_PORT'] ?? '') == 443;
}
public function ip(): string
{
// Forwarded headers are not trusted; configure proxies at the web server.
return $this->server['REMOTE_ADDR'] ?? '';
}
public function requireSecurePost(bool $allowLocalHttp, string $csrf): void
{
if (($this->server['REQUEST_METHOD'] ?? '') !== 'POST') {
header('Allow: POST');
throw new HttpException('فقط درخواست POST پذیرفته می‌شود.', 405);
}
$loopback = in_array($this->ip(), ['127.0.0.1', '::1'], true);
if (!$this->isHttps() && !($allowLocalHttp && $loopback)) {
throw new HttpException('برای ورود امن از آدرس HTTPS استفاده کنید.', 403);
}
if (!hash_equals($csrf, $this->server['HTTP_X_CSRF_TOKEN'] ?? '')) {
throw new HttpException('نشست مرورگر معتبر نیست؛ صفحه را تازه کنید.', 403);
}
}
public function json(): array
{
if (!str_starts_with(strtolower($this->server['CONTENT_TYPE'] ?? ''), 'application/json')) {
throw new HttpException('نوع درخواست باید JSON باشد.', 415);
}
$raw = file_get_contents('php://input', false, null, 0, 20001);
if ($raw === false || strlen($raw) > 20000) {
throw new HttpException('درخواست بیش از حد بزرگ است.', 413);
}
try {
$body = json_decode($raw, true, 32, JSON_THROW_ON_ERROR);
} catch (\JsonException $error) {
throw new HttpException('ساختار JSON معتبر نیست.', 400);
}
if (!is_array($body)) {
throw new HttpException('درخواست معتبر نیست.');
}
return $body;
}
}