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..22c0fc6
--- /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.5","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/.gitignore b/.gitignore
index f56cefe..e6cb83b 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,4 +1,25 @@
-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/*
+
+# Alchemy
+.alchemy
+
+# Alchemy-generated (kept for IDE support, never committed)
+phpunit.xml
diff --git a/README.md b/README.md
index 7ab4a4e..a213ab0 100644
--- a/README.md
+++ b/README.md
@@ -1,27 +1,74 @@
-
-
Leaf HTTP Module
-
+
+
-# Leaf PHP
+Leaf Http
-[](https://packagist.org/packages/leafs/http)
-[](https://packagist.org/packages/leafs/http)
-[](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 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
-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
+
+You can find the full documentation on how to use Leaf Http [here](https://leafphp.dev/docs/http/request).
+
+## 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 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
+- You can also learn from [codelabs](https://leafphp.dev/codelabs/) and contribute as well.
+
+## 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.
+
+## 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.
-Built with ❤ by [**Mychi Darko**](https://mychi.netlify.app)
+And to all our [existing cash/code contributors](https://leafphp.dev#sponsors), we love you all ❤️
diff --git a/alchemy.yml b/alchemy.yml
new file mode 100644
index 0000000..a41d29a
--- /dev/null
+++ b/alchemy.yml
@@ -0,0 +1,60 @@
+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.5'
+ - '8.4'
+ - '8.3'
+ - '8.2'
+ events:
+ - push
+ - pull_request
diff --git a/composer.json b/composer.json
index d83e2e1..3a8f846 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",
@@ -10,7 +10,7 @@
"php",
"framework"
],
- "homepage": "https://leafphp.netlify.app/#/",
+ "homepage": "https://leafphp.dev/modules/http/v/2/request.html",
"type": "library",
"license": "MIT",
"authors": [
@@ -26,12 +26,31 @@
"Leaf\\Http\\": "src"
},
"files": [
- "src/functions.php"
- ]
+ "src/functions.php"
+ ]
},
"minimum-stability": "dev",
- "prefer-stable": true,
+ "prefer-stable": true,
"require": {
- "leafs/anchor": "^1.0"
+ "php": "^8.2",
+ "leafs/anchor": "^5.0",
+ "leafs/form": "^5.0",
+ "leafs/fs": "^5.0"
+ },
+ "require-dev": {
+ "friendsofphp/php-cs-fixer": "*",
+ "pestphp/pest": "*",
+ "leafs/alchemy": "^5.0"
+ },
+ "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"
}
}
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 35b4836..6a131dd 100755
--- a/src/Headers.php
+++ b/src/Headers.php
@@ -22,14 +22,18 @@ 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;
+ 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)
{
@@ -43,8 +47,13 @@ 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());
+ if (class_exists('Leaf\Eien\Server') && PHP_SAPI === 'cli') {
+ return \Leaf\Config::getStatic('request.headers');
+ }
+
+ return ($safeOutput === false) ?
+ self::findHeaders() :
+ \Leaf\Anchor::sanitize(self::findHeaders());
}
/**
@@ -57,27 +66,30 @@ 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) {
$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) {
@@ -100,12 +112,25 @@ 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 array_key_exists(
+ strtolower($header),
+ array_change_key_case(static::all(), CASE_LOWER)
+ );
+ }
+
/**
* Set the content-type to plain text
*/
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);
}
/**
@@ -113,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);
}
/**
@@ -121,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);
}
/**
@@ -129,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);
@@ -146,18 +171,98 @@ 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()) {
+ 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 784ba00..1e8aed2 100755
--- a/src/Request.php
+++ b/src/Request.php
@@ -12,44 +12,31 @@
*
* @author Michael Darko
* @since 1.0.0
+ * @version 2.3.0
*/
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
- */
+ 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'];
/**
- * HTTP Headers
- * @var Headers
- */
- public static $headers;
-
- /**
- * HTTP Cookies
- */
- public static $cookies;
-
- /**
- * The Request Body
+ * Internal instance of Leaf Form
+ * @var \Leaf\Form
*/
- protected static $request;
+ protected static $validator;
public function __construct()
{
- $handler = fopen('php://input', 'r');
- static::$request = stream_get_contents($handler);
- static::$headers = new Headers();
+ static::$validator = new \Leaf\Form();
}
/**
@@ -57,10 +44,35 @@ public function __construct()
* @return string
*/
public static function getMethod(): string
+ {
+ return static::methodOverride() ?? 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' && $method = static::get(static::METHOD_OVERRIDE)) {
+ return strtoupper($method);
+ }
+
+ return null;
+ }
+
/**
* Check for request method type
*
@@ -75,12 +87,12 @@ public static function typeIs(string $type): bool
/**
* Find if request has a particular header
*
- * @param string $header Header to check for
+ * @param string $header Header to check for
* @return bool
*/
- public static function hasHeader(String $header): bool
+ public static function hasHeader(string $header): bool
{
- return !!static::$headers->get($header);
+ return Headers::has($header);
}
/**
@@ -89,10 +101,7 @@ 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;
-
- return false;
+ return !!static::params('isajax') || Headers::get('X-Requested-With') === 'XMLHttpRequest';
}
/**
@@ -105,24 +114,32 @@ public static function isXhr(): bool
}
/**
- * 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
+ * Access stream that allows you to read raw data from the request body. **This is not for form data**
*
- * @return mixed
+ * @param bool $safeData Sanitize data?
*/
- public static function params(string $key = null, mixed $default = null): mixed
+ public static function input(bool $safeData = true)
{
- $union = static::body();
-
- if ($key) return $union[$key] ?? $default;
+ $handler = fopen('php://input', 'r');
+ $data = stream_get_contents($handler);
+
+ // 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 ($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];
+ }
- return $union;
+ return $safeData ? \Leaf\Anchor::sanitize($data) : $data;
}
/**
@@ -143,12 +160,13 @@ public static function try(array $params, bool $safeData = true, bool $noEmptySt
$dataKeys = array_keys($data);
foreach ($dataKeys as $key) {
- if (!$data[$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]);
}
}
@@ -156,27 +174,112 @@ 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)
+ {
+ 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 query($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
+ * 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)
{
- if (is_string($params)) return static::body($safeData)[$params] ?? null;
+ if ($params === null) {
+ return static::body($safeData);
+ }
- $data = [];
+ if (is_string($params)) {
+ return static::body($safeData)[$params] ?? null;
+ }
+
+ 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));
+ }
+
+ /**
+ * 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) ?? (is_callable($default) ? $default(static::body()) : $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;
}
/**
@@ -186,8 +289,24 @@ 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(static::urlData(), $_FILES, static::postData(), static::input(false));
+
+ return $safeData ?
+ \Leaf\Anchor::sanitize($finalData) :
+ $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)));
}
/**
@@ -197,13 +316,19 @@ 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) {
$files[$filename] = $_FILES[$filename] ?? null;
}
+
return $files;
}
@@ -211,14 +336,39 @@ 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
+ * @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 ? \Leaf\Http\Cookie::get($key) : \Leaf\Http\Cookie::all();
+ 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);
+ }
+
+ /**
+ * 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 ?? 'default');
}
/**
@@ -229,14 +379,14 @@ 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 && static::getContentType() === null) || in_array(static::getMediaType(), static::$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.
+ * 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
@@ -245,8 +395,166 @@ 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);
+ }
+
+ /**
+ * Validate the request data
+ *
+ * @param array $rules The rules to validate against
+ * @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();
+ }
+
+ $data = static::$validator->validate(static::body(false), $rules);
+
+ if ($data === false) {
+ return false;
+ }
+
+ return $returnFullData ? static::body() : $data;
+ }
+
+ /**
+ * 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
+ */
+ protected static function auth()
+ {
+ if (!class_exists('\Leaf\Auth')) {
+ throw new \Exception('You need to install the leafs/auth module to use the auth helper');
+ }
+
+ if (!(\Leaf\Config::getStatic('auth'))) {
+ \Leaf\Config::singleton('auth', function () {
+ return new \Leaf\Auth();
+ });
+ }
+
+ return \Leaf\Config::get('auth');
+ }
+
+ /**
+ * Get the authenticated user
+ */
+ 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.
+ *
+ * @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 = [])
+ {
+ $file = static::files($key);
+
+ if (!$file) {
+ static::$errors['upload'] = 'No file was uploaded.';
+
+ 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);
+
+ if (!in_array($fileExtension, $config['extensions'])) {
+ static::$errors['upload'] = 'Invalid file extension.';
+
+ return false;
+ }
+ }
+
+ $fileSystem = new \Leaf\FS\File();
+
+ if (!isset($config['rename']) || !$config['rename']) {
+ $config['unique'] = true;
+ }
+
+ $uploadedFile = $fileSystem->upload(
+ $file,
+ preg_replace(
+ '/\/$/',
+ '',
+ $destination
+ ) . '/',
+ $config
+ );
+
+ return $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 = [])
+ {
+ $fileExtension = pathinfo($_FILES[$key]['name'], PATHINFO_EXTENSION);
+
+ $config['rename'] = true;
+ $config['name'] = $name . '.' . $fileExtension;
+
+ return static::upload($key, $destination, $config);
}
/**
@@ -255,7 +563,19 @@ 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');
+ }
+
+ /**
+ * 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;
}
/**
@@ -265,6 +585,7 @@ public static function getContentType(): ?string
public static function getMediaType(): ?string
{
$contentType = static::getContentType();
+
if ($contentType) {
$contentTypeParts = preg_split('/\s*[;,]\s*/', $contentType);
@@ -280,8 +601,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);
@@ -303,6 +624,7 @@ public static function getMediaTypeParams(): array
public static function getContentCharset(): ?string
{
$mediaTypeParams = static::getMediaTypeParams();
+
if (isset($mediaTypeParams['charset'])) {
return $mediaTypeParams['charset'];
}
@@ -316,7 +638,7 @@ public static function getContentCharset(): ?string
*/
public static function getContentLength(): int
{
- return static::$headers->get('CONTENT_LENGTH') ?? 0;
+ return (int) (Headers::get('Content-Length') ?? 0);
}
/**
@@ -328,7 +650,7 @@ 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];
@@ -355,7 +677,7 @@ public static function getHostWithPort(): string
*/
public static function getPort(): int
{
- return (int) $_SERVER['SERVER_PORT'] ?? 80;
+ return (int) ($_SERVER['SERVER_PORT'] ?? 80);
}
/**
@@ -368,7 +690,7 @@ public static function getScheme(): string
}
/**
- * Get Script Name (physical path)
+ * Get Script Name
* @return string
*/
public static function getScriptName(): string
@@ -377,12 +699,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)
+ );
}
/**
@@ -394,6 +730,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'] ?? parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY) ?? null;
+ }
+
/**
* Get URL (scheme + host [ + port if non-standard ])
* @return string
@@ -403,27 +748,98 @@ 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;
}
+ /**
+ * Get Full URL (scheme + host [ + port if non-standard ] + path + query string)
+ * @return string
+ */
+ public static function getFullUrl(): string
+ {
+ // 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() : '');
+ }
+
/**
* Get IP
* @return string
*/
public static function getIp(): string
{
- $keys = ['X_FORWARDED_FOR', 'HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR'];
+ $ip = $_SERVER['HTTP_CLIENT_IP']
+ ?? $_SERVER['HTTP_X_FORWARDED_FOR']
+ ?? $_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;
+ }
+
+ /**
+ * 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()
+ );
+ }
- foreach ($keys as $key) {
- if (isset($_SERVER[$key])) {
- return $_SERVER[$key];
+ /**
+ * 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 {
+ $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);
+
+ $data = json_decode($res ?? '{}', true);
+
+ if (($data['status'] ?? false) === 'success') {
+ $response = array_merge($response, $data);
}
+ } catch (\Exception $e) {
}
- return $_SERVER['REMOTE_ADDR'];
+ return $response;
}
/**
@@ -432,7 +848,7 @@ public static function getIp(): string
*/
public static function getReferrer(): ?string
{
- return static::$headers->get('HTTP_REFERER');
+ return $_SERVER['HTTP_REFERER'] ?? null;
}
/**
@@ -450,6 +866,20 @@ public static function getReferer(): ?string
*/
public static function getUserAgent(): ?string
{
- return static::$headers->get('HTTP_USER_AGENT');
+ return Headers::get('USER-AGENT');
+ }
+
+ /**
+ * Handle errors from validation/auth/upload
+ * @return array
+ */
+ public static function errors()
+ {
+ return array_merge(
+ static::$errors,
+ static::$validator ? static::$validator->errors() : [],
+ class_exists('\Leaf\Auth') ? static::auth()->errors() : [],
+ \Leaf\FS\File::errors()
+ );
}
}
diff --git a/src/Response.php b/src/Response.php
index 61ef5e1..770192d 100755
--- a/src/Response.php
+++ b/src/Response.php
@@ -11,98 +11,93 @@
*
* @author Michael Darko
* @since 1.0.0
+ * @version 2.0
*/
class Response
{
+ /**
+ * @var array
+ */
+ public $headers = [];
+
+ /**
+ * @var array
+ */
+ public $cookies = [];
+
+ /**
+ * @var string
+ */
+ protected $content = '';
+
/**
* @var int HTTP status code
*/
- protected static $status;
-
- /**
- * @var \Leaf\Http\Headers
- */
- public static $headers;
-
- /**
- * @var array HTTP response codes and messages
- */
- 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'
- ];
-
- public function __construct()
+ protected $status = 200;
+
+ /**
+ * @var array|null [start byte, length] window for range downloads
+ */
+ protected $downloadRange = null;
+
+ /**
+ * @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;
+ }
+
+ /**
+ * 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)
{
- static::$headers = Headers::class;
- Headers::contentHtml();
+ $this->status = $code;
+ $this->headers['Content-Type'] ??= 'text/plain';
+ $this->content = $data;
+
+ $this->send();
}
/**
* Output plain text
- *
+ *
* @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;
+
+ $this->send();
}
/**
@@ -111,128 +106,405 @@ 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(string $data, int $code = 200)
{
- Headers::contentXml($code);
- echo $data;
+ $this->status = $code;
+ $this->headers['Content-Type'] = 'application/xml';
+ $this->content = $data;
+
+ $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
- *
+ *
* @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 static function json($data, int $code = 200, bool $showCode = false, bool $useMessage = false)
+ public function json($data, int $code = 200, bool $showCode = false)
{
- if ($showCode) {
- $dataToPrint = ["data" => $data, "code" => $code];
+ $this->status = $code;
- if ($useMessage) {
- $dataToPrint = ["data" => $data, "message" => self::$messages[$code] ?? $code];
- }
+ if ($showCode) {
+ $dataToPrint = [
+ 'data' => $data,
+ 'status' => [
+ 'code' => $code,
+ '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();
}
+ /**
+ * 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';
+
+ \ob_start();
+ require $file;
+ $this->content = ob_get_contents();
+ ob_end_clean();
+
+ $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
- *
+ *
* @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
*/
- 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.");
+
+ return;
}
-
- if ($name === null) $name = basename($file);
- Headers::status($code);
- Headers::set([
- 'Content-Length' => filesize($file),
- 'Content-Disposition' => "attachment; filename=$name",
+ $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',
+ 'Accept-Ranges' => 'bytes',
+ 'Content-Length' => $length,
+ 'Cache-Control' => 'must-revalidate',
+ 'Content-Description' => 'File Transfer',
+ 'Content-Type' => 'application/octet-stream',
+ 'Content-Disposition' => 'attachment; filename="' . ($name ?? basename($file)) . '"',
]);
-
- readfile($file);
- exit;
+
+ $this->content = $file;
+ $this->downloadRange = [$start, $length];
+
+ $this->send();
}
/**
- * Throw an error and break the application
+ * 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 static function throwErr($error, int $code = 500, bool $useMessage = false)
+ public function noContent()
{
- $dataToPrint = ["error" => $error, "code" => $code];
- if ($useMessage) $dataToPrint = ["error" => $error, "message" => self::$messages[$code] ?? $code];
+ $this->status = 204;
+ $this->send();
+ }
- Headers::contentJSON($code);
- echo json_encode($dataToPrint);
- exit();
+ /**
+ * 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
+ * @param int $code The response status code
+ */
+ public function view(string $view, array $data = [], int $code = 200)
+ {
+ if (function_exists('view')) {
+ return $this->markup(
+ view($view, $data),
+ $code,
+ );
+ }
+
+ $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;
+ }
+
+ return $this->markup(
+ $engine->render($view, $data),
+ $code,
+ );
}
- public static function page(string $file, int $code = null)
+ /**
+ * 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()
{
- Headers::contentHtml($code);
- require $file;
+ if (!class_exists('Leaf\Config')) {
+ return null;
+ }
+
+ 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;
}
- public static function markup(String $markup, int $code = null)
+ /**
+ * 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
+ * @param int $code The response status code
+ */
+ public function render(string $view, array $data = [], int $code = 200)
{
- Headers::contentHtml($code);
- echo <<view($view, $data, $code);
+ }
+
+ /**
+ * 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
+ * @param int $code The response status code (eg. 404 for a not-found page)
+ */
+ public function inertia(string $view, array $data = [], int $code = 200)
+ {
+ if (function_exists('inertia')) {
+ return inertia($view, $data, $code);
+ }
+
+ trigger_error('Inertia not found. Run `leaf install inertia` or `composer require leafs/inertia`');
}
- public static function cors(String $allow_origin = "*", String $allow_headers = "*")
+ /**
+ * Output some data and break the application
+ *
+ * @param mixed $data The data to output
+ * @param int $code The Http status code
+ */
+ public function exit($data, int $code = 500)
{
- Headers::accessControl(["Allow-Origin" => $allow_origin, "Allow-Headers" => $allow_headers]);
+ $this->status = $code;
+
+ if (is_array($data)) {
+ $this->headers['Content-Type'] = 'application/json';
+ $this->content = json_encode($data);
+ } else {
+ $this->content = $data;
+ }
+
+ $this->send();
+
+ exit();
}
/**
- * Get and set header
- *
- * @param string $name Header name
- * @param string|null $value Header value
- * @return string Header value
+ * 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
+ *
+ * This method prepares this response to return an HTTP Redirect response
+ * to the HTTP client.
+ *
+ * @param string|array $url The redirect destination
+ * @param int $status The redirect HTTP status code
+ */
+ public function redirect($url, int $status = 302, bool $exit = true)
+ {
+ if (is_array($url)) {
+ $url = app()->route($url[0], ...array_slice($url, 1));
+ }
+
+ if (class_exists('Leaf\App') && !strpos($url, '://')) {
+ $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);
+
+ if ($exit) {
+ exit($status);
+ }
+ }
+
+ /**
+ * Pass data to the route handler
+ *
+ * @param mixed $data The data to pass
*/
- public static function header(string $name, string $value = null): string
+ public function next($data)
{
- if (!is_null($value)) Headers::set($name, $value);
- return Headers::get($name);
+ \Leaf\Config::set('middleware.data', $data);
}
/**
- * Set HTTP status code
+ * Force set HTTP status code
+ *
+ * @param int|null code The response code to set
*/
- public static function status($code = null)
+ public function status(?int $code = null): Response
{
- return Headers::status($code);
+ if ($code !== null) {
+ $this->status = $code;
+ Headers::status($code);
+ }
+
+ return $this;
}
/**
- * Set cookie
+ * Set common security headers on the response
*
- * Set a new cookie
+ * ```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
*
- * @param string|array $name The name of the cookie
- * @param string $value If string, the value of cookie
- * @param array $options Settings for cookie
+ * @param string|array $name Header name
+ * @param string|null $value Header value
+ * @param bool $replace Replace existing header
+ * @param int $httpCode The HTTP status code
*/
- public static function setCookie($name, string $value, array $options = [])
+ public function withHeader($name, ?string $value = '', bool $replace = true, int $httpCode = 200): Response
{
- Cookie::set($name, $value, $options);
+ 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);
+
+ return $this;
+ }
+
+ if ($replace === false || $httpCode !== 200) {
+ Headers::set($name, $value, $replace, $httpCode);
+ } else {
+ $this->headers[$name] = $value;
+ }
+
+ return $this;
}
/**
@@ -240,46 +512,206 @@ public static function setCookie($name, string $value, array $options = [])
*
* @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 static function simpleCookie(string $name, string $value, string $expire = "7 days")
+ public function withCookie(string $name, string $value, ?int $expire = null): Response
{
- Cookie::simpleCookie($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);
+ }
+
+ return $this;
}
/**
* Delete cookie
*
- * @param string $name The name of the cookie
+ * @param mixed $name The name of the cookie
*/
- public static function deleteCookie(string $name)
+ public function withoutCookie($name): Response
{
- Cookie::unset($name);
+ 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') {
+ \Leaf\Config::set('response.cookies', $this->cookies);
+ }
+
+ return $this;
}
/**
- * Redirect
+ * Flash a piece of data to the session.
*
- * This method prepares this response to return an HTTP Redirect response
- * to the HTTP client.
+ * @param string|array key The key of the item to set
+ * @param mixed $value The value of flash item
*
- * @param string $url The redirect destination
- * @param int $status The redirect HTTP status code
+ * @return Response
*/
- public static function redirect(string $url, int $status = 302)
+ public function withFlash($key, $value = null): Response
{
- Headers::status($status);
- Headers::set('Location', $url);
+ 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);
+ }
+
+ return $this;
+ }
+
+ \Leaf\Flash::set($value, $key);
+
+ return $this;
}
/**
* Get message for HTTP status code
- *
+ *
* @param int $status
* @return string|null
*/
public static function getMessageForCode(int $status): ?string
{
- return self::$messages[$status] ?? null;
+ return Status::$statusTexts[$status] ?? 'unknown status';
+ }
+
+ /**
+ * Sends HTTP headers.
+ *
+ * @return $this
+ */
+ public function sendHeaders(): Response
+ {
+ 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;
+ }
+
+ Headers::set($this->headers);
+
+ // status
+ header(sprintf('%s %s %s', $this->httpVersion(), $this->status, Status::$statusTexts[$this->status] ?? ''), true, $this->status);
+
+ return $this;
+ }
+
+ /**
+ * Send cookies
+ */
+ 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')) {
+ foreach ($this->cookies as $key => $value) {
+ Cookie::set($key, $value[0], ['expire' => $value[1]]);
+ }
+ }
+
+ return $this;
+ }
+
+ /**
+ * Sends content for the current web response.
+ *
+ * @return $this
+ */
+ public function sendContent(): Response
+ {
+ if (strpos($this->headers['Content-Disposition'] ?? '', 'attachment') !== false) {
+ $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;
+ }
+
+ return $this;
+ }
+
+ /**
+ * Send the Http headers and content
+ *
+ * @return $this
+ */
+ public function send(): Response
+ {
+ $this->sendHeaders()->sendCookies()->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);
+ }
+
+ return $this;
+ }
+
+ /**
+ * 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();
+ }
+ }
}
}
diff --git a/src/Status.php b/src/Status.php
new file mode 100644
index 0000000..6e81ca9
--- /dev/null
+++ b/src/Status.php
@@ -0,0 +1,154 @@
+
+ *
+ * @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
+ ];
+}
diff --git a/src/functions.php b/src/functions.php
index 731c4d6..e19eb72 100644
--- a/src/functions.php
+++ b/src/functions.php
@@ -5,10 +5,21 @@
* 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')) {
+ if (!\Leaf\Config::getStatic('request')) {
+ \Leaf\Config::singleton('request', function () {
+ return new \Leaf\Http\Request();
+ });
+ }
+
+ return \Leaf\Config::get('request');
+ }
+
return new \Leaf\Http\Request();
}
}
@@ -18,10 +29,21 @@ 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')) {
+ if (!\Leaf\Config::getStatic('response')) {
+ \Leaf\Config::singleton('response', function () {
+ return new \Leaf\Http\Response();
+ });
+ }
+
+ return \Leaf\Config::get('response');
+ }
+
return new \Leaf\Http\Response();
}
}
diff --git a/tests/Pest.php b/tests/Pest.php
new file mode 100644
index 0000000..a5c0dc6
--- /dev/null
+++ b/tests/Pest.php
@@ -0,0 +1,158 @@
+ 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);
+
+ 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__);
+
+/**
+ * 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);
+
+ 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..09e2258
--- /dev/null
+++ b/tests/features.test.php
@@ -0,0 +1,142 @@
+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');
+});
+
+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/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..fc2f687
--- /dev/null
+++ b/tests/response.test.php
@@ -0,0 +1,137 @@
+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('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();
+
+ 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..896d6d5
--- /dev/null
+++ b/tests/server.php
@@ -0,0 +1,162 @@
+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 === '/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');
+
+ (new Response())->download($fixture, 'range.txt');
+
+ return;
+}
+
+header('Content-Type: application/json');
+
+if ($path === '/body') {
+ echo json_encode([
+ 'method' => 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]);