Request.php

<?php

namespace Lia\Http;

/**
 * A value-object to represent a web request.
 */
class Request {
    
    
    /**
     * $_GET or $_POST params or null, depending on the request method.
     */
    public readonly array $data;
    /**
     * Url Path (no query string, no domain)
     */
    public readonly string $url;
    /**
     * The method, GET, POST, PUT, etc
     */
    public readonly string $method;

    /**
     * Create an HTTP Request.
     *
     * @param $url string url. 
     * @param $method ?string "GET" or "POST" or null to use $_SERVER['REQUEST_METHOD']
     * @param $data ?array of request data or null to use $_GET or $_POST, as determined by the $method.
     */
    public function __construct(?string $url = null, ?string $method=null, ?array $data = null){
        $url = $url ?? $_SERVER['REQUEST_URI'];
        $this->url = parse_url($url, PHP_URL_PATH);
        
        $this->method = strtoupper(
            $method ?? $_SERVER['REQUEST_METHOD'] ?? 'GET'
        );
        $this->data = $data ?? 
            $this->method=='GET'
                ? $_GET 
                : ($this->method=='POST' 
                ? $_POST 
                : []);
    }
    
}