From 47cd93fd51c9ac033ae4d5ee4c6eab455ec62b02 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:46:10 +0000 Subject: [PATCH 001/129] :fire: remove constructor --- src/Response.php | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/src/Response.php b/src/Response.php index 61ef5e1..a1f78ac 100755 --- a/src/Response.php +++ b/src/Response.php @@ -19,11 +19,6 @@ class Response */ protected static $status; - /** - * @var \Leaf\Http\Headers - */ - public static $headers; - /** * @var array HTTP response codes and messages */ @@ -87,12 +82,6 @@ class Response 511 => '511 Network Authentication Required' ]; - public function __construct() - { - static::$headers = Headers::class; - Headers::contentHtml(); - } - /** * Output plain text * From a9cabbdb7a4ba9882319890cdb7fd580a4a6ed1c Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:47:20 +0000 Subject: [PATCH 002/129] :fire: remove cors method --- src/Response.php | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/Response.php b/src/Response.php index a1f78ac..8ee0fee 100755 --- a/src/Response.php +++ b/src/Response.php @@ -106,7 +106,6 @@ public static function xml($data, int $code = 200) echo $data; } - /** * Output json encoded data with an HTTP code/message * @@ -131,7 +130,6 @@ public static function json($data, int $code = 200, bool $showCode = false, bool echo json_encode($dataToPrint); } - /** * Output plain text * @@ -184,11 +182,6 @@ public static function markup(String $markup, int $code = null) EOT; } - public static function cors(String $allow_origin = "*", String $allow_headers = "*") - { - Headers::accessControl(["Allow-Origin" => $allow_origin, "Allow-Headers" => $allow_headers]); - } - /** * Get and set header * From 795e927492e9326fc6cec662f267e34d9b4a3cfe Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:48:01 +0000 Subject: [PATCH 003/129] :sparkles: added withHeader method --- src/Response.php | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/Response.php b/src/Response.php index 8ee0fee..32c6579 100755 --- a/src/Response.php +++ b/src/Response.php @@ -183,16 +183,15 @@ public static function markup(String $markup, int $code = null) } /** - * Get and set header + * set header * - * @param string $name Header name + * @param string|array $name Header name * @param string|null $value Header value - * @return string Header value */ - public static function header(string $name, string $value = null): string + public function withHeader($name, ?string $value = '', $replace = true, int $httpCode = 200) { - if (!is_null($value)) Headers::set($name, $value); - return Headers::get($name); + Headers::set($name, $value, $replace, $httpCode); + return $this; } /** From 076a2778e5ff9e1ec33be6a9117cce45edda2df0 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:48:49 +0000 Subject: [PATCH 004/129] :sparkles: added return this for status --- src/Response.php | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Response.php b/src/Response.php index 32c6579..340a624 100755 --- a/src/Response.php +++ b/src/Response.php @@ -197,9 +197,10 @@ public function withHeader($name, ?string $value = '', $replace = true, int $htt /** * Set HTTP status code */ - public static function status($code = null) + public function status($code = null) { - return Headers::status($code); + Headers::status($code); + return $this; } /** From 508c67035936a0067c3b6ba2440d75dd1a47f9a5 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:50:56 +0000 Subject: [PATCH 005/129] :sparkles: swapped out cookie methods --- src/Response.php | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/Response.php b/src/Response.php index 340a624..837d0fe 100755 --- a/src/Response.php +++ b/src/Response.php @@ -203,20 +203,6 @@ public function status($code = null) return $this; } - /** - * Set cookie - * - * Set a new cookie - * - * @param string|array $name The name of the cookie - * @param string $value If string, the value of cookie - * @param array $options Settings for cookie - */ - public static function setCookie($name, string $value, array $options = []) - { - Cookie::set($name, $value, $options); - } - /** * Shorthand method of setting a cookie + value + expire time * @@ -224,9 +210,16 @@ public static function setCookie($name, string $value, array $options = []) * @param string $value The value of cookie * @param string $expire When the cookie expires. Default: 7 days */ - public static function simpleCookie(string $name, string $value, string $expire = "7 days") + public function withCookie(string $name, string $value, string $expire = "7 days") { + if (!class_exists('Leaf\Http\Cookie')) { + Headers::contentHtml(); + trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); + } + Cookie::simpleCookie($name, $value, $expire); + + return $this; } /** @@ -234,9 +227,16 @@ public static function simpleCookie(string $name, string $value, string $expire * * @param string $name The name of the cookie */ - public static function deleteCookie(string $name) + public function withoutCookie(string $name) { + if (!class_exists('Leaf\Http\Cookie')) { + Headers::contentHtml(); + trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); + } + Cookie::unset($name); + + return $this; } /** From d3c702647c3af1b6e4cbe0ac1efa377162b0160e Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:52:35 +0000 Subject: [PATCH 006/129] :sparkles: added status code helper --- src/Status.php | 153 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 153 insertions(+) create mode 100644 src/Status.php diff --git a/src/Status.php b/src/Status.php new file mode 100644 index 0000000..e0dda58 --- /dev/null +++ b/src/Status.php @@ -0,0 +1,153 @@ + + * + * @var array + */ + public static $statusTexts = [ + 100 => 'Continue', + 101 => 'Switching Protocols', + 102 => 'Processing', // RFC2518 + 103 => 'Early Hints', + 200 => 'OK', + 201 => 'Created', + 202 => 'Accepted', + 203 => 'Non-Authoritative Information', + 204 => 'No Content', + 205 => 'Reset Content', + 206 => 'Partial Content', + 207 => 'Multi-Status', // RFC4918 + 208 => 'Already Reported', // RFC5842 + 226 => 'IM Used', // RFC3229 + 300 => 'Multiple Choices', + 301 => 'Moved Permanently', + 302 => 'Found', + 303 => 'See Other', + 304 => 'Not Modified', + 305 => 'Use Proxy', + 307 => 'Temporary Redirect', + 308 => 'Permanent Redirect', // RFC7238 + 400 => 'Bad Request', + 401 => 'Unauthorized', + 402 => 'Payment Required', + 403 => 'Forbidden', + 404 => 'Not Found', + 405 => 'Method Not Allowed', + 406 => 'Not Acceptable', + 407 => 'Proxy Authentication Required', + 408 => 'Request Timeout', + 409 => 'Conflict', + 410 => 'Gone', + 411 => 'Length Required', + 412 => 'Precondition Failed', + 413 => 'Content Too Large', // RFC-ietf-httpbis-semantics + 414 => 'URI Too Long', + 415 => 'Unsupported Media Type', + 416 => 'Range Not Satisfiable', + 417 => 'Expectation Failed', + 418 => 'I\'m a teapot', // RFC2324 + 421 => 'Misdirected Request', // RFC7540 + 422 => 'Unprocessable Content', // RFC-ietf-httpbis-semantics + 423 => 'Locked', // RFC4918 + 424 => 'Failed Dependency', // RFC4918 + 425 => 'Too Early', // RFC-ietf-httpbis-replay-04 + 426 => 'Upgrade Required', // RFC2817 + 428 => 'Precondition Required', // RFC6585 + 429 => 'Too Many Requests', // RFC6585 + 431 => 'Request Header Fields Too Large', // RFC6585 + 451 => 'Unavailable For Legal Reasons', // RFC7725 + 500 => 'Internal Server Error', + 501 => 'Not Implemented', + 502 => 'Bad Gateway', + 503 => 'Service Unavailable', + 504 => 'Gateway Timeout', + 505 => 'HTTP Version Not Supported', + 506 => 'Variant Also Negotiates', // RFC2295 + 507 => 'Insufficient Storage', // RFC4918 + 508 => 'Loop Detected', // RFC5842 + 510 => 'Not Extended', // RFC2774 + 511 => 'Network Authentication Required', // RFC6585 + ]; +} From f46118f8771344b6e94cb7344065a6f2997b097f Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 20:53:40 +0000 Subject: [PATCH 007/129] :sparkles: added withFlash method --- src/Response.php | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/Response.php b/src/Response.php index 837d0fe..fec2818 100755 --- a/src/Response.php +++ b/src/Response.php @@ -239,6 +239,30 @@ public function withoutCookie(string $name) return $this; } + /** + * Flash a piece of data to the session. + * + * @param string|array $name The key of the item to set + * @param string $value The value of flash item + */ + public function withFlash($key, string $value) + { + if (!class_exists('Leaf\Http\Session')) { + Headers::contentHtml(); + trigger_error('Leaf session not found. Run `leaf install session` or `composer require leafs/session`'); + } + + if (is_array($key)) { + foreach ($key as $k => $v) { + $this->withFlash($k, $v); + } + } + + \Leaf\Flash::set($key, $value); + + return $this; + } + /** * Redirect * From 39c8d6e3933dff260a3bec7ba34699c5abc84079 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 21:06:22 +0000 Subject: [PATCH 008/129] :sparkles: added base for restructure --- src/Response.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index fec2818..7698842 100755 --- a/src/Response.php +++ b/src/Response.php @@ -14,10 +14,15 @@ */ class Response { + /** + * @var array + */ + public $headers = []; + /** * @var int HTTP status code */ - protected static $status; + protected static $status = 200; /** * @var array HTTP response codes and messages From 1100cf2d55baf342e2f7e13801d1c8aab5de2c3a Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 May 2022 21:24:15 +0000 Subject: [PATCH 009/129] =?UTF-8?q?=F0=9F=8F=97=EF=B8=8F=20create=20founda?= =?UTF-8?q?tion=20for=20restructure?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Response.php | 124 +++++++++++++++++------------------------------ 1 file changed, 44 insertions(+), 80 deletions(-) diff --git a/src/Response.php b/src/Response.php index 7698842..5dc4277 100755 --- a/src/Response.php +++ b/src/Response.php @@ -20,72 +20,14 @@ class Response public $headers = []; /** - * @var int HTTP status code + * @var string */ - protected static $status = 200; + protected $content = ''; /** - * @var array HTTP response codes and messages + * @var int HTTP status code */ - protected static $messages = [ - //Informational 1xx - 100 => '100 Continue', - 101 => '101 Switching Protocols', - //Successful 2xx - 200 => '200 OK', - 201 => '201 Created', - 202 => '202 Accepted', - 203 => '203 Non-Authoritative Information', - 204 => '204 No Content', - 205 => '205 Reset Content', - 206 => '206 Partial Content', - 226 => '226 IM Used', - //Redirection 3xx - 300 => '300 Multiple Choices', - 301 => '301 Moved Permanently', - 302 => '302 Found', - 303 => '303 See Other', - 304 => '304 Not Modified', - 305 => '305 Use Proxy', - 306 => '306 (Unused)', - 307 => '307 Temporary Redirect', - //Client Error 4xx - 400 => '400 Bad Request', - 401 => '401 Unauthorized', - 402 => '402 Payment Required', - 403 => '403 Forbidden', - 404 => '404 Not Found', - 405 => '405 Method Not Allowed', - 406 => '406 Not Acceptable', - 407 => '407 Proxy Authentication Required', - 408 => '408 Request Timeout', - 409 => '409 Conflict', - 410 => '410 Gone', - 411 => '411 Length Required', - 412 => '412 Precondition Failed', - 413 => '413 Request Entity Too Large', - 414 => '414 Request-URI Too Long', - 415 => '415 Unsupported Media Type', - 416 => '416 Requested Range Not Satisfiable', - 417 => '417 Expectation Failed', - 418 => '418 I\'m a teapot', - 422 => '422 Unprocessable Entity', - 423 => '423 Locked', - 426 => '426 Upgrade Required', - 428 => '428 Precondition Required', - 429 => '429 Too Many Requests', - 431 => '431 Request Header Fields Too Large', - //Server Error 5xx - 500 => '500 Internal Server Error', - 501 => '501 Not Implemented', - 502 => '502 Bad Gateway', - 503 => '503 Service Unavailable', - 504 => '504 Gateway Timeout', - 505 => '505 HTTP Version Not Supported', - 506 => '506 Variant Also Negotiates', - 510 => '510 Not Extended', - 511 => '511 Network Authentication Required' - ]; + protected static $status = 200; /** * Output plain text @@ -93,10 +35,13 @@ class Response * @param mixed $data The data to output * @param int $code The response status code */ - public static function plain($data, int $code = 200) + public function plain($data, int $code = 200) { - Headers::contentPlain($code); - echo $data; + $this->status = $code; + $this->headers['Content-Type'] = 'text/plain'; + $this->content = $data; + + return $this; } /** @@ -105,10 +50,13 @@ public static function plain($data, int $code = 200) * @param string $data The data to output * @param int $code The response status code */ - public static function xml($data, int $code = 200) + public function xml($data, int $code = 200) { - Headers::contentXml($code); - echo $data; + $this->status = $code; + $this->headers['Content-Type'] = 'application/xml'; + $this->content = $data; + + return $this; } /** @@ -145,6 +93,7 @@ public static function json($data, int $code = 200, bool $showCode = false, bool public static function download(string $file, string $name = null, int $code = 200) { if (!file_exists($file)) { + Headers::contentHtml(); trigger_error("$file not found. Confirm your file path."); } @@ -161,30 +110,45 @@ public static function download(string $file, string $name = null, int $code = 2 } /** - * Throw an error and break the application + * Output some data and break the application + * + * @param mixed $error The data to output + * @param int $code The Http status code */ - public static function throwErr($error, int $code = 500, bool $useMessage = false) + public function exit($error, int $code = 500) { - $dataToPrint = ["error" => $error, "code" => $code]; - if ($useMessage) $dataToPrint = ["error" => $error, "message" => self::$messages[$code] ?? $code]; + $this->status = $code; + + if (is_array($error)) { + $this->headers['Content-Type'] = 'application/json'; + $this->content = json_encode($error); + } else { + $this->content = $error; + } + + $this->send(); - Headers::contentJSON($code); - echo json_encode($dataToPrint); exit(); } - public static function page(string $file, int $code = null) + public function page(string $file, int $code = null) { - Headers::contentHtml($code); - require $file; + $this->status = $code; + $this->headers['Content-Type'] = 'text/html'; + $this->content = require $file; + + return $this; } - public static function markup(String $markup, int $code = null) + public function markup(String $markup, int $code = null) { - Headers::contentHtml($code); - echo <<status = $code; + $this->headers['Content-Type'] = 'application/xml'; + $this->content = << Date: Sat, 14 May 2022 00:50:03 +0000 Subject: [PATCH 010/129] =?UTF-8?q?=F0=9F=92=A5=20update=20response?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Response.php | 221 +++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 185 insertions(+), 36 deletions(-) diff --git a/src/Response.php b/src/Response.php index 5dc4277..bd4ce24 100755 --- a/src/Response.php +++ b/src/Response.php @@ -27,7 +27,26 @@ class Response /** * @var int HTTP status code */ - protected static $status = 200; + protected $status = 200; + + /** + * @var string HTTP Version + */ + protected $version; + + /** + * Get/Set Http Version + */ + public function httpVersion(?string $version = null) + { + if (!$version || (is_string($version) && strlen($version) === 0)) { + return $this->version ?? $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1'; + } + + $this->version = 'HTTP/' . str_replace('HTTP/', '', $version); + + return $this; + } /** * Output plain text @@ -41,7 +60,7 @@ public function plain($data, int $code = 200) $this->headers['Content-Type'] = 'text/plain'; $this->content = $data; - return $this; + $this->send(); } /** @@ -56,7 +75,7 @@ public function xml($data, int $code = 200) $this->headers['Content-Type'] = 'application/xml'; $this->content = $data; - return $this; + $this->send(); } /** @@ -67,20 +86,24 @@ public function xml($data, int $code = 200) * @param bool $showCode Show response code in body? * @param bool $useMessage Show message instead of code */ - public static function json($data, int $code = 200, bool $showCode = false, bool $useMessage = false) + public function json($data, int $code = 200, bool $showCode = false, bool $useMessage = false) { + $this->status = $code; + if ($showCode) { - $dataToPrint = ["data" => $data, "code" => $code]; + $dataToPrint = ['data' => $data, 'code' => $code]; if ($useMessage) { - $dataToPrint = ["data" => $data, "message" => self::$messages[$code] ?? $code]; + $dataToPrint = ['data' => $data, 'message' => Status::$statusTexts[$code] ?? 'unknown status']; } } else { $dataToPrint = $data; } - Headers::contentJSON($code); - echo json_encode($dataToPrint); + $this->headers['Content-Type'] = 'application/json'; + $this->content = json_encode($dataToPrint); + + $this->send(); } /** @@ -90,40 +113,42 @@ public static function json($data, int $code = 200, bool $showCode = false, bool * @param string|null $name The of the file as shown to user * @param int $code The response status code */ - public static function download(string $file, string $name = null, int $code = 200) + public function download(string $file, string $name = null, int $code = 200) { + $this->status = $code; + if (!file_exists($file)) { Headers::contentHtml(); trigger_error("$file not found. Confirm your file path."); } - + if ($name === null) $name = basename($file); - Headers::status($code); - Headers::set([ + $this->headers = array_merge($this->headers, [ 'Content-Length' => filesize($file), 'Content-Disposition' => "attachment; filename=$name", ]); - - readfile($file); - exit; + + $this->content = $file; + + $this->send(); } /** * Output some data and break the application * - * @param mixed $error The data to output + * @param mixed $data The data to output * @param int $code The Http status code */ - public function exit($error, int $code = 500) + public function exit($data, int $code = 500) { $this->status = $code; - if (is_array($error)) { + if (is_array($data)) { $this->headers['Content-Type'] = 'application/json'; - $this->content = json_encode($error); + $this->content = json_encode($data); } else { - $this->content = $error; + $this->content = $data; } $this->send(); @@ -131,23 +156,32 @@ public function exit($error, int $code = 500) exit(); } - public function page(string $file, int $code = null) + public function page(string $file, int $code = 200) { $this->status = $code; $this->headers['Content-Type'] = 'text/html'; $this->content = require $file; - return $this; + $this->send(); } - public function markup(String $markup, int $code = null) + public function markup(String $markup, int $code = 200) { $this->status = $code; - $this->headers['Content-Type'] = 'application/xml'; + $this->headers['Content-Type'] = 'text/html'; $this->content = <<send(); + } + + /** + * Set HTTP status code + */ + public function status($code = null) + { + Headers::status($code); return $this; } @@ -159,16 +193,20 @@ public function markup(String $markup, int $code = null) */ public function withHeader($name, ?string $value = '', $replace = true, int $httpCode = 200) { - Headers::set($name, $value, $replace, $httpCode); - return $this; - } + $this->status = $httpCode; + Headers::status($httpCode); + + if (is_array($name)) { + $this->headers = array_merge($this->headers, $name); + return $this; + } + + if ($replace === false || $httpCode !== 200) { + Headers::set($name, $value, $replace, $httpCode); + } else { + $this->headers[$name] = $value; + } - /** - * Set HTTP status code - */ - public function status($code = null) - { - Headers::status($code); return $this; } @@ -241,10 +279,21 @@ public function withFlash($key, string $value) * @param string $url The redirect destination * @param int $status The redirect HTTP status code */ - public static function redirect(string $url, int $status = 302) + public function redirect(string $url, int $status = 302) { Headers::status($status); - Headers::set('Location', $url); + Headers::set('Location', $url, true, $status); + } + + /** + * The HTTP 204 No Content success status response code indicates + * that a request has succeeded, but that the client doesn't + * need to navigate away from its current page. + */ + public function noContent() + { + $this->status = 204; + $this->send(); } /** @@ -255,6 +304,106 @@ public static function redirect(string $url, int $status = 302) */ public static function getMessageForCode(int $status): ?string { - return self::$messages[$status] ?? null; + return Status::$statusTexts[$status] ?? 'unknown status'; + } + + /** + * Sends HTTP headers. + * + * @param int $code The http status code to attach + * + * @return $this + */ + public function sendHeaders() + { + // headers have already been sent by the developer + if (headers_sent()) { + return $this; + } + + Headers::set($this->headers); + + // status + header(sprintf('%s %s %s', $this->httpVersion(), $this->status, Status::$statusTexts[$this->status]), true, $this->status); + + return $this; + } + + /** + * Sends content for the current web response. + * + * @param string $content The content to output + * + * @return $this + */ + public function sendContent() + { + if (strpos($this->headers['Content-Disposition'] ?? '', 'attachment') !== false) { + readfile($this->content); + } else { + echo $this->content; + } + + return $this; + } + + /** + * Send the Http headers and content + * + * @return $this + */ + public function send() + { + $this->sendHeaders()->sendContent(); + + if (\function_exists('fastcgi_finish_request')) { + fastcgi_finish_request(); + } elseif (\function_exists('litespeed_finish_request')) { + \litespeed_finish_request(); + } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { + $this->closeOutputBuffers(0, true); + } + } + + /** + * Cleans or flushes output buffers up to target level. + * + * Resulting level can be greater than target level if a non-removable buffer has been encountered. + * + * @final + */ + public static function closeOutputBuffers(int $targetLevel, bool $flush): void + { + $status = ob_get_status(true); + $level = \count($status); + $flags = \PHP_OUTPUT_HANDLER_REMOVABLE | ($flush ? \PHP_OUTPUT_HANDLER_FLUSHABLE : \PHP_OUTPUT_HANDLER_CLEANABLE); + + while ($level-- > $targetLevel && ($s = $status[$level]) && (!isset($s['del']) ? !isset($s['flags']) || ($s['flags'] & $flags) === $flags : $s['del'])) { + if ($flush) { + ob_end_flush(); + } else { + ob_end_clean(); + } + } + } + + /** + * Returns the Response as an HTTP string. + * + * The string representation of the Response is the same as the + * one that will be sent to the client only if the prepare() method + * has been called before. + * + * @return string + */ + public function __toString() + { + Headers::contentPlain(); + return + sprintf('%s %s %s', $this->httpVersion(), $this->status, Status::$statusTexts[$this->status]) . "\r\n" . + implode("", array_map(function ($key, $value) { + return sprintf("%s: %s\r\n", $key, $value); + }, array_keys($this->headers), array_values($this->headers))) . + $this->content; } } From 37d523e2dd348114d06afed4fe5ddf6bc75d3632 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 14:39:27 +0000 Subject: [PATCH 011/129] :sparkles: added functional mode cache --- src/functions.php | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/functions.php b/src/functions.php index 731c4d6..4567f05 100644 --- a/src/functions.php +++ b/src/functions.php @@ -9,6 +9,18 @@ function request($data = null) { if ($data !== null) return \Leaf\Http\Request::get($data); + + if (class_exists('\Leaf\Config')) { + $request = Leaf\Config::get("request")["instance"] ?? null; + + if (!$request) { + $request = new \Leaf\Http\Request; + Leaf\Config::set("request", ["instance" => $request]); + } + + return $request; + } + return new \Leaf\Http\Request(); } } @@ -22,6 +34,18 @@ function request($data = null) function response($data = null) { if ($data !== null) return \Leaf\Http\Response::json($data); + + if (class_exists('\Leaf\Config')) { + $response = Leaf\Config::get("response")["instance"] ?? null; + + if (!$response) { + $response = new \Leaf\Http\Response; + Leaf\Config::set("response", ["instance" => $response]); + } + + return $response; + } + return new \Leaf\Http\Response(); } } From 5acf357d0e6f5c1fa5e67cb212a9eb7a07914437 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 15:18:36 +0000 Subject: [PATCH 012/129] :memo: update readme --- README.md | 141 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 136 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 7ab4a4e..b383377 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@



-

Leaf HTTP Module

+

Leaf Http v2



@@ -12,16 +12,147 @@ [![Total Downloads](https://poser.pugx.org/leafs/http/downloads)](https://packagist.org/packages/leafs/http) [![License](https://poser.pugx.org/leafs/http/license)](https://packagist.org/packages/leafs/http) -Leaf's core http functionality packaged as a serve-yourself module. Although seperated from Leaf core, it is still part of the default initial installation and doesn't need to be installed manually (unless you want a particular version). +Leaf's core http functionality packaged as a serve-yourself module. **Although seperated from Leaf core, it is still part of the default initial installation and doesn't need to be installed manually (unless you want a particular version).** ## Installation -You can easily install Leaf using [Composer](https://getcomposer.org/). +You can easily install Leaf using the [Leaf CLI](https://cli.leafphp.dev) + +```sh +leaf install http +``` + +[Composer](https://getcomposer.org/). ```bash composer require leafs/http ``` -## View Leaf's docs [here](https://leafphp.netlify.app/#/) +## Basic Usage + +The http module comes with a bunch of packages which help you manage the input and output of your app or API. This module comes with the most used Http related functionality like requests, responses, ... + +The available classes in the Http module are: + +- [`Leaf\Http\Request`](https://leafphp.dev/modules/http/request) +- [`Leaf\Http\Response`](https://leafphp.dev/modules/http/response) +- [`Leaf\Http\Headers`](https://leafphp.dev/modules/http/headers) +- [`Leaf\Http\Cache`](https://leafphp.dev/modules/http/cache) +- [`Leaf\Http\Status`](https://leafphp.dev/modules/http/status) + +**The docs for Leaf Http v2 can be found at [https://leafphp.dev/modules/http/v1/](https://leafphp.dev/modules/http/v1/).** + +## Request + +This is a developer friendly interface which allows you to interact with data coming into your application. [Read the docs](https://leafphp.dev/modules/http/request) + +## Response + +This interface allows you to output data from your application in different forms. [Read the docs](https://leafphp.dev/modules/http/response) + +## Headers + +This interface allows you to manage headers in your application. [Read the docs](https://leafphp.dev/modules/http/headers) + +## Cache + +This interface allows you to manage http cache in your app. [Read the docs](https://leafphp.dev/modules/http/cache) + +## Status + +This interface allows you to manage http status codes in your app. [Read the docs](https://leafphp.dev/modules/http/status) + +**There are also some add on classes which can be installed on demand.** + +## Session (module) + +This module allows you to manage session in your application. [Read the docs](/modules/session/) + +## Cookies (module) + +This module allows you to manage cookies in your application. [Read the docs](/modules/cookies) + +## 💬 Stay In Touch + +- [Twitter](https://twitter.com/leafphp) +- [Join the forum](https://github.com/leafsphp/leaf/discussions/37) +- [Chat on discord](https://discord.com/invite/Pkrm9NJPE3) + +## 📓 Learning Leaf 3 + +- Leaf has a very easy to understand [documentation](https://leafphp.dev) which contains information on all operations in Leaf. +- You can also check out our [youtube channel](https://www.youtube.com/channel/UCllE-GsYy10RkxBUK0HIffw) which has video tutorials on different topics +- We are also working on codelabs which will bring hands-on tutorials you can follow and contribute to. + +## 😇 Contributing + +We are glad to have you. All contributions are welcome! To get started, familiarize yourself with our [contribution guide](https://leafphp.dev/community/contributing.html) and you'll be ready to make your first pull request 🚀. + +To report a security vulnerability, you can reach out to [@mychidarko](https://twitter.com/mychidarko) or [@leafphp](https://twitter.com/leafphp) on twitter. We will coordinate the fix and eventually commit the solution in this project. + +### Code contributors + + + + + + +
+ + +
+ + Michael Darko + +
+
+ + +
+ + Dreamer0x01 + +
+
+ +## 🤩 Sponsoring Leaf + +Your cash contributions go a long way to help us make Leaf even better for you. You can sponsor Leaf and any of our packages on [open collective](https://opencollective.com/leaf) or check the [contribution page](https://leafphp.dev/support/) for a list of ways to contribute. + +And to all our existing cash/code contributors, we love you all ❤️ + +### Cash contributors + + + + + + + +
+ + +
+ Aaron Smith +
+
+ + +
+ Peter Bogner +
+
+ + +
+ Vano +
+
+ +## 🤯 Links/Projects -Built with ❤ by [**Mychi Darko**](https://mychi.netlify.app) +- [Aloe CLI](https://leafphp.dev/aloe-cli/) +- [Leaf Docs](https://leafphp.dev) +- [Leaf MVC](https://mvc.leafphp.dev) +- [Leaf API](https://api.leafphp.dev) +- [Leaf CLI](https://cli.leafphp.dev) From f480f1cd855dd16b2c8a3563c767a3c17bab8844 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 15:24:34 +0000 Subject: [PATCH 013/129] :memo: update readme --- README.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/README.md b/README.md index b383377..f698ce3 100644 --- a/README.md +++ b/README.md @@ -146,6 +146,17 @@ And to all our existing cash/code contributors, we love you all ❤️ Vano + + + +
+ Casprine +
+ From 498a94e77c8513f309430ee113303a02a7063da7 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 16:47:39 +0000 Subject: [PATCH 014/129] :bookmark: update version --- src/Response.php | 1 + 1 file changed, 1 insertion(+) diff --git a/src/Response.php b/src/Response.php index bd4ce24..0e470ed 100755 --- a/src/Response.php +++ b/src/Response.php @@ -11,6 +11,7 @@ * * @author Michael Darko * @since 1.0.0 + * @version 2.0 */ class Response { From 83b0c59305f62d231b0fa9656d6335278e38e3b9 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 18:41:10 +0000 Subject: [PATCH 015/129] =?UTF-8?q?=F0=9F=8F=97=EF=B8=8F=20update=20intern?= =?UTF-8?q?als=20for=20better=20usability?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Request.php | 70 +++++++++++++++++++++++++------------------------ 1 file changed, 36 insertions(+), 34 deletions(-) diff --git a/src/Request.php b/src/Request.php index 784ba00..fc9c4c7 100755 --- a/src/Request.php +++ b/src/Request.php @@ -12,6 +12,7 @@ * * @author Michael Darko * @since 1.0.0 + * @version 2.0 */ class Request { @@ -29,29 +30,6 @@ class Request */ protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; - /** - * HTTP Headers - * @var Headers - */ - public static $headers; - - /** - * HTTP Cookies - */ - public static $cookies; - - /** - * The Request Body - */ - protected static $request; - - public function __construct() - { - $handler = fopen('php://input', 'r'); - static::$request = stream_get_contents($handler); - static::$headers = new Headers(); - } - /** * Get HTTP method * @return string @@ -80,7 +58,7 @@ public static function typeIs(string $type): bool */ public static function hasHeader(String $header): bool { - return !!static::$headers->get($header); + return !!Headers::get($header); } /** @@ -90,7 +68,8 @@ public static function hasHeader(String $header): bool public static function isAjax(): bool { if (static::params('isajax')) return true; - if (static::$headers->get('X_REQUESTED_WITH') && static::$headers->get('X_REQUESTED_WITH') === 'XMLHttpRequest') return true; + + if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') return true; return false; } @@ -104,6 +83,23 @@ public static function isXhr(): bool return static::isAjax(); } + /** + * Access stream that allows you to read raw data from the request body. **This is not for form data** + * + * @param boolean $safeData Sanitize data? + */ + public static function input($safeData = true) + { + $handler = fopen('php://input', 'r'); + $data = stream_get_contents($handler); + if (!$data) $data = json_encode([]); + + $parsedData = json_decode($data, true); + if (is_array($parsedData)) $data = $parsedData; + + return $safeData ? \Leaf\Anchor::sanitize($data) : $data; + } + /** * Fetch GET and POST data * @@ -186,8 +182,11 @@ public static function get($params, bool $safeData = true) */ public static function body(bool $safeData = true) { - $req = is_array(json_decode(static::$request, true)) ? json_decode(static::$request, true) : []; - return $safeData ? \Leaf\Anchor::sanitize(array_merge($_GET, $_FILES, $_POST, $req)) : array_merge($_GET, $_FILES, $_POST, $req); + $finalData = array_merge($_GET, $_FILES, $_POST, static::input($safeData)); + + return $safeData ? + \Leaf\Anchor::sanitize($finalData) : + $finalData; } /** @@ -218,7 +217,9 @@ public static function files($filenames = null) */ public static function cookies(string $key = null) { - return $key ? \Leaf\Http\Cookie::get($key) : \Leaf\Http\Cookie::all(); + return $key === null ? + Cookie::all() : + Cookie::get($key); } /** @@ -245,8 +246,9 @@ public static function isFormData(): bool */ public static function headers($key = null, bool $safeData = true) { - if ($key) return static::$headers->get($key, $safeData); - return static::$headers->all($safeData); + return ($key === null) ? + Headers::all($safeData) : + Headers::get($key, $safeData); } /** @@ -255,7 +257,7 @@ public static function headers($key = null, bool $safeData = true) */ public static function getContentType(): ?string { - return static::$headers->get('CONTENT_TYPE'); + return Headers::get('CONTENT_TYPE'); } /** @@ -316,7 +318,7 @@ public static function getContentCharset(): ?string */ public static function getContentLength(): int { - return static::$headers->get('CONTENT_LENGTH') ?? 0; + return Headers::get('CONTENT_LENGTH') ?? 0; } /** @@ -432,7 +434,7 @@ public static function getIp(): string */ public static function getReferrer(): ?string { - return static::$headers->get('HTTP_REFERER'); + return Headers::get('HTTP_REFERER'); } /** @@ -450,6 +452,6 @@ public static function getReferer(): ?string */ public static function getUserAgent(): ?string { - return static::$headers->get('HTTP_USER_AGENT'); + return Headers::get('HTTP_USER_AGENT'); } } From 05f08d39b4f5041c063edfb4c6cbb02122c49a64 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 21:26:34 +0000 Subject: [PATCH 016/129] :sparkles: add headers has method --- src/Headers.php | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/src/Headers.php b/src/Headers.php index 35b4836..d14ac32 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -43,8 +43,9 @@ public static function resetStatus($httpCode = 200) */ public static function all(bool $safeOutput = false): array { - if ($safeOutput === false) return self::findHeaders(); - return \Leaf\Anchor::sanitize(self::findHeaders()); + return ($safeOutput === false) ? + self::findHeaders() : + \Leaf\Anchor::sanitize(self::findHeaders()); } /** @@ -160,4 +161,14 @@ protected static function findHeaders() } return $headers; } + + /** + * Check if a header is present + * + * @param string $header The header to check + */ + public static function has(string $header) + { + return in_array($header, static::all()); + } } From aead66a4f874e5de30bd59718700ac052e0eb987 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 21:27:32 +0000 Subject: [PATCH 017/129] :sparkles: add support for x-www-form-urlencoded data --- src/Request.php | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index fc9c4c7..3de29a8 100755 --- a/src/Request.php +++ b/src/Request.php @@ -92,10 +92,21 @@ public static function input($safeData = true) { $handler = fopen('php://input', 'r'); $data = stream_get_contents($handler); - if (!$data) $data = json_encode([]); - $parsedData = json_decode($data, true); - if (is_array($parsedData)) $data = $parsedData; + if (Headers::get('Content-Type') === 'application/x-www-form-urlencoded') { + $d = $data; + $data = []; + + foreach (explode('&', $d) as $chunk) { + $param = explode("=", $chunk); + $data[$param[0]] = $param[1]; + } + } else { + if (!$data) $data = json_encode([]); + + $parsedData = json_decode($data, true); + if (is_array($parsedData)) $data = $parsedData; + } return $safeData ? \Leaf\Anchor::sanitize($data) : $data; } From 365e782f7ec9c34eea9fa8ccc5d6befd308afb95 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 21:58:04 +0000 Subject: [PATCH 018/129] :memo: update readme --- README.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/README.md b/README.md index f698ce3..915edbc 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,10 @@



-

Leaf Http v2



-# Leaf PHP +# Leaf Http v2 [![Latest Stable Version](https://poser.pugx.org/leafs/http/v/stable)](https://packagist.org/packages/leafs/http) [![Total Downloads](https://poser.pugx.org/leafs/http/downloads)](https://packagist.org/packages/leafs/http) From b54add6cf8760b6a14725455c7f33963736274bd Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sat, 14 May 2022 23:20:15 +0000 Subject: [PATCH 019/129] :memo: update readme --- README.md | 26 +++++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 915edbc..0440509 100644 --- a/README.md +++ b/README.md @@ -2,14 +2,30 @@



-

+

-# Leaf Http v2 +

Leaf Http v2

-[![Latest Stable Version](https://poser.pugx.org/leafs/http/v/stable)](https://packagist.org/packages/leafs/http) -[![Total Downloads](https://poser.pugx.org/leafs/http/downloads)](https://packagist.org/packages/leafs/http) -[![License](https://poser.pugx.org/leafs/http/license)](https://packagist.org/packages/leafs/http) +

+ Latest Stable Version + Total Downloads + License +

+
+
Leaf's core http functionality packaged as a serve-yourself module. **Although seperated from Leaf core, it is still part of the default initial installation and doesn't need to be installed manually (unless you want a particular version).** From bce6cda661ea7b6152d48250aba28dbea5fbb0fd Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sun, 15 May 2022 15:24:09 +0000 Subject: [PATCH 020/129] =?UTF-8?q?=F0=9F=A7=B1=20standardadize=20function?= =?UTF-8?q?al=20mode?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/functions.php | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/functions.php b/src/functions.php index 4567f05..864143c 100644 --- a/src/functions.php +++ b/src/functions.php @@ -5,11 +5,11 @@ * Return request or request data * * @param array|string $data — Get data from request + * + * @return \Leaf\Http\Request */ - function request($data = null) + function request() { - if ($data !== null) return \Leaf\Http\Request::get($data); - if (class_exists('\Leaf\Config')) { $request = Leaf\Config::get("request")["instance"] ?? null; @@ -30,11 +30,11 @@ function request($data = null) * Return response or set response data * * @param array|string $data — The JSON response to set + * + * @return \Leaf\Http\Response */ - function response($data = null) + function response() { - if ($data !== null) return \Leaf\Http\Response::json($data); - if (class_exists('\Leaf\Config')) { $response = Leaf\Config::get("response")["instance"] ?? null; From bd51313febc25e1edc2e808af55987dc3ef65fc1 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 16 May 2022 19:27:06 +0000 Subject: [PATCH 021/129] :sparkles: added has method --- src/Headers.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Headers.php b/src/Headers.php index d14ac32..8bb04cd 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -101,6 +101,16 @@ public static function remove($keys) } } + /** + * Check if a header is present + * + * @param string $header The header to check + */ + public static function has(string $header) + { + return in_array($header, static::all()); + } + /** * Set the content-type to plain text */ @@ -161,14 +171,4 @@ protected static function findHeaders() } return $headers; } - - /** - * Check if a header is present - * - * @param string $header The header to check - */ - public static function has(string $header) - { - return in_array($header, static::all()); - } } From 429580d91cf797fd62c9027e3c1a166e6920ff55 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 16 May 2022 19:57:49 +0000 Subject: [PATCH 022/129] :boom: remove 4th param on json --- src/Response.php | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Response.php b/src/Response.php index 0e470ed..e5affcd 100755 --- a/src/Response.php +++ b/src/Response.php @@ -85,18 +85,19 @@ public function xml($data, int $code = 200) * @param mixed $data The data to output * @param int $code The response status code * @param bool $showCode Show response code in body? - * @param bool $useMessage Show message instead of code */ - public function json($data, int $code = 200, bool $showCode = false, bool $useMessage = false) + public function json($data, int $code = 200, bool $showCode = false) { $this->status = $code; if ($showCode) { - $dataToPrint = ['data' => $data, 'code' => $code]; - - if ($useMessage) { - $dataToPrint = ['data' => $data, 'message' => Status::$statusTexts[$code] ?? 'unknown status']; - } + $dataToPrint = [ + 'data' => $data, + 'status' => [ + 'code' => $code, + 'message' => Status::$statusTexts[$code] ?? 'unknown status', + ], + ]; } else { $dataToPrint = $data; } From 69a3b5b4c10491598c0aea633f3a5718fbe7ab8e Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 16 May 2022 20:03:56 +0000 Subject: [PATCH 023/129] :memo: updated PHP doc --- src/Response.php | 52 +++++++++++++++++++++++++++++------------------- 1 file changed, 32 insertions(+), 20 deletions(-) diff --git a/src/Response.php b/src/Response.php index e5affcd..71376f8 100755 --- a/src/Response.php +++ b/src/Response.php @@ -108,6 +108,38 @@ public function json($data, int $code = 200, bool $showCode = false) $this->send(); } + /** + * Output data from an HTML or PHP file + * + * @param string $file The file to output + * @param int $code The http status code + */ + public function page(string $file, int $code = 200) + { + $this->status = $code; + $this->headers['Content-Type'] = 'text/html'; + $this->content = require $file; + + $this->send(); + } + + /** + * Output some html/PHP + * + * @param string $markup The data to output + * @param int $code The http status code + */ + public function markup(string $markup, int $code = 200) + { + $this->status = $code; + $this->headers['Content-Type'] = 'text/html'; + $this->content = <<send(); + } + /** * Output plain text * @@ -158,26 +190,6 @@ public function exit($data, int $code = 500) exit(); } - public function page(string $file, int $code = 200) - { - $this->status = $code; - $this->headers['Content-Type'] = 'text/html'; - $this->content = require $file; - - $this->send(); - } - - public function markup(String $markup, int $code = 200) - { - $this->status = $code; - $this->headers['Content-Type'] = 'text/html'; - $this->content = <<send(); - } - /** * Set HTTP status code */ From d1de313ed3ac8e8d021f73fe2c2a0d797fc32932 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Fri, 20 May 2022 08:04:01 +0000 Subject: [PATCH 024/129] :sparkles: restructured redirect and noContent --- src/Response.php | 52 ++++++++++++++++++++++++------------------------ 1 file changed, 26 insertions(+), 26 deletions(-) diff --git a/src/Response.php b/src/Response.php index 71376f8..276a014 100755 --- a/src/Response.php +++ b/src/Response.php @@ -168,6 +168,17 @@ public function download(string $file, string $name = null, int $code = 200) $this->send(); } + /** + * The HTTP 204 No Content success status response code indicates + * that a request has succeeded, but that the client doesn't + * need to navigate away from its current page. + */ + public function noContent() + { + $this->status = 204; + $this->send(); + } + /** * Output some data and break the application * @@ -190,6 +201,21 @@ public function exit($data, int $code = 500) exit(); } + /** + * Redirect + * + * This method prepares this response to return an HTTP Redirect response + * to the HTTP client. + * + * @param string $url The redirect destination + * @param int $status The redirect HTTP status code + */ + public function redirect(string $url, int $status = 302) + { + Headers::status($status); + Headers::set('Location', $url, true, $status); + } + /** * Set HTTP status code */ @@ -284,32 +310,6 @@ public function withFlash($key, string $value) return $this; } - /** - * Redirect - * - * This method prepares this response to return an HTTP Redirect response - * to the HTTP client. - * - * @param string $url The redirect destination - * @param int $status The redirect HTTP status code - */ - public function redirect(string $url, int $status = 302) - { - Headers::status($status); - Headers::set('Location', $url, true, $status); - } - - /** - * The HTTP 204 No Content success status response code indicates - * that a request has succeeded, but that the client doesn't - * need to navigate away from its current page. - */ - public function noContent() - { - $this->status = 204; - $this->send(); - } - /** * Get message for HTTP status code * From b5a90090dd3065d757cee1051eed16f3458c1468 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sun, 29 May 2022 09:32:56 +0000 Subject: [PATCH 025/129] :memo: updated phpdoc --- src/Response.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/Response.php b/src/Response.php index 276a014..7176205 100755 --- a/src/Response.php +++ b/src/Response.php @@ -230,6 +230,8 @@ public function status($code = null) * * @param string|array $name Header name * @param string|null $value Header value + * @param boolean $replace Replace existing header + * @param int $httpCode The HTTP status code */ public function withHeader($name, ?string $value = '', $replace = true, int $httpCode = 200) { From 6afa66e799b48e55eaaf43642f3b5478def8b446 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sun, 29 May 2022 10:34:06 +0000 Subject: [PATCH 026/129] :sparkles: update cookie unset types --- src/Response.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Response.php b/src/Response.php index 7176205..23451cc 100755 --- a/src/Response.php +++ b/src/Response.php @@ -274,9 +274,9 @@ public function withCookie(string $name, string $value, string $expire = "7 days /** * Delete cookie * - * @param string $name The name of the cookie + * @param mixed $name The name of the cookie */ - public function withoutCookie(string $name) + public function withoutCookie($name) { if (!class_exists('Leaf\Http\Cookie')) { Headers::contentHtml(); From ea0d9b14b38409e2b21eff4b43f5cd387b813d8c Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sun, 29 May 2022 17:18:28 +0000 Subject: [PATCH 027/129] :memo: update readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 0440509..3780c46 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ The available classes in the Http module are: - [`Leaf\Http\Cache`](https://leafphp.dev/modules/http/cache) - [`Leaf\Http\Status`](https://leafphp.dev/modules/http/status) -**The docs for Leaf Http v2 can be found at [https://leafphp.dev/modules/http/v1/](https://leafphp.dev/modules/http/v1/).** +**The docs for Leaf Http v2 can be found at [https://leafphp.dev/modules/http/v/2/](https://leafphp.dev/modules/http/v/2/).** ## Request From 16095b08204758f1b7b10a1c8e84997528d2e29c Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 6 Sep 2022 19:12:44 +0000 Subject: [PATCH 028/129] fix: switch page to internal output buffers --- src/Response.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index 23451cc..361b587 100755 --- a/src/Response.php +++ b/src/Response.php @@ -118,7 +118,11 @@ public function page(string $file, int $code = 200) { $this->status = $code; $this->headers['Content-Type'] = 'text/html'; - $this->content = require $file; + + \ob_start(); + require $file; + $this->content = ob_get_contents(); + ob_end_clean(); $this->send(); } From 57d5724b8862ed431a5d88b61859a2ab44a687f2 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 6 Sep 2022 20:02:50 +0000 Subject: [PATCH 029/129] chore: update leaf anchor --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index d83e2e1..261b5c9 100644 --- a/composer.json +++ b/composer.json @@ -32,6 +32,6 @@ "minimum-stability": "dev", "prefer-stable": true, "require": { - "leafs/anchor": "^1.0" + "leafs/anchor": "*" } } From 4e761f04def47acc30d46d2b2e62e4f18f4875e3 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 6 Sep 2022 20:03:13 +0000 Subject: [PATCH 030/129] feat: add rawData method --- src/Request.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Request.php b/src/Request.php index 3de29a8..d38176c 100755 --- a/src/Request.php +++ b/src/Request.php @@ -163,6 +163,21 @@ public static function try(array $params, bool $safeData = true, bool $noEmptySt return $data; } + /** + * Get raw request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function rawData($item = null, $default = null) + { + $handler = fopen('php://input', 'r'); + $decoded = json_decode(stream_get_contents($handler), true); + $data = is_array($decoded) ? $decoded : []; + + return \Leaf\Anchor::deepGet($data, $item) ?? $default; + } + /** * Returns request data * From 4fc936956db9afd751324f0fbfb24ba0dfeeeffe Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 6 Sep 2022 20:13:25 +0000 Subject: [PATCH 031/129] feat: add urlData method --- src/Request.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Request.php b/src/Request.php index d38176c..f08bb1e 100755 --- a/src/Request.php +++ b/src/Request.php @@ -178,6 +178,17 @@ public static function rawData($item = null, $default = null) return \Leaf\Anchor::deepGet($data, $item) ?? $default; } + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function urlData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; + } + /** * Returns request data * From 2ab36719a4223f38577d93c61422920eb321413a Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 6 Sep 2022 20:14:17 +0000 Subject: [PATCH 032/129] feat: add postData method --- src/Request.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Request.php b/src/Request.php index f08bb1e..69b943d 100755 --- a/src/Request.php +++ b/src/Request.php @@ -189,6 +189,17 @@ public static function urlData($item = null, $default = null) return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; } + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function postData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_POST, $item) ?? $default; + } + /** * Returns request data * From 934c5329a65046cb27da620dcaf0f8f6ebd13d0b Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 6 Sep 2022 23:41:44 +0000 Subject: [PATCH 033/129] feat: update request object --- src/Request.php | 65 +++++++++++++++++++++++++++++-------------------- 1 file changed, 39 insertions(+), 26 deletions(-) diff --git a/src/Request.php b/src/Request.php index 69b943d..7eca29e 100755 --- a/src/Request.php +++ b/src/Request.php @@ -67,9 +67,13 @@ public static function hasHeader(String $header): bool */ public static function isAjax(): bool { - if (static::params('isajax')) return true; + if (static::params('isajax')) { + return true; + } - if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') return true; + if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') { + return true; + } return false; } @@ -85,7 +89,7 @@ public static function isXhr(): bool /** * Access stream that allows you to read raw data from the request body. **This is not for form data** - * + * * @param boolean $safeData Sanitize data? */ public static function input($safeData = true) @@ -102,10 +106,15 @@ public static function input($safeData = true) $data[$param[0]] = $param[1]; } } else { - if (!$data) $data = json_encode([]); + if (!$data) { + $data = json_encode([]); + } $parsedData = json_decode($data, true); - if (is_array($parsedData)) $data = $parsedData; + if (is_array($parsedData)) { + $data = $parsedData; + } + } return $safeData ? \Leaf\Anchor::sanitize($data) : $data; @@ -127,7 +136,9 @@ public static function params(string $key = null, mixed $default = null): mixed { $union = static::body(); - if ($key) return $union[$key] ?? $default; + if ($key) { + return $union[$key] ?? $default; + } return $union; } @@ -144,8 +155,7 @@ public static function params(string $key = null, mixed $default = null): mixed * @param bool $safeData Sanitize output? * @param bool $noEmptyString Remove empty strings from return data? */ - public static function try(array $params, bool $safeData = true, bool $noEmptyString = false) - { + function try (array $params, bool $safeData = true, bool $noEmptyString = false) { $data = static::get($params, $safeData); $dataKeys = array_keys($data); @@ -165,22 +175,18 @@ public static function try(array $params, bool $safeData = true, bool $noEmptySt /** * Get raw request data - * + * * @param string|array $item The items to output * @param mixed $default The default value to return if no data is available */ public static function rawData($item = null, $default = null) { - $handler = fopen('php://input', 'r'); - $decoded = json_decode(stream_get_contents($handler), true); - $data = is_array($decoded) ? $decoded : []; - - return \Leaf\Anchor::deepGet($data, $item) ?? $default; + return \Leaf\Anchor::deepGet(static::input(false), $item) ?? $default; } /** * Return only get request data - * + * * @param string|array $item The items to output * @param mixed $default The default value to return if no data is available */ @@ -191,7 +197,7 @@ public static function urlData($item = null, $default = null) /** * Return only get request data - * + * * @param string|array $item The items to output * @param mixed $default The default value to return if no data is available */ @@ -212,7 +218,9 @@ public static function postData($item = null, $default = null) */ public static function get($params, bool $safeData = true) { - if (is_string($params)) return static::body($safeData)[$params] ?? null; + if (is_string($params)) { + return static::body($safeData)[$params] ?? null; + } $data = []; @@ -230,11 +238,11 @@ public static function get($params, bool $safeData = true) */ public static function body(bool $safeData = true) { - $finalData = array_merge($_GET, $_FILES, $_POST, static::input($safeData)); + $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input($safeData)); return $safeData ? - \Leaf\Anchor::sanitize($finalData) : - $finalData; + \Leaf\Anchor::sanitize($finalData) : + $finalData; } /** @@ -244,8 +252,13 @@ public static function body(bool $safeData = true) */ public static function files($filenames = null) { - if ($filenames == null) return $_FILES; - if (is_string($filenames)) return $_FILES[$filenames] ?? null; + if ($filenames == null) { + return $_FILES; + } + + if (is_string($filenames)) { + return $_FILES[$filenames] ?? null; + } $files = []; foreach ($filenames as $filename) { @@ -266,8 +279,8 @@ public static function files($filenames = null) public static function cookies(string $key = null) { return $key === null ? - Cookie::all() : - Cookie::get($key); + Cookie::all() : + Cookie::get($key); } /** @@ -295,8 +308,8 @@ public static function isFormData(): bool public static function headers($key = null, bool $safeData = true) { return ($key === null) ? - Headers::all($safeData) : - Headers::get($key, $safeData); + Headers::all($safeData) : + Headers::get($key, $safeData); } /** From 6f0cf02a6b74663fe790aed8c139712ff8e1358e Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 2 Oct 2022 13:54:03 +0000 Subject: [PATCH 034/129] style: patch up errors --- src/Headers.php | 2 + src/Request.php | 998 +++++++++++++++++++++++------------------------ src/Response.php | 6 +- 3 files changed, 505 insertions(+), 501 deletions(-) diff --git a/src/Headers.php b/src/Headers.php index 8bb04cd..3aa54aa 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -30,6 +30,8 @@ public static function status(int $httpCode = null) /** * Force an HTTP code for response using PHP's `http_response_code` + * + * @param int $httpCode The response code to set */ public static function resetStatus($httpCode = 200) { diff --git a/src/Request.php b/src/Request.php index 7eca29e..0d32acc 100755 --- a/src/Request.php +++ b/src/Request.php @@ -16,503 +16,503 @@ */ class Request { - const METHOD_HEAD = 'HEAD'; - const METHOD_GET = 'GET'; - const METHOD_POST = 'POST'; - const METHOD_PUT = 'PUT'; - const METHOD_PATCH = 'PATCH'; - const METHOD_DELETE = 'DELETE'; - const METHOD_OPTIONS = 'OPTIONS'; - const METHOD_OVERRIDE = '_METHOD'; - - /** - * @var array - */ - protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; - - /** - * Get HTTP method - * @return string - */ - public static function getMethod(): string - { - return $_SERVER['REQUEST_METHOD']; - } - - /** - * Check for request method type - * - * @param string $type The type of request to check for - * @return bool - */ - public static function typeIs(string $type): bool - { - return static::getMethod() === strtoupper($type); - } - - /** - * Find if request has a particular header - * - * @param string $header Header to check for - * @return bool - */ - public static function hasHeader(String $header): bool - { - return !!Headers::get($header); - } - - /** - * Is this an AJAX request? - * @return bool - */ - public static function isAjax(): bool - { - if (static::params('isajax')) { - return true; - } - - if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') { - return true; - } - - return false; - } - - /** - * Is this an XHR request? (alias of Leaf_Http_Request::isAjax) - * @return bool - */ - public static function isXhr(): bool - { - return static::isAjax(); - } - - /** - * Access stream that allows you to read raw data from the request body. **This is not for form data** - * - * @param boolean $safeData Sanitize data? - */ - public static function input($safeData = true) - { - $handler = fopen('php://input', 'r'); - $data = stream_get_contents($handler); - - if (Headers::get('Content-Type') === 'application/x-www-form-urlencoded') { - $d = $data; - $data = []; - - foreach (explode('&', $d) as $chunk) { - $param = explode("=", $chunk); - $data[$param[0]] = $param[1]; - } - } else { - if (!$data) { - $data = json_encode([]); - } - - $parsedData = json_decode($data, true); - if (is_array($parsedData)) { - $data = $parsedData; - } - - } - - return $safeData ? \Leaf\Anchor::sanitize($data) : $data; - } - - /** - * Fetch GET and POST data - * - * This method returns a union of GET and POST data as a key-value array, or the value - * of the array key if requested. If the array key does not exist, NULL is returned, - * unless there is a default value specified. - * - * @param string|null $key - * @param mixed|null $default - * - * @return mixed - */ - public static function params(string $key = null, mixed $default = null): mixed - { - $union = static::body(); - - if ($key) { - return $union[$key] ?? $default; - } - - return $union; - } - - /** - * Attempt to retrieve data from the request. - * - * Data which is not found in the request parameters will - * be completely removed instead of returning null. Use `get` - * if you want to return null or `params` if you want to set - * a default value. - * - * @param array $params The parameters to return - * @param bool $safeData Sanitize output? - * @param bool $noEmptyString Remove empty strings from return data? - */ - function try (array $params, bool $safeData = true, bool $noEmptyString = false) { - $data = static::get($params, $safeData); - $dataKeys = array_keys($data); - - foreach ($dataKeys as $key) { - if (!$data[$key]) { - unset($data[$key]); - continue; - } - - if ($noEmptyString && !strlen($data[$key])) { - unset($data[$key]); - } - } - - return $data; - } - - /** - * Get raw request data - * - * @param string|array $item The items to output - * @param mixed $default The default value to return if no data is available - */ - public static function rawData($item = null, $default = null) - { - return \Leaf\Anchor::deepGet(static::input(false), $item) ?? $default; - } - - /** - * Return only get request data - * - * @param string|array $item The items to output - * @param mixed $default The default value to return if no data is available - */ - public static function urlData($item = null, $default = null) - { - return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; - } - - /** - * Return only get request data - * - * @param string|array $item The items to output - * @param mixed $default The default value to return if no data is available - */ - public static function postData($item = null, $default = null) - { - return \Leaf\Anchor::deepGet($_POST, $item) ?? $default; - } - - /** - * Returns request data - * - * This methods returns data passed into the request (request or form data). - * This method returns get, post, put patch, delete or raw faw form data or NULL - * if the data isn't found. - * - * @param array|string $params The parameter(s) to return - * @param bool $safeData Sanitize output - */ - public static function get($params, bool $safeData = true) - { - if (is_string($params)) { - return static::body($safeData)[$params] ?? null; - } - - $data = []; - - foreach ($params as $param) { - $data[$param] = static::get($param, $safeData); - } - - return $data; - } - - /** - * Get all the request data as an associative array - * - * @param bool $safeData Sanitize output - */ - public static function body(bool $safeData = true) - { - $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input($safeData)); - - return $safeData ? - \Leaf\Anchor::sanitize($finalData) : - $finalData; - } - - /** - * Get all files passed into the request. - * - * @param array|string|null $filenames The file(s) you want to get - */ - public static function files($filenames = null) - { - if ($filenames == null) { - return $_FILES; - } - - if (is_string($filenames)) { - return $_FILES[$filenames] ?? null; - } - - $files = []; - foreach ($filenames as $filename) { - $files[$filename] = $_FILES[$filename] ?? null; - } - return $files; - } - - /** - * Fetch COOKIE data - * - * This method returns a key-value array of Cookie data sent in the HTTP request, or - * the value of a array key if requested; if the array key does not exist, NULL is returned. - * - * @param string|null $key - * @return array|string|null - */ - public static function cookies(string $key = null) - { - return $key === null ? - Cookie::all() : - Cookie::get($key); - } - - /** - * Does the Request body contain parsed form data? - * @return bool - */ - public static function isFormData(): bool - { - $method = static::getMethod(); - - return ($method === self::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), self::$formDataMediaTypes); - } - - /** - * Get Headers - * - * This method returns a key-value array of headers sent in the HTTP request, or - * the value of a hash key if requested; if the array key does not exist, NULL is returned. - * - * @param array|string|null $key The header(s) to return - * @param bool $safeData Attempt to sanitize headers - * - * @return array|string|null - */ - public static function headers($key = null, bool $safeData = true) - { - return ($key === null) ? - Headers::all($safeData) : - Headers::get($key, $safeData); - } - - /** - * Get Content Type - * @return string|null - */ - public static function getContentType(): ?string - { - return Headers::get('CONTENT_TYPE'); - } - - /** - * Get Media Type (type/subtype within Content Type header) - * @return string|null - */ - public static function getMediaType(): ?string - { - $contentType = static::getContentType(); - if ($contentType) { - $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); - - return strtolower($contentTypeParts[0]); - } - - return null; - } - - /** - * Get Media Type Params - * @return array - */ - public static function getMediaTypeParams(): array - { - $contentType = static::getContentType(); - $contentTypeParams = []; - - if ($contentType) { - $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); - $contentTypePartsLength = count($contentTypeParts); - - for ($i = 1; $i < $contentTypePartsLength; $i++) { - $paramParts = explode('=', $contentTypeParts[$i]); - $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; - } - } - - return $contentTypeParams; - } - - /** - * Get Content Charset - * @return string|null - */ - public static function getContentCharset(): ?string - { - $mediaTypeParams = static::getMediaTypeParams(); - if (isset($mediaTypeParams['charset'])) { - return $mediaTypeParams['charset']; - } - - return null; - } - - /** - * Get Content-Length - * @return int - */ - public static function getContentLength(): int - { - return Headers::get('CONTENT_LENGTH') ?? 0; - } - - /** - * Get Host - * @return string - */ - public static function getHost(): string - { - if (isset($_SERVER['HTTP_HOST'])) { - if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $_SERVER['HTTP_HOST'], $matches)) { - return $matches[1]; - } else if (strpos($_SERVER['HTTP_HOST'], ':') !== false) { - $hostParts = explode(':', $_SERVER['HTTP_HOST']); - - return $hostParts[0]; - } - - return $_SERVER['HTTP_HOST']; - } - - return $_SERVER['SERVER_NAME']; - } - - /** - * Get Host with Port - * @return string - */ - public static function getHostWithPort(): string - { - return sprintf('%s:%s', static::getHost(), static::getPort()); - } - - /** - * Get Port - * @return int - */ - public static function getPort(): int - { - return (int) $_SERVER['SERVER_PORT'] ?? 80; - } - - /** - * Get Scheme (https or http) - * @return string - */ - public static function getScheme(): string - { - return empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; - } - - /** - * Get Script Name (physical path) - * @return string - */ - public static function getScriptName(): string - { - return $_SERVER['SCRIPT_NAME']; - } - - /** - * Get Path (physical path + virtual path) - * @return string - */ - public static function getPath(): string - { - return static::getScriptName() . static::getPathInfo(); - } - - /** - * Get Path Info (virtual path) - * @return string|null - */ - public static function getPathInfo(): ?string - { - return $_SERVER['REQUEST_URI'] ?? null; - } - - /** - * Get URL (scheme + host [ + port if non-standard ]) - * @return string - */ - public static function getUrl(): string - { - $url = static::getScheme() . '://' . static::getHost(); - - if ((static::getScheme() === 'https' && static::getPort() !== 443) || (static::getScheme() === 'http' && static::getPort() !== 80)) { - $url .= ":" . static::getPort(); - } - - return $url; - } - - /** - * Get IP - * @return string - */ - public static function getIp(): string - { - $keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR']; - - foreach ($keys as $key) { - if (isset($_SERVER[$key])) { - return $_SERVER[$key]; - } - } - - return $_SERVER['REMOTE_ADDR']; - } - - /** - * Get Referrer - * @return string|null - */ - public static function getReferrer(): ?string - { - return Headers::get('HTTP_REFERER'); - } - - /** - * Get Referer (for those who can't spell) - * @return string|null - */ - public static function getReferer(): ?string - { - return static::getReferrer(); - } - - /** - * Get User Agent - * @return string|null - */ - public static function getUserAgent(): ?string - { - return Headers::get('HTTP_USER_AGENT'); - } + const METHOD_HEAD = 'HEAD'; + const METHOD_GET = 'GET'; + const METHOD_POST = 'POST'; + const METHOD_PUT = 'PUT'; + const METHOD_PATCH = 'PATCH'; + const METHOD_DELETE = 'DELETE'; + const METHOD_OPTIONS = 'OPTIONS'; + const METHOD_OVERRIDE = '_METHOD'; + + /** + * @var array + */ + protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; + + /** + * Get HTTP method + * @return string + */ + public static function getMethod(): string + { + return $_SERVER['REQUEST_METHOD']; + } + + /** + * Check for request method type + * + * @param string $type The type of request to check for + * @return bool + */ + public static function typeIs(string $type): bool + { + return static::getMethod() === strtoupper($type); + } + + /** + * Find if request has a particular header + * + * @param string $header Header to check for + * @return bool + */ + public static function hasHeader(String $header): bool + { + return !!Headers::get($header); + } + + /** + * Is this an AJAX request? + * @return bool + */ + public static function isAjax(): bool + { + if (static::params('isajax')) { + return true; + } + + if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') { + return true; + } + + return false; + } + + /** + * Is this an XHR request? (alias of Leaf_Http_Request::isAjax) + * @return bool + */ + public static function isXhr(): bool + { + return static::isAjax(); + } + + /** + * Access stream that allows you to read raw data from the request body. **This is not for form data** + * + * @param boolean $safeData Sanitize data? + */ + public static function input($safeData = true) + { + $handler = fopen('php://input', 'r'); + $data = stream_get_contents($handler); + + if (Headers::get('Content-Type') === 'application/x-www-form-urlencoded') { + $d = $data; + $data = []; + + foreach (explode('&', $d) as $chunk) { + $param = explode("=", $chunk); + $data[$param[0]] = $param[1]; + } + } else { + if (!$data) { + $data = json_encode([]); + } + + $parsedData = json_decode($data, true); + if (is_array($parsedData)) { + $data = $parsedData; + } + } + + return $safeData ? \Leaf\Anchor::sanitize($data) : $data; + } + + /** + * Fetch GET and POST data + * + * This method returns a union of GET and POST data as a key-value array, or the value + * of the array key if requested. If the array key does not exist, NULL is returned, + * unless there is a default value specified. + * + * @param string|null $key + * @param mixed|null $default + * + * @return mixed + */ + public static function params(string $key = null, mixed $default = null): mixed + { + $union = static::body(); + + if ($key) { + return $union[$key] ?? $default; + } + + return $union; + } + + /** + * Attempt to retrieve data from the request. + * + * Data which is not found in the request parameters will + * be completely removed instead of returning null. Use `get` + * if you want to return null or `params` if you want to set + * a default value. + * + * @param array $params The parameters to return + * @param bool $safeData Sanitize output? + * @param bool $noEmptyString Remove empty strings from return data? + */ + function try(array $params, bool $safeData = true, bool $noEmptyString = false) + { + $data = static::get($params, $safeData); + $dataKeys = array_keys($data); + + foreach ($dataKeys as $key) { + if (!$data[$key]) { + unset($data[$key]); + continue; + } + + if ($noEmptyString && !strlen($data[$key])) { + unset($data[$key]); + } + } + + return $data; + } + + /** + * Get raw request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function rawData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet(static::input(false), $item) ?? $default; + } + + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function urlData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; + } + + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function postData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_POST, $item) ?? $default; + } + + /** + * Returns request data + * + * This methods returns data passed into the request (request or form data). + * This method returns get, post, put patch, delete or raw faw form data or NULL + * if the data isn't found. + * + * @param array|string $params The parameter(s) to return + * @param bool $safeData Sanitize output + */ + public static function get($params, bool $safeData = true) + { + if (is_string($params)) { + return static::body($safeData)[$params] ?? null; + } + + $data = []; + + foreach ($params as $param) { + $data[$param] = static::get($param, $safeData); + } + + return $data; + } + + /** + * Get all the request data as an associative array + * + * @param bool $safeData Sanitize output + */ + public static function body(bool $safeData = true) + { + $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input($safeData)); + + return $safeData ? + \Leaf\Anchor::sanitize($finalData) : + $finalData; + } + + /** + * Get all files passed into the request. + * + * @param array|string|null $filenames The file(s) you want to get + */ + public static function files($filenames = null) + { + if ($filenames == null) { + return $_FILES; + } + + if (is_string($filenames)) { + return $_FILES[$filenames] ?? null; + } + + $files = []; + foreach ($filenames as $filename) { + $files[$filename] = $_FILES[$filename] ?? null; + } + return $files; + } + + /** + * Fetch COOKIE data + * + * This method returns a key-value array of Cookie data sent in the HTTP request, or + * the value of a array key if requested; if the array key does not exist, NULL is returned. + * + * @param string|null $key + * @return array|string|null + */ + public static function cookies(string $key = null) + { + return $key === null ? + Cookie::all() : + Cookie::get($key); + } + + /** + * Does the Request body contain parsed form data? + * @return bool + */ + public static function isFormData(): bool + { + $method = static::getMethod(); + + return ($method === self::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), self::$formDataMediaTypes); + } + + /** + * Get Headers + * + * This method returns a key-value array of headers sent in the HTTP request, or + * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * + * @param array|string|null $key The header(s) to return + * @param bool $safeData Attempt to sanitize headers + * + * @return array|string|null + */ + public static function headers($key = null, bool $safeData = true) + { + return ($key === null) ? + Headers::all($safeData) : + Headers::get($key, $safeData); + } + + /** + * Get Content Type + * @return string|null + */ + public static function getContentType(): ?string + { + return Headers::get('CONTENT_TYPE'); + } + + /** + * Get Media Type (type/subtype within Content Type header) + * @return string|null + */ + public static function getMediaType(): ?string + { + $contentType = static::getContentType(); + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + + return strtolower($contentTypeParts[0]); + } + + return null; + } + + /** + * Get Media Type Params + * @return array + */ + public static function getMediaTypeParams(): array + { + $contentType = static::getContentType(); + $contentTypeParams = []; + + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + $contentTypePartsLength = count($contentTypeParts); + + for ($i = 1; $i < $contentTypePartsLength; $i++) { + $paramParts = explode('=', $contentTypeParts[$i]); + $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; + } + } + + return $contentTypeParams; + } + + /** + * Get Content Charset + * @return string|null + */ + public static function getContentCharset(): ?string + { + $mediaTypeParams = static::getMediaTypeParams(); + if (isset($mediaTypeParams['charset'])) { + return $mediaTypeParams['charset']; + } + + return null; + } + + /** + * Get Content-Length + * @return int + */ + public static function getContentLength(): int + { + return Headers::get('CONTENT_LENGTH') ?? 0; + } + + /** + * Get Host + * @return string + */ + public static function getHost(): string + { + if (isset($_SERVER['HTTP_HOST'])) { + if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $_SERVER['HTTP_HOST'], $matches)) { + return $matches[1]; + } else if (strpos($_SERVER['HTTP_HOST'], ':') !== false) { + $hostParts = explode(':', $_SERVER['HTTP_HOST']); + + return $hostParts[0]; + } + + return $_SERVER['HTTP_HOST']; + } + + return $_SERVER['SERVER_NAME']; + } + + /** + * Get Host with Port + * @return string + */ + public static function getHostWithPort(): string + { + return sprintf('%s:%s', static::getHost(), static::getPort()); + } + + /** + * Get Port + * @return int + */ + public static function getPort(): int + { + return (int) $_SERVER['SERVER_PORT'] ?? 80; + } + + /** + * Get Scheme (https or http) + * @return string + */ + public static function getScheme(): string + { + return empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; + } + + /** + * Get Script Name (physical path) + * @return string + */ + public static function getScriptName(): string + { + return $_SERVER['SCRIPT_NAME']; + } + + /** + * Get Path (physical path + virtual path) + * @return string + */ + public static function getPath(): string + { + return static::getScriptName() . static::getPathInfo(); + } + + /** + * Get Path Info (virtual path) + * @return string|null + */ + public static function getPathInfo(): ?string + { + return $_SERVER['REQUEST_URI'] ?? null; + } + + /** + * Get URL (scheme + host [ + port if non-standard ]) + * @return string + */ + public static function getUrl(): string + { + $url = static::getScheme() . '://' . static::getHost(); + + if ((static::getScheme() === 'https' && static::getPort() !== 443) || (static::getScheme() === 'http' && static::getPort() !== 80)) { + $url .= ":" . static::getPort(); + } + + return $url; + } + + /** + * Get IP + * @return string + */ + public static function getIp(): string + { + $keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR']; + + foreach ($keys as $key) { + if (isset($_SERVER[$key])) { + return $_SERVER[$key]; + } + } + + return $_SERVER['REMOTE_ADDR']; + } + + /** + * Get Referrer + * @return string|null + */ + public static function getReferrer(): ?string + { + return Headers::get('HTTP_REFERER'); + } + + /** + * Get Referer (for those who can't spell) + * @return string|null + */ + public static function getReferer(): ?string + { + return static::getReferrer(); + } + + /** + * Get User Agent + * @return string|null + */ + public static function getUserAgent(): ?string + { + return Headers::get('HTTP_USER_AGENT'); + } } diff --git a/src/Response.php b/src/Response.php index 361b587..f2e4f66 100755 --- a/src/Response.php +++ b/src/Response.php @@ -221,11 +221,13 @@ public function redirect(string $url, int $status = 302) } /** - * Set HTTP status code + * Force set HTTP status code + * + * @param int $httpCode The response code to set */ public function status($code = null) { - Headers::status($code); + Headers::resetStatus($code); return $this; } From 76bd52139517cddbe50a0161026c1d61e3a57c57 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 2 Oct 2022 16:47:40 +0000 Subject: [PATCH 035/129] fix: make try static --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 0d32acc..200d014 100755 --- a/src/Request.php +++ b/src/Request.php @@ -154,7 +154,7 @@ public static function params(string $key = null, mixed $default = null): mixed * @param bool $safeData Sanitize output? * @param bool $noEmptyString Remove empty strings from return data? */ - function try(array $params, bool $safeData = true, bool $noEmptyString = false) + public static function try(array $params, bool $safeData = true, bool $noEmptyString = false) { $data = static::get($params, $safeData); $dataKeys = array_keys($data); From 21cfbfe2ad235773f51bb21f5c4c71f1ca94f2a3 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 2 Oct 2022 16:52:58 +0000 Subject: [PATCH 036/129] fix: patch up errors with input() --- src/Request.php | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Request.php b/src/Request.php index 200d014..a038622 100755 --- a/src/Request.php +++ b/src/Request.php @@ -105,15 +105,16 @@ public static function input($safeData = true) $param = explode("=", $chunk); $data[$param[0]] = $param[1]; } + } else if (Headers::get('Content-Type') !== 'application/json' && strpos(Headers::get('Content-Type'), "multipart/form-data") !== 0) { + $safeData = false; + $data = [$data]; } else { if (!$data) { $data = json_encode([]); } $parsedData = json_decode($data, true); - if (is_array($parsedData)) { - $data = $parsedData; - } + $data = is_array($parsedData) ? $parsedData : [$parsedData]; } return $safeData ? \Leaf\Anchor::sanitize($data) : $data; @@ -238,7 +239,7 @@ public static function get($params, bool $safeData = true) */ public static function body(bool $safeData = true) { - $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input($safeData)); + $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input()); return $safeData ? \Leaf\Anchor::sanitize($finalData) : From 6e5e47f0792f46fa0fc48efb2ec096468c4ea7b2 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 2 Oct 2022 21:58:19 +0000 Subject: [PATCH 037/129] fix: patch up status --- src/Response.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index f2e4f66..83f45ae 100755 --- a/src/Response.php +++ b/src/Response.php @@ -227,7 +227,8 @@ public function redirect(string $url, int $status = 302) */ public function status($code = null) { - Headers::resetStatus($code); + $this->status = $code; + Headers::status($code); return $this; } From 368624d8dfb4e5470c2dcc37ac217d91d32bf2c9 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 6 Oct 2022 02:55:39 +0000 Subject: [PATCH 038/129] feat: temporarily save each response --- src/Response.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Response.php b/src/Response.php index 83f45ae..79a53b5 100755 --- a/src/Response.php +++ b/src/Response.php @@ -379,6 +379,15 @@ public function send() { $this->sendHeaders()->sendContent(); + if (class_exists('Leaf\Eien\Server')) { + \Leaf\Config::set('response.data', [ + 'headers' => $this->headers, + 'body' => strpos($this->headers['Content-Disposition'] ?? '', 'attachment') !== false + ? readfile($this->content) + : $this->content, + ]); + } + if (\function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } elseif (\function_exists('litespeed_finish_request')) { From 773cc8f7c83fa7caadab0e73f130937b247ed2a2 Mon Sep 17 00:00:00 2001 From: Jei <112980298+jeis4n@users.noreply.github.com> Date: Fri, 7 Oct 2022 16:55:04 -0600 Subject: [PATCH 039/129] Fixed Content-Type json UTF-8 If Content-Type is 'application/json; charset=UTF-8' then it doesn't recognize it as json. --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index a038622..c3a444e 100755 --- a/src/Request.php +++ b/src/Request.php @@ -105,7 +105,7 @@ public static function input($safeData = true) $param = explode("=", $chunk); $data[$param[0]] = $param[1]; } - } else if (Headers::get('Content-Type') !== 'application/json' && strpos(Headers::get('Content-Type'), "multipart/form-data") !== 0) { + } else if (strpos(Headers::get('Content-Type'), "application/json") !== 0 && strpos(Headers::get('Content-Type'), "multipart/form-data") !== 0) { $safeData = false; $data = [$data]; } else { From edb888860d07939336cf590a9b179873b401433f Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 14 Oct 2022 14:07:03 +0000 Subject: [PATCH 040/129] fix: falsy values not showing --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 7eca29e..c5df0b6 100755 --- a/src/Request.php +++ b/src/Request.php @@ -160,7 +160,7 @@ function try (array $params, bool $safeData = true, bool $noEmptyString = false) $dataKeys = array_keys($data); foreach ($dataKeys as $key) { - if (!$data[$key]) { + if (!isset($data[$key])) { unset($data[$key]); continue; } From c98625011463e20c4c78cd1a2f2158cf46e4fa2a Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 14 Oct 2022 18:10:07 +0000 Subject: [PATCH 041/129] feat: add cookie array --- src/Response.php | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Response.php b/src/Response.php index 361b587..0bd4409 100755 --- a/src/Response.php +++ b/src/Response.php @@ -19,6 +19,11 @@ class Response * @var array */ public $headers = []; + + /** + * @var array + */ + public $cookies = []; /** * @var string From 82c0e4f2b02fbdca5c2f5a7aa0f5c6c4ebe55247 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 14 Oct 2022 18:22:55 +0000 Subject: [PATCH 042/129] fix: patch up strpos error --- src/Request.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 25e764f..315cbe6 100755 --- a/src/Request.php +++ b/src/Request.php @@ -102,10 +102,10 @@ public static function input($safeData = true) $data = []; foreach (explode('&', $d) as $chunk) { - $param = explode("=", $chunk); + $param = explode('=', $chunk); $data[$param[0]] = $param[1]; } - } else if (strpos(Headers::get('Content-Type'), "application/json") !== 0 && strpos(Headers::get('Content-Type'), "multipart/form-data") !== 0) { + } else if (strpos(Headers::get('Content-Type') ?? '', 'application/json') !== 0 && strpos(Headers::get('Content-Type'), 'multipart/form-data') !== 0) { $safeData = false; $data = [$data]; } else { @@ -467,7 +467,7 @@ public static function getUrl(): string $url = static::getScheme() . '://' . static::getHost(); if ((static::getScheme() === 'https' && static::getPort() !== 443) || (static::getScheme() === 'http' && static::getPort() !== 80)) { - $url .= ":" . static::getPort(); + $url .= ':' . static::getPort(); } return $url; From 5768ef052be48fb5ee8ab7810f64a164924203ce Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 14 Oct 2022 22:12:31 +0000 Subject: [PATCH 043/129] feat: add support for eien --- src/Response.php | 72 +++++++++++++++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 19 deletions(-) diff --git a/src/Response.php b/src/Response.php index d5b34b8..9c97cfa 100755 --- a/src/Response.php +++ b/src/Response.php @@ -221,6 +221,11 @@ public function exit($data, int $code = 500) */ public function redirect(string $url, int $status = 302) { + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.headers', array_merge($this->headers, ['Location' => $url])); + return; + } + Headers::status($status); Headers::set('Location', $url, true, $status); } @@ -252,9 +257,18 @@ public function withHeader($name, ?string $value = '', $replace = true, int $htt if (is_array($name)) { $this->headers = array_merge($this->headers, $name); + + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.headers', $this->headers); + } + return $this; } + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.headers', array_merge($this->headers, [$name => $value])); + } + if ($replace === false || $httpCode !== 200) { Headers::set($name, $value, $replace, $httpCode); } else { @@ -273,12 +287,11 @@ public function withHeader($name, ?string $value = '', $replace = true, int $htt */ public function withCookie(string $name, string $value, string $expire = "7 days") { - if (!class_exists('Leaf\Http\Cookie')) { - Headers::contentHtml(); - trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); - } + $this->cookies[] = [$name, $value, $expire]; - Cookie::simpleCookie($name, $value, $expire); + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.cookies', $this->cookies); + } return $this; } @@ -290,12 +303,11 @@ public function withCookie(string $name, string $value, string $expire = "7 days */ public function withoutCookie($name) { - if (!class_exists('Leaf\Http\Cookie')) { - Headers::contentHtml(); - trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); - } + $this->cookies[] = [$name, '', -1]; - Cookie::unset($name); + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.cookies', $this->cookies); + } return $this; } @@ -344,6 +356,11 @@ public static function getMessageForCode(int $status): ?string */ public function sendHeaders() { + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.headers', $this->headers); + return $this; + } + // headers have already been sent by the developer if (headers_sent()) { return $this; @@ -357,6 +374,28 @@ public function sendHeaders() return $this; } + /** + * Send cookies + */ + public function sendCookies() + { + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.cookies', $this->cookies); + return $this; + } + + if (!class_exists('Leaf\Http\Cookie')) { + Headers::contentHtml(); + trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); + } + + foreach ($this->cookies as $cookie) { + Cookie::set(...$cookie); + } + + return $this; + } + /** * Sends content for the current web response. * @@ -382,15 +421,10 @@ public function sendContent() */ public function send() { - $this->sendHeaders()->sendContent(); - - if (class_exists('Leaf\Eien\Server')) { - \Leaf\Config::set('response.data', [ - 'headers' => $this->headers, - 'body' => strpos($this->headers['Content-Disposition'] ?? '', 'attachment') !== false - ? readfile($this->content) - : $this->content, - ]); + $this->sendHeaders()->sendCookies()->sendContent(); + + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.headers', $this->headers); } if (\function_exists('fastcgi_finish_request')) { From 731883029af6cf580c115f5aa99c50f0113d7a1b Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 16 Oct 2022 23:52:39 +0000 Subject: [PATCH 044/129] feat: added support for new eien functions --- src/Response.php | 58 +++++++++++++++--------------------------------- 1 file changed, 18 insertions(+), 40 deletions(-) diff --git a/src/Response.php b/src/Response.php index 9c97cfa..35af1e4 100755 --- a/src/Response.php +++ b/src/Response.php @@ -19,7 +19,7 @@ class Response * @var array */ public $headers = []; - + /** * @var array */ @@ -222,7 +222,7 @@ public function exit($data, int $code = 500) public function redirect(string $url, int $status = 302) { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { - \Leaf\Config::set('response.headers', array_merge($this->headers, ['Location' => $url])); + \Leaf\Config::set('response.redirect', [$url, $status]); return; } @@ -252,23 +252,25 @@ public function status($code = null) */ public function withHeader($name, ?string $value = '', $replace = true, int $httpCode = 200) { + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + $this->headers = array_merge( + $this->headers, + is_array($name) ? $name : [$name => $value] + ); + + \Leaf\Config::set('response.headers', $this->headers); + + return $this; + } + $this->status = $httpCode; Headers::status($httpCode); if (is_array($name)) { $this->headers = array_merge($this->headers, $name); - - if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { - \Leaf\Config::set('response.headers', $this->headers); - } - return $this; } - if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { - \Leaf\Config::set('response.headers', array_merge($this->headers, [$name => $value])); - } - if ($replace === false || $httpCode !== 200) { Headers::set($name, $value, $replace, $httpCode); } else { @@ -285,9 +287,9 @@ public function withHeader($name, ?string $value = '', $replace = true, int $htt * @param string $value The value of cookie * @param string $expire When the cookie expires. Default: 7 days */ - public function withCookie(string $name, string $value, string $expire = "7 days") + public function withCookie(string $name, string $value, int $expire = null) { - $this->cookies[] = [$name, $value, $expire]; + $this->cookies[$name] = [$value, $expire ?? (time() + 604800)]; if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.cookies', $this->cookies); @@ -303,7 +305,7 @@ public function withCookie(string $name, string $value, string $expire = "7 days */ public function withoutCookie($name) { - $this->cookies[] = [$name, '', -1]; + $this->cookies[$name] = ['', -1]; if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.cookies', $this->cookies); @@ -389,8 +391,8 @@ public function sendCookies() trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); } - foreach ($this->cookies as $cookie) { - Cookie::set(...$cookie); + foreach ($this->cookies as $key => $value) { + Cookie::set($key, $value[0], ['expire' => $value[1]]); } return $this; @@ -423,10 +425,6 @@ public function send() { $this->sendHeaders()->sendCookies()->sendContent(); - if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { - \Leaf\Config::set('response.headers', $this->headers); - } - if (\function_exists('fastcgi_finish_request')) { fastcgi_finish_request(); } elseif (\function_exists('litespeed_finish_request')) { @@ -457,24 +455,4 @@ public static function closeOutputBuffers(int $targetLevel, bool $flush): void } } } - - /** - * Returns the Response as an HTTP string. - * - * The string representation of the Response is the same as the - * one that will be sent to the client only if the prepare() method - * has been called before. - * - * @return string - */ - public function __toString() - { - Headers::contentPlain(); - return - sprintf('%s %s %s', $this->httpVersion(), $this->status, Status::$statusTexts[$this->status]) . "\r\n" . - implode("", array_map(function ($key, $value) { - return sprintf("%s: %s\r\n", $key, $value); - }, array_keys($this->headers), array_values($this->headers))) . - $this->content; - } } From 593dc1befd6eb00ead6a84298a6f9f600458faa2 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 23 Oct 2022 13:43:58 +0000 Subject: [PATCH 045/129] feat: add support for request headers --- src/Headers.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Headers.php b/src/Headers.php index 3aa54aa..24f5fa9 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -45,6 +45,10 @@ public static function resetStatus($httpCode = 200) */ public static function all(bool $safeOutput = false): array { + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + return \Leaf\Config::get('request.headers'); + } + return ($safeOutput === false) ? self::findHeaders() : \Leaf\Anchor::sanitize(self::findHeaders()); From db6ea4eae8957cdc29586a5d1a3553498313433b Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 22 Dec 2022 01:38:27 +0000 Subject: [PATCH 046/129] fix: remove cookie restriction --- src/Response.php | 66 +++++++++++++++++++++++------------------------- 1 file changed, 32 insertions(+), 34 deletions(-) diff --git a/src/Response.php b/src/Response.php index 35af1e4..c030aff 100755 --- a/src/Response.php +++ b/src/Response.php @@ -56,7 +56,7 @@ public function httpVersion(?string $version = null) /** * Output plain text - * + * * @param mixed $data The data to output * @param int $code The response status code */ @@ -75,7 +75,7 @@ public function plain($data, int $code = 200) * @param string $data The data to output * @param int $code The response status code */ - public function xml($data, int $code = 200) + public function xml(string $data, int $code = 200) { $this->status = $code; $this->headers['Content-Type'] = 'application/xml'; @@ -86,7 +86,7 @@ public function xml($data, int $code = 200) /** * Output json encoded data with an HTTP code/message - * + * * @param mixed $data The data to output * @param int $code The response status code * @param bool $showCode Show response code in body? @@ -115,7 +115,7 @@ public function json($data, int $code = 200, bool $showCode = false) /** * Output data from an HTML or PHP file - * + * * @param string $file The file to output * @param int $code The http status code */ @@ -134,7 +134,7 @@ public function page(string $file, int $code = 200) /** * Output some html/PHP - * + * * @param string $markup The data to output * @param int $code The http status code */ @@ -151,7 +151,7 @@ public function markup(string $markup, int $code = 200) /** * Output plain text - * + * * @param string $file Path to the file to download * @param string|null $name The of the file as shown to user * @param int $code The response status code @@ -190,7 +190,7 @@ public function noContent() /** * Output some data and break the application - * + * * @param mixed $data The data to output * @param int $code The Http status code */ @@ -232,25 +232,26 @@ public function redirect(string $url, int $status = 302) /** * Force set HTTP status code - * - * @param int $httpCode The response code to set + * + * @param int|null code The response code to set */ - public function status($code = null) + public function status(?int $code = null): Response { $this->status = $code; Headers::status($code); + return $this; } /** * set header - * + * * @param string|array $name Header name * @param string|null $value Header value * @param boolean $replace Replace existing header * @param int $httpCode The HTTP status code */ - public function withHeader($name, ?string $value = '', $replace = true, int $httpCode = 200) + public function withHeader($name, ?string $value = '', bool $replace = true, int $httpCode = 200): Response { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { $this->headers = array_merge( @@ -285,9 +286,11 @@ public function withHeader($name, ?string $value = '', $replace = true, int $htt * * @param string $name The name of the cookie * @param string $value The value of cookie - * @param string $expire When the cookie expires. Default: 7 days + * @param int|null $expire When the cookie expires. Default: 7 days + * + * @return Response */ - public function withCookie(string $name, string $value, int $expire = null) + public function withCookie(string $name, string $value, int $expire = null): Response { $this->cookies[$name] = [$value, $expire ?? (time() + 604800)]; @@ -303,7 +306,7 @@ public function withCookie(string $name, string $value, int $expire = null) * * @param mixed $name The name of the cookie */ - public function withoutCookie($name) + public function withoutCookie($name): Response { $this->cookies[$name] = ['', -1]; @@ -317,10 +320,10 @@ public function withoutCookie($name) /** * Flash a piece of data to the session. * - * @param string|array $name The key of the item to set + * @param string|array key The key of the item to set * @param string $value The value of flash item */ - public function withFlash($key, string $value) + public function withFlash($key, string $value): Response { if (!class_exists('Leaf\Http\Session')) { Headers::contentHtml(); @@ -340,7 +343,7 @@ public function withFlash($key, string $value) /** * Get message for HTTP status code - * + * * @param int $status * @return string|null */ @@ -351,12 +354,10 @@ public static function getMessageForCode(int $status): ?string /** * Sends HTTP headers. - * - * @param int $code The http status code to attach * * @return $this */ - public function sendHeaders() + public function sendHeaders(): Response { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.headers', $this->headers); @@ -379,20 +380,17 @@ public function sendHeaders() /** * Send cookies */ - public function sendCookies() + public function sendCookies(): Response { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.cookies', $this->cookies); return $this; } - if (!class_exists('Leaf\Http\Cookie')) { - Headers::contentHtml(); - trigger_error('Leaf cookie not found. Run `leaf install cookie` or `composer require leafs/cookie`'); - } - - foreach ($this->cookies as $key => $value) { - Cookie::set($key, $value[0], ['expire' => $value[1]]); + if (class_exists('Leaf\Http\Cookie')) { + foreach ($this->cookies as $key => $value) { + Cookie::set($key, $value[0], ['expire' => $value[1]]); + } } return $this; @@ -400,12 +398,10 @@ public function sendCookies() /** * Sends content for the current web response. - * - * @param string $content The content to output * * @return $this */ - public function sendContent() + public function sendContent(): Response { if (strpos($this->headers['Content-Disposition'] ?? '', 'attachment') !== false) { readfile($this->content); @@ -418,10 +414,10 @@ public function sendContent() /** * Send the Http headers and content - * + * * @return $this */ - public function send() + public function send(): Response { $this->sendHeaders()->sendCookies()->sendContent(); @@ -432,6 +428,8 @@ public function send() } elseif (!\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) { $this->closeOutputBuffers(0, true); } + + return $this; } /** From 7eb83c47ad92d38636917a61988ee6f960f6e20a Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 22 Dec 2022 08:57:57 +0000 Subject: [PATCH 047/129] fix: patch up null header issue --- src/Request.php | 1001 ++++++++++++++++++++++++----------------------- 1 file changed, 501 insertions(+), 500 deletions(-) diff --git a/src/Request.php b/src/Request.php index 315cbe6..2ba33fa 100755 --- a/src/Request.php +++ b/src/Request.php @@ -16,504 +16,505 @@ */ class Request { - const METHOD_HEAD = 'HEAD'; - const METHOD_GET = 'GET'; - const METHOD_POST = 'POST'; - const METHOD_PUT = 'PUT'; - const METHOD_PATCH = 'PATCH'; - const METHOD_DELETE = 'DELETE'; - const METHOD_OPTIONS = 'OPTIONS'; - const METHOD_OVERRIDE = '_METHOD'; - - /** - * @var array - */ - protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; - - /** - * Get HTTP method - * @return string - */ - public static function getMethod(): string - { - return $_SERVER['REQUEST_METHOD']; - } - - /** - * Check for request method type - * - * @param string $type The type of request to check for - * @return bool - */ - public static function typeIs(string $type): bool - { - return static::getMethod() === strtoupper($type); - } - - /** - * Find if request has a particular header - * - * @param string $header Header to check for - * @return bool - */ - public static function hasHeader(String $header): bool - { - return !!Headers::get($header); - } - - /** - * Is this an AJAX request? - * @return bool - */ - public static function isAjax(): bool - { - if (static::params('isajax')) { - return true; - } - - if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') { - return true; - } - - return false; - } - - /** - * Is this an XHR request? (alias of Leaf_Http_Request::isAjax) - * @return bool - */ - public static function isXhr(): bool - { - return static::isAjax(); - } - - /** - * Access stream that allows you to read raw data from the request body. **This is not for form data** - * - * @param boolean $safeData Sanitize data? - */ - public static function input($safeData = true) - { - $handler = fopen('php://input', 'r'); - $data = stream_get_contents($handler); - - if (Headers::get('Content-Type') === 'application/x-www-form-urlencoded') { - $d = $data; - $data = []; - - foreach (explode('&', $d) as $chunk) { - $param = explode('=', $chunk); - $data[$param[0]] = $param[1]; - } - } else if (strpos(Headers::get('Content-Type') ?? '', 'application/json') !== 0 && strpos(Headers::get('Content-Type'), 'multipart/form-data') !== 0) { - $safeData = false; - $data = [$data]; - } else { - if (!$data) { - $data = json_encode([]); - } - - $parsedData = json_decode($data, true); - $data = is_array($parsedData) ? $parsedData : [$parsedData]; - } - - return $safeData ? \Leaf\Anchor::sanitize($data) : $data; - } - - /** - * Fetch GET and POST data - * - * This method returns a union of GET and POST data as a key-value array, or the value - * of the array key if requested. If the array key does not exist, NULL is returned, - * unless there is a default value specified. - * - * @param string|null $key - * @param mixed|null $default - * - * @return mixed - */ - public static function params(string $key = null, mixed $default = null): mixed - { - $union = static::body(); - - if ($key) { - return $union[$key] ?? $default; - } - - return $union; - } - - /** - * Attempt to retrieve data from the request. - * - * Data which is not found in the request parameters will - * be completely removed instead of returning null. Use `get` - * if you want to return null or `params` if you want to set - * a default value. - * - * @param array $params The parameters to return - * @param bool $safeData Sanitize output? - * @param bool $noEmptyString Remove empty strings from return data? - */ - public static function try(array $params, bool $safeData = true, bool $noEmptyString = false) - { - $data = static::get($params, $safeData); - $dataKeys = array_keys($data); - - foreach ($dataKeys as $key) { - if (!isset($data[$key])) { - unset($data[$key]); - continue; - } - - if ($noEmptyString && !strlen($data[$key])) { - unset($data[$key]); - } - } - - return $data; - } - - /** - * Get raw request data - * - * @param string|array $item The items to output - * @param mixed $default The default value to return if no data is available - */ - public static function rawData($item = null, $default = null) - { - return \Leaf\Anchor::deepGet(static::input(false), $item) ?? $default; - } - - /** - * Return only get request data - * - * @param string|array $item The items to output - * @param mixed $default The default value to return if no data is available - */ - public static function urlData($item = null, $default = null) - { - return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; - } - - /** - * Return only get request data - * - * @param string|array $item The items to output - * @param mixed $default The default value to return if no data is available - */ - public static function postData($item = null, $default = null) - { - return \Leaf\Anchor::deepGet($_POST, $item) ?? $default; - } - - /** - * Returns request data - * - * This methods returns data passed into the request (request or form data). - * This method returns get, post, put patch, delete or raw faw form data or NULL - * if the data isn't found. - * - * @param array|string $params The parameter(s) to return - * @param bool $safeData Sanitize output - */ - public static function get($params, bool $safeData = true) - { - if (is_string($params)) { - return static::body($safeData)[$params] ?? null; - } - - $data = []; - - foreach ($params as $param) { - $data[$param] = static::get($param, $safeData); - } - - return $data; - } - - /** - * Get all the request data as an associative array - * - * @param bool $safeData Sanitize output - */ - public static function body(bool $safeData = true) - { - $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input()); - - return $safeData ? - \Leaf\Anchor::sanitize($finalData) : - $finalData; - } - - /** - * Get all files passed into the request. - * - * @param array|string|null $filenames The file(s) you want to get - */ - public static function files($filenames = null) - { - if ($filenames == null) { - return $_FILES; - } - - if (is_string($filenames)) { - return $_FILES[$filenames] ?? null; - } - - $files = []; - foreach ($filenames as $filename) { - $files[$filename] = $_FILES[$filename] ?? null; - } - return $files; - } - - /** - * Fetch COOKIE data - * - * This method returns a key-value array of Cookie data sent in the HTTP request, or - * the value of a array key if requested; if the array key does not exist, NULL is returned. - * - * @param string|null $key - * @return array|string|null - */ - public static function cookies(string $key = null) - { - return $key === null ? - Cookie::all() : - Cookie::get($key); - } - - /** - * Does the Request body contain parsed form data? - * @return bool - */ - public static function isFormData(): bool - { - $method = static::getMethod(); - - return ($method === self::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), self::$formDataMediaTypes); - } - - /** - * Get Headers - * - * This method returns a key-value array of headers sent in the HTTP request, or - * the value of a hash key if requested; if the array key does not exist, NULL is returned. - * - * @param array|string|null $key The header(s) to return - * @param bool $safeData Attempt to sanitize headers - * - * @return array|string|null - */ - public static function headers($key = null, bool $safeData = true) - { - return ($key === null) ? - Headers::all($safeData) : - Headers::get($key, $safeData); - } - - /** - * Get Content Type - * @return string|null - */ - public static function getContentType(): ?string - { - return Headers::get('CONTENT_TYPE'); - } - - /** - * Get Media Type (type/subtype within Content Type header) - * @return string|null - */ - public static function getMediaType(): ?string - { - $contentType = static::getContentType(); - if ($contentType) { - $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); - - return strtolower($contentTypeParts[0]); - } - - return null; - } - - /** - * Get Media Type Params - * @return array - */ - public static function getMediaTypeParams(): array - { - $contentType = static::getContentType(); - $contentTypeParams = []; - - if ($contentType) { - $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); - $contentTypePartsLength = count($contentTypeParts); - - for ($i = 1; $i < $contentTypePartsLength; $i++) { - $paramParts = explode('=', $contentTypeParts[$i]); - $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; - } - } - - return $contentTypeParams; - } - - /** - * Get Content Charset - * @return string|null - */ - public static function getContentCharset(): ?string - { - $mediaTypeParams = static::getMediaTypeParams(); - if (isset($mediaTypeParams['charset'])) { - return $mediaTypeParams['charset']; - } - - return null; - } - - /** - * Get Content-Length - * @return int - */ - public static function getContentLength(): int - { - return Headers::get('CONTENT_LENGTH') ?? 0; - } - - /** - * Get Host - * @return string - */ - public static function getHost(): string - { - if (isset($_SERVER['HTTP_HOST'])) { - if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $_SERVER['HTTP_HOST'], $matches)) { - return $matches[1]; - } else if (strpos($_SERVER['HTTP_HOST'], ':') !== false) { - $hostParts = explode(':', $_SERVER['HTTP_HOST']); - - return $hostParts[0]; - } - - return $_SERVER['HTTP_HOST']; - } - - return $_SERVER['SERVER_NAME']; - } - - /** - * Get Host with Port - * @return string - */ - public static function getHostWithPort(): string - { - return sprintf('%s:%s', static::getHost(), static::getPort()); - } - - /** - * Get Port - * @return int - */ - public static function getPort(): int - { - return (int) $_SERVER['SERVER_PORT'] ?? 80; - } - - /** - * Get Scheme (https or http) - * @return string - */ - public static function getScheme(): string - { - return empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; - } - - /** - * Get Script Name (physical path) - * @return string - */ - public static function getScriptName(): string - { - return $_SERVER['SCRIPT_NAME']; - } - - /** - * Get Path (physical path + virtual path) - * @return string - */ - public static function getPath(): string - { - return static::getScriptName() . static::getPathInfo(); - } - - /** - * Get Path Info (virtual path) - * @return string|null - */ - public static function getPathInfo(): ?string - { - return $_SERVER['REQUEST_URI'] ?? null; - } - - /** - * Get URL (scheme + host [ + port if non-standard ]) - * @return string - */ - public static function getUrl(): string - { - $url = static::getScheme() . '://' . static::getHost(); - - if ((static::getScheme() === 'https' && static::getPort() !== 443) || (static::getScheme() === 'http' && static::getPort() !== 80)) { - $url .= ':' . static::getPort(); - } - - return $url; - } - - /** - * Get IP - * @return string - */ - public static function getIp(): string - { - $keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR']; - - foreach ($keys as $key) { - if (isset($_SERVER[$key])) { - return $_SERVER[$key]; - } - } - - return $_SERVER['REMOTE_ADDR']; - } - - /** - * Get Referrer - * @return string|null - */ - public static function getReferrer(): ?string - { - return Headers::get('HTTP_REFERER'); - } - - /** - * Get Referer (for those who can't spell) - * @return string|null - */ - public static function getReferer(): ?string - { - return static::getReferrer(); - } - - /** - * Get User Agent - * @return string|null - */ - public static function getUserAgent(): ?string - { - return Headers::get('HTTP_USER_AGENT'); - } + const METHOD_HEAD = 'HEAD'; + const METHOD_GET = 'GET'; + const METHOD_POST = 'POST'; + const METHOD_PUT = 'PUT'; + const METHOD_PATCH = 'PATCH'; + const METHOD_DELETE = 'DELETE'; + const METHOD_OPTIONS = 'OPTIONS'; + const METHOD_OVERRIDE = '_METHOD'; + + /** + * @var array + */ + protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; + + /** + * Get HTTP method + * @return string + */ + public static function getMethod(): string + { + return $_SERVER['REQUEST_METHOD']; + } + + /** + * Check for request method type + * + * @param string $type The type of request to check for + * @return bool + */ + public static function typeIs(string $type): bool + { + return static::getMethod() === strtoupper($type); + } + + /** + * Find if request has a particular header + * + * @param string $header Header to check for + * @return bool + */ + public static function hasHeader(string $header): bool + { + return !!Headers::get($header); + } + + /** + * Is this an AJAX request? + * @return bool + */ + public static function isAjax(): bool + { + if (static::params('isajax')) { + return true; + } + + if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') { + return true; + } + + return false; + } + + /** + * Is this an XHR request? (alias of Leaf_Http_Request::isAjax) + * @return bool + */ + public static function isXhr(): bool + { + return static::isAjax(); + } + + /** + * Access stream that allows you to read raw data from the request body. **This is not for form data** + * + * @param bool $safeData Sanitize data? + */ + public static function input(bool $safeData = true) + { + $handler = fopen('php://input', 'r'); + $data = stream_get_contents($handler); + $content_type = Headers::get('Content-Type') ?? ''; + + if ($content_type === 'application/x-www-form-urlencoded') { + $d = $data; + $data = []; + + foreach (explode('&', $d) as $chunk) { + $param = explode('=', $chunk); + $data[$param[0]] = $param[1]; + } + } else if (strpos($content_type, 'application/json') !== 0 && strpos($content_type, 'multipart/form-data') !== 0) { + $safeData = false; + $data = [$data]; + } else { + if (!$data) { + $data = json_encode([]); + } + + $parsedData = json_decode($data, true); + $data = is_array($parsedData) ? $parsedData : [$parsedData]; + } + + return $safeData ? \Leaf\Anchor::sanitize($data) : $data; + } + + /** + * Fetch GET and POST data + * + * This method returns a union of GET and POST data as a key-value array, or the value + * of the array key if requested. If the array key does not exist, NULL is returned, + * unless there is a default value specified. + * + * @param string|null $key + * @param mixed|null $default + * + * @return mixed + */ + public static function params(string $key = null, $default = null) + { + $union = static::body(); + + if ($key) { + return $union[$key] ?? $default; + } + + return $union; + } + + /** + * Attempt to retrieve data from the request. + * + * Data which is not found in the request parameters will + * be completely removed instead of returning null. Use `get` + * if you want to return null or `params` if you want to set + * a default value. + * + * @param array $params The parameters to return + * @param bool $safeData Sanitize output? + * @param bool $noEmptyString Remove empty strings from return data? + */ + public static function try(array $params, bool $safeData = true, bool $noEmptyString = false) + { + $data = static::get($params, $safeData); + $dataKeys = array_keys($data); + + foreach ($dataKeys as $key) { + if (!isset($data[$key])) { + unset($data[$key]); + continue; + } + + if ($noEmptyString && !strlen($data[$key])) { + unset($data[$key]); + } + } + + return $data; + } + + /** + * Get raw request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function rawData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet(static::input(false), $item) ?? $default; + } + + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function urlData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; + } + + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function postData($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_POST, $item) ?? $default; + } + + /** + * Returns request data + * + * This methods returns data passed into the request (request or form data). + * This method returns get, post, put patch, delete or raw faw form data or NULL + * if the data isn't found. + * + * @param array|string $params The parameter(s) to return + * @param bool $safeData Sanitize output + */ + public static function get($params, bool $safeData = true) + { + if (is_string($params)) { + return static::body($safeData)[$params] ?? null; + } + + $data = []; + + foreach ($params as $param) { + $data[$param] = static::get($param, $safeData); + } + + return $data; + } + + /** + * Get all the request data as an associative array + * + * @param bool $safeData Sanitize output + */ + public static function body(bool $safeData = true) + { + $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input()); + + return $safeData ? + \Leaf\Anchor::sanitize($finalData) : + $finalData; + } + + /** + * Get all files passed into the request. + * + * @param array|string|null $filenames The file(s) you want to get + */ + public static function files($filenames = null) + { + if ($filenames == null) { + return $_FILES; + } + + if (is_string($filenames)) { + return $_FILES[$filenames] ?? null; + } + + $files = []; + foreach ($filenames as $filename) { + $files[$filename] = $_FILES[$filename] ?? null; + } + return $files; + } + + /** + * Fetch COOKIE data + * + * This method returns a key-value array of Cookie data sent in the HTTP request, or + * the value of a array key if requested; if the array key does not exist, NULL is returned. + * + * @param string|null $key + * @return array|string|null + */ + public static function cookies(string $key = null) + { + return $key === null ? + Cookie::all() : + Cookie::get($key); + } + + /** + * Does the Request body contain parsed form data? + * @return bool + */ + public static function isFormData(): bool + { + $method = static::getMethod(); + + return ($method === self::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), self::$formDataMediaTypes); + } + + /** + * Get Headers + * + * This method returns a key-value array of headers sent in the HTTP request, or + * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * + * @param array|string|null $key The header(s) to return + * @param bool $safeData Attempt to sanitize headers + * + * @return array|string|null + */ + public static function headers($key = null, bool $safeData = true) + { + return ($key === null) ? + Headers::all($safeData) : + Headers::get($key, $safeData); + } + + /** + * Get Content Type + * @return string|null + */ + public static function getContentType(): ?string + { + return Headers::get('CONTENT_TYPE'); + } + + /** + * Get Media Type (type/subtype within Content Type header) + * @return string|null + */ + public static function getMediaType(): ?string + { + $contentType = static::getContentType(); + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + + return strtolower($contentTypeParts[0]); + } + + return null; + } + + /** + * Get Media Type Params + * @return array + */ + public static function getMediaTypeParams(): array + { + $contentType = static::getContentType(); + $contentTypeParams = []; + + if ($contentType) { + $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); + $contentTypePartsLength = count($contentTypeParts); + + for ($i = 1; $i < $contentTypePartsLength; $i++) { + $paramParts = explode('=', $contentTypeParts[$i]); + $contentTypeParams[strtolower($paramParts[0])] = $paramParts[1]; + } + } + + return $contentTypeParams; + } + + /** + * Get Content Charset + * @return string|null + */ + public static function getContentCharset(): ?string + { + $mediaTypeParams = static::getMediaTypeParams(); + if (isset($mediaTypeParams['charset'])) { + return $mediaTypeParams['charset']; + } + + return null; + } + + /** + * Get Content-Length + * @return int + */ + public static function getContentLength(): int + { + return Headers::get('CONTENT_LENGTH') ?? 0; + } + + /** + * Get Host + * @return string + */ + public static function getHost(): string + { + if (isset($_SERVER['HTTP_HOST'])) { + if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $_SERVER['HTTP_HOST'], $matches)) { + return $matches[1]; + } else if (strpos($_SERVER['HTTP_HOST'], ':') !== false) { + $hostParts = explode(':', $_SERVER['HTTP_HOST']); + + return $hostParts[0]; + } + + return $_SERVER['HTTP_HOST']; + } + + return $_SERVER['SERVER_NAME']; + } + + /** + * Get Host with Port + * @return string + */ + public static function getHostWithPort(): string + { + return sprintf('%s:%s', static::getHost(), static::getPort()); + } + + /** + * Get Port + * @return int + */ + public static function getPort(): int + { + return (int)$_SERVER['SERVER_PORT'] ?? 80; + } + + /** + * Get Scheme (https or http) + * @return string + */ + public static function getScheme(): string + { + return empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === 'off' ? 'http' : 'https'; + } + + /** + * Get Script Name (physical path) + * @return string + */ + public static function getScriptName(): string + { + return $_SERVER['SCRIPT_NAME']; + } + + /** + * Get Path (physical path + virtual path) + * @return string + */ + public static function getPath(): string + { + return static::getScriptName() . static::getPathInfo(); + } + + /** + * Get Path Info (virtual path) + * @return string|null + */ + public static function getPathInfo(): ?string + { + return $_SERVER['REQUEST_URI'] ?? null; + } + + /** + * Get URL (scheme + host [ + port if non-standard ]) + * @return string + */ + public static function getUrl(): string + { + $url = static::getScheme() . '://' . static::getHost(); + + if ((static::getScheme() === 'https' && static::getPort() !== 443) || (static::getScheme() === 'http' && static::getPort() !== 80)) { + $url .= ':' . static::getPort(); + } + + return $url; + } + + /** + * Get IP + * @return string + */ + public static function getIp(): string + { + $keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR']; + + foreach ($keys as $key) { + if (isset($_SERVER[$key])) { + return $_SERVER[$key]; + } + } + + return $_SERVER['REMOTE_ADDR']; + } + + /** + * Get Referrer + * @return string|null + */ + public static function getReferrer(): ?string + { + return Headers::get('HTTP_REFERER'); + } + + /** + * Get Referer (for those who can't spell) + * @return string|null + */ + public static function getReferer(): ?string + { + return static::getReferrer(); + } + + /** + * Get User Agent + * @return string|null + */ + public static function getUserAgent(): ?string + { + return Headers::get('HTTP_USER_AGENT'); + } } From 2809c6e5ed4c691d9d4b5d188e0c2af91e4f9b90 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 22 Dec 2022 18:41:12 +0000 Subject: [PATCH 048/129] fix: patch up dirty urlencoded data --- src/Request.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Request.php b/src/Request.php index 2ba33fa..3d38306 100755 --- a/src/Request.php +++ b/src/Request.php @@ -104,7 +104,7 @@ public static function input(bool $safeData = true) foreach (explode('&', $d) as $chunk) { $param = explode('=', $chunk); - $data[$param[0]] = $param[1]; + $data[$param[0]] = urldecode($param[1]); } } else if (strpos($content_type, 'application/json') !== 0 && strpos($content_type, 'multipart/form-data') !== 0) { $safeData = false; @@ -211,7 +211,7 @@ public static function postData($item = null, $default = null) /** * Returns request data * - * This methods returns data passed into the request (request or form data). + * This method returns data passed into the request (request or form data). * This method returns get, post, put patch, delete or raw faw form data or NULL * if the data isn't found. * @@ -240,7 +240,7 @@ public static function get($params, bool $safeData = true) */ public static function body(bool $safeData = true) { - $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input()); + $finalData = array_merge(static::urlData(), $_FILES, static::postData(), static::input(false)); return $safeData ? \Leaf\Anchor::sanitize($finalData) : @@ -273,7 +273,7 @@ public static function files($filenames = null) * Fetch COOKIE data * * This method returns a key-value array of Cookie data sent in the HTTP request, or - * the value of a array key if requested; if the array key does not exist, NULL is returned. + * the value of an array key if requested. If the array key does not exist, NULL is returned. * * @param string|null $key * @return array|string|null @@ -300,7 +300,7 @@ public static function isFormData(): bool * Get Headers * * This method returns a key-value array of headers sent in the HTTP request, or - * the value of a hash key if requested; if the array key does not exist, NULL is returned. + * the value of a hash key if requested. If the array key does not exist, NULL is returned. * * @param array|string|null $key The header(s) to return * @param bool $safeData Attempt to sanitize headers From aecb2892da2e162ca55c217569bdb7bac51c14c1 Mon Sep 17 00:00:00 2001 From: induwara16 <122541423+induwara16@users.noreply.github.com> Date: Thu, 12 Jan 2023 19:54:38 +0530 Subject: [PATCH 049/129] Make Headers::get case insensitive Because if a header is set like this: `Content-type: application/json` ``` Headers::get('Content-Type'); // null Headers::get('Content-type'); // 'application/json' ``` Causes problems in the `Request::get` method because it looks exactly for `Content-Type`. --- src/Headers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Headers.php b/src/Headers.php index 24f5fa9..0fd3cc9 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -64,7 +64,7 @@ public static function all(bool $safeOutput = false): array */ public static function get($params, bool $safeOutput = false) { - if (is_string($params)) return self::all($safeOutput)[$params] ?? null; + if (is_string($params)) return array_change_key_case(self::all($safeOutput), CASE_LOWER)[strtolower($params)] ?? null; $data = []; foreach ($params as $param) { From 10ad20ba719b2e0e93e01d3108af4581ce62bda6 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 20 Apr 2023 20:15:44 +0000 Subject: [PATCH 050/129] fix: add content headers for download --- src/Response.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Response.php b/src/Response.php index c030aff..9c7e73f 100755 --- a/src/Response.php +++ b/src/Response.php @@ -165,11 +165,14 @@ public function download(string $file, string $name = null, int $code = 200) trigger_error("$file not found. Confirm your file path."); } - if ($name === null) $name = basename($file); - $this->headers = array_merge($this->headers, [ + 'Expires' => '0', + 'Pragma' => 'public', 'Content-Length' => filesize($file), - 'Content-Disposition' => "attachment; filename=$name", + 'Cache-Control' => 'must-revalidate', + 'Content-Description' => 'File Transfer', + 'Content-Type' => 'application/octet-stream', + 'Content-Disposition' => 'attachment; filename="' . $name ?? basename($file) . '"', ]); $this->content = $file; From 672727050cf57c04dc6318233fcbf44aa27d4e1a Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 20 Apr 2023 20:16:16 +0000 Subject: [PATCH 051/129] chore: update gitignore --- .gitignore | 23 +++++++++++++++++++---- 1 file changed, 19 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index f56cefe..fa28908 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,19 @@ -test -Experimental -vendor -composer.lock \ No newline at end of file +# Global +.phpunit* +.composer +composer.lock +package-lock.json +.phpunit.result.cache +.php-cs-fixer.cache +vendor/ +test/ + +# OS Generated +.DS_Store* +ehthumbs.db +Icon? +Thumbs.db +*.swp + +# phpstorm +.idea/* From 77eebb3db4c722f04f9ca53ee28e9c62a5294505 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 20 Apr 2023 20:43:16 +0000 Subject: [PATCH 052/129] chore: update composer.json --- composer.json | 68 +++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/composer.json b/composer.json index 261b5c9..49ae879 100644 --- a/composer.json +++ b/composer.json @@ -1,37 +1,37 @@ { - "name": "leafs/http", - "description": "Leaf PHP HTTP module.", - "keywords": [ - "http", - "request", - "response", - "headers", - "leaf", - "php", - "framework" - ], - "homepage": "https://leafphp.netlify.app/#/", - "type": "library", - "license": "MIT", - "authors": [ - { - "name": "Michael Darko", - "email": "mickdd22@gmail.com", - "homepage": "https://mychi.netlify.app", - "role": "Developer" - } - ], - "autoload": { - "psr-4": { - "Leaf\\Http\\": "src" - }, - "files": [ - "src/functions.php" - ] - }, - "minimum-stability": "dev", - "prefer-stable": true, - "require": { - "leafs/anchor": "*" + "name": "leafs/http", + "description": "Leaf PHP HTTP module.", + "keywords": [ + "http", + "request", + "response", + "headers", + "leaf", + "php", + "framework" + ], + "homepage": "https://leafphp.dev/modules/http/v/2/request.html", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Michael Darko", + "email": "mickdd22@gmail.com", + "homepage": "https://mychi.netlify.app", + "role": "Developer" } + ], + "autoload": { + "psr-4": { + "Leaf\\Http\\": "src" + }, + "files": [ + "src/functions.php" + ] + }, + "minimum-stability": "dev", + "prefer-stable": true, + "require": { + "leafs/anchor": "*" + } } From bc80630ba62656a6e0e57d9689535dfc101df47a Mon Sep 17 00:00:00 2001 From: kczx3 Date: Wed, 26 Apr 2023 18:48:44 -0400 Subject: [PATCH 053/129] fix: isAjax header correction (#15) Correct the header name format to determine if the request is an ajax one --- src/Request.php | 10 +--------- 1 file changed, 1 insertion(+), 9 deletions(-) diff --git a/src/Request.php b/src/Request.php index 3d38306..1be60e2 100755 --- a/src/Request.php +++ b/src/Request.php @@ -67,15 +67,7 @@ public static function hasHeader(string $header): bool */ public static function isAjax(): bool { - if (static::params('isajax')) { - return true; - } - - if (Headers::get('X_REQUESTED_WITH') && Headers::get('X_REQUESTED_WITH') === 'XMLHttpRequest') { - return true; - } - - return false; + return !!static::params('isajax') || Headers::get('X-Requested-With') === 'XMLHttpRequest'; } /** From e971c95279f5dd1177ffdbe296c586620df431a8 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 19 Jul 2023 23:16:44 +0000 Subject: [PATCH 054/129] feat: add request validation --- composer.json | 5 +++-- src/Request.php | 22 +++++++++++++++++++++- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/composer.json b/composer.json index 49ae879..196d1f4 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "leafs/http", - "description": "Leaf PHP HTTP module.", + "description": "Http abstraction for Leaf PHP", "keywords": [ "http", "request", @@ -32,6 +32,7 @@ "minimum-stability": "dev", "prefer-stable": true, "require": { - "leafs/anchor": "*" + "leafs/anchor": "*", + "leafs/form": "v2.x-dev" } } diff --git a/src/Request.php b/src/Request.php index 1be60e2..7129b34 100755 --- a/src/Request.php +++ b/src/Request.php @@ -306,6 +306,25 @@ public static function headers($key = null, bool $safeData = true) Headers::get($key, $safeData); } + /** + * Validate the request data + * @param array $rules The rules to validate against + * @return bool + */ + public static function validate(array $rules) + { + return \Leaf\Form::validate(static::body(false), $rules); + } + + /** + * Handle errors from validation + * @return array + */ + public static function errors() + { + return \Leaf\Form::errors(); + } + /** * Get Content Type * @return string|null @@ -360,6 +379,7 @@ public static function getMediaTypeParams(): array public static function getContentCharset(): ?string { $mediaTypeParams = static::getMediaTypeParams(); + if (isset($mediaTypeParams['charset'])) { return $mediaTypeParams['charset']; } @@ -412,7 +432,7 @@ public static function getHostWithPort(): string */ public static function getPort(): int { - return (int)$_SERVER['SERVER_PORT'] ?? 80; + return (int) $_SERVER['SERVER_PORT'] ?? 80; } /** From cc03c75373a80987a00529df561c6ace47d9615c Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 24 Jul 2023 09:57:16 +0000 Subject: [PATCH 055/129] feat: added support for auth functions --- src/Request.php | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/src/Request.php b/src/Request.php index 7129b34..be75198 100755 --- a/src/Request.php +++ b/src/Request.php @@ -12,7 +12,7 @@ * * @author Michael Darko * @since 1.0.0 - * @version 2.0 + * @version 2.3.0 */ class Request { @@ -316,13 +316,40 @@ public static function validate(array $rules) return \Leaf\Form::validate(static::body(false), $rules); } + /** + * @return \Leaf\Auth + */ + protected static function auth() + { + if (!class_exists('\Leaf\Auth')) { + throw new \Exception("You need to install the leaf-auth package to use the auth helper"); + } + + if (!(\Leaf\Config::get('auth.instance'))) { + \Leaf\Config::set('auth.instance', new \Leaf\Auth()); + } + + return \Leaf\Config::get('auth.instance'); + } + + /** + * Get the authenticated user + */ + public static function user() + { + return static::auth()->user(); + } + /** * Handle errors from validation * @return array */ public static function errors() { - return \Leaf\Form::errors(); + return array_merge( + \Leaf\Form::errors(), + static::auth()->errors() + ); } /** From 0373670eac4b1a045f2ab3bdd7ed4abfd68b6027 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 12 Aug 2023 14:30:29 +0000 Subject: [PATCH 056/129] fix: patch up content_type issue --- src/Request.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Request.php b/src/Request.php index be75198..d0192d2 100755 --- a/src/Request.php +++ b/src/Request.php @@ -88,9 +88,9 @@ public static function input(bool $safeData = true) { $handler = fopen('php://input', 'r'); $data = stream_get_contents($handler); - $content_type = Headers::get('Content-Type') ?? ''; + $contentType = Headers::get('Content-Type') ?? ''; - if ($content_type === 'application/x-www-form-urlencoded') { + if ($contentType === 'application/x-www-form-urlencoded') { $d = $data; $data = []; @@ -98,7 +98,7 @@ public static function input(bool $safeData = true) $param = explode('=', $chunk); $data[$param[0]] = urldecode($param[1]); } - } else if (strpos($content_type, 'application/json') !== 0 && strpos($content_type, 'multipart/form-data') !== 0) { + } else if (strpos($contentType, 'application/json') !== 0 && strpos($contentType, 'multipart/form-data') !== 0) { $safeData = false; $data = [$data]; } else { @@ -358,7 +358,7 @@ public static function errors() */ public static function getContentType(): ?string { - return Headers::get('CONTENT_TYPE'); + return Headers::get('Content-Type'); } /** From a7db41477cfe8bc82d42b3b689166d796c90e99c Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 12 Aug 2023 14:35:31 +0000 Subject: [PATCH 057/129] feat: return parsed data when validation succeeds --- src/Request.php | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index d0192d2..8aa694a 100755 --- a/src/Request.php +++ b/src/Request.php @@ -308,21 +308,30 @@ public static function headers($key = null, bool $safeData = true) /** * Validate the request data + * * @param array $rules The rules to validate against - * @return bool + * + * @return false|array Returns false if validation fails, or the validated data if validation passes */ public static function validate(array $rules) { - return \Leaf\Form::validate(static::body(false), $rules); + $data = \Leaf\Form::validate(static::body(false), $rules); + + if ($data === false) { + return false; + } + + return static::body(); } /** + * Return the auth instance * @return \Leaf\Auth */ protected static function auth() { if (!class_exists('\Leaf\Auth')) { - throw new \Exception("You need to install the leaf-auth package to use the auth helper"); + throw new \Exception("You need to install the leafs/auth package to use the auth helper"); } if (!(\Leaf\Config::get('auth.instance'))) { From 36be8ac1c960f4c5581598cb901352fe3e986685 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 19 Aug 2023 20:18:15 +0000 Subject: [PATCH 058/129] feat: add option to return full data --- src/Request.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 8aa694a..94e8c92 100755 --- a/src/Request.php +++ b/src/Request.php @@ -310,10 +310,11 @@ public static function headers($key = null, bool $safeData = true) * Validate the request data * * @param array $rules The rules to validate against + * @param boolean $returnFullData Return the full data or just the validated data? * * @return false|array Returns false if validation fails, or the validated data if validation passes */ - public static function validate(array $rules) + public static function validate(array $rules, bool $returnFullData = false) { $data = \Leaf\Form::validate(static::body(false), $rules); @@ -321,7 +322,7 @@ public static function validate(array $rules) return false; } - return static::body(); + return $returnFullData ? $data : static::get(array_keys($rules)); } /** @@ -331,7 +332,7 @@ public static function validate(array $rules) protected static function auth() { if (!class_exists('\Leaf\Auth')) { - throw new \Exception("You need to install the leafs/auth package to use the auth helper"); + throw new \Exception('You need to install the leafs/auth package to use the auth helper'); } if (!(\Leaf\Config::get('auth.instance'))) { From d54f6dc5c28a4e0c0294c39ebdd05d3c059d86f2 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 24 Aug 2023 22:52:10 +0000 Subject: [PATCH 059/129] fix: patch up deps versions --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 196d1f4..971662e 100644 --- a/composer.json +++ b/composer.json @@ -33,6 +33,6 @@ "prefer-stable": true, "require": { "leafs/anchor": "*", - "leafs/form": "v2.x-dev" + "leafs/form": "*" } } From 5a04b4c0a145f97629757876a7983e4efb5e6660 Mon Sep 17 00:00:00 2001 From: Abdulbasit Rubeya Date: Wed, 7 Aug 2024 01:04:00 +0300 Subject: [PATCH 060/129] Added `store` and `storeAs` methods --- src/Request.php | 72 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/Request.php b/src/Request.php index 94e8c92..97f519d 100755 --- a/src/Request.php +++ b/src/Request.php @@ -566,4 +566,76 @@ public static function getUserAgent(): ?string { return Headers::get('HTTP_USER_AGENT'); } + + /** + * Store a file from the request. + * + * @param string $key The name of the file input the request. + * @param string $destination The directory where the file should be stored. + * @param array $configs Optional configurations: max_file_size, file_type, extensions + * @return array An array containing the status, path, and error message. + */ + public static function store(string $key, string $destination, array $configs = []): object + { + $configs["unique"] = true; + + # See PR notes #1 + if(isset($configs["extensions"])) { + $file = self::get($key); + $fileExtension = pathinfo($file["name"], PATHINFO_EXTENSION); + if(!in_array($fileExtension, $configs["extensions"])) { + return (object) [ + 'status' => false, + 'error' => 'Invalid file extension.' + ]; + } + } + + $fileSystem = new \Leaf\FS; + $uploadedFile = $fileSystem::uploadFile(self::get($key), $destination, $configs); + if(!$uploadedFile) + return (object) [ + 'status' => false, + 'error' => $fileSystem::$errorsArray['upload'] + ]; + + return (object) array_shift($fileSystem::$uploadInfo); + } + + /** + * Store a file from the request with a specific name. + * + * @param string $key The name of the file input the request. + * @param string $destination The directory where the file should be stored. + * @param string $filename The name to give the stored file. + * @param array $configs Optional configurations: max_file_size, file_type, extensions + * @return array An array containing the status, path, and error message. + */ + public static function storeAs(string $key, string $destination, string $filename, array $configs = []): object + { + $configs["rename"] = true; + $configs["name"] = $filename; + + # See PR notes #1 + if(isset($configs["extensions"])) { + $file = self::get($key); + $fileExtension = pathinfo($file["name"], PATHINFO_EXTENSION); + if(!in_array($fileExtension, $configs["extensions"])) { + return (object) [ + 'status' => false, + 'error' => 'Invalid file extension.' + ]; + } + } + + $fileSystem = new \Leaf\FS; + $uploadedFile = $fileSystem::uploadFile(self::get($key), $destination, $configs); + if(!$uploadedFile) + return (object) [ + 'status' => false, + 'error' => $fileSystem::$errorsArray['upload'] + ]; + + return (object) array_shift($fileSystem::$uploadInfo); + } } From 6c5a221a686a457e2d3cdb4264d63d0d0b880757 Mon Sep 17 00:00:00 2001 From: Abdulbasit Rubeya Date: Wed, 7 Aug 2024 01:06:42 +0300 Subject: [PATCH 061/129] Update composer.json Require leafs/fs for store and storeAs methods to work --- composer.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 971662e..f6f5af2 100644 --- a/composer.json +++ b/composer.json @@ -33,6 +33,7 @@ "prefer-stable": true, "require": { "leafs/anchor": "*", - "leafs/form": "*" + "leafs/form": "*", + "leafs/fs": "*" } } From 0dc32fcd41bbaa4ce2d8567f9ecd8be30701495d Mon Sep 17 00:00:00 2001 From: Abdulbasit Rubeya Date: Sat, 10 Aug 2024 23:14:14 +0300 Subject: [PATCH 062/129] Prefixed file destination to the storage basePath --- src/Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Request.php b/src/Request.php index 97f519d..90ff53c 100755 --- a/src/Request.php +++ b/src/Request.php @@ -592,7 +592,7 @@ public static function store(string $key, string $destination, array $configs = } $fileSystem = new \Leaf\FS; - $uploadedFile = $fileSystem::uploadFile(self::get($key), $destination, $configs); + $uploadedFile = $fileSystem::uploadFile(self::get($key), StoragePath($destination), $configs); if(!$uploadedFile) return (object) [ 'status' => false, @@ -629,7 +629,7 @@ public static function storeAs(string $key, string $destination, string $filenam } $fileSystem = new \Leaf\FS; - $uploadedFile = $fileSystem::uploadFile(self::get($key), $destination, $configs); + $uploadedFile = $fileSystem::uploadFile(self::get($key), storagePath($destination), $configs); if(!$uploadedFile) return (object) [ 'status' => false, From 103d4bcee4e49603436527de3e7aaa40afec20fa Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 14 Aug 2024 04:35:42 +0000 Subject: [PATCH 063/129] feat: switch to new leaf DI --- src/functions.php | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/functions.php b/src/functions.php index 864143c..43711e2 100644 --- a/src/functions.php +++ b/src/functions.php @@ -11,14 +11,13 @@ function request() { if (class_exists('\Leaf\Config')) { - $request = Leaf\Config::get("request")["instance"] ?? null; - - if (!$request) { - $request = new \Leaf\Http\Request; - Leaf\Config::set("request", ["instance" => $request]); + if (!\Leaf\Config::getStatic('request')) { + \Leaf\Config::singleton('request', function () { + return new \Leaf\Http\Request; + }); } - return $request; + return \Leaf\Config::get('request'); } return new \Leaf\Http\Request(); @@ -36,14 +35,13 @@ function request() function response() { if (class_exists('\Leaf\Config')) { - $response = Leaf\Config::get("response")["instance"] ?? null; - - if (!$response) { - $response = new \Leaf\Http\Response; - Leaf\Config::set("response", ["instance" => $response]); + if (!\Leaf\Config::getStatic('response')) { + \Leaf\Config::singleton('response', function () { + return new \Leaf\Http\Response; + }); } - return $response; + return \Leaf\Config::get('response'); } return new \Leaf\Http\Response(); From 192092d6d85600155cd8f44607ad775422a699a0 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 14 Aug 2024 04:36:20 +0000 Subject: [PATCH 064/129] feat: update upload & fix request issues --- src/Request.php | 147 ++++++++++++++++++++---------------------------- 1 file changed, 61 insertions(+), 86 deletions(-) diff --git a/src/Request.php b/src/Request.php index 90ff53c..d2c8630 100755 --- a/src/Request.php +++ b/src/Request.php @@ -29,6 +29,7 @@ class Request * @var array */ protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; + protected static $errors = []; /** * Get HTTP method @@ -285,7 +286,7 @@ public static function isFormData(): bool { $method = static::getMethod(); - return ($method === self::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), self::$formDataMediaTypes); + return ($method === static::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), static::$formDataMediaTypes); } /** @@ -318,10 +319,6 @@ public static function validate(array $rules, bool $returnFullData = false) { $data = \Leaf\Form::validate(static::body(false), $rules); - if ($data === false) { - return false; - } - return $returnFullData ? $data : static::get(array_keys($rules)); } @@ -332,14 +329,16 @@ public static function validate(array $rules, bool $returnFullData = false) protected static function auth() { if (!class_exists('\Leaf\Auth')) { - throw new \Exception('You need to install the leafs/auth package to use the auth helper'); + throw new \Exception('You need to install the leafs/auth module to use the auth helper'); } - if (!(\Leaf\Config::get('auth.instance'))) { - \Leaf\Config::set('auth.instance', new \Leaf\Auth()); + if (!(\Leaf\Config::getStatic('auth'))) { + \Leaf\Config::singleton('auth', function () { + return new \Leaf\Auth; + }); } - return \Leaf\Config::get('auth.instance'); + return \Leaf\Config::get('auth'); } /** @@ -351,15 +350,50 @@ public static function user() } /** - * Handle errors from validation - * @return array + * Store a file from the request. + * + * @param string $key The name of the file input the request. + * @param string $destination The directory where the file should be stored. + * @param array $config Optional configurations: max_file_size, file_type, extensions + * + * @return array|false An array containing the status or false for a failure. */ - public static function errors() + public static function upload(string $key, string $destination, array $config = []) { - return array_merge( - \Leaf\Form::errors(), - static::auth()->errors() + $file = static::files($key); + + if (!$file) { + static::$errors['upload'] = 'No file was uploaded.'; + return false; + } + + if (isset($config['extensions'])) { + $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION); + + if (!in_array($fileExtension, $config['extensions'])) { + static::$errors['upload'] = 'Invalid file extension.'; + return false; + } + } + + $config['unique'] = true; + $fileSystem = new \Leaf\FS; + $uploadedFile = $fileSystem->uploadFile( + $file, + preg_replace( + '/\/$/', + '', + $destination + ) . '/', + $config ); + + if (!$uploadedFile) { + static::$errors = $fileSystem->errors(); + return false; + } + + return $fileSystem->uploadInfo($uploadedFile); } /** @@ -378,6 +412,7 @@ public static function getContentType(): ?string public static function getMediaType(): ?string { $contentType = static::getContentType(); + if ($contentType) { $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); @@ -393,8 +428,8 @@ public static function getMediaType(): ?string */ public static function getMediaTypeParams(): array { - $contentType = static::getContentType(); $contentTypeParams = []; + $contentType = static::getContentType(); if ($contentType) { $contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType); @@ -444,7 +479,6 @@ public static function getHost(): string return $matches[1]; } else if (strpos($_SERVER['HTTP_HOST'], ':') !== false) { $hostParts = explode(':', $_SERVER['HTTP_HOST']); - return $hostParts[0]; } @@ -568,74 +602,15 @@ public static function getUserAgent(): ?string } /** - * Store a file from the request. - * - * @param string $key The name of the file input the request. - * @param string $destination The directory where the file should be stored. - * @param array $configs Optional configurations: max_file_size, file_type, extensions - * @return array An array containing the status, path, and error message. - */ - public static function store(string $key, string $destination, array $configs = []): object - { - $configs["unique"] = true; - - # See PR notes #1 - if(isset($configs["extensions"])) { - $file = self::get($key); - $fileExtension = pathinfo($file["name"], PATHINFO_EXTENSION); - if(!in_array($fileExtension, $configs["extensions"])) { - return (object) [ - 'status' => false, - 'error' => 'Invalid file extension.' - ]; - } - } - - $fileSystem = new \Leaf\FS; - $uploadedFile = $fileSystem::uploadFile(self::get($key), StoragePath($destination), $configs); - if(!$uploadedFile) - return (object) [ - 'status' => false, - 'error' => $fileSystem::$errorsArray['upload'] - ]; - - return (object) array_shift($fileSystem::$uploadInfo); - } - - /** - * Store a file from the request with a specific name. - * - * @param string $key The name of the file input the request. - * @param string $destination The directory where the file should be stored. - * @param string $filename The name to give the stored file. - * @param array $configs Optional configurations: max_file_size, file_type, extensions - * @return array An array containing the status, path, and error message. - */ - public static function storeAs(string $key, string $destination, string $filename, array $configs = []): object - { - $configs["rename"] = true; - $configs["name"] = $filename; - - # See PR notes #1 - if(isset($configs["extensions"])) { - $file = self::get($key); - $fileExtension = pathinfo($file["name"], PATHINFO_EXTENSION); - if(!in_array($fileExtension, $configs["extensions"])) { - return (object) [ - 'status' => false, - 'error' => 'Invalid file extension.' - ]; - } - } - - $fileSystem = new \Leaf\FS; - $uploadedFile = $fileSystem::uploadFile(self::get($key), storagePath($destination), $configs); - if(!$uploadedFile) - return (object) [ - 'status' => false, - 'error' => $fileSystem::$errorsArray['upload'] - ]; - - return (object) array_shift($fileSystem::$uploadInfo); + * Handle errors from validation/auth/upload + * @return array + */ + public static function errors() + { + return array_merge( + static::$errors, + \Leaf\Form::errors(), + class_exists('\Leaf\Auth') ? static::auth()->errors() : [] + ); } } From 75743d6485087855a227af65b70bfadf2b52ae64 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 14 Aug 2024 04:37:12 +0000 Subject: [PATCH 065/129] fix: patch up redirect base url --- src/Response.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Response.php b/src/Response.php index 9c7e73f..7890ae0 100755 --- a/src/Response.php +++ b/src/Response.php @@ -229,6 +229,10 @@ public function redirect(string $url, int $status = 302) return; } + if (class_exists('Leaf\App')) { + $url = str_replace('//', '/', app()->getBasePath() . $url); + } + Headers::status($status); Headers::set('Location', $url, true, $status); } From 2be5cbbf2c60c86e8b56c71aefefb20868b97388 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 19 Aug 2024 19:08:49 +0000 Subject: [PATCH 066/129] feat: use new config API --- src/Headers.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Headers.php b/src/Headers.php index 0fd3cc9..51bb7df 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -46,7 +46,7 @@ public static function resetStatus($httpCode = 200) public static function all(bool $safeOutput = false): array { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { - return \Leaf\Config::get('request.headers'); + return \Leaf\Config::getStatic('request.headers'); } return ($safeOutput === false) ? From 1882a7c784fa62a18bd81a030eaafae08be490fb Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 24 Aug 2024 20:59:50 +0000 Subject: [PATCH 067/129] feat: restore uploadAs --- src/Request.php | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/src/Request.php b/src/Request.php index d2c8630..458eae8 100755 --- a/src/Request.php +++ b/src/Request.php @@ -396,6 +396,22 @@ public static function upload(string $key, string $destination, array $config = return $fileSystem->uploadInfo($uploadedFile); } + /** + * Store a file from the request with a given name + * + * @param string $key The name of the file input the request. + * @param string $destination The directory where the file should be stored. + * @param string $name The name to store the file as. + * @param array $config Optional configurations: max_file_size, file_type, extensions + */ + public static function uploadAs(string $key, string $destination, string $name, array $config = []) + { + $config['name'] = $name; + $config['rename'] = true; + + return static::upload($key, $destination, $config); + } + /** * Get Content Type * @return string|null From 8f3b9d47cb40f3aa8d3d71d4f848c05b12638544 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 24 Aug 2024 21:08:39 +0000 Subject: [PATCH 068/129] fix: temporary fix (will update later) --- src/Request.php | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/Request.php b/src/Request.php index 458eae8..db74b6e 100755 --- a/src/Request.php +++ b/src/Request.php @@ -319,6 +319,10 @@ public static function validate(array $rules, bool $returnFullData = false) { $data = \Leaf\Form::validate(static::body(false), $rules); + if ($data === false) { + return false; + } + return $returnFullData ? $data : static::get(array_keys($rules)); } From c7753c1f7fe566ff4e9a450b6e44414f097b4ac5 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 16 Sep 2024 17:17:25 +0000 Subject: [PATCH 069/129] feat: add middleware data --- src/Request.php | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/src/Request.php b/src/Request.php index db74b6e..e57f258 100755 --- a/src/Request.php +++ b/src/Request.php @@ -25,11 +25,8 @@ class Request const METHOD_OPTIONS = 'OPTIONS'; const METHOD_OVERRIDE = '_METHOD'; - /** - * @var array - */ - protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; protected static $errors = []; + protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; /** * Get HTTP method @@ -353,6 +350,18 @@ public static function user() return static::auth()->user(); } + /** + * Get data passed from the previous middleware + * + * @param string|null $key The key to get from the middleware data + */ + public static function next($key = null) + { + $middlewareData = \Leaf\Config::getStatic('middleware.data'); + + return $key ? $middlewareData[$key] : $middlewareData; + } + /** * Store a file from the request. * From b413eb905a5daec9e8943e083e4a6f821e11219e Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 16 Sep 2024 17:57:05 +0000 Subject: [PATCH 070/129] feat: add response->die --- src/Response.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Response.php b/src/Response.php index 7890ae0..0bc869b 100755 --- a/src/Response.php +++ b/src/Response.php @@ -213,6 +213,17 @@ public function exit($data, int $code = 500) exit(); } + /** + * Output some data and break the application + * + * @param mixed $data The data to output + * @param int $code The Http status code + */ + public function die($data, int $code = 500) + { + $this->exit($data, $code); + } + /** * Redirect * From 9a02b3c3dd70241c1c5bd7178ce35a75360d6fd7 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 16 Sep 2024 17:57:47 +0000 Subject: [PATCH 071/129] feat: add query and getOrDefault methods --- src/Request.php | 69 +++++++++++++++++++++++++++++++------------------ 1 file changed, 44 insertions(+), 25 deletions(-) diff --git a/src/Request.php b/src/Request.php index e57f258..530b010 100755 --- a/src/Request.php +++ b/src/Request.php @@ -111,29 +111,6 @@ public static function input(bool $safeData = true) return $safeData ? \Leaf\Anchor::sanitize($data) : $data; } - /** - * Fetch GET and POST data - * - * This method returns a union of GET and POST data as a key-value array, or the value - * of the array key if requested. If the array key does not exist, NULL is returned, - * unless there is a default value specified. - * - * @param string|null $key - * @param mixed|null $default - * - * @return mixed - */ - public static function params(string $key = null, $default = null) - { - $union = static::body(); - - if ($key) { - return $union[$key] ?? $default; - } - - return $union; - } - /** * Attempt to retrieve data from the request. * @@ -187,6 +164,17 @@ public static function urlData($item = null, $default = null) return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; } + /** + * Return only get request data + * + * @param string|array $item The items to output + * @param mixed $default The default value to return if no data is available + */ + public static function query($item = null, $default = null) + { + return \Leaf\Anchor::deepGet($_GET, $item) ?? $default; + } + /** * Return only get request data * @@ -201,8 +189,7 @@ public static function postData($item = null, $default = null) /** * Returns request data * - * This method returns data passed into the request (request or form data). - * This method returns get, post, put patch, delete or raw faw form data or NULL + * This method returns get, post, put patch, delete or raw form data or NULL * if the data isn't found. * * @param array|string $params The parameter(s) to return @@ -223,6 +210,38 @@ public static function get($params, bool $safeData = true) return $data; } + /** + * Returns request data + * + * This method returns get, post, put patch, delete or raw form data or NULL + * if the data isn't found. + * + * @param string|null $key + * @param mixed|null $default + * + * @return mixed + */ + public static function params(string $key = null, $default = null) + { + return static::get($key) ?? $default; + } + + /** + * Returns request data + * + * This method returns get, post, put patch, delete or raw form data or NULL + * if the data isn't found. + * + * @param string|null $key + * @param mixed|null $default + * + * @return mixed + */ + public static function getOrDefault(string $key = null, $default = null) + { + return static::get($key) ?? $default; + } + /** * Get all the request data as an associative array * From c506a576a7dc23275a81d68993761c57fc0ced8f Mon Sep 17 00:00:00 2001 From: Torben Buck Date: Fri, 27 Sep 2024 13:16:40 +0200 Subject: [PATCH 072/129] add custom responses (fix #21) (#22) * add custom echo response resolves #21 * add js response --- src/Response.php | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/src/Response.php b/src/Response.php index 0bc869b..93adcc2 100755 --- a/src/Response.php +++ b/src/Response.php @@ -54,6 +54,21 @@ public function httpVersion(?string $version = null) return $this; } + /** + * Output any text + * + * @param string $data The data to output + * @param int $code The response status code + */ + public function echo(string $data, int $code = 200) + { + $this->status = $code; + $this->headers['Content-Type'] ??= 'text/plain'; + $this->content = $data; + + $this->send(); + } + /** * Output plain text * @@ -83,6 +98,21 @@ public function xml(string $data, int $code = 200) $this->send(); } + + /** + * Output js script + * + * @param string $data The data to output + * @param int $code The response status code + */ + public function js(string $data, int $code = 200) + { + $this->status = $code; + $this->headers['Content-Type'] = 'text/javascript'; + $this->content = $data; + + $this->send(); + } /** * Output json encoded data with an HTTP code/message From c7397aa3605b10c74c614bf0f4997eb12324ab95 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 1 Oct 2024 16:12:08 +0000 Subject: [PATCH 073/129] feat: add response::next method --- src/Response.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Response.php b/src/Response.php index 93adcc2..17056e1 100755 --- a/src/Response.php +++ b/src/Response.php @@ -278,6 +278,17 @@ public function redirect(string $url, int $status = 302) Headers::set('Location', $url, true, $status); } + + /** + * Pass data to the route handler + * + * @param mixed $data The data to pass + */ + public function next($data) + { + \Leaf\Config::set('middleware.data', $data); + } + /** * Force set HTTP status code * From 7be4caa852cc8b317b9ef8afc34b2ed26d10131c Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 1 Oct 2024 16:28:07 +0000 Subject: [PATCH 074/129] chore: clean up --- src/Response.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index 17056e1..a4c77c4 100755 --- a/src/Response.php +++ b/src/Response.php @@ -278,7 +278,6 @@ public function redirect(string $url, int $status = 302) Headers::set('Location', $url, true, $status); } - /** * Pass data to the route handler * From 0e25aa984b2a5c71ac8c425afb754808bd06e08a Mon Sep 17 00:00:00 2001 From: Abdulbasit Rubeya Date: Sat, 12 Oct 2024 21:51:40 +0300 Subject: [PATCH 075/129] fix: prevent unique name generation when rename is true --- src/Request.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Request.php b/src/Request.php index 530b010..0ba96fe 100755 --- a/src/Request.php +++ b/src/Request.php @@ -407,9 +407,9 @@ public static function upload(string $key, string $destination, array $config = return false; } } - - $config['unique'] = true; + $fileSystem = new \Leaf\FS; + (isset($config['rename']) || $config['rename']) ?: $config['unique'] = true; $uploadedFile = $fileSystem->uploadFile( $file, preg_replace( From fe50aef2682e16d1b1fddda21efdeae6e7de917a Mon Sep 17 00:00:00 2001 From: Abdulbasit Rubeya Date: Sat, 12 Oct 2024 22:41:47 +0300 Subject: [PATCH 076/129] fix: prevent unique name generation when rename is true --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 0ba96fe..0c311f7 100755 --- a/src/Request.php +++ b/src/Request.php @@ -409,7 +409,7 @@ public static function upload(string $key, string $destination, array $config = } $fileSystem = new \Leaf\FS; - (isset($config['rename']) || $config['rename']) ?: $config['unique'] = true; + if(!isset($config['rename']) || !$config['rename']) $config['unique'] = true; $uploadedFile = $fileSystem->uploadFile( $file, preg_replace( From aa42931f0db37696ef67c33e864a034061bc743d Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 4 Nov 2024 20:54:04 +0000 Subject: [PATCH 077/129] chore: update readme --- README.md | 140 ++++++------------------------------------------------ 1 file changed, 15 insertions(+), 125 deletions(-) diff --git a/README.md b/README.md index 3780c46..a213ab0 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,11 @@



- +

-

Leaf Http v2

+

Leaf Http


-Leaf's core http functionality packaged as a serve-yourself module. **Although seperated from Leaf core, it is still part of the default initial installation and doesn't need to be installed manually (unless you want a particular version).** +Leaf's HTTP abstraction is a developer friendly way to interact with HTTP requests and responses. If you are using it within a Leaf app, there's no need to install anything as it comes pre-installed with Leaf. If you are using it outside of Leaf, you can install it via composer. ## Installation @@ -45,140 +45,30 @@ composer require leafs/http ## Basic Usage -The http module comes with a bunch of packages which help you manage the input and output of your app or API. This module comes with the most used Http related functionality like requests, responses, ... +You can find the full documentation on how to use Leaf Http [here](https://leafphp.dev/docs/http/request). -The available classes in the Http module are: - -- [`Leaf\Http\Request`](https://leafphp.dev/modules/http/request) -- [`Leaf\Http\Response`](https://leafphp.dev/modules/http/response) -- [`Leaf\Http\Headers`](https://leafphp.dev/modules/http/headers) -- [`Leaf\Http\Cache`](https://leafphp.dev/modules/http/cache) -- [`Leaf\Http\Status`](https://leafphp.dev/modules/http/status) - -**The docs for Leaf Http v2 can be found at [https://leafphp.dev/modules/http/v/2/](https://leafphp.dev/modules/http/v/2/).** - -## Request - -This is a developer friendly interface which allows you to interact with data coming into your application. [Read the docs](https://leafphp.dev/modules/http/request) - -## Response - -This interface allows you to output data from your application in different forms. [Read the docs](https://leafphp.dev/modules/http/response) - -## Headers - -This interface allows you to manage headers in your application. [Read the docs](https://leafphp.dev/modules/http/headers) - -## Cache - -This interface allows you to manage http cache in your app. [Read the docs](https://leafphp.dev/modules/http/cache) - -## Status - -This interface allows you to manage http status codes in your app. [Read the docs](https://leafphp.dev/modules/http/status) - -**There are also some add on classes which can be installed on demand.** - -## Session (module) - -This module allows you to manage session in your application. [Read the docs](/modules/session/) - -## Cookies (module) - -This module allows you to manage cookies in your application. [Read the docs](/modules/cookies) - -## 💬 Stay In Touch +## Stay In Touch - [Twitter](https://twitter.com/leafphp) - [Join the forum](https://github.com/leafsphp/leaf/discussions/37) - [Chat on discord](https://discord.com/invite/Pkrm9NJPE3) -## 📓 Learning Leaf 3 +## Learning Leaf PHP - Leaf has a very easy to understand [documentation](https://leafphp.dev) which contains information on all operations in Leaf. - You can also check out our [youtube channel](https://www.youtube.com/channel/UCllE-GsYy10RkxBUK0HIffw) which has video tutorials on different topics -- We are also working on codelabs which will bring hands-on tutorials you can follow and contribute to. +- You can also learn from [codelabs](https://leafphp.dev/codelabs/) and contribute as well. -## 😇 Contributing +## Contributing We are glad to have you. All contributions are welcome! To get started, familiarize yourself with our [contribution guide](https://leafphp.dev/community/contributing.html) and you'll be ready to make your first pull request 🚀. To report a security vulnerability, you can reach out to [@mychidarko](https://twitter.com/mychidarko) or [@leafphp](https://twitter.com/leafphp) on twitter. We will coordinate the fix and eventually commit the solution in this project. -### Code contributors - - - - - - -
- - -
- - Michael Darko - -
-
- - -
- - Dreamer0x01 - -
-
- -## 🤩 Sponsoring Leaf - -Your cash contributions go a long way to help us make Leaf even better for you. You can sponsor Leaf and any of our packages on [open collective](https://opencollective.com/leaf) or check the [contribution page](https://leafphp.dev/support/) for a list of ways to contribute. - -And to all our existing cash/code contributors, we love you all ❤️ - -### Cash contributors - - - - - - - - -
- - -
- Aaron Smith -
-
- - -
- Peter Bogner -
-
- - -
- Vano -
-
- - -
- Casprine -
-
- -## 🤯 Links/Projects - -- [Aloe CLI](https://leafphp.dev/aloe-cli/) -- [Leaf Docs](https://leafphp.dev) -- [Leaf MVC](https://mvc.leafphp.dev) -- [Leaf API](https://api.leafphp.dev) -- [Leaf CLI](https://cli.leafphp.dev) +## Sponsoring Leaf + +We are committed to keeping Leaf open-source and free, but maintaining and developing new features now requires significant time and resources. As the project has grown, so have the costs, which have been mostly covered by the team. To sustain and grow Leaf, we need your help to support full-time maintainers. + +You can sponsor Leaf and any of our packages on [open collective](https://opencollective.com/leaf) or check the [contribution page](https://leafphp.dev/support/) for a list of ways to contribute. + +And to all our [existing cash/code contributors](https://leafphp.dev#sponsors), we love you all ❤️ From 82103fa74d6e59d6791df23de50acaa63c5656dd Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 4 Nov 2024 22:32:08 +0000 Subject: [PATCH 078/129] feat: add support for named routes on redirect --- src/Response.php | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/src/Response.php b/src/Response.php index a4c77c4..c194d62 100755 --- a/src/Response.php +++ b/src/Response.php @@ -260,20 +260,24 @@ public function die($data, int $code = 500) * This method prepares this response to return an HTTP Redirect response * to the HTTP client. * - * @param string $url The redirect destination + * @param string|array $url The redirect destination * @param int $status The redirect HTTP status code */ - public function redirect(string $url, int $status = 302) + public function redirect($url, int $status = 302) { - if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { - \Leaf\Config::set('response.redirect', [$url, $status]); - return; + if (is_array($url)) { + $url = app()->route($url[0]); } if (class_exists('Leaf\App')) { $url = str_replace('//', '/', app()->getBasePath() . $url); } + if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { + \Leaf\Config::set('response.redirect', [$url, $status]); + return; + } + Headers::status($status); Headers::set('Location', $url, true, $status); } From e9149bfdb15f7441fb7013c5e72f7c63d3ad089b Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 4 Nov 2024 22:33:03 +0000 Subject: [PATCH 079/129] feat: add internal validator instance --- src/Request.php | 38 +++++++++++++++++++++++++++++++++++--- 1 file changed, 35 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 0c311f7..2ff0273 100755 --- a/src/Request.php +++ b/src/Request.php @@ -27,6 +27,17 @@ class Request protected static $errors = []; protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; + + /** + * Internal instance of Leaf Form + * @var \Leaf\Form + */ + protected static $validator; + + public function __construct() + { + static::$validator = new \Leaf\Form; + } /** * Get HTTP method @@ -333,7 +344,11 @@ public static function headers($key = null, bool $safeData = true) */ public static function validate(array $rules, bool $returnFullData = false) { - $data = \Leaf\Form::validate(static::body(false), $rules); + if (!static::$validator) { + static::$validator = new \Leaf\Form; + } + + $data = static::$validator->validate(static::body(false), $rules); if ($data === false) { return false; @@ -342,6 +357,19 @@ public static function validate(array $rules, bool $returnFullData = false) return $returnFullData ? $data : static::get(array_keys($rules)); } + /** + * Return validator instance + * @return \Leaf\Form + */ + public static function validator() + { + if (!static::$validator) { + static::$validator = new \Leaf\Form; + } + + return static::$validator; + } + /** * Return the auth instance * @return \Leaf\Auth @@ -409,7 +437,11 @@ public static function upload(string $key, string $destination, array $config = } $fileSystem = new \Leaf\FS; - if(!isset($config['rename']) || !$config['rename']) $config['unique'] = true; + + if (!isset($config['rename']) || !$config['rename']) { + $config['unique'] = true; + } + $uploadedFile = $fileSystem->uploadFile( $file, preg_replace( @@ -657,7 +689,7 @@ public static function errors() { return array_merge( static::$errors, - \Leaf\Form::errors(), + static::$validator ? static::$validator->errors() : [], class_exists('\Leaf\Auth') ? static::auth()->errors() : [] ); } From 78dca3cfafe47d54ce8cd729b386d3aa436cd294 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 6 Nov 2024 14:02:25 +0000 Subject: [PATCH 080/129] chore: add fs constraint --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index f6f5af2..0b2ce7d 100644 --- a/composer.json +++ b/composer.json @@ -34,6 +34,6 @@ "require": { "leafs/anchor": "*", "leafs/form": "*", - "leafs/fs": "*" + "leafs/fs": "^1.3" } } From 32e152e23e73da29610d46ed771a390cd3b8802d Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 8 Nov 2024 13:49:20 +0000 Subject: [PATCH 081/129] fix: patch up withFlash function --- src/Response.php | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/src/Response.php b/src/Response.php index c194d62..33763f0 100755 --- a/src/Response.php +++ b/src/Response.php @@ -56,7 +56,7 @@ public function httpVersion(?string $version = null) /** * Output any text - * + * * @param string $data The data to output * @param int $code The response status code */ @@ -98,10 +98,10 @@ public function xml(string $data, int $code = 200) $this->send(); } - + /** * Output js script - * + * * @param string $data The data to output * @param int $code The response status code */ @@ -245,7 +245,7 @@ public function exit($data, int $code = 500) /** * Output some data and break the application - * + * * @param mixed $data The data to output * @param int $code The Http status code */ @@ -284,7 +284,7 @@ public function redirect($url, int $status = 302) /** * Pass data to the route handler - * + * * @param mixed $data The data to pass */ public function next($data) @@ -383,9 +383,11 @@ public function withoutCookie($name): Response * Flash a piece of data to the session. * * @param string|array key The key of the item to set - * @param string $value The value of flash item + * @param mixed $value The value of flash item + * + * @return Response */ - public function withFlash($key, string $value): Response + public function withFlash($key, $value = null): Response { if (!class_exists('Leaf\Http\Session')) { Headers::contentHtml(); @@ -398,7 +400,7 @@ public function withFlash($key, string $value): Response } } - \Leaf\Flash::set($key, $value); + \Leaf\Flash::set($value, $key); return $this; } From af449772496d8c1670b6a4fdec0e226d79c35911 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 8 Nov 2024 14:49:16 +0000 Subject: [PATCH 082/129] fix: patch up validation returnFullData --- src/Request.php | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/Request.php b/src/Request.php index 2ff0273..4f66668 100755 --- a/src/Request.php +++ b/src/Request.php @@ -27,7 +27,7 @@ class Request protected static $errors = []; protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; - + /** * Internal instance of Leaf Form * @var \Leaf\Form @@ -236,7 +236,7 @@ public static function params(string $key = null, $default = null) { return static::get($key) ?? $default; } - + /** * Returns request data * @@ -336,10 +336,10 @@ public static function headers($key = null, bool $safeData = true) /** * Validate the request data - * + * * @param array $rules The rules to validate against * @param boolean $returnFullData Return the full data or just the validated data? - * + * * @return false|array Returns false if validation fails, or the validated data if validation passes */ public static function validate(array $rules, bool $returnFullData = false) @@ -354,7 +354,7 @@ public static function validate(array $rules, bool $returnFullData = false) return false; } - return $returnFullData ? $data : static::get(array_keys($rules)); + return $returnFullData ? static::body() : $data; } /** @@ -399,7 +399,7 @@ public static function user() /** * Get data passed from the previous middleware - * + * * @param string|null $key The key to get from the middleware data */ public static function next($key = null) @@ -415,7 +415,7 @@ public static function next($key = null) * @param string $key The name of the file input the request. * @param string $destination The directory where the file should be stored. * @param array $config Optional configurations: max_file_size, file_type, extensions - * + * * @return array|false An array containing the status or false for a failure. */ public static function upload(string $key, string $destination, array $config = []) @@ -435,13 +435,13 @@ public static function upload(string $key, string $destination, array $config = return false; } } - + $fileSystem = new \Leaf\FS; if (!isset($config['rename']) || !$config['rename']) { $config['unique'] = true; } - + $uploadedFile = $fileSystem->uploadFile( $file, preg_replace( @@ -462,7 +462,7 @@ public static function upload(string $key, string $destination, array $config = /** * Store a file from the request with a given name - * + * * @param string $key The name of the file input the request. * @param string $destination The directory where the file should be stored. * @param string $name The name to store the file as. From e5bb44cce7324099e161d4b22c7f62b7401d682e Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 8 Nov 2024 15:09:32 +0000 Subject: [PATCH 083/129] feat: add redirect exit --- src/Response.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index 33763f0..0e4146b 100755 --- a/src/Response.php +++ b/src/Response.php @@ -263,7 +263,7 @@ public function die($data, int $code = 500) * @param string|array $url The redirect destination * @param int $status The redirect HTTP status code */ - public function redirect($url, int $status = 302) + public function redirect($url, int $status = 302, bool $exit = true) { if (is_array($url)) { $url = app()->route($url[0]); @@ -280,6 +280,10 @@ public function redirect($url, int $status = 302) Headers::status($status); Headers::set('Location', $url, true, $status); + + if ($exit) { + exit($status); + } } /** From af0dba3c071f2f1ac625d537d2c359ee8c8dce19 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 8 Nov 2024 23:41:04 +0000 Subject: [PATCH 084/129] feat: update version constraints --- .gitignore | 3 +++ composer.json | 72 +++++++++++++++++++++++++-------------------------- 2 files changed, 39 insertions(+), 36 deletions(-) diff --git a/.gitignore b/.gitignore index fa28908..945d7be 100644 --- a/.gitignore +++ b/.gitignore @@ -17,3 +17,6 @@ Thumbs.db # phpstorm .idea/* + +# Alchemy +.alchemy diff --git a/composer.json b/composer.json index 0b2ce7d..96afa5e 100644 --- a/composer.json +++ b/composer.json @@ -1,39 +1,39 @@ { - "name": "leafs/http", - "description": "Http abstraction for Leaf PHP", - "keywords": [ - "http", - "request", - "response", - "headers", - "leaf", - "php", - "framework" - ], - "homepage": "https://leafphp.dev/modules/http/v/2/request.html", - "type": "library", - "license": "MIT", - "authors": [ - { - "name": "Michael Darko", - "email": "mickdd22@gmail.com", - "homepage": "https://mychi.netlify.app", - "role": "Developer" - } - ], - "autoload": { - "psr-4": { - "Leaf\\Http\\": "src" + "name": "leafs/http", + "description": "Http abstraction for Leaf PHP", + "keywords": [ + "http", + "request", + "response", + "headers", + "leaf", + "php", + "framework" + ], + "homepage": "https://leafphp.dev/modules/http/v/2/request.html", + "type": "library", + "license": "MIT", + "authors": [ + { + "name": "Michael Darko", + "email": "mickdd22@gmail.com", + "homepage": "https://mychi.netlify.app", + "role": "Developer" + } + ], + "autoload": { + "psr-4": { + "Leaf\\Http\\": "src" + }, + "files": [ + "src/functions.php" + ] }, - "files": [ - "src/functions.php" - ] - }, - "minimum-stability": "dev", - "prefer-stable": true, - "require": { - "leafs/anchor": "*", - "leafs/form": "*", - "leafs/fs": "^1.3" - } + "minimum-stability": "dev", + "prefer-stable": true, + "require": { + "leafs/anchor": "*", + "leafs/form": "^3.0", + "leafs/fs": "^2.0" + } } From c0553e5cfd603ea0364c2f12b3f07c73870eef0d Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Sun, 10 Nov 2024 22:54:57 +0000 Subject: [PATCH 085/129] fix: patch up empty form error (#24) --- src/Request.php | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 4f66668..bcc0f55 100755 --- a/src/Request.php +++ b/src/Request.php @@ -103,9 +103,11 @@ public static function input(bool $safeData = true) $d = $data; $data = []; - foreach (explode('&', $d) as $chunk) { - $param = explode('=', $chunk); - $data[$param[0]] = urldecode($param[1]); + if ($d) { + foreach (explode('&', $d) as $chunk) { + $param = explode('=', $chunk); + $data[$param[0]] = urldecode($param[1]); + } } } else if (strpos($contentType, 'application/json') !== 0 && strpos($contentType, 'multipart/form-data') !== 0) { $safeData = false; From 38edd9a56e3d7046b04f6700d8b20419604cb793 Mon Sep 17 00:00:00 2001 From: Joan Miquel Date: Wed, 27 Nov 2024 16:28:33 +0100 Subject: [PATCH 086/129] Update Request.php fix explicit nullable php 8.4 (#27) * Update Request.php fix explicit nullable php 8.4 * Update Response.php fix explicit nullable php 8.4 * Update Headers.php fix explicit nullable php 8.4 --- src/Headers.php | 2 +- src/Request.php | 6 +++--- src/Response.php | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Headers.php b/src/Headers.php index 51bb7df..2bea2d1 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -22,7 +22,7 @@ class Headers * * @param int|null $httpCode The current response code. */ - public static function status(int $httpCode = null) + public static function status(?int $httpCode = null) { if ($httpCode === null) return self::$httpCode; self::$httpCode = $httpCode; diff --git a/src/Request.php b/src/Request.php index bcc0f55..45a6501 100755 --- a/src/Request.php +++ b/src/Request.php @@ -234,7 +234,7 @@ public static function get($params, bool $safeData = true) * * @return mixed */ - public static function params(string $key = null, $default = null) + public static function params(?string $key = null, $default = null) { return static::get($key) ?? $default; } @@ -250,7 +250,7 @@ public static function params(string $key = null, $default = null) * * @return mixed */ - public static function getOrDefault(string $key = null, $default = null) + public static function getOrDefault(?string $key = null, $default = null) { return static::get($key) ?? $default; } @@ -300,7 +300,7 @@ public static function files($filenames = null) * @param string|null $key * @return array|string|null */ - public static function cookies(string $key = null) + public static function cookies(?string $key = null) { return $key === null ? Cookie::all() : diff --git a/src/Response.php b/src/Response.php index 0e4146b..e676aa5 100755 --- a/src/Response.php +++ b/src/Response.php @@ -186,7 +186,7 @@ public function markup(string $markup, int $code = 200) * @param string|null $name The of the file as shown to user * @param int $code The response status code */ - public function download(string $file, string $name = null, int $code = 200) + public function download(string $file, ?string $name = null, int $code = 200) { $this->status = $code; @@ -356,7 +356,7 @@ public function withHeader($name, ?string $value = '', bool $replace = true, int * * @return Response */ - public function withCookie(string $name, string $value, int $expire = null): Response + public function withCookie(string $name, string $value, ?int $expire = null): Response { $this->cookies[$name] = [$value, $expire ?? (time() + 604800)]; From 75ebfa2eb7af6fdbd6cada8cc49e4eca648691e3 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 4 Dec 2024 14:49:53 +0000 Subject: [PATCH 087/129] fix: patch up external url redirects --- src/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index e676aa5..afb540d 100755 --- a/src/Response.php +++ b/src/Response.php @@ -269,7 +269,7 @@ public function redirect($url, int $status = 302, bool $exit = true) $url = app()->route($url[0]); } - if (class_exists('Leaf\App')) { + if (class_exists('Leaf\App') && !strpos($url, '://')) { $url = str_replace('//', '/', app()->getBasePath() . $url); } From f311f5357c59b3731bb964bfe24062b3bb55e420 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 5 Dec 2024 21:15:48 +0000 Subject: [PATCH 088/129] feat: add custom method --- src/Response.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index afb540d..0eb80a4 100755 --- a/src/Response.php +++ b/src/Response.php @@ -55,12 +55,23 @@ public function httpVersion(?string $version = null) } /** - * Output any text + * Alias of custom * * @param string $data The data to output * @param int $code The response status code */ public function echo(string $data, int $code = 200) + { + $this->custom($data, $code); + } + + /** + * Output any text + * + * @param string $data The data to output + * @param int $code The response status code + */ + public function custom(string $data, int $code = 200) { $this->status = $code; $this->headers['Content-Type'] ??= 'text/plain'; From 8713b4d3f54b5598c1f9b9a257c5fb510c6253a0 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 6 Dec 2024 14:38:14 +0000 Subject: [PATCH 089/129] fix: normalize request path methods --- src/Request.php | 29 ++++++++++++++++++++++++++--- 1 file changed, 26 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 45a6501..44eb82b 100755 --- a/src/Request.php +++ b/src/Request.php @@ -598,7 +598,7 @@ public static function getScheme(): string } /** - * Get Script Name (physical path) + * Get Script Name * @return string */ public static function getScriptName(): string @@ -607,12 +607,26 @@ public static function getScriptName(): string } /** - * Get Path (physical path + virtual path) + * Get physical path + * @return string + */ + public static function getPhysicalPath(): string + { + return dirname($_SERVER['SCRIPT_NAME']); + } + + /** + * Get Path * @return string */ public static function getPath(): string { - return static::getScriptName() . static::getPathInfo(); + $physicalPath = static::getPhysicalPath(); + + return substr( + parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH), + $physicalPath == '/' ? 0 : strlen($physicalPath) + ); } /** @@ -624,6 +638,15 @@ public static function getPathInfo(): ?string return $_SERVER['REQUEST_URI'] ?? null; } + /** + * Get query string + * @return string|null + */ + public static function getQueryString(): ?string + { + return $_SERVER['QUERY_STRING'] ?? null; + } + /** * Get URL (scheme + host [ + port if non-standard ]) * @return string From 7a8500a50c329aff57a9db95b134df4092194600 Mon Sep 17 00:00:00 2001 From: Roman Andreevich <38112007+phederal@users.noreply.github.com> Date: Fri, 6 Dec 2024 17:39:34 +0300 Subject: [PATCH 090/129] support router args if using router with name (#28) --- src/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index 0eb80a4..560a407 100755 --- a/src/Response.php +++ b/src/Response.php @@ -277,7 +277,7 @@ public function die($data, int $code = 500) public function redirect($url, int $status = 302, bool $exit = true) { if (is_array($url)) { - $url = app()->route($url[0]); + $url = app()->route($url[0], ...array_slice($url, 1)); } if (class_exists('Leaf\App') && !strpos($url, '://')) { From e276d9026a6fae5393c155e89f56c0c9dd12901b Mon Sep 17 00:00:00 2001 From: Abdulbasit Rubeya Date: Mon, 23 Dec 2024 14:31:46 +0300 Subject: [PATCH 091/129] fix: Compatibility with the latest `Leaf\FS` package --- src/Request.php | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/src/Request.php b/src/Request.php index 44eb82b..62c0a1d 100755 --- a/src/Request.php +++ b/src/Request.php @@ -438,13 +438,13 @@ public static function upload(string $key, string $destination, array $config = } } - $fileSystem = new \Leaf\FS; + $fileSystem = new \Leaf\FS\File; if (!isset($config['rename']) || !$config['rename']) { $config['unique'] = true; } - $uploadedFile = $fileSystem->uploadFile( + $uploadedFile = $fileSystem->upload( $file, preg_replace( '/\/$/', @@ -454,12 +454,7 @@ public static function upload(string $key, string $destination, array $config = $config ); - if (!$uploadedFile) { - static::$errors = $fileSystem->errors(); - return false; - } - - return $fileSystem->uploadInfo($uploadedFile); + return $uploadedFile; } /** @@ -472,8 +467,10 @@ public static function upload(string $key, string $destination, array $config = */ public static function uploadAs(string $key, string $destination, string $name, array $config = []) { - $config['name'] = $name; + $fileExtension = pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION); + $config['rename'] = true; + $config['name'] = $name . '.' . $fileExtension; return static::upload($key, $destination, $config); } From b56629036d1571eaeacd650566dd060d702b6e16 Mon Sep 17 00:00:00 2001 From: Etom Usang Date: Thu, 16 Jan 2025 18:40:51 +0100 Subject: [PATCH 092/129] Fixed issue: 'Fatal error with unofficial http status codes' (#34) --- src/Response.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Response.php b/src/Response.php index 560a407..737721b 100755 --- a/src/Response.php +++ b/src/Response.php @@ -451,7 +451,7 @@ public function sendHeaders(): Response Headers::set($this->headers); // status - header(sprintf('%s %s %s', $this->httpVersion(), $this->status, Status::$statusTexts[$this->status]), true, $this->status); + header(sprintf('%s %s %s', $this->httpVersion(), $this->status, Status::$statusTexts[$this->status] ?? ''), true, $this->status); return $this; } From 05351738e7a7123e2ff3f6b3fb64c5b46c5b030d Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 17 Jan 2025 00:27:39 +0000 Subject: [PATCH 093/129] feat: add support for method overrides --- src/Request.php | 47 ++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 38 insertions(+), 9 deletions(-) diff --git a/src/Request.php b/src/Request.php index 62c0a1d..61bb291 100755 --- a/src/Request.php +++ b/src/Request.php @@ -16,14 +16,14 @@ */ class Request { - const METHOD_HEAD = 'HEAD'; - const METHOD_GET = 'GET'; - const METHOD_POST = 'POST'; - const METHOD_PUT = 'PUT'; - const METHOD_PATCH = 'PATCH'; - const METHOD_DELETE = 'DELETE'; - const METHOD_OPTIONS = 'OPTIONS'; - const METHOD_OVERRIDE = '_METHOD'; + public const METHOD_HEAD = 'HEAD'; + public const METHOD_GET = 'GET'; + public const METHOD_POST = 'POST'; + public const METHOD_PUT = 'PUT'; + public const METHOD_PATCH = 'PATCH'; + public const METHOD_DELETE = 'DELETE'; + public const METHOD_OPTIONS = 'OPTIONS'; + public const METHOD_OVERRIDE = '_METHOD'; protected static $errors = []; protected static $formDataMediaTypes = ['application/x-www-form-urlencoded']; @@ -44,10 +44,39 @@ public function __construct() * @return string */ public static function getMethod(): string + { + if ($method = static::methodOverride()) { + return $method; + } + + return static::getOriginalMethod(); + } + + /** + * Get original method + */ + public static function getOriginalMethod(): string { return $_SERVER['REQUEST_METHOD']; } + /** + * Is this a method override request? + * @return string|null + */ + public static function methodOverride() + { + if ($method = static::headers('X-Http-Method-Override')) { + return strtoupper($method); + } + + if (static::getOriginalMethod() === 'POST') { + return strtoupper(static::get(static::METHOD_OVERRIDE)); + } + + return null; + } + /** * Check for request method type * @@ -468,7 +497,7 @@ public static function upload(string $key, string $destination, array $config = public static function uploadAs(string $key, string $destination, string $name, array $config = []) { $fileExtension = pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION); - + $config['rename'] = true; $config['name'] = $name . '.' . $fileExtension; From 92346172290d189385b668fbd9a315dc9df7a400 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 17 Jan 2025 00:29:58 +0000 Subject: [PATCH 094/129] chore: clean up --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 61bb291..7146079 100755 --- a/src/Request.php +++ b/src/Request.php @@ -499,7 +499,7 @@ public static function uploadAs(string $key, string $destination, string $name, $fileExtension = pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION); $config['rename'] = true; - $config['name'] = $name . '.' . $fileExtension; + $config['name'] = "$name.$fileExtension"; return static::upload($key, $destination, $config); } From b757da89c0e9d9f24e9eb0d4b574ee1aec35d25e Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 17 Jan 2025 12:00:41 +0000 Subject: [PATCH 095/129] fix: patch up _method check --- src/Request.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 7146079..59ecbfd 100755 --- a/src/Request.php +++ b/src/Request.php @@ -70,8 +70,8 @@ public static function methodOverride() return strtoupper($method); } - if (static::getOriginalMethod() === 'POST') { - return strtoupper(static::get(static::METHOD_OVERRIDE)); + if (static::getOriginalMethod() === 'POST' && $method = static::get(static::METHOD_OVERRIDE)) { + return strtoupper($method); } return null; @@ -499,7 +499,7 @@ public static function uploadAs(string $key, string $destination, string $name, $fileExtension = pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION); $config['rename'] = true; - $config['name'] = "$name.$fileExtension"; + $config['name'] = $name . '.' . $fileExtension; return static::upload($key, $destination, $config); } From 1f722e3f6f0c555b5fecdac98fd0ad4fb28a70f2 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 17 Jan 2025 12:33:39 +0000 Subject: [PATCH 096/129] chore: clean up --- src/Request.php | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Request.php b/src/Request.php index 59ecbfd..211486c 100755 --- a/src/Request.php +++ b/src/Request.php @@ -45,11 +45,7 @@ public function __construct() */ public static function getMethod(): string { - if ($method = static::methodOverride()) { - return $method; - } - - return static::getOriginalMethod(); + return static::methodOverride() ?? static::getOriginalMethod(); } /** From 6e25044310dfbe12665f70c7a1990b68fe253836 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 28 Jan 2025 20:59:12 +0000 Subject: [PATCH 097/129] feat: add response::view function to render configured views --- src/Response.php | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/src/Response.php b/src/Response.php index 737721b..fcd8f86 100755 --- a/src/Response.php +++ b/src/Response.php @@ -232,6 +232,33 @@ public function noContent() $this->send(); } + /** + * Render a view file if a view engine is available + * + * @param string $view The view file to render + * @param array $data The data to pass to the view + */ + public function view(string $view, array $data = []) + { + if (!function_exists('view')) { + $this->markup( + view($view, $data), + ); + } + + if (app()->blade()) { + $this->markup( + app()->blade()->render($view, $data), + ); + } + + if (app()->template()) { + $this->markup( + app()->template()->render($view, $data), + ); + } + } + /** * Output some data and break the application * From 476a4ae7b7e84412cba101893084f1c1952216b7 Mon Sep 17 00:00:00 2001 From: Rui Trigo <148787540+ruitrigo-dev@users.noreply.github.com> Date: Wed, 29 Jan 2025 02:36:46 +0000 Subject: [PATCH 098/129] fix: getUserAgent() doesn't handle the header properly because of further conversion. (#35) Co-authored-by: Rui Trigo --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 211486c..6d9c3a8 100755 --- a/src/Request.php +++ b/src/Request.php @@ -725,7 +725,7 @@ public static function getReferer(): ?string */ public static function getUserAgent(): ?string { - return Headers::get('HTTP_USER_AGENT'); + return Headers::get('USER-AGENT'); } /** From 8bd945f274734668c52e1e4b8720cc535c2a8be5 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 29 Jan 2025 18:15:49 +0000 Subject: [PATCH 099/129] feat: add render function --- src/Response.php | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/Response.php b/src/Response.php index fcd8f86..e59c160 100755 --- a/src/Response.php +++ b/src/Response.php @@ -259,6 +259,17 @@ public function view(string $view, array $data = []) } } + /** + * Render a view file if a view engine is available + * + * @param string $view The view file to render + * @param array $data The data to pass to the view + */ + public function render(string $view, array $data = []) + { + $this->view($view, $data); + } + /** * Output some data and break the application * From d05393ae8a9cbbb4426ae6a4d8366a53b0adb309 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 29 Jan 2025 18:43:46 +0000 Subject: [PATCH 100/129] fix: patch up response::view() --- src/Response.php | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Response.php b/src/Response.php index e59c160..af977a3 100755 --- a/src/Response.php +++ b/src/Response.php @@ -240,20 +240,20 @@ public function noContent() */ public function view(string $view, array $data = []) { - if (!function_exists('view')) { - $this->markup( + if (function_exists('view')) { + return $this->markup( view($view, $data), ); } if (app()->blade()) { - $this->markup( + return $this->markup( app()->blade()->render($view, $data), ); } if (app()->template()) { - $this->markup( + return $this->markup( app()->template()->render($view, $data), ); } From d9eaa2106866bed7727addba9a846bb8be0ef421 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 14 Feb 2025 07:32:53 +0000 Subject: [PATCH 101/129] feat: add flash messaging to request --- src/Request.php | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 6d9c3a8..f41d593 100755 --- a/src/Request.php +++ b/src/Request.php @@ -332,6 +332,17 @@ public static function cookies(?string $key = null) Cookie::get($key); } + /** + * Display a flash message from the previous request + * + * @param string|null $key The key to get from the flash data + * @return array|string|null + */ + public static function flash(?string $key = null) + { + return \Leaf\Flash::display($key); + } + /** * Does the Request body contain parsed form data? * @return bool @@ -340,7 +351,7 @@ public static function isFormData(): bool { $method = static::getMethod(); - return ($method === static::METHOD_POST && is_null(static::getContentType())) || in_array(static::getMediaType(), static::$formDataMediaTypes); + return ($method === static::METHOD_POST && static::getContentType() === null) || in_array(static::getMediaType(), static::$formDataMediaTypes); } /** From e3b0465d640664b9a58b3660e1763cb01b18a6bb Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 24 Feb 2025 08:21:45 +0000 Subject: [PATCH 102/129] feat: add inertia response --- src/Response.php | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/src/Response.php b/src/Response.php index af977a3..649bd63 100755 --- a/src/Response.php +++ b/src/Response.php @@ -270,6 +270,21 @@ public function render(string $view, array $data = []) $this->view($view, $data); } + /** + * Render an inertia view file if inertia is installed + * + * @param string $view The view file to render + * @param array $data The data to pass to the view + */ + public function inertia(string $view, array $data = []) + { + if (function_exists('inertia')) { + return inertia($view, $data); + } + + trigger_error('Inertia not found. Run `leaf install inertia` or `composer require leafs/inertia`'); + } + /** * Output some data and break the application * From 66ea0dd2c2b8b7f333fcc33306475b9b707c003a Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 24 Feb 2025 13:48:19 +0000 Subject: [PATCH 103/129] feat: add fallback for server QUERY_STRING --- src/Request.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index f41d593..62340a3 100755 --- a/src/Request.php +++ b/src/Request.php @@ -677,7 +677,7 @@ public static function getPathInfo(): ?string */ public static function getQueryString(): ?string { - return $_SERVER['QUERY_STRING'] ?? null; + return $_SERVER['QUERY_STRING'] ?? parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY) ?? null; } /** From e31686d35f53c5612cc6707751c7a07f5024a4d6 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 24 Feb 2025 14:06:42 +0000 Subject: [PATCH 104/129] feat: add getFullUrl method --- src/Request.php | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/Request.php b/src/Request.php index 62340a3..5999e7a 100755 --- a/src/Request.php +++ b/src/Request.php @@ -695,6 +695,15 @@ public static function getUrl(): string return $url; } + /** + * Get Full URL (scheme + host [ + port if non-standard ] + path + query string) + * @return string + */ + public static function getFullUrl(): string + { + return static::getUrl() . static::getPathInfo() . (static::getQueryString() ? '?' . static::getQueryString() : ''); + } + /** * Get IP * @return string From 558bf53cbed8b31ddf1fb5dd03e18b3acf27eb94 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Fri, 28 Feb 2025 16:24:48 +0000 Subject: [PATCH 105/129] feat: update deps --- composer.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/composer.json b/composer.json index 96afa5e..c5e5076 100644 --- a/composer.json +++ b/composer.json @@ -34,6 +34,6 @@ "require": { "leafs/anchor": "*", "leafs/form": "^3.0", - "leafs/fs": "^2.0" + "leafs/fs": "^4.0" } } From 61e0f83c9f94cb74c9611f891b59743fd18bd897 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 26 Mar 2025 10:11:23 +0000 Subject: [PATCH 106/129] feat: add support for multiple input files --- src/Request.php | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 5999e7a..aefdc56 100755 --- a/src/Request.php +++ b/src/Request.php @@ -334,7 +334,7 @@ public static function cookies(?string $key = null) /** * Display a flash message from the previous request - * + * * @param string|null $key The key to get from the flash data * @return array|string|null */ @@ -465,6 +465,22 @@ public static function upload(string $key, string $destination, array $config = return false; } + if (is_array($file['name'])) { + $uploadedFiles = []; + + foreach ($file['name'] as $fileKey => $image) { + $uploadedFiles[] = \Leaf\FS\File::upload([ + 'name' => $file['name'][$fileKey], + 'type' => $file['type'][$fileKey], + 'tmp_name' => $file['tmp_name'][$fileKey], + 'error' => $file['error'][$fileKey], + 'size' => $file['size'][$fileKey], + ], $destination, $config); + } + + return $uploadedFiles; + } + if (isset($config['extensions'])) { $fileExtension = pathinfo($file['name'], PATHINFO_EXTENSION); From 4ac870cfc17deb40dcf0d5f57d7d5e267428eb86 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 25 Jun 2025 12:02:09 +0000 Subject: [PATCH 107/129] feat: add support for ip geolocation --- src/Request.php | 53 ++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/src/Request.php b/src/Request.php index aefdc56..12df3ac 100755 --- a/src/Request.php +++ b/src/Request.php @@ -726,15 +726,58 @@ public static function getFullUrl(): string */ public static function getIp(): string { - $keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR']; + return $_SERVER['HTTP_CLIENT_IP'] + ?? $_SERVER['HTTP_X_FORWARDED_FOR'] + ?? $_SERVER['REMOTE_ADDR']; + } - foreach ($keys as $key) { - if (isset($_SERVER[$key])) { - return $_SERVER[$key]; + /** + * Get Current User Location using IP + * @see https://ip-api.com/docs/api:json + * @uses \Leaf\Http\Request::getLocationFromIp + * @return array + */ + public static function getUserLocation(): array + { + return static::getLocationFromIp( + static::getIp() + ); + } + + /** + * Get IP-based Location using ip-api + * @see https://ip-api.com/docs/api:json + * @return array + */ + public static function getLocationFromIp(string $ip): array + { + $response = [ + 'country' => null, + 'countryCode' => null, + 'region' => null, + 'regionName' => null, + 'currency' => null, + 'city' => null, + 'zip' => null, + 'lat' => null, + 'lon' => null, + 'timezone' => null, + 'ip' => $ip, + 'continent' => null, + 'continentCode' => null, + ]; + + try { + $res = file_get_contents("http://ip-api.com/json/{$response['ip']}?fields=status,continent,continentCode,country,countryCode,region,regionName,city,zip,lat,lon,timezone,currency,query"); + $data = json_decode($res ?? '{}', true); + + if (($data['status'] ?? false) === 'success') { + $response = array_merge($response, $data); } + } catch (\Exception $e) { } - return $_SERVER['REMOTE_ADDR']; + return $response; } /** From c41ef17db0eb3c05900d577eeea049668e816ccb Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 15 Jul 2025 23:40:51 +0000 Subject: [PATCH 108/129] feat: switch api call to curl --- src/Request.php | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 12df3ac..fa5822b 100755 --- a/src/Request.php +++ b/src/Request.php @@ -768,7 +768,14 @@ public static function getLocationFromIp(string $ip): array ]; try { - $res = file_get_contents("http://ip-api.com/json/{$response['ip']}?fields=status,continent,continentCode,country,countryCode,region,regionName,city,zip,lat,lon,timezone,currency,query"); + $ch = curl_init(); + curl_setopt($ch, CURLOPT_URL, "http://ip-api.com/json/{$ip}?fields=status,continent,continentCode,country,countryCode,region,regionName,city,zip,lat,lon,timezone,currency,query"); + curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); + curl_setopt($ch, CURLOPT_TIMEOUT, 5); + + $res = curl_exec($ch); + curl_close($ch); + $data = json_decode($res ?? '{}', true); if (($data['status'] ?? false) === 'success') { From fca29b500f4bf8419d1c5e1105501379f4415598 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 18 Aug 2025 16:30:01 +0000 Subject: [PATCH 109/129] fix: patch up ip pipeline --- src/Request.php | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index fa5822b..1f0600d 100755 --- a/src/Request.php +++ b/src/Request.php @@ -726,9 +726,12 @@ public static function getFullUrl(): string */ public static function getIp(): string { - return $_SERVER['HTTP_CLIENT_IP'] - ?? $_SERVER['HTTP_X_FORWARDED_FOR'] - ?? $_SERVER['REMOTE_ADDR']; + if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { + $ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); + return trim($ipAddresses[0]); // Get the first IP in the list + } + + return $_SERVER['REMOTE_ADDR'] ?? $_SERVER['HTTP_CLIENT_IP']; } /** From 2ff6d21f84429b916bbeb74a438e20432afa7e57 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Mon, 8 Dec 2025 10:12:09 +0000 Subject: [PATCH 110/129] feat: add callable defaults + content type helper --- src/Request.php | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/src/Request.php b/src/Request.php index 1f0600d..233400a 100755 --- a/src/Request.php +++ b/src/Request.php @@ -261,7 +261,7 @@ public static function get($params, bool $safeData = true) */ public static function params(?string $key = null, $default = null) { - return static::get($key) ?? $default; + return static::get($key) ?? is_callable($default) ? $default(static::body()) : $default; } /** @@ -536,6 +536,18 @@ public static function getContentType(): ?string return Headers::get('Content-Type'); } + /** + * Check if content type matches + * @param string $type The content type to check for + * @return bool + */ + public static function contentTypeIs(string $type): bool + { + $contentType = static::getContentType(); + + return $contentType && stripos($contentType, $type) === 0; + } + /** * Get Media Type (type/subtype within Content Type header) * @return string|null @@ -726,12 +738,9 @@ public static function getFullUrl(): string */ public static function getIp(): string { - if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { - $ipAddresses = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']); - return trim($ipAddresses[0]); // Get the first IP in the list - } - - return $_SERVER['REMOTE_ADDR'] ?? $_SERVER['HTTP_CLIENT_IP']; + return $_SERVER['HTTP_CLIENT_IP'] + ?? $_SERVER['HTTP_X_FORWARDED_FOR'] + ?? $_SERVER['REMOTE_ADDR']; } /** @@ -796,7 +805,7 @@ public static function getLocationFromIp(string $ip): array */ public static function getReferrer(): ?string { - return Headers::get('HTTP_REFERER'); + return $_SERVER['HTTP_REFERER'] ?? null; } /** From f01dcfd735d83436fc7e412eba8564fdcec34d5c Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 9 Dec 2025 16:22:02 +0000 Subject: [PATCH 111/129] feat: add support for function getters --- src/Request.php | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 233400a..9e01d8d 100755 --- a/src/Request.php +++ b/src/Request.php @@ -230,7 +230,7 @@ public static function postData($item = null, $default = null) * This method returns get, post, put patch, delete or raw form data or NULL * if the data isn't found. * - * @param array|string $params The parameter(s) to return + * @param array|string|callable $params The parameter(s) to return * @param bool $safeData Sanitize output */ public static function get($params, bool $safeData = true) @@ -239,6 +239,10 @@ public static function get($params, bool $safeData = true) return static::body($safeData)[$params] ?? null; } + if (is_callable($params)) { + return $params(static::body($safeData)); + } + $data = []; foreach ($params as $param) { From 7e6a2f3575063b4c9d9bf1bad157c14029123bf5 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sat, 13 Dec 2025 09:34:54 +0000 Subject: [PATCH 112/129] fix: patch up params error --- src/Request.php | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Request.php b/src/Request.php index 9e01d8d..c21c580 100755 --- a/src/Request.php +++ b/src/Request.php @@ -235,14 +235,14 @@ public static function postData($item = null, $default = null) */ public static function get($params, bool $safeData = true) { - if (is_string($params)) { - return static::body($safeData)[$params] ?? null; - } - if (is_callable($params)) { return $params(static::body($safeData)); } + if (is_string($params)) { + return static::body($safeData)[$params] ?? null; + } + $data = []; foreach ($params as $param) { @@ -265,7 +265,7 @@ public static function get($params, bool $safeData = true) */ public static function params(?string $key = null, $default = null) { - return static::get($key) ?? is_callable($default) ? $default(static::body()) : $default; + return static::get($key) ?? (is_callable($default) ? $default(static::body()) : $default); } /** From 85bec7832e2fa92161e823b782ff44199eab2a46 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 15 Jan 2026 09:21:30 +0000 Subject: [PATCH 113/129] fix: patch up getting callables --- src/Request.php | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/src/Request.php b/src/Request.php index c21c580..db3ef2a 100755 --- a/src/Request.php +++ b/src/Request.php @@ -235,21 +235,21 @@ public static function postData($item = null, $default = null) */ public static function get($params, bool $safeData = true) { - if (is_callable($params)) { - return $params(static::body($safeData)); - } - if (is_string($params)) { return static::body($safeData)[$params] ?? null; } - $data = []; + if (is_array($params)) { + $data = []; + + foreach ($params as $param) { + $data[$param] = static::get($param, $safeData); + } - foreach ($params as $param) { - $data[$param] = static::get($param, $safeData); + return $data; } - return $data; + return $params(static::body($safeData)); } /** From 53f7d2618c5ef37c2550d6883dd45b0927e1dfe1 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 26 Jul 2026 11:11:53 +0000 Subject: [PATCH 114/129] chore: setup v5 base --- composer.json | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/composer.json b/composer.json index c5e5076..53b7999 100644 --- a/composer.json +++ b/composer.json @@ -35,5 +35,10 @@ "leafs/anchor": "*", "leafs/form": "^3.0", "leafs/fs": "^4.0" + }, + "extra": { + "branch-alias": { + "dev-v5.x": "5.0.x-dev" + } } -} +} \ No newline at end of file From aac33c57c02434e5fb99ea5de3551adf369b72ce Mon Sep 17 00:00:00 2001 From: mychidarko Date: Tue, 28 Jul 2026 14:28:05 +0000 Subject: [PATCH 115/129] test: add http tests --- .github/workflows/lint.yml | 27 ++++++ .github/workflows/tests.yml | 32 ++++++++ alchemy.yml | 59 ++++++++++++++ composer.json | 18 +++- src/Cache.php | 158 ++++++++++++++++++------------------ src/Headers.php | 49 +++++++---- src/Request.php | 79 ++++++++++-------- src/Response.php | 30 +++++-- src/Status.php | 7 +- src/functions.php | 8 +- tests/Pest.php | 124 ++++++++++++++++++++++++++++ tests/integration.test.php | 100 +++++++++++++++++++++++ tests/request.test.php | 123 ++++++++++++++++++++++++++++ tests/response.test.php | 116 ++++++++++++++++++++++++++ tests/server.php | 75 +++++++++++++++++ 15 files changed, 862 insertions(+), 143 deletions(-) create mode 100644 .github/workflows/lint.yml create mode 100644 .github/workflows/tests.yml create mode 100644 alchemy.yml create mode 100644 tests/Pest.php create mode 100644 tests/integration.test.php create mode 100644 tests/request.test.php create mode 100644 tests/response.test.php create mode 100644 tests/server.php diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..8baa32f --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,27 @@ +name: Lint code + +on: ["push","pull_request"] + +jobs: + lint: + runs-on: ubuntu-latest + + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + ref: ${{ github.head_ref }} + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + extensions: json, zip, curl + tools: composer:v2 + coverage: none + + - name: Install PHP dependencies + run: composer update --no-interaction --no-progress + + - name: Run Linter + run: composer run lint -- --check diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..afe6289 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,32 @@ +name: Run Tests + +on: ["push","pull_request"] + +jobs: + tests: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: true + matrix: + os: ["macos-latest","ubuntu-latest","windows-latest"] + php: ["8.4","8.3","8.2"] + + name: PHP ${{ matrix.php }} - ${{ matrix.os }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: json, zip, curl + tools: composer:v2 + coverage: xdebug + + - name: Install PHP dependencies + run: composer update --no-interaction --no-progress + + - name: Run Tests + run: composer run test -- --flags=coverage diff --git a/alchemy.yml b/alchemy.yml new file mode 100644 index 0000000..1bbc492 --- /dev/null +++ b/alchemy.yml @@ -0,0 +1,59 @@ +app: + - src + +tests: + engine: pest + parallel: false + paths: + - tests + files: + - '*.test.php' + coverage: + processUncoveredFiles: true + +lint: + preset: PSR12 + rules: + single_quote: true + phpdoc_scalar: true + no_unused_imports: true + unary_operator_spaces: true + binary_operator_spaces: true + phpdoc_var_without_name: true + trailing_comma_in_multiline: true + phpdoc_single_line_var_spacing: true + single_trait_insert_per_statement: true + not_operator_with_successor_space: false + array_syntax: + syntax: short + ordered_imports: + sort_algorithm: alpha + method_argument_space: + on_multiline: ensure_fully_multiline + keep_multiple_spaces_after_comma: true + blank_line_before_statement: + statements: + - try + - break + - throw + - return + - declare + - continue + +actions: + run: + - lint + - tests + os: + - macos-latest + - ubuntu-latest + - windows-latest + php: + extensions: json, zip, curl + versions: # library supports ^7.4|^8.0, but pest 3 needs 8.2+ + - '8.4' + - '8.3' + - '8.2' + events: + - push + - pull_request diff --git a/composer.json b/composer.json index 53b7999..c297ac3 100644 --- a/composer.json +++ b/composer.json @@ -40,5 +40,21 @@ "branch-alias": { "dev-v5.x": "5.0.x-dev" } + }, + "require-dev": { + "friendsofphp/php-cs-fixer": "^3.95", + "pestphp/pest": "*", + "leafs/alchemy": "v5.x-dev" + }, + "config": { + "allow-plugins": { + "pestphp/pest-plugin": true + } + }, + "scripts": { + "test": "./vendor/bin/alchemy test", + "lint": "./vendor/bin/alchemy lint", + "fmt": "./vendor/bin/alchemy fmt", + "ci": "./vendor/bin/alchemy ci" } -} \ No newline at end of file +} diff --git a/src/Cache.php b/src/Cache.php index 1b55b0b..872d9d4 100755 --- a/src/Cache.php +++ b/src/Cache.php @@ -6,97 +6,99 @@ * Leaf Http Caching * ------------------------------------ * HTTP Caching made simple with Leaf - * + * * @author Michael Darko * @since 3.0.0 */ class Cache { - /** - * Set Last-Modified HTTP Response Header - * - * Set the HTTP 'Last-Modified' header and stop if a conditional - * GET request's `If-Modified-Since` header matches the last modified time - * of the resource. The `time` argument is a UNIX timestamp integer value. - * When the current request includes an 'If-Modified-Since' header that - * matches the specified last modified time, the application will stop - * and send a '304 Not Modified' response to the client. - * - * @param int $time The last modified UNIX timestamp - */ - public static function lastModified(int $time) - { - Headers::set('Last-Modified', gmdate('D, d M Y H:i:s T', $time)); + /** + * Set Last-Modified HTTP Response Header + * + * Set the HTTP 'Last-Modified' header and stop if a conditional + * GET request's `If-Modified-Since` header matches the last modified time + * of the resource. The `time` argument is a UNIX timestamp integer value. + * When the current request includes an 'If-Modified-Since' header that + * matches the specified last modified time, the application will stop + * and send a '304 Not Modified' response to the client. + * + * @param int $time The last modified UNIX timestamp + */ + public static function lastModified(int $time) + { + Headers::set('Last-Modified', gmdate('D, d M Y H:i:s T', $time)); - if ($time === strtotime(Headers::get('If-Modified-Since'))) { - \Leaf\App::halt(304); - } - } + $ifModifiedSince = Headers::get('If-Modified-Since'); - /** - * Set ETag HTTP Response Header - * - * Set the etag header and stop if the conditional GET request matches. - * The `value` argument is a unique identifier for the current resource. - * The `type` argument indicates whether the etag should be used as a strong or - * weak cache validator. - * - * When the current request includes an 'If-None-Match' header with - * a matching etag, execution is immediately stopped. If the request - * method is GET or HEAD, a '304 Not Modified' response is sent. - * - * @param string $value The etag value - * @param string $type The type of etag to create; either "strong" or "weak" - */ - public static function etag(string $value, string $type = "strong") - { - if (!in_array($type, ["strong", "weak"])) { - trigger_error("Invalid Leaf::etag type. Expected either \"strong\" or \"weak\"."); - } + if ($ifModifiedSince && $time === strtotime($ifModifiedSince)) { + \Leaf\App::halt(304); + } + } - $value = "\"$value\""; + /** + * Set ETag HTTP Response Header + * + * Set the etag header and stop if the conditional GET request matches. + * The `value` argument is a unique identifier for the current resource. + * The `type` argument indicates whether the etag should be used as a strong or + * weak cache validator. + * + * When the current request includes an 'If-None-Match' header with + * a matching etag, execution is immediately stopped. If the request + * method is GET or HEAD, a '304 Not Modified' response is sent. + * + * @param string $value The etag value + * @param string $type The type of etag to create; either "strong" or "weak" + */ + public static function etag(string $value, string $type = 'strong') + { + if (!in_array($type, ['strong', 'weak'])) { + trigger_error('Invalid Leaf::etag type. Expected either "strong" or "weak".'); + } - if ($type === "weak") { - $value = "W/" . $value; - } + $value = "\"$value\""; - Headers::set("ETag", $value); + if ($type === 'weak') { + $value = 'W/' . $value; + } - if ($etagsHeader = Headers::get("If-None-Match")) { - $etags = preg_split("@\s*,\s*@", $etagsHeader); + Headers::set('ETag', $value); - if (in_array($value, $etags) || in_array("*", $etags)) { - $_304Methods = [Request::METHOD_GET, Request::METHOD_HEAD]; + if ($etagsHeader = Headers::get('If-None-Match')) { + $etags = preg_split("@\s*,\s*@", $etagsHeader); - if (in_array(Request::getMethod(), $_304Methods)) { - \Leaf\App::halt(304); - } else { - // according to https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 - // all methods besides GET and HEAD should return a 421 (Precondition Failed) - \Leaf\App::halt(412); - } - } - } - } + if (in_array($value, $etags) || in_array('*', $etags)) { + $_304Methods = [Request::METHOD_GET, Request::METHOD_HEAD]; - /** - * Set Expires HTTP response header - * - * The `Expires` header tells the HTTP client the time at which - * the current resource should be considered stale. At that time the HTTP - * client will send a conditional GET request to the server; the server - * may return a 200 OK if the resource has changed, else a 304 Not Modified - * if the resource has not changed. The `Expires` header should be used in - * conjunction with the `etag()` or `lastModified()` methods above. - * - * @param string|int $time If string, a time to be parsed by `strtotime()`; If int, a UNIX timestamp; - */ - public static function expires($time) - { - if (is_string($time)) { - $time = strtotime($time); - } + if (in_array(Request::getMethod(), $_304Methods)) { + \Leaf\App::halt(304); + } else { + // according to https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26 + // all methods besides GET and HEAD should return a 421 (Precondition Failed) + \Leaf\App::halt(412); + } + } + } + } - Headers::set('Expires', gmdate('D, d M Y H:i:s T', $time)); - } + /** + * Set Expires HTTP response header + * + * The `Expires` header tells the HTTP client the time at which + * the current resource should be considered stale. At that time the HTTP + * client will send a conditional GET request to the server; the server + * may return a 200 OK if the resource has changed, else a 304 Not Modified + * if the resource has not changed. The `Expires` header should be used in + * conjunction with the `etag()` or `lastModified()` methods above. + * + * @param string|int $time If string, a time to be parsed by `strtotime()`; If int, a UNIX timestamp; + */ + public static function expires($time) + { + if (is_string($time)) { + $time = strtotime($time); + } + + Headers::set('Expires', gmdate('D, d M Y H:i:s T', $time)); + } } diff --git a/src/Headers.php b/src/Headers.php index 2bea2d1..4656879 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -24,13 +24,15 @@ class Headers */ public static function status(?int $httpCode = null) { - if ($httpCode === null) return self::$httpCode; + if ($httpCode === null) { + return self::$httpCode; + } self::$httpCode = $httpCode; } /** * Force an HTTP code for response using PHP's `http_response_code` - * + * * @param int $httpCode The response code to set */ public static function resetStatus($httpCode = 200) @@ -64,27 +66,30 @@ public static function all(bool $safeOutput = false): array */ public static function get($params, bool $safeOutput = false) { - if (is_string($params)) return array_change_key_case(self::all($safeOutput), CASE_LOWER)[strtolower($params)] ?? null; + if (is_string($params)) { + return array_change_key_case(self::all($safeOutput), CASE_LOWER)[strtolower($params)] ?? null; + } $data = []; foreach ($params as $param) { $data[$param] = self::get($param, $safeOutput); } + return $data; } /** * Set a new header */ - public static function set($key, string $value = "", $replace = true, int $httpCode = 200): void + public static function set($key, string $value = '', $replace = true, ?int $httpCode = null): void { if (!is_array($key)) { - $code = $httpCode ?? self::$httpCode; - - if (!$code) { + // only touch the response status when a code is explicitly + // passed in — setting a header should not reset the status + if (!$httpCode) { header("$key: $value", $replace); } else { - header("$key: $value", $replace, $code); + header("$key: $value", $replace, $httpCode); } } else { foreach ($key as $header => $headerValue) { @@ -109,12 +114,15 @@ public static function remove($keys) /** * Check if a header is present - * + * * @param string $header The header to check */ public static function has(string $header) { - return in_array($header, static::all()); + return array_key_exists( + strtolower($header), + array_change_key_case(static::all(), CASE_LOWER) + ); } /** @@ -122,7 +130,7 @@ public static function has(string $header) */ public static function contentPlain($code = 200): void { - self::set("Content-Type", "text/plain", true, $code ?? self::$httpCode); + self::set('Content-Type', 'text/plain', true, $code ?? self::$httpCode); } /** @@ -130,7 +138,7 @@ public static function contentPlain($code = 200): void */ public static function contentHtml($code = 200): void { - self::set("Content-Type", "text/html", true, $code ?? self::$httpCode); + self::set('Content-Type', 'text/html', true, $code ?? self::$httpCode); } /** @@ -138,7 +146,7 @@ public static function contentHtml($code = 200): void */ public static function contentXml($code = 200): void { - self::set("Content-Type", "application/xml", true, $code ?? self::$httpCode); + self::set('Content-Type', 'application/xml', true, $code ?? self::$httpCode); } /** @@ -146,13 +154,13 @@ public static function contentXml($code = 200): void */ public static function contentJSON($code = 200): void { - self::set("Content-Type", "application/json", true, $code ?? self::$httpCode); + self::set('Content-Type', 'application/json', true, $code ?? self::$httpCode); } /** * Quickly set an access control header */ - public static function accessControl($key, $value = "", $code = 200) + public static function accessControl($key, $value = '', $code = 200) { if (is_string($key)) { self::set("Access-Control-$key", $value, true, $code ?? self::$httpCode); @@ -165,16 +173,21 @@ public static function accessControl($key, $value = "", $code = 200) protected static function findHeaders() { - if (function_exists("getallheaders") && \getallheaders()) { + if (function_exists('getallheaders') && \getallheaders()) { return \getallheaders(); } $headers = []; foreach ($_SERVER as $name => $value) { - if ((substr($name, 0, 5) == 'HTTP_') || ($name == 'CONTENT_TYPE') || ($name == 'CONTENT_LENGTH')) { - $headers[str_replace([' ', 'Http'], ['-', 'HTTP'], ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))))] = $value; + if (substr($name, 0, 5) === 'HTTP_') { + $name = substr($name, 5); + } elseif ($name !== 'CONTENT_TYPE' && $name !== 'CONTENT_LENGTH') { + continue; } + + $headers[str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', $name))))] = $value; } + return $headers; } } diff --git a/src/Request.php b/src/Request.php index db3ef2a..2cab7df 100755 --- a/src/Request.php +++ b/src/Request.php @@ -36,7 +36,7 @@ class Request public function __construct() { - static::$validator = new \Leaf\Form; + static::$validator = new \Leaf\Form(); } /** @@ -92,7 +92,7 @@ public static function typeIs(string $type): bool */ public static function hasHeader(string $header): bool { - return !!Headers::get($header); + return Headers::has($header); } /** @@ -122,28 +122,21 @@ public static function input(bool $safeData = true) { $handler = fopen('php://input', 'r'); $data = stream_get_contents($handler); - $contentType = Headers::get('Content-Type') ?? ''; - if ($contentType === 'application/x-www-form-urlencoded') { - $d = $data; - $data = []; + // media type is the content type minus any charset/boundary suffix, + // already lower-cased — so "Application/JSON; charset=utf-8" matches + $mediaType = static::getMediaType() ?? ''; - if ($d) { - foreach (explode('&', $d) as $chunk) { - $param = explode('=', $chunk); - $data[$param[0]] = urldecode($param[1]); - } - } - } else if (strpos($contentType, 'application/json') !== 0 && strpos($contentType, 'multipart/form-data') !== 0) { + if ($mediaType === 'application/x-www-form-urlencoded') { + parse_str($data ?: '', $data); + } elseif ($mediaType === '' || $mediaType === 'application/json' || $mediaType === 'multipart/form-data') { + // multipart bodies are already parsed into $_POST/$_FILES by PHP, + // and requests without a content type usually have no body at all + $parsedData = json_decode($data ?: '[]', true); + $data = is_array($parsedData) ? $parsedData : [$parsedData]; + } else { $safeData = false; $data = [$data]; - } else { - if (!$data) { - $data = json_encode([]); - } - - $parsedData = json_decode($data, true); - $data = is_array($parsedData) ? $parsedData : [$parsedData]; } return $safeData ? \Leaf\Anchor::sanitize($data) : $data; @@ -169,10 +162,11 @@ public static function try(array $params, bool $safeData = true, bool $noEmptySt foreach ($dataKeys as $key) { if (!isset($data[$key])) { unset($data[$key]); + continue; } - if ($noEmptyString && !strlen($data[$key])) { + if ($noEmptyString && is_string($data[$key]) && !strlen($data[$key])) { unset($data[$key]); } } @@ -235,6 +229,10 @@ public static function postData($item = null, $default = null) */ public static function get($params, bool $safeData = true) { + if ($params === null) { + return static::body($safeData); + } + if (is_string($params)) { return static::body($safeData)[$params] ?? null; } @@ -317,6 +315,7 @@ public static function files($filenames = null) foreach ($filenames as $filename) { $files[$filename] = $_FILES[$filename] ?? null; } + return $files; } @@ -380,14 +379,14 @@ public static function headers($key = null, bool $safeData = true) * Validate the request data * * @param array $rules The rules to validate against - * @param boolean $returnFullData Return the full data or just the validated data? + * @param bool $returnFullData Return the full data or just the validated data? * * @return false|array Returns false if validation fails, or the validated data if validation passes */ public static function validate(array $rules, bool $returnFullData = false) { if (!static::$validator) { - static::$validator = new \Leaf\Form; + static::$validator = new \Leaf\Form(); } $data = static::$validator->validate(static::body(false), $rules); @@ -406,7 +405,7 @@ public static function validate(array $rules, bool $returnFullData = false) public static function validator() { if (!static::$validator) { - static::$validator = new \Leaf\Form; + static::$validator = new \Leaf\Form(); } return static::$validator; @@ -424,7 +423,7 @@ protected static function auth() if (!(\Leaf\Config::getStatic('auth'))) { \Leaf\Config::singleton('auth', function () { - return new \Leaf\Auth; + return new \Leaf\Auth(); }); } @@ -466,6 +465,7 @@ public static function upload(string $key, string $destination, array $config = if (!$file) { static::$errors['upload'] = 'No file was uploaded.'; + return false; } @@ -490,11 +490,12 @@ public static function upload(string $key, string $destination, array $config = if (!in_array($fileExtension, $config['extensions'])) { static::$errors['upload'] = 'Invalid file extension.'; + return false; } } - $fileSystem = new \Leaf\FS\File; + $fileSystem = new \Leaf\FS\File(); if (!isset($config['rename']) || !$config['rename']) { $config['unique'] = true; @@ -612,7 +613,7 @@ public static function getContentCharset(): ?string */ public static function getContentLength(): int { - return Headers::get('CONTENT_LENGTH') ?? 0; + return (int) (Headers::get('Content-Length') ?? 0); } /** @@ -624,8 +625,9 @@ public static function getHost(): string if (isset($_SERVER['HTTP_HOST'])) { if (preg_match('/^(\[[a-fA-F0-9:.]+\])(:\d+)?\z/', $_SERVER['HTTP_HOST'], $matches)) { return $matches[1]; - } else if (strpos($_SERVER['HTTP_HOST'], ':') !== false) { + } elseif (strpos($_SERVER['HTTP_HOST'], ':') !== false) { $hostParts = explode(':', $_SERVER['HTTP_HOST']); + return $hostParts[0]; } @@ -650,7 +652,7 @@ public static function getHostWithPort(): string */ public static function getPort(): int { - return (int) $_SERVER['SERVER_PORT'] ?? 80; + return (int) ($_SERVER['SERVER_PORT'] ?? 80); } /** @@ -733,7 +735,11 @@ public static function getUrl(): string */ public static function getFullUrl(): string { - return static::getUrl() . static::getPathInfo() . (static::getQueryString() ? '?' . static::getQueryString() : ''); + // REQUEST_URI already contains the query string, so we only take + // its path portion before appending the query ourselves + $path = parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH) ?? ''; + + return static::getUrl() . $path . (static::getQueryString() ? '?' . static::getQueryString() : ''); } /** @@ -742,9 +748,18 @@ public static function getFullUrl(): string */ public static function getIp(): string { - return $_SERVER['HTTP_CLIENT_IP'] + $ip = $_SERVER['HTTP_CLIENT_IP'] ?? $_SERVER['HTTP_X_FORWARDED_FOR'] - ?? $_SERVER['REMOTE_ADDR']; + ?? $_SERVER['REMOTE_ADDR'] + ?? ''; + + // X-Forwarded-For can be a list: "client, proxy1, proxy2" — + // the original client is always the first entry + if (strpos($ip, ',') !== false) { + $ip = trim(explode(',', $ip)[0]); + } + + return $ip; } /** diff --git a/src/Response.php b/src/Response.php index 649bd63..16c7fe7 100755 --- a/src/Response.php +++ b/src/Response.php @@ -204,6 +204,8 @@ public function download(string $file, ?string $name = null, int $code = 200) if (!file_exists($file)) { Headers::contentHtml(); trigger_error("$file not found. Confirm your file path."); + + return; } $this->headers = array_merge($this->headers, [ @@ -213,7 +215,7 @@ public function download(string $file, ?string $name = null, int $code = 200) 'Cache-Control' => 'must-revalidate', 'Content-Description' => 'File Transfer', 'Content-Type' => 'application/octet-stream', - 'Content-Disposition' => 'attachment; filename="' . $name ?? basename($file) . '"', + 'Content-Disposition' => 'attachment; filename="' . ($name ?? basename($file)) . '"', ]); $this->content = $file; @@ -234,7 +236,7 @@ public function noContent() /** * Render a view file if a view engine is available - * + * * @param string $view The view file to render * @param array $data The data to pass to the view */ @@ -246,6 +248,12 @@ public function view(string $view, array $data = []) ); } + if (!function_exists('app')) { + trigger_error('No view engine found. response()->view() needs Leaf or a view() helper to render views.'); + + return; + } + if (app()->blade()) { return $this->markup( app()->blade()->render($view, $data), @@ -261,7 +269,7 @@ public function view(string $view, array $data = []) /** * Render a view file if a view engine is available - * + * * @param string $view The view file to render * @param array $data The data to pass to the view */ @@ -272,7 +280,7 @@ public function render(string $view, array $data = []) /** * Render an inertia view file if inertia is installed - * + * * @param string $view The view file to render * @param array $data The data to pass to the view */ @@ -339,6 +347,7 @@ public function redirect($url, int $status = 302, bool $exit = true) if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.redirect', [$url, $status]); + return; } @@ -367,8 +376,10 @@ public function next($data) */ public function status(?int $code = null): Response { - $this->status = $code; - Headers::status($code); + if ($code !== null) { + $this->status = $code; + Headers::status($code); + } return $this; } @@ -378,7 +389,7 @@ public function status(?int $code = null): Response * * @param string|array $name Header name * @param string|null $value Header value - * @param boolean $replace Replace existing header + * @param bool $replace Replace existing header * @param int $httpCode The HTTP status code */ public function withHeader($name, ?string $value = '', bool $replace = true, int $httpCode = 200): Response @@ -399,6 +410,7 @@ public function withHeader($name, ?string $value = '', bool $replace = true, int if (is_array($name)) { $this->headers = array_merge($this->headers, $name); + return $this; } @@ -466,6 +478,8 @@ public function withFlash($key, $value = null): Response foreach ($key as $k => $v) { $this->withFlash($k, $v); } + + return $this; } \Leaf\Flash::set($value, $key); @@ -493,6 +507,7 @@ public function sendHeaders(): Response { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.headers', $this->headers); + return $this; } @@ -516,6 +531,7 @@ public function sendCookies(): Response { if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { \Leaf\Config::set('response.cookies', $this->cookies); + return $this; } diff --git a/src/Status.php b/src/Status.php index e0dda58..6e81ca9 100644 --- a/src/Status.php +++ b/src/Status.php @@ -4,11 +4,12 @@ /** * Leaf Status Code Helper - * + * * @since 2.0 * @version 1.0 */ -class Status { +class Status +{ public const HTTP_CONTINUE = 100; public const HTTP_SWITCHING_PROTOCOLS = 101; public const HTTP_PROCESSING = 102; // RFC2518 @@ -81,7 +82,7 @@ class Status { * (last updated 2021-10-01). * * Unless otherwise noted, the status code is defined in RFC2616. - * + * * @author Fabien Potencier * * @var array diff --git a/src/functions.php b/src/functions.php index 43711e2..e19eb72 100644 --- a/src/functions.php +++ b/src/functions.php @@ -5,7 +5,7 @@ * Return request or request data * * @param array|string $data — Get data from request - * + * * @return \Leaf\Http\Request */ function request() @@ -13,7 +13,7 @@ function request() if (class_exists('\Leaf\Config')) { if (!\Leaf\Config::getStatic('request')) { \Leaf\Config::singleton('request', function () { - return new \Leaf\Http\Request; + return new \Leaf\Http\Request(); }); } @@ -29,7 +29,7 @@ function request() * Return response or set response data * * @param array|string $data — The JSON response to set - * + * * @return \Leaf\Http\Response */ function response() @@ -37,7 +37,7 @@ function response() if (class_exists('\Leaf\Config')) { if (!\Leaf\Config::getStatic('response')) { \Leaf\Config::singleton('response', function () { - return new \Leaf\Http\Response; + return new \Leaf\Http\Response(); }); } diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..c71b956 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,124 @@ + serverUrl($path), + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 5, + CURLOPT_CUSTOMREQUEST => $options['method'] ?? 'GET', + CURLOPT_HTTPHEADER => $options['headers'] ?? [], + ]); + + if (isset($options['body'])) { + curl_setopt($ch, CURLOPT_POSTFIELDS, $options['body']); + } + + $response = curl_exec($ch); + $error = curl_error($ch); + curl_close($ch); + + if ($error) { + throw new RuntimeException("test request failed: $error"); + } + + return json_decode($response, true) ?? []; +} + +function canConnect(string $host, int $port): bool +{ + // pest's error handler reports fsockopen's connection-refused warning + // even when suppressed, so we mute it properly for the probe + set_error_handler(fn () => true); + $connection = fsockopen($host, $port, $errno, $errstr, 0.2); + restore_error_handler(); + + if (is_resource($connection)) { + fclose($connection); + + return true; + } + + return false; +} + +function bootTestServer(): void +{ + static $booted = false; + + if ($booted) { + return; + } + + $booted = true; + + if (canConnect(HTTP_TEST_HOST, HTTP_TEST_PORT)) { + return; + } + + $process = proc_open( + [PHP_BINARY, '-S', HTTP_TEST_HOST . ':' . HTTP_TEST_PORT, __DIR__ . '/server.php'], + [1 => ['file', sys_get_temp_dir() . '/leaf-http-test-server.log', 'a'], 2 => ['file', sys_get_temp_dir() . '/leaf-http-test-server.log', 'a']], + $pipes + ); + + if (!is_resource($process)) { + throw new RuntimeException('could not start the test server'); + } + + register_shutdown_function(function () use ($process) { + if (is_resource($process)) { + proc_terminate($process); + } + }); + + $deadline = microtime(true) + 10; + + while (microtime(true) < $deadline) { + if (canConnect(HTTP_TEST_HOST, HTTP_TEST_PORT)) { + return; + } + + usleep(100000); + } + + throw new RuntimeException('test server did not come up on port ' . HTTP_TEST_PORT); +} + +/** + * Reset superglobals for in-process unit tests. + */ +function fakeRequest(array $server = [], array $get = [], array $post = []): void +{ + foreach (array_keys($_SERVER) as $key) { + if (strpos($key, 'HTTP_') === 0 || in_array($key, ['REQUEST_METHOD', 'REQUEST_URI', 'QUERY_STRING', 'SERVER_PORT', 'HTTPS', 'CONTENT_TYPE', 'CONTENT_LENGTH'])) { + unset($_SERVER[$key]); + } + } + + $_SERVER = array_merge($_SERVER, ['REQUEST_METHOD' => 'GET', 'HTTP_HOST' => 'leaf.test'], $server); + $_GET = $get; + $_POST = $post; + $_FILES = []; +} + +uses() + ->beforeEach(function () { + fakeRequest(); + }) + ->in(__DIR__); diff --git a/tests/integration.test.php b/tests/integration.test.php new file mode 100644 index 0000000..2b83593 --- /dev/null +++ b/tests/integration.test.php @@ -0,0 +1,100 @@ + 'POST', + 'headers' => ['Content-Type: application/json'], + 'body' => json_encode(['name' => 'Mika', 'likes' => 3]), + ]); + + expect($res['method'])->toBe('POST'); + expect($res['body']['name'])->toBe('Mika'); + expect($res['body']['likes'])->toBe(3); +}); + +test('json with a charset suffix still parses', function () { + $res = call('/body', [ + 'method' => 'POST', + 'headers' => ['Content-Type: application/json; charset=utf-8'], + 'body' => json_encode(['name' => 'Mika']), + ]); + + expect($res['body']['name'])->toBe('Mika'); +}); + +test('urlencoded bodies parse safely, including flags and special characters', function () { + $res = call('/body', [ + 'method' => 'PUT', + 'headers' => ['Content-Type: application/x-www-form-urlencoded'], + 'body' => 'name=Mika&equation=1%2B1%3D2&flag', + ]); + + expect($res['input']['name'])->toBe('Mika'); + expect($res['input']['equation'])->toBe('1+1=2'); + expect($res['input'])->toHaveKey('flag'); +}); + +test('urlencoded with a charset suffix still parses as a form', function () { + $res = call('/body', [ + 'method' => 'POST', + 'headers' => ['Content-Type: application/x-www-form-urlencoded; charset=utf-8'], + 'body' => 'name=Mika', + ]); + + expect($res['input']['name'])->toBe('Mika'); +}); + +test('query string data lands in the body on GET requests', function () { + $res = call('/body?name=Mika&page=2'); + + expect($res['body']['name'])->toBe('Mika'); + expect($res['body']['page'])->toBe('2'); +}); + +test('get, params and try behave over a real request', function () { + $res = call('/get?name=Mika'); + + expect($res['single'])->toBe('Mika'); + expect($res['multiple'])->toBe(['name' => 'Mika', 'missing' => null]); + expect($res['params'])->toBe('fallback'); + expect($res['try'])->toBe(['name' => 'Mika']); +}); + +test('headers flow through with correct casing, existence checks and length', function () { + $res = call('/headers', [ + 'method' => 'POST', + 'headers' => ['X-Custom: custom-value', 'User-Agent: leaf-tests', 'Content-Type: application/json'], + 'body' => '{"a":1}', + ]); + + expect($res['single'])->toBe('custom-value'); + expect($res['lowercase'])->toBe('custom-value'); + expect($res['has'])->toBeTrue(); + expect($res['hasValue'])->toBeFalse(); + expect($res['contentLength'])->toBe(7); + expect($res['userAgent'])->toBe('leaf-tests'); +}); + +test('urls resolve correctly through a real server', function () { + $res = call('/url?page=2'); + + expect($res['host'])->toBe('127.0.0.1'); + expect($res['port'])->toBe(8974); + expect($res['scheme'])->toBe('http'); + expect($res['url'])->toBe('http://127.0.0.1:8974'); + expect($res['fullUrl'])->toBe('http://127.0.0.1:8974/url?page=2'); + expect($res['ip'])->toBe('127.0.0.1'); +}); + +test('method override works over a real request', function () { + $res = call('/override', [ + 'method' => 'POST', + 'headers' => ['X-Http-Method-Override: DELETE'], + ]); + + expect($res['method'])->toBe('DELETE'); + expect($res['original'])->toBe('POST'); +}); diff --git a/tests/request.test.php b/tests/request.test.php new file mode 100644 index 0000000..0929dd1 --- /dev/null +++ b/tests/request.test.php @@ -0,0 +1,123 @@ + 'POST']); + + expect(Request::getMethod())->toBe('POST'); + expect(Request::typeIs('post'))->toBeTrue(); +}); + +test('method override header wins over the real method', function () { + fakeRequest(['REQUEST_METHOD' => 'POST', 'HTTP_X_HTTP_METHOD_OVERRIDE' => 'put']); + + expect(Request::getMethod())->toBe('PUT'); + expect(Request::getOriginalMethod())->toBe('POST'); +}); + +test('query data is readable through urlData and query', function () { + fakeRequest([], ['name' => 'Mika', 'page' => '2']); + + expect(Request::urlData('name'))->toBe('Mika'); + expect(Request::query('page'))->toBe('2'); + expect(Request::query('missing', 'fallback'))->toBe('fallback'); +}); + +test('get reads a single key, an array of keys, or a callable', function () { + fakeRequest([], ['name' => 'Mika', 'likes' => '3']); + + expect(Request::get('name'))->toBe('Mika'); + expect(Request::get(['name', 'missing']))->toBe(['name' => 'Mika', 'missing' => null]); + expect(Request::get(fn ($body) => $body['likes']))->toBe('3'); +}); + +test('params with no key returns the whole body instead of crashing', function () { + fakeRequest([], ['name' => 'Mika']); + + $body = Request::params(); + + expect($body)->toBeArray(); + expect($body['name'])->toBe('Mika'); +}); + +test('params falls back to defaults, including callable defaults', function () { + fakeRequest([], ['name' => 'Mika']); + + expect(Request::params('missing', 'fallback'))->toBe('fallback'); + expect(Request::params('missing', fn ($body) => $body['name'] . '!'))->toBe('Mika!'); +}); + +test('try drops missing keys and optionally empty strings', function () { + fakeRequest([], ['name' => 'Mika', 'empty' => '']); + + expect(Request::try(['name', 'missing']))->toBe(['name' => 'Mika']); + expect(Request::try(['name', 'empty'], true, true))->toBe(['name' => 'Mika']); + expect(Request::try(['name', 'empty'], true, false))->toBe(['name' => 'Mika', 'empty' => '']); +}); + +test('headers are readable case-insensitively', function () { + fakeRequest(['HTTP_X_CUSTOM' => 'custom-value']); + + expect(Request::headers('X-Custom'))->toBe('custom-value'); + expect(Request::headers('x-custom'))->toBe('custom-value'); + expect(Request::hasHeader('X-Custom'))->toBeTrue(); + expect(Request::hasHeader('X-Missing'))->toBeFalse(); +}); + +test('content type helpers parse media type, params and charset', function () { + fakeRequest(['CONTENT_TYPE' => 'Application/JSON; charset=UTF-8']); + + expect(Request::getMediaType())->toBe('application/json'); + expect(Request::getContentCharset())->toBe('UTF-8'); + expect(Request::contentTypeIs('application/json'))->toBeTrue(); +}); + +test('content length is read from the real header', function () { + fakeRequest(['CONTENT_TYPE' => 'application/json', 'CONTENT_LENGTH' => '42']); + + expect(Request::getContentLength())->toBe(42); +}); + +test('host, port, scheme and urls resolve correctly', function () { + fakeRequest([ + 'HTTP_HOST' => 'leaf.test', + 'SERVER_PORT' => '8080', + 'REQUEST_URI' => '/todos?page=2', + 'QUERY_STRING' => 'page=2', + ]); + + expect(Request::getHost())->toBe('leaf.test'); + expect(Request::getPort())->toBe(8080); + expect(Request::getScheme())->toBe('http'); + expect(Request::getUrl())->toBe('http://leaf.test:8080'); + expect(Request::getFullUrl())->toBe('http://leaf.test:8080/todos?page=2'); +}); + +test('getPort falls back to 80 when the server does not report one', function () { + fakeRequest(); + unset($_SERVER['SERVER_PORT']); + + expect(Request::getPort())->toBe(80); +}); + +test('the full url never duplicates the query string', function () { + fakeRequest(['HTTP_HOST' => 'leaf.test', 'SERVER_PORT' => '80', 'REQUEST_URI' => '/a?b=1', 'QUERY_STRING' => 'b=1']); + + expect(substr_count(Request::getFullUrl(), 'b=1'))->toBe(1); +}); + +test('getIp takes the first address from a forwarded list', function () { + fakeRequest(['HTTP_X_FORWARDED_FOR' => '203.0.113.7, 10.0.0.1, 10.0.0.2', 'REMOTE_ADDR' => '10.0.0.2']); + + expect(Request::getIp())->toBe('203.0.113.7'); +}); + +test('files returns one, many, or all uploaded files', function () { + fakeRequest(); + $_FILES = ['avatar' => ['name' => 'me.png'], 'doc' => ['name' => 'cv.pdf']]; + + expect(Request::files('avatar'))->toBe(['name' => 'me.png']); + expect(Request::files(['avatar', 'missing']))->toBe(['avatar' => ['name' => 'me.png'], 'missing' => null]); + expect(Request::files())->toHaveKeys(['avatar', 'doc']); +}); diff --git a/tests/response.test.php b/tests/response.test.php new file mode 100644 index 0000000..d32d36d --- /dev/null +++ b/tests/response.test.php @@ -0,0 +1,116 @@ +json(['name' => 'Mika'], 201); + $output = ob_get_clean(); + + expect($output)->toBe('{"name":"Mika"}'); + expect($response->headers['Content-Type'])->toBe('application/json'); +}); + +test('json can wrap the payload with the status code', function () { + $response = new Response(); + + ob_start(); + $response->json(['ok' => true], 201, true); + $output = json_decode(ob_get_clean(), true); + + expect($output['data'])->toBe(['ok' => true]); + expect($output['status'])->toBe(['code' => 201, 'message' => 'Created']); +}); + +test('plain and markup set their content types', function () { + $response = new Response(); + + ob_start(); + $response->plain('hello'); + ob_end_clean(); + expect($response->headers['Content-Type'])->toBe('text/plain'); + + ob_start(); + $response->markup('

hello

'); + $markup = ob_get_clean(); + expect($markup)->toBe('

hello

'); + expect($response->headers['Content-Type'])->toBe('text/html'); +}); + +test('download builds a complete content disposition with and without a name', function () { + $file = tempnam(sys_get_temp_dir(), 'leafhttp') . '.txt'; + file_put_contents($file, 'report data'); + $response = new Response(); + + ob_start(); + $response->download($file, 'report.txt'); + ob_get_clean(); + expect($response->headers['Content-Disposition'])->toBe('attachment; filename="report.txt"'); + + $response = new Response(); + ob_start(); + $response->download($file); + ob_get_clean(); + expect($response->headers['Content-Disposition'])->toBe('attachment; filename="' . basename($file) . '"'); + + unlink($file); +}); + +test('download of a missing file warns and does not build broken headers', function () { + $response = new Response(); + $captured = null; + + set_error_handler(function ($errno, $errstr) use (&$captured) { + $captured = $errstr; + + return true; + }); + $response->download('/nowhere/nothing.txt'); + restore_error_handler(); + + expect($captured)->toContain('not found'); + expect($response->headers)->not->toHaveKey('Content-Disposition'); +}); + +test('withHeader collects single headers and arrays', function () { + $response = new Response(); + $response->withHeader('X-One', '1')->withHeader(['X-Two' => '2', 'X-Three' => '3']); + + expect($response->headers)->toBe(['X-One' => '1', 'X-Two' => '2', 'X-Three' => '3']); +}); + +test('withCookie and withoutCookie queue cookies', function () { + $response = new Response(); + $response->withCookie('session', 'abc', 1000)->withoutCookie('old'); + + expect($response->cookies['session'])->toBe(['abc', 1000]); + expect($response->cookies['old'])->toBe(['', -1]); +}); + +test('status is chainable and ignores null instead of wiping the code', function () { + $response = new Response(); + + expect($response->status(404))->toBeInstanceOf(Response::class); + expect(Headers::status())->toBe(404); + + $response->status(null); + expect(Headers::status())->toBe(404); + + Headers::status(200); +}); + +test('getMessageForCode translates status codes', function () { + expect(Response::getMessageForCode(404))->toBe('Not Found'); + expect(Response::getMessageForCode(999))->toBe('unknown status'); +}); + +test('headers has checks names, not values', function () { + fakeRequest(['HTTP_X_TESTER' => 'hello']); + + expect(Headers::has('X-Tester'))->toBeTrue(); + expect(Headers::has('x-tester'))->toBeTrue(); + expect(Headers::has('hello'))->toBeFalse(); +}); diff --git a/tests/server.php b/tests/server.php new file mode 100644 index 0000000..59fe88e --- /dev/null +++ b/tests/server.php @@ -0,0 +1,75 @@ + Request::getMethod(), + 'body' => Request::body(false), + 'input' => Request::input(false), + ]); + + return; +} + +if ($path === '/get') { + echo json_encode([ + 'single' => Request::get('name', false), + 'multiple' => Request::get(['name', 'missing'], false), + 'params' => Request::params('missing', 'fallback'), + 'try' => Request::try(['name', 'missing'], false), + ]); + + return; +} + +if ($path === '/headers') { + echo json_encode([ + 'all' => Headers::all(), + 'single' => Headers::get('X-Custom'), + 'lowercase' => Headers::get('x-custom'), + 'has' => Headers::has('X-Custom'), + 'hasValue' => Headers::has('custom-value'), + 'contentLength' => Request::getContentLength(), + 'userAgent' => Request::getUserAgent(), + ]); + + return; +} + +if ($path === '/url') { + echo json_encode([ + 'host' => Request::getHost(), + 'port' => Request::getPort(), + 'scheme' => Request::getScheme(), + 'url' => Request::getUrl(), + 'fullUrl' => Request::getFullUrl(), + 'path' => Request::getPath(), + 'query' => Request::getQueryString(), + 'ip' => Request::getIp(), + ]); + + return; +} + +if ($path === '/override') { + echo json_encode([ + 'method' => Request::getMethod(), + 'original' => Request::getOriginalMethod(), + ]); + + return; +} + +echo json_encode(['path' => $path]); From 698b497c5ce6d44d39b931217a0b168fd8ab4069 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 30 Jul 2026 10:16:00 +0000 Subject: [PATCH 116/129] chore: add minimum PHP version 8.2 --- .gitignore | 3 +++ composer.json | 1 + 2 files changed, 4 insertions(+) diff --git a/.gitignore b/.gitignore index 945d7be..e6cb83b 100644 --- a/.gitignore +++ b/.gitignore @@ -20,3 +20,6 @@ Thumbs.db # Alchemy .alchemy + +# Alchemy-generated (kept for IDE support, never committed) +phpunit.xml diff --git a/composer.json b/composer.json index c297ac3..ce7b2b1 100644 --- a/composer.json +++ b/composer.json @@ -32,6 +32,7 @@ "minimum-stability": "dev", "prefer-stable": true, "require": { + "php": "^8.2", "leafs/anchor": "*", "leafs/form": "^3.0", "leafs/fs": "^4.0" From 3e2fcad491fcbe9b76214bc28ef9f3d86319580b Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 30 Jul 2026 13:09:29 +0000 Subject: [PATCH 117/129] feat: add request.object() as object for of body() --- composer.json | 4 ++-- src/Request.php | 13 +++++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/composer.json b/composer.json index ce7b2b1..09987f1 100644 --- a/composer.json +++ b/composer.json @@ -34,8 +34,8 @@ "require": { "php": "^8.2", "leafs/anchor": "*", - "leafs/form": "^3.0", - "leafs/fs": "^4.0" + "leafs/form": "*", + "leafs/fs": "*" }, "extra": { "branch-alias": { diff --git a/src/Request.php b/src/Request.php index 2cab7df..18dbeef 100755 --- a/src/Request.php +++ b/src/Request.php @@ -296,6 +296,19 @@ public static function body(bool $safeData = true) $finalData; } + /** + * Get the request data as an object instead of an array — + * nested structures become objects too, lists stay arrays + * + * @param bool $safeData Sanitize output + * + * @return object + */ + public static function object(bool $safeData = true) + { + return json_decode(json_encode((object) static::body($safeData))); + } + /** * Get all files passed into the request. * From 13f75400f2802720e447a0a69c6e055d7beb150a Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 30 Jul 2026 13:11:26 +0000 Subject: [PATCH 118/129] fix: add codes on view/render + add resumable support on download() --- src/Response.php | 75 ++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 70 insertions(+), 5 deletions(-) diff --git a/src/Response.php b/src/Response.php index 16c7fe7..e616c22 100755 --- a/src/Response.php +++ b/src/Response.php @@ -35,6 +35,11 @@ class Response */ protected $status = 200; + /** + * @var array|null [start byte, length] window for range downloads + */ + protected $downloadRange = null; + /** * @var string HTTP Version */ @@ -208,10 +213,43 @@ public function download(string $file, ?string $name = null, int $code = 200) return; } + $size = filesize($file); + $start = 0; + $length = $size; + + $range = $_SERVER['HTTP_RANGE'] ?? null; + + if ($code === 200 && $range && preg_match('/^bytes=(\d*)-(\d*)$/', trim($range), $rangeParts) && ($rangeParts[1] !== '' || $rangeParts[2] !== '')) { + if ($rangeParts[1] === '') { + // suffix range: the last N bytes + $start = max(0, $size - (int) $rangeParts[2]); + $end = $size - 1; + } else { + $start = (int) $rangeParts[1]; + $end = $rangeParts[2] === '' ? $size - 1 : min((int) $rangeParts[2], $size - 1); + } + + if ($start >= $size || $start > $end) { + $this->status = 416; + $this->headers = array_merge($this->headers, [ + 'Accept-Ranges' => 'bytes', + 'Content-Range' => "bytes */$size", + ]); + $this->content = ''; + + return $this->send(); + } + + $this->status = 206; + $length = $end - $start + 1; + $this->headers['Content-Range'] = "bytes $start-$end/$size"; + } + $this->headers = array_merge($this->headers, [ 'Expires' => '0', 'Pragma' => 'public', - 'Content-Length' => filesize($file), + 'Accept-Ranges' => 'bytes', + 'Content-Length' => $length, 'Cache-Control' => 'must-revalidate', 'Content-Description' => 'File Transfer', 'Content-Type' => 'application/octet-stream', @@ -219,6 +257,7 @@ public function download(string $file, ?string $name = null, int $code = 200) ]); $this->content = $file; + $this->downloadRange = [$start, $length]; $this->send(); } @@ -239,12 +278,14 @@ public function noContent() * * @param string $view The view file to render * @param array $data The data to pass to the view + * @param int $code The response status code */ - public function view(string $view, array $data = []) + public function view(string $view, array $data = [], int $code = 200) { if (function_exists('view')) { return $this->markup( view($view, $data), + $code, ); } @@ -257,12 +298,14 @@ public function view(string $view, array $data = []) if (app()->blade()) { return $this->markup( app()->blade()->render($view, $data), + $code, ); } if (app()->template()) { return $this->markup( app()->template()->render($view, $data), + $code, ); } } @@ -272,10 +315,11 @@ public function view(string $view, array $data = []) * * @param string $view The view file to render * @param array $data The data to pass to the view + * @param int $code The response status code */ - public function render(string $view, array $data = []) + public function render(string $view, array $data = [], int $code = 200) { - $this->view($view, $data); + $this->view($view, $data, $code); } /** @@ -552,7 +596,28 @@ public function sendCookies(): Response public function sendContent(): Response { if (strpos($this->headers['Content-Disposition'] ?? '', 'attachment') !== false) { - readfile($this->content); + $handle = fopen($this->content, 'rb'); + + if ($handle !== false) { + [$start, $remaining] = $this->downloadRange ?? [0, filesize($this->content)]; + + fseek($handle, $start); + + // stream in 1MB pieces — memory stays flat for any file size + while ($remaining > 0 && !feof($handle)) { + $chunk = fread($handle, min(1048576, $remaining)); + + if ($chunk === false || $chunk === '') { + break; + } + + echo $chunk; + + $remaining -= strlen($chunk); + } + + fclose($handle); + } } else { echo $this->content; } From cd22c5297e668db5d6ec13cc864b917eeecf0e9b Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 30 Jul 2026 13:11:55 +0000 Subject: [PATCH 119/129] test: update tests to include all features --- tests/Pest.php | 36 +++++++++++++++++++ tests/features.test.php | 76 +++++++++++++++++++++++++++++++++++++++++ tests/server.php | 43 +++++++++++++++++++++++ 3 files changed, 155 insertions(+) create mode 100644 tests/features.test.php diff --git a/tests/Pest.php b/tests/Pest.php index c71b956..2861d24 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -122,3 +122,39 @@ function fakeRequest(array $server = [], array $get = [], array $post = []): voi fakeRequest(); }) ->in(__DIR__); + +/** + * Fire a real HTTP request and return status, raw headers and raw body — + * for endpoints that don't reply with JSON (downloads, rendered views). + */ +function callRaw(string $path, array $options = []): array +{ + bootTestServer(); + + $ch = curl_init(); + + curl_setopt_array($ch, [ + CURLOPT_URL => serverUrl($path), + CURLOPT_RETURNTRANSFER => true, + CURLOPT_HEADER => true, + CURLOPT_TIMEOUT => 5, + CURLOPT_CUSTOMREQUEST => $options['method'] ?? 'GET', + CURLOPT_HTTPHEADER => $options['headers'] ?? [], + ]); + + $response = curl_exec($ch); + $error = curl_error($ch); + $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); + $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); + curl_close($ch); + + if ($error) { + throw new RuntimeException("test request failed: $error"); + } + + return [ + 'status' => $status, + 'headers' => substr($response, 0, $headerSize), + 'body' => substr($response, $headerSize), + ]; +} diff --git a/tests/features.test.php b/tests/features.test.php new file mode 100644 index 0000000..830ab9b --- /dev/null +++ b/tests/features.test.php @@ -0,0 +1,76 @@ +object(), view/render status codes, and +// range-aware streaming downloads — all against the real test server. + +test('request body is available as an object', function () { + // https://github.com/leafsphp/http/issues/38 + $res = call('/object', [ + 'method' => 'POST', + 'headers' => ['Content-Type: application/json'], + 'body' => json_encode(['name' => 'Mika', 'meta' => ['tag' => 'x'], 'tags' => ['a', 'b']]), + ]); + + expect($res['isObject'])->toBeTrue() + ->and($res['name'])->toBe('Mika') + ->and($res['nested'])->toBe('x') + ->and($res['list'])->toBe(['a', 'b']); // lists stay arrays +}); + +test('view can set an http status code', function () { + // https://github.com/leafsphp/http/issues/39 + $res = callRaw('/view-status'); + + expect($res['status'])->toBe(404) + ->and($res['body'])->toContain('rendered:demo'); +}); + +test('render can set an http status code', function () { + $res = callRaw('/render-status'); + + expect($res['status'])->toBe(201) + ->and($res['body'])->toContain('rendered:demo'); +}); + +test('downloads send the full file with range support advertised', function () { + $res = callRaw('/download'); + + expect($res['status'])->toBe(200) + ->and($res['body'])->toBe('0123456789') + ->and($res['headers'])->toContain('Accept-Ranges: bytes') + ->and($res['headers'])->toContain('Content-Length: 10'); +}); + +test('downloads honor byte ranges with 206 partial content', function () { + $res = callRaw('/download', ['headers' => ['Range: bytes=2-5']]); + + expect($res['status'])->toBe(206) + ->and($res['body'])->toBe('2345') + ->and($res['headers'])->toContain('Content-Range: bytes 2-5/10') + ->and($res['headers'])->toContain('Content-Length: 4'); +}); + +test('downloads honor open-ended and suffix ranges', function () { + $openEnded = callRaw('/download', ['headers' => ['Range: bytes=7-']]); + $suffix = callRaw('/download', ['headers' => ['Range: bytes=-3']]); + + expect($openEnded['status'])->toBe(206) + ->and($openEnded['body'])->toBe('789') + ->and($suffix['status'])->toBe(206) + ->and($suffix['body'])->toBe('789') + ->and($suffix['headers'])->toContain('Content-Range: bytes 7-9/10'); +}); + +test('unsatisfiable ranges get 416 with the total size', function () { + $res = callRaw('/download', ['headers' => ['Range: bytes=99-']]); + + expect($res['status'])->toBe(416) + ->and($res['headers'])->toContain('Content-Range: bytes */10'); +}); + +test('malformed range headers fall back to a full 200 download', function () { + $res = callRaw('/download', ['headers' => ['Range: bytes=abc']]); + + expect($res['status'])->toBe(200) + ->and($res['body'])->toBe('0123456789'); +}); diff --git a/tests/server.php b/tests/server.php index 59fe88e..f827503 100644 --- a/tests/server.php +++ b/tests/server.php @@ -9,8 +9,51 @@ use Leaf\Http\Headers; use Leaf\Http\Request; +use Leaf\Http\Response; + $path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); +// response()->view() falls back to a global view() helper when present +function view(string $view, array $data = []): string +{ + return "

rendered:$view

"; +} + +if ($path === '/object') { + header('Content-Type: application/json'); + $object = Leaf\Http\Request::object(false); + + echo json_encode([ + 'isObject' => is_object($object), + 'name' => $object->name ?? null, + 'nested' => $object->meta->tag ?? null, + 'list' => $object->tags ?? null, + ]); + + return; +} + +if ($path === '/view-status') { + (new Response())->view('demo', [], 404); + + return; +} + +if ($path === '/render-status') { + (new Response())->render('demo', [], 201); + + return; +} + +if ($path === '/download') { + $fixture = sys_get_temp_dir() . '/leafhttp-range-fixture.txt'; + file_put_contents($fixture, '0123456789'); + + (new Response())->download($fixture, 'range.txt'); + + return; +} + header('Content-Type: application/json'); if ($path === '/body') { From 04de57b86339a92a489785749e5a8d9d40895bda Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 6 Aug 2026 08:58:06 +0000 Subject: [PATCH 120/129] feat: add support for content security headers --- src/Headers.php | 75 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) diff --git a/src/Headers.php b/src/Headers.php index 4656879..6a131dd 100755 --- a/src/Headers.php +++ b/src/Headers.php @@ -171,6 +171,81 @@ public static function accessControl($key, $value = '', $code = 200) } } + /** + * Set common security headers in one call + * + * Pass `true` for the sensible defaults, or an array to pick your own + * values. Any option set to `false` is skipped. + * + * ```php + * Headers::security(); + * Headers::security(['frameOptions' => 'SAMEORIGIN', 'hsts' => false]); + * ``` + * + * @param array|bool $options Headers to set + */ + public static function security($options = true): void + { + $defaults = [ + 'frameOptions' => 'DENY', + 'contentTypeOptions' => 'nosniff', + 'referrerPolicy' => 'no-referrer-when-downgrade', + 'permissionsPolicy' => false, + 'csp' => false, + 'hsts' => false, + ]; + + $options = array_merge($defaults, is_array($options) ? $options : []); + + $headers = [ + 'frameOptions' => 'X-Frame-Options', + 'contentTypeOptions' => 'X-Content-Type-Options', + 'referrerPolicy' => 'Referrer-Policy', + 'permissionsPolicy' => 'Permissions-Policy', + 'csp' => 'Content-Security-Policy', + ]; + + foreach ($headers as $option => $header) { + if ($options[$option] === false || $options[$option] === null) { + continue; + } + + self::set($header, self::policyValue($options[$option])); + } + + if ($options['hsts'] !== false && $options['hsts'] !== null) { + // browsers ignore HSTS over plain http, and sending it there is + // how you lock yourself out of a domain you can't serve securely + if (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') { + self::set('Strict-Transport-Security', is_string($options['hsts']) + ? $options['hsts'] + : 'max-age=31536000; includeSubDomains'); + } + } + } + + /** + * Build a policy header value from a string or a directive map + * + * @param string|array $value The value or directives to build from + */ + protected static function policyValue($value): string + { + if (!is_array($value)) { + return (string) $value; + } + + $directives = []; + + foreach ($value as $directive => $sources) { + $directives[] = is_int($directive) + ? $sources + : trim($directive . ' ' . (is_array($sources) ? implode(' ', $sources) : $sources)); + } + + return implode('; ', $directives); + } + protected static function findHeaders() { if (function_exists('getallheaders') && \getallheaders()) { From a8208658adb3a287098321a03cbaa8fd1ab032ae Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 6 Aug 2026 08:58:15 +0000 Subject: [PATCH 121/129] feat: add support for content security headers --- src/Response.php | 17 +++++++++++ tests/features.test.php | 66 +++++++++++++++++++++++++++++++++++++++++ tests/server.php | 44 +++++++++++++++++++++++++++ 3 files changed, 127 insertions(+) diff --git a/src/Response.php b/src/Response.php index e616c22..29ef658 100755 --- a/src/Response.php +++ b/src/Response.php @@ -428,6 +428,23 @@ public function status(?int $code = null): Response return $this; } + /** + * Set common security headers on the response + * + * ```php + * response()->security(); + * response()->security(['csp' => ['default-src' => "'self'"]]); + * ``` + * + * @param array|bool $options Headers to set, or true for the defaults + */ + public function security($options = true): Response + { + Headers::security($options); + + return $this; + } + /** * set header * diff --git a/tests/features.test.php b/tests/features.test.php index 830ab9b..09e2258 100644 --- a/tests/features.test.php +++ b/tests/features.test.php @@ -74,3 +74,69 @@ expect($res['status'])->toBe(200) ->and($res['body'])->toBe('0123456789'); }); + +test('security() sets sensible default headers', function () { + $res = callRaw('/security-defaults'); + $headers = strtolower($res['headers']); + + expect($res['status'])->toBe(200) + ->and($headers)->toContain('x-frame-options: deny') + ->and($headers)->toContain('x-content-type-options: nosniff') + ->and($headers)->toContain('referrer-policy: no-referrer-when-downgrade'); +}); + +test('security() leaves opt-in headers off by default', function () { + $headers = strtolower(callRaw('/security-defaults')['headers']); + + // csp and permissions-policy need app-specific values, so they only + // ship when asked for + expect($headers)->not->toContain('content-security-policy') + ->and($headers)->not->toContain('permissions-policy'); +}); + +test('security() accepts custom values and builds csp from directives', function () { + $headers = callRaw('/security-custom')['headers']; + + expect($headers)->toContain('X-Frame-Options: SAMEORIGIN') + ->and($headers)->toContain("Content-Security-Policy: default-src 'self'; img-src 'self' data:") + ->and($headers)->toContain('Permissions-Policy: geolocation=()'); +}); + +test('security() skips headers set to false', function () { + $headers = strtolower(callRaw('/security-custom')['headers']); + + expect($headers)->not->toContain('referrer-policy'); +}); + +test('security() does not send hsts over plain http', function () { + $headers = strtolower(callRaw('/security-hsts')['headers']); + + // the test server speaks http, and an hsts header there is either + // ignored or actively harmful + expect($headers)->not->toContain('strict-transport-security'); +}); + +test('security() chains with json and keeps the status code', function () { + $res = callRaw('/security-chain-json'); + + expect($res['status'])->toBe(201) + ->and(strtolower($res['headers']))->toContain('x-frame-options: deny') + ->and($res['headers'])->toContain('application/json') + ->and($res['body'])->toContain('"ok":true'); +}); + +test('security() leaves the response status alone', function () { + // security() only writes headers: the 404 here comes from json(), and + // security() sitting in the middle of the chain doesn't disturb it + $res = callRaw('/security-chain-status-first'); + + expect($res['status'])->toBe(404) + ->and(strtolower($res['headers']))->toContain('x-content-type-options: nosniff'); +}); + +test('security() composes with withHeader', function () { + $res = callRaw('/security-chain-header'); + + expect(strtolower($res['headers']))->toContain('x-custom: yes') + ->and(strtolower($res['headers']))->toContain('x-frame-options: deny'); +}); diff --git a/tests/server.php b/tests/server.php index f827503..896d6d5 100644 --- a/tests/server.php +++ b/tests/server.php @@ -45,6 +45,50 @@ function view(string $view, array $data = []): string return; } +if ($path === '/security-defaults') { + (new Response())->security(); + echo 'ok'; + + return; +} + +if ($path === '/security-custom') { + (new Response())->security([ + 'frameOptions' => 'SAMEORIGIN', + 'referrerPolicy' => false, + 'csp' => ['default-src' => "'self'", 'img-src' => ["'self'", 'data:']], + 'permissionsPolicy' => 'geolocation=()', + ]); + echo 'ok'; + + return; +} + +if ($path === '/security-hsts') { + (new Response())->security(['hsts' => true]); + echo 'ok'; + + return; +} + +if ($path === '/security-chain-json') { + (new Response())->security()->json(['ok' => true], 201); + + return; +} + +if ($path === '/security-chain-status-first') { + (new Response())->status(404)->security()->json(['missing' => true], 404); + + return; +} + +if ($path === '/security-chain-header') { + (new Response())->security()->withHeader('X-Custom', 'yes')->json(['ok' => true]); + + return; +} + if ($path === '/download') { $fixture = sys_get_temp_dir() . '/leafhttp-range-fixture.txt'; file_put_contents($fixture, '0123456789'); From 7a10da58a36b41431c3a001ebe254594cfe23d08 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 6 Aug 2026 21:03:26 +0000 Subject: [PATCH 122/129] fix: patch up cookies and flash display --- src/Request.php | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/Request.php b/src/Request.php index 18dbeef..3a55cfc 100755 --- a/src/Request.php +++ b/src/Request.php @@ -338,14 +338,26 @@ public static function files($filenames = null) * This method returns a key-value array of Cookie data sent in the HTTP request, or * the value of an array key if requested. If the array key does not exist, NULL is returned. * - * @param string|null $key + * @param string|array|null $key A cookie name, a list of cookie names, or null for all cookies * @return array|string|null */ - public static function cookies(?string $key = null) + public static function cookies($key = null) { - return $key === null ? - Cookie::all() : - Cookie::get($key); + if ($key === null) { + return Cookie::all(); + } + + if (is_array($key)) { + $cookies = []; + + foreach ($key as $name) { + $cookies[$name] = Cookie::get($name); + } + + return $cookies; + } + + return Cookie::get($key); } /** @@ -356,7 +368,7 @@ public static function cookies(?string $key = null) */ public static function flash(?string $key = null) { - return \Leaf\Flash::display($key); + return \Leaf\Flash::display($key ?? 'default'); } /** From 166a6cc24d74a9eb09a23d0901708832b08d4af5 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 6 Aug 2026 21:03:42 +0000 Subject: [PATCH 123/129] fix: patch up withoutCookie() --- src/Response.php | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/src/Response.php b/src/Response.php index 29ef658..47e5cee 100755 --- a/src/Response.php +++ b/src/Response.php @@ -511,6 +511,14 @@ public function withCookie(string $name, string $value, ?int $expire = null): Re */ public function withoutCookie($name): Response { + if (is_array($name)) { + foreach ($name as $cookie) { + $this->withoutCookie($cookie); + } + + return $this; + } + $this->cookies[$name] = ['', -1]; if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') { From caa555281d06eede85c577ff39e127aa0eb0d6a3 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Wed, 12 Aug 2026 23:15:01 +0000 Subject: [PATCH 124/129] chore: update deps --- composer.json | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/composer.json b/composer.json index 09987f1..3a8f846 100644 --- a/composer.json +++ b/composer.json @@ -33,19 +33,14 @@ "prefer-stable": true, "require": { "php": "^8.2", - "leafs/anchor": "*", - "leafs/form": "*", - "leafs/fs": "*" - }, - "extra": { - "branch-alias": { - "dev-v5.x": "5.0.x-dev" - } + "leafs/anchor": "^5.0", + "leafs/form": "^5.0", + "leafs/fs": "^5.0" }, "require-dev": { - "friendsofphp/php-cs-fixer": "^3.95", + "friendsofphp/php-cs-fixer": "*", "pestphp/pest": "*", - "leafs/alchemy": "v5.x-dev" + "leafs/alchemy": "^5.0" }, "config": { "allow-plugins": { From f31b4ee14d826cc989090d9a95c331789f5000aa Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 23 Aug 2026 20:06:29 +0000 Subject: [PATCH 125/129] fix: add engine resolver to fix missing view engine error --- src/Response.php | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/Response.php b/src/Response.php index 47e5cee..45aad38 100755 --- a/src/Response.php +++ b/src/Response.php @@ -289,25 +289,47 @@ public function view(string $view, array $data = [], int $code = 200) ); } - if (!function_exists('app')) { - trigger_error('No view engine found. response()->view() needs Leaf or a view() helper to render views.'); + $engine = $this->resolveViewEngine(); + + if ($engine === null) { + trigger_error('No view engine found. response()->view() needs Leaf with an attached view engine (attachView()) or a view() helper to render views.'); return; } - if (app()->blade()) { - return $this->markup( - app()->blade()->render($view, $data), - $code, - ); + return $this->markup( + $engine->render($view, $data), + $code, + ); + } + + /** + * Find an attached view engine without triggering App::__call, + * which throws when the named engine is not attached. + * + * Order: blade, template (BareUI), then any other attached engine with a render() method. + */ + protected function resolveViewEngine() + { + if (!class_exists('Leaf\Config')) { + return null; } - if (app()->template()) { - return $this->markup( - app()->template()->render($view, $data), - $code, - ); + foreach (['blade', 'template'] as $name) { + $engine = \Leaf\Config::view($name); + + if ($engine !== null) { + return $engine; + } } + + foreach (\Leaf\Config::get() as $key => $value) { + if (strpos($key, 'views.') === 0 && is_object($value) && method_exists($value, 'render')) { + return $value; + } + } + + return null; } /** From 9cf97b6314f6f627c64dd7ac74d08874baf00056 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Sun, 13 Sep 2026 23:04:19 +0000 Subject: [PATCH 126/129] fix: remove curl close --- src/Request.php | 1 - tests/Pest.php | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/Request.php b/src/Request.php index 3a55cfc..31dcb85 100755 --- a/src/Request.php +++ b/src/Request.php @@ -830,7 +830,6 @@ public static function getLocationFromIp(string $ip): array curl_setopt($ch, CURLOPT_TIMEOUT, 5); $res = curl_exec($ch); - curl_close($ch); $data = json_decode($res ?? '{}', true); diff --git a/tests/Pest.php b/tests/Pest.php index 2861d24..a5c0dc6 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -31,7 +31,6 @@ function call(string $path, array $options = []): array $response = curl_exec($ch); $error = curl_error($ch); - curl_close($ch); if ($error) { throw new RuntimeException("test request failed: $error"); @@ -146,7 +145,6 @@ function callRaw(string $path, array $options = []): array $error = curl_error($ch); $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE); $headerSize = curl_getinfo($ch, CURLINFO_HEADER_SIZE); - curl_close($ch); if ($error) { throw new RuntimeException("test request failed: $error"); From 2a1b8e8b5118bf7d1a7a7c8a86ce0401d9e4f102 Mon Sep 17 00:00:00 2001 From: mychidarko Date: Thu, 17 Sep 2026 09:21:56 +0000 Subject: [PATCH 127/129] feat: add support for code on inertia() --- src/Response.php | 5 +++-- tests/response.test.php | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/Response.php b/src/Response.php index 45aad38..770192d 100755 --- a/src/Response.php +++ b/src/Response.php @@ -349,11 +349,12 @@ public function render(string $view, array $data = [], int $code = 200) * * @param string $view The view file to render * @param array $data The data to pass to the view + * @param int $code The response status code (eg. 404 for a not-found page) */ - public function inertia(string $view, array $data = []) + public function inertia(string $view, array $data = [], int $code = 200) { if (function_exists('inertia')) { - return inertia($view, $data); + return inertia($view, $data, $code); } trigger_error('Inertia not found. Run `leaf install inertia` or `composer require leafs/inertia`'); diff --git a/tests/response.test.php b/tests/response.test.php index d32d36d..fc2f687 100644 --- a/tests/response.test.php +++ b/tests/response.test.php @@ -25,6 +25,27 @@ expect($output['status'])->toBe(['code' => 201, 'message' => 'Created']); }); +test('inertia forwards the view, props and status to the inertia helper', function () { + if (!function_exists('inertia')) { + function inertia(string $component, array $props = [], int $status = 200) + { + $GLOBALS['__inertiaCall'] = compact('component', 'props', 'status'); + } + } + + (new Response())->inertia('not-found', ['slug' => 'x'], 404); + + expect($GLOBALS['__inertiaCall'])->toBe([ + 'component' => 'not-found', + 'props' => ['slug' => 'x'], + 'status' => 404, + ]); + + (new Response())->inertia('home'); + + expect($GLOBALS['__inertiaCall']['status'])->toBe(200); +}); + test('plain and markup set their content types', function () { $response = new Response(); From 1e6fd74c6e2e1ba30849b0348a5d05639f186d31 Mon Sep 17 00:00:00 2001 From: Michael Darko Date: Mon, 9 Nov 2026 14:11:10 +0000 Subject: [PATCH 128/129] ci: add PHP 8.5 to the test matrix (#40) * ci: add PHP 8.5 to alchemy php versions * ci: add PHP 8.5 to the test matrix --- .github/workflows/tests.yml | 2 +- alchemy.yml | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index afe6289..22c0fc6 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -9,7 +9,7 @@ jobs: fail-fast: true matrix: os: ["macos-latest","ubuntu-latest","windows-latest"] - php: ["8.4","8.3","8.2"] + php: ["8.5","8.4","8.3","8.2"] name: PHP ${{ matrix.php }} - ${{ matrix.os }} diff --git a/alchemy.yml b/alchemy.yml index 1bbc492..a41d29a 100644 --- a/alchemy.yml +++ b/alchemy.yml @@ -51,6 +51,7 @@ actions: php: extensions: json, zip, curl versions: # library supports ^7.4|^8.0, but pest 3 needs 8.2+ + - '8.5' - '8.4' - '8.3' - '8.2' From 4602c019799409f6f3153eacb84b946d6e8dfd02 Mon Sep 17 00:00:00 2001 From: William Date: Wed, 18 Nov 2026 11:03:24 +0000 Subject: [PATCH 129/129] fix: include Leaf\FS\File errors in Request::errors() --- src/Request.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/Request.php b/src/Request.php index 31dcb85..1e8aed2 100755 --- a/src/Request.php +++ b/src/Request.php @@ -878,7 +878,8 @@ public static function errors() return array_merge( static::$errors, static::$validator ? static::$validator->errors() : [], - class_exists('\Leaf\Auth') ? static::auth()->errors() : [] + class_exists('\Leaf\Auth') ? static::auth()->errors() : [], + \Leaf\FS\File::errors() ); } }