Initial commit
This commit is contained in:
102
backend/app/Core/Request.php
Normal file
102
backend/app/Core/Request.php
Normal file
@@ -0,0 +1,102 @@
|
||||
<?php
|
||||
|
||||
namespace App\Core;
|
||||
|
||||
/**
|
||||
* Handles HTTP requests, extracting query params, body data, and headers.
|
||||
*/
|
||||
class Request
|
||||
{
|
||||
private string $method;
|
||||
private string $path;
|
||||
private array $queryParams;
|
||||
private array $bodyParams;
|
||||
private array $headers;
|
||||
|
||||
public function __construct()
|
||||
{
|
||||
$this->method = strtoupper($_SERVER['REQUEST_METHOD'] ?? 'GET');
|
||||
|
||||
// Extract clean path without query parameters
|
||||
$uri = $_SERVER['REQUEST_URI'] ?? '/';
|
||||
$path = explode('?', $uri)[0];
|
||||
$this->path = '/' . trim($path, '/');
|
||||
|
||||
$this->queryParams = $_GET;
|
||||
$this->headers = $this->extractHeaders();
|
||||
$this->bodyParams = $this->parseBody();
|
||||
}
|
||||
|
||||
public function getMethod(): string
|
||||
{
|
||||
return $this->method;
|
||||
}
|
||||
|
||||
public function getPath(): string
|
||||
{
|
||||
return $this->path;
|
||||
}
|
||||
|
||||
public function getQueryParams(): array
|
||||
{
|
||||
return $this->queryParams;
|
||||
}
|
||||
|
||||
public function getQuery(string $key, $default = null)
|
||||
{
|
||||
return $this->queryParams[$key] ?? $default;
|
||||
}
|
||||
|
||||
public function getBody(): array
|
||||
{
|
||||
return $this->bodyParams;
|
||||
}
|
||||
|
||||
public function get(string $key, $default = null)
|
||||
{
|
||||
return $this->bodyParams[$key] ?? ($this->queryParams[$key] ?? $default);
|
||||
}
|
||||
|
||||
public function getHeaders(): array
|
||||
{
|
||||
return $this->headers;
|
||||
}
|
||||
|
||||
public function getHeader(string $key, $default = null): ?string
|
||||
{
|
||||
$keyLower = strtolower($key);
|
||||
return $this->headers[$keyLower] ?? $default;
|
||||
}
|
||||
|
||||
private function extractHeaders(): array
|
||||
{
|
||||
$headers = [];
|
||||
foreach ($_SERVER as $name => $value) {
|
||||
if (substr($name, 0, 5) == 'HTTP_') {
|
||||
$headers[strtolower(str_replace('_', '-', substr($name, 5)))] = $value;
|
||||
} elseif ($name == 'CONTENT_TYPE') {
|
||||
$headers['content-type'] = $value;
|
||||
} elseif ($name == 'CONTENT_LENGTH') {
|
||||
$headers['content-length'] = $value;
|
||||
}
|
||||
}
|
||||
return $headers;
|
||||
}
|
||||
|
||||
private function parseBody(): array
|
||||
{
|
||||
if ($this->method === 'GET') {
|
||||
return [];
|
||||
}
|
||||
|
||||
$contentType = $this->getHeader('content-type', '');
|
||||
|
||||
if (strpos($contentType, 'application/json') !== false) {
|
||||
$input = file_get_contents('php://input');
|
||||
$data = json_decode($input, true);
|
||||
return is_array($data) ? $data : [];
|
||||
}
|
||||
|
||||
return $_POST;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user