Request.php

<?php

namespace Lia\Obj;

/**
 * A simple object to represent a web request
 */
class Request {
    
    /*
     * Info about WHAT is being requested (never WHO):
     * - url
     * - queryString
     * - query paramaters
     * - post paramaters
     * - POST vs GET vs PUT vs whatever
     * - headers
     * - cookies
     */
    
    
    /**
     * $_GET or $_POST params or null, depending on the request method.
     */
    protected $data;
    /**
     * Url Path (no query string, no domain)
     */
    protected $url;
    /**
     * The method, GET, POST, PUT, etc
     */
    protected $method;

    /**
     * @param $url a url. Query string is discarded
     * @param $method HTTP verb like GET, POST, PUT, etc
     */
    public function __construct($url=null, $method=null){
        $url = $url ?? $_SERVER['REQUEST_URI'];// ?? '/';
        $this->url = parse_url($url, PHP_URL_PATH);
        
        $method = $method ?? $_SERVER['REQUEST_METHOD'] ?? 'GET';// ?? 'GET';
        if (strtoupper($method)=='GET'){
            $this->data = $_GET;
        } else if (strtoupper($method)=='POST'){
            $this->data = $_POST;
        }
        $this->method = strtoupper($method);
    }
    
    /**
     * Get the url
     */
    public function url(): string{
        return $this->url;
    }
    /**
     * Get the request method (GET, PUT, POST, etc)
     */
    public function method(): string {
        return $this->method;
    }
    /**
     * Get the request data (from `$_GET` or `$_POST` or null)
     */
    public function data(): array {
        return $this->data;
    }
}