diff --git a/README.md b/README.md index ad60be5..c69e69b 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ $input->hasRaw('token'); ## Documentation -Full developer documentation lives in [`docs/`](docs/README.md): +Full developer documentation lives in [`docs/`](docs/Home.md): getting started, each source, the priority model, validation, the facade, a complete API reference and an FAQ. diff --git a/docs/API-Reference.md b/docs/API-Reference.md new file mode 100644 index 0000000..a485ad6 --- /dev/null +++ b/docs/API-Reference.md @@ -0,0 +1,148 @@ +# API Reference + +Every public symbol in the package. Unless noted, the shared accessor +signature is: + +```php +function (string $key, mixed $default = null, ?array $validation = null): mixed +``` + +- **`$key`** — the parameter name (case-sensitive). +- **`$default`** — returned when the key is absent or the value fails + validation. Defaults to `null`. +- **`$validation`** — a list of + [validation rules](https://github.com/InitPHP/Validation/wiki/Rules-Reference) + (DSL strings and/or callables). Empty or `null` skips validation. + +--- + +## Interface `InputInterface` + +`InitPHP\Input\InputInterface` — the contract implemented by `Inputs`. +Type-hint this in your services for dependency injection. + +### Single source + +| Method | Reads from | +| -------- | ------------------------------- | +| `get()` | `$_GET` | +| `post()` | `$_POST` | +| `raw()` | decoded JSON `php://input` body | + +### Priority (first source that has the key wins) + +| Method | Order | +| -------------- | ------------------ | +| `getPost()` | get → post | +| `getRaw()` | get → raw | +| `getPostRaw()` | get → post → raw | +| `getRawPost()` | get → raw → post | +| `postGet()` | post → get | +| `postRaw()` | post → raw | +| `postGetRaw()` | post → get → raw | +| `postRawGet()` | post → raw → get | +| `rawGet()` | raw → get | +| `rawPost()` | raw → post | +| `rawGetPost()` | raw → get → post | +| `rawPostGet()` | raw → post → get | + +### Presence + +| Method | Returns | +| ---------------------------- | ---------------------------------- | +| `hasGet(string $key): bool` | whether `$key` exists in `$_GET` | +| `hasPost(string $key): bool` | whether `$key` exists in `$_POST` | +| `hasRaw(string $key): bool` | whether `$key` exists in the body | + +A key whose stored value is `null` still counts as present. + +--- + +## Class `Inputs` + +`InitPHP\Input\Inputs` — `final`, implements `InputInterface`. + +### `__construct()` + +```php +public function __construct( + ?array $get = null, + ?array $post = null, + ?array $raw = null, + ?\InitPHP\Validation\Validation $validation = null +) +``` + +Builds an instance over the three sources. Each `null` argument falls back +to its global: + +| Argument | Falls back to | +| --- | --- | +| `$get` | `$_GET` | +| `$post` | `$_POST` | +| `$raw` | the decoded `php://input` body | +| `$validation` | a fresh `Validation` instance | + +The argument names are part of the public API — named arguments such as +`new Inputs(get: [...], raw: [...])` are supported and encouraged. + +```php +$input = new Inputs( + get: ['name' => 'Jane'], + post: ['email' => 'jane@example.com'], + raw: ['token' => 'abc123'], +); +``` + +### `decodeJsonBody()` + +```php +public static function decodeJsonBody(string $body): array +``` + +JSON-decode a raw request body into an input array. An empty string, a +scalar (`5`, `"x"`, `true`), or malformed JSON returns `[]`, so a scalar +payload can never reach the underlying container. + +```php +Inputs::decodeJsonBody('{"a":1}'); // ['a' => 1] +Inputs::decodeJsonBody('42'); // [] +Inputs::decodeJsonBody('oops'); // [] +Inputs::decodeJsonBody(''); // [] +``` + +--- + +## Facade `Facade\Inputs` + +`InitPHP\Input\Facade\Inputs` — `final`. A static proxy over a single +`InputInterface` instance; all `InputInterface` methods are callable +statically (e.g. `Inputs::get(...)`). + +| Method | Description | +| --- | --- | +| `setInstance(InputInterface $instance): void` | Replace the backing instance (tests, DI). | +| `reset(): void` | Forget the backing instance; the next call rebuilds it. | + +See [The Facade](The-Facade.md). + +--- + +## Behaviour notes + +- **Case sensitivity.** Keys are matched exactly; `name` and `Name` differ. +- **Value types.** Values are returned as the source provides them — + query/form values are strings, JSON-body values keep their decoded type. +- **Flat storage.** Each source is a flat bag; a dotted key is a literal + key, not a path into nested data. +- **No fall-through on invalid.** In a priority helper, the first source + that has the key is committed to; an invalid value returns the default + rather than trying the next source. +- **Isolation.** Instances share no static state; two `Inputs` objects + never interfere. + +## Next + +- [Reading Sources](Reading-Sources.md) +- [Source Priority](Source-Priority.md) +- [Validation](Validation.md) diff --git a/docs/faq.md b/docs/FAQ.md similarity index 52% rename from docs/faq.md rename to docs/FAQ.md index 6740f14..27bf484 100644 --- a/docs/faq.md +++ b/docs/FAQ.md @@ -1,28 +1,32 @@ # FAQ -Common pitfalls and clarifications. +Common questions and pitfalls. See also [Migration from 1.x](Migration-from-1.x.md). ## Are keys case-insensitive? No. `get('name')` and `get('Name')` are different keys, and -`hasGet('Name')` is `false` when the stored key is `name`. This mirrors -how HTTP query and body parameters actually behave. +`hasGet('Name')` is `false` when the stored key is `name`. This mirrors how +HTTP query and body parameters actually behave. -> Earlier 1.x releases folded keys to lower-case. Version 2 matches keys -> exactly. If you relied on the old behaviour, normalise the key yourself -> before calling, e.g. `get(strtolower($key))`. +> Version 1.x folded keys to lower-case. 2.0 matches them exactly. If you +> relied on the old behaviour, normalise the key yourself: +> `get(strtolower($key))`. ## Why did `get()` return a string for a number? Query and form values are always strings (`'2'`, not `2`) — that is what -the SAPI provides. JSON-body values keep their decoded type. Cast -explicitly, or validate with a rule like `['integer']` and convert after. +PHP's SAPI provides. JSON-body values keep their decoded type. Cast +explicitly, or validate with a rule like `['integer']` and convert after: + +```php +$page = (int) $input->get('page', 1, ['integer']); +``` ## In a priority helper, why didn't it use the valid value from the next source? Priority is decided by **presence**, not validity. The first source that -*contains* the key is committed to. If that value fails validation you -get the default — the helper does not roll over to the next source. +*contains* the key is committed to. If that value fails validation you get +the default — the helper does **not** roll over to the next source. ```php $input = new Inputs( @@ -32,28 +36,30 @@ $input = new Inputs( $input->getPost('year', 2015, ['range(1970...2070)']); // 2015 ``` -If you need the next source's value, read the sources separately, or -order the helper so the trusted source comes first. +If you need the next source's value, read the sources separately, or order +the helper so the trusted source comes first. See +[Source Priority](Source-Priority.md) and [Validation](Validation.md). ## My JSON body isn't showing up in `raw()`. Why? Three common causes: 1. **The body was already read.** `php://input` can usually be read only - once per request. Build `Inputs` once (or use the facade) and reuse - it; or decode the body yourself and pass it via `new Inputs(raw: ...)`. -2. **The payload is a scalar or invalid JSON.** Only a JSON object or - array becomes data; `42`, `"x"`, `true` or malformed JSON decode to an - empty set by design. + once per request. Build `Inputs` once (or use the facade) and reuse it; + or decode the body yourself and pass it via `new Inputs(raw: ...)`. +2. **The payload is a scalar or invalid JSON.** Only a JSON object or array + becomes data; `42`, `"x"`, `true` or malformed JSON decode to an empty + set by design. 3. **Nested access.** Each source is a *flat* bag — `raw('user.name')` looks up the literal key `user.name`, it does not descend. Read the nested array and index it: `$input->raw('user')['name'] ?? null`. ## Does the facade share data with a `new Inputs()` I create? -No. They are independent objects. The facade caches its own instance; -your `new Inputs()` reads its own sources. To put specific data behind -the facade, use `Facade\Inputs::setInstance(new Inputs(...))`. +No. They are independent objects. The facade caches its own instance; your +`new Inputs()` reads its own sources. To put specific data behind the +facade, use `Facade\Inputs::setInstance(new Inputs(...))`. See +[The Facade](The-Facade.md). ## How do I test code that uses the facade? @@ -68,11 +74,13 @@ Input::setInstance(new Inputs(get: ['name' => 'Jane'])); Input::reset(); // in tearDown() ``` +See [Testing](Testing.md). + ## Can I use my own validator configuration? Yes. Pass a preconfigured `InitPHP\Validation\Validation` as the fourth -constructor argument — for example one with a custom locale or -`extend()`-ed rules — and it will be used for every validated lookup: +constructor argument — for example one with a custom locale or `extend()`-ed +rules — and it is used for every validated lookup: ```php $validator = (new \InitPHP\Validation\Validation()) @@ -82,6 +90,31 @@ $input = new Inputs(get: ['n' => '4'], validation: $validator); $input->get('n', null, ['even']); // '4' ``` +## Can I read all values at once? + +Not through this package — it is deliberately a *single value* reader. +If you need the whole array, read the source you want directly (`$_GET`, +`$_POST`, or the decoded body) or wrap it in +[`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag). + +## Does it support nested / dotted keys? + +No. Sources are stored as flat bags, so `get('a.b')` is a lookup for the +literal key `a.b`. For nested structures, read the parent and index into +it, or use [`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag) +in multi mode. + ## Which PHP versions are supported? -PHP 8.1 and later. The package is checked on 8.1–8.4 in CI. +PHP 8.2 and later. The package is tested on 8.2–8.5 in CI. + +## Where do I report a bug or request a feature? + +[Open an issue](https://github.com/InitPHP/Input/issues/new) on the +repository, or start a thread in +[Discussions](https://github.com/orgs/InitPHP/discussions). + +## Next + +- [API Reference](API-Reference.md) +- [Migration from 1.x](Migration-from-1.x.md) diff --git a/docs/Home.md b/docs/Home.md new file mode 100644 index 0000000..c569c7a --- /dev/null +++ b/docs/Home.md @@ -0,0 +1,92 @@ +# InitPHP Input — Wiki + +Welcome to the official documentation for **`initphp/input`** — a small, +focused library for reading a single request value from the query string, +the submitted form fields, or the JSON request body, with configurable +**source priority** and optional **validation**, behind one tidy API. + +Built for **PHP 8.2+**. + +```bash +composer require initphp/input +``` + +```php +use InitPHP\Input\Facade\Inputs as Input; + +// GET /?page=2 +$page = Input::get('page', 1); // '2' +$year = Input::getPost('year', 2015, ['range(1970...2070)']); +$token = Input::raw('token'); // from the JSON body +``` + +## The package in one table + +| Symbol | Role | +| --- | --- | +| [`Inputs`](API-Reference.md#class-inputs) | The implementation. Wraps the three sources and reads values from them. | +| [`InputInterface`](API-Reference.md#interface-inputinterface) | The contract every accessor implements — type-hint this in your services. | +| [`Facade\Inputs`](The-Facade.md) | A static proxy over a single `Inputs` instance: `Input::get(...)`. | +| [`Inputs::decodeJsonBody()`](API-Reference.md#decodejsonbody) | Safely turn a raw JSON body into an input array (scalars/garbage become `[]`). | + +## Start here + +- **New to the package?** Read [Installation](Installation.md), then + [Quick Start](Quick-Start.md). +- **Reading one source?** [Reading Sources](Reading-Sources.md) covers + `get`, `post` and `raw`. +- **Value might be in several places?** [Source Priority](Source-Priority.md) + explains the twelve priority helpers and the *first source that has the + key wins* rule. +- **Want to reject bad input?** [Validation](Validation.md). +- **Prefer static calls?** [The Facade](The-Facade.md). +- **Coming from 1.x?** Read [Migration from 1.x](Migration-from-1.x.md) — 2.0 + is a breaking release. + +## What you get + +- **Three sources behind one API.** `get` (`$_GET`), `post` (`$_POST`) and + `raw` (the decoded JSON `php://input` body). See + [Reading Sources](Reading-Sources.md). +- **Twelve priority helpers.** `getPost`, `postRawGet`, `rawGetPost`, … + read the sources in a defined order and return the first one that + contains the key. See [Source Priority](Source-Priority.md). +- **Per-call validation.** Hand a list of rules to any accessor; a value + that fails yields the default. Powered by + [initphp/validation](https://github.com/InitPHP/Validation). See + [Validation](Validation.md). +- **A safe JSON body reader.** A scalar or malformed body decodes to an + empty set instead of a fatal error. +- **A facade and an injectable instance.** Use `Input::get(...)` for app + code, or `new Inputs(...)` with explicit data for tests and DI. See + [The Facade](The-Facade.md) and [Testing](Testing.md). +- **No shared static state.** Two `Inputs` objects never interfere; + PHPStan level max clean; 100% test coverage. + +## The three sources at a glance + +| Source | Backed by | Accessor | Presence check | +| ------ | -------------- | -------- | -------------- | +| `get` | `$_GET` | `get()` | `hasGet()` | +| `post` | `$_POST` | `post()` | `hasPost()` | +| `raw` | `php://input`* | `raw()` | `hasRaw()` | + +\* The body is read once and JSON-decoded. Only a JSON object/array +becomes data; anything else is treated as empty. + +## Package metadata + +- **License**: MIT +- **Minimum PHP**: 8.2 +- **Required extensions**: `ext-json` +- **Runtime dependencies**: + [`initphp/parameterbag ^2.0`](https://github.com/InitPHP/ParameterBag), + [`initphp/validation ^2.0`](https://github.com/InitPHP/Validation) +- **Packagist**: [`initphp/input`](https://packagist.org/packages/initphp/input) +- **Source**: [github.com/InitPHP/Input](https://github.com/InitPHP/Input) +- **Issues**: [github.com/InitPHP/Input/issues](https://github.com/InitPHP/Input/issues) +- **Discussions**: [github.com/orgs/InitPHP/discussions](https://github.com/orgs/InitPHP/discussions) + +If something in this wiki is unclear, wrong, or out of date, +[open an issue](https://github.com/InitPHP/Input/issues/new) — documentation +fixes are merged eagerly. diff --git a/docs/Installation.md b/docs/Installation.md new file mode 100644 index 0000000..c4f38b3 --- /dev/null +++ b/docs/Installation.md @@ -0,0 +1,61 @@ +# Installation + +## Requirements + +| Requirement | Version | +| --- | --- | +| PHP | 8.2 or later | +| `ext-json` | bundled with PHP | +| [`initphp/parameterbag`](https://github.com/InitPHP/ParameterBag) | `^2.0` | +| [`initphp/validation`](https://github.com/InitPHP/Validation) | `^2.0` | + +The two InitPHP dependencies are installed automatically by Composer. + +## Install with Composer + +```bash +composer require initphp/input +``` + +Then make sure the Composer autoloader is loaded once in your application's +entry point: + +```php +require_once __DIR__ . '/vendor/autoload.php'; +``` + +## Verify the install + +```php + 'pong']); + +echo $input->get('ping'); // pong +``` + +If that prints `pong`, you are ready to go. + +## The two classes you will use + +```php +use InitPHP\Input\Inputs; // the instance API +use InitPHP\Input\Facade\Inputs as Input; // the static facade +``` + +- **`Inputs`** — create it yourself (`new Inputs()`), optionally with + explicit data. Best for dependency injection and tests. +- **`Facade\Inputs`** — a static proxy that lazily builds one `Inputs` + from the superglobals. Best for quick reads in application code. + +Both expose exactly the same methods. See [The Facade](The-Facade.md) for the +difference and when to use which. + +## Next + +- [Quick Start](Quick-Start.md) +- [Reading Sources](Reading-Sources.md) diff --git a/docs/Migration-from-1.x.md b/docs/Migration-from-1.x.md new file mode 100644 index 0000000..98b405d --- /dev/null +++ b/docs/Migration-from-1.x.md @@ -0,0 +1,118 @@ +# Migration from 1.x + +Version **2.0 is a breaking release**. It raises the PHP floor, moves to the +2.0 line of its dependencies, and fixes long-standing correctness issues in +the way state was shared. Most application code that used the facade keeps +working unchanged; the breaking changes mostly affect edge cases and direct +instantiation. + +> This page describes the 1.x to 2.0 changes, which raised the PHP floor to +> 8.1. The development line after 2.0.0 raises it again to PHP 8.2 (see the +> [CHANGELOG](https://github.com/InitPHP/Input/blob/main/CHANGELOG.md)), +> so check [Installation](Installation.md) for the current requirement. + +## At a glance + +| Area | 1.x | 2.0 | +| --- | --- | --- | +| Minimum PHP | 7.2 | **8.1** | +| `initphp/parameterbag` | `^1.1` | **`^2.0`** | +| `initphp/validation` | `^1.0` | **`^2.0`** | +| Key matching | case-**insensitive** | case-**sensitive** | +| Instance state | shared `static` bags | per-instance, isolated | +| Destructor | `__destruct` cleared shared bags | removed | +| Facade instance `__call` | present | removed (`__callStatic` only) | +| New: `InputInterface` | — | added | +| New: constructor injection | — | `new Inputs(get:…, post:…, raw:…)` | +| New: `Inputs::decodeJsonBody()` | — | added | +| New: `Facade::setInstance()` / `reset()` | — | added | + +## 1. Bump your PHP and dependencies + +Version 2.0 requires **PHP 8.1+** because `initphp/validation ^2.0` does. +Update your environment, then: + +```bash +composer require initphp/input:^2.0 +``` + +## 2. Keys are now case-sensitive + +1.x folded every key to lower-case, so `get('Name')` and `get('name')` were +the same key. **2.0 matches keys exactly**, mirroring how HTTP query and +body parameters actually behave. + +```php +$input = new Inputs(get: ['Name' => 'Jane']); + +$input->get('Name'); // 'Jane' +$input->get('name'); // null (1.x would have returned 'Jane') +``` + +**If you relied on the old behaviour**, normalise the key yourself before +calling: + +```php +$input->get(strtolower($key)); +``` + +## 3. Instances no longer share state + +In 1.x the three source bags were `static` and a destructor cleared them, +which meant a second `Inputs` instance — or a temporary one being garbage +collected — could silently empty the data for everyone. + +**2.0 stores state per instance.** Each `Inputs` is independent, and the +destructor is gone. This is the bug fix you most likely want, but if any of +your code *depended* on two `Inputs` objects sharing data through statics, +that no longer happens — give them the same data explicitly, or use the +[facade](The-Facade.md), which holds a single shared instance. + +## 4. The facade gained inject/reset, lost instance `__call` + +The facade is still used exactly the same way: + +```php +use InitPHP\Input\Facade\Inputs as Input; + +Input::get('name', 'John'); // unchanged +``` + +What changed: + +- The unused instance-level `__call` was removed; only the static + `__callStatic` proxy remains. (Calling facade methods on an *instance* of + the facade was never the intended usage.) +- New `Input::setInstance(...)` and `Input::reset()` let you inject a + configured instance — see [The Facade](The-Facade.md) and [Testing](Testing.md). + +## 5. Validation rule names + +Validation moved to 2.0 as well. The rules used by this package's examples — +`required`, `range(...)`, `again(...)`, `integer`, `mail`, … — still exist +and behave the same. If you used more exotic rules, check the Validation +wiki's +[Rules Reference](https://github.com/InitPHP/Validation/wiki/Rules-Reference) +and [Migration from 1.x](https://github.com/InitPHP/Validation/wiki/Migration-from-1.x). + +## 6. New things you may want to adopt + +- **`InputInterface`** — type-hint it in your services instead of the + concrete class (see [Recipes](Recipes.md#dependency-injection-with-the-interface)). +- **Constructor injection** — `new Inputs(get: [...], post: [...], raw: [...])` + for tests and custom request abstractions. +- **`Inputs::decodeJsonBody()`** — a safe, reusable JSON-body decoder. + +## Upgrade checklist + +- [ ] PHP runtime is 8.1+ +- [ ] `composer require initphp/input:^2.0` +- [ ] Audit any case-sensitive key lookups +- [ ] Remove any code that relied on static cross-instance state +- [ ] (Optional) switch service type-hints to `InputInterface` + +## Next + +- [Quick Start](Quick-Start.md) +- [API Reference](API-Reference.md) +- [FAQ](FAQ.md) diff --git a/docs/Presence-Checks.md b/docs/Presence-Checks.md new file mode 100644 index 0000000..fe80337 --- /dev/null +++ b/docs/Presence-Checks.md @@ -0,0 +1,84 @@ +# Presence Checks + +Use the `has*` methods to test whether a key exists in a source without +reading its value. + +```php +public function hasGet(string $key): bool; +public function hasPost(string $key): bool; +public function hasRaw(string $key): bool; +``` + +Each is the equivalent of `array_key_exists()` against its source — and, +like `array_key_exists()`, a key whose value is `null` still counts as +present. + +## Working example + +```php +use InitPHP\Input\Inputs; + +$input = new Inputs( + get: ['debug' => '1', 'note' => null], + post: ['email' => 'jane@example.com'], + raw: ['token' => 'abc'], +); + +$input->hasGet('debug'); // true +$input->hasGet('note'); // true — present even though the value is null +$input->hasGet('email'); // false — that key is in post, not get + +$input->hasPost('email'); // true +$input->hasRaw('token'); // true +$input->hasRaw('debug'); // false +``` + +## Presence vs. truthiness + +`hasGet()` answers *"is the key there?"*, not *"does it hold a useful +value?"*. Use it to tell an **absent** field apart from one submitted +**empty** — the classic unchecked vs. empty checkbox problem: + +```php +$input = new Inputs(get: ['newsletter' => '']); + +$input->hasGet('newsletter'); // true — the field was submitted +$input->get('newsletter') === ''; // true — but it is empty +``` + +When you need a non-empty value, combine a presence check with a value read +or, better, validate with a `required` rule: + +```php +$name = $input->post('name', null, ['required']); // null when missing OR empty +``` + +## Keys are case-sensitive + +```php +$input = new Inputs(get: ['Token' => 'abc']); + +$input->hasGet('Token'); // true +$input->hasGet('token'); // false — different key +``` + +## Expected output + +| Call | Result | +| --- | --- | +| `hasGet('note')` | `true` | +| `hasGet('email')` | `false` | +| `hasRaw('token')` | `true` | + +## Common mistakes + +- **Assuming case-insensitivity.** `hasGet('Debug')` is `false` when the + stored key is `debug`. (1.x folded keys to lower-case; 2.0 does not — see + [Migration from 1.x](Migration-from-1.x.md).) +- **Using presence as a truthiness test.** A present key can still be an + empty string. + +## Next + +- [The Facade](The-Facade.md) +- [Reading Sources](Reading-Sources.md) diff --git a/docs/Quick-Start.md b/docs/Quick-Start.md new file mode 100644 index 0000000..0ffcbbd --- /dev/null +++ b/docs/Quick-Start.md @@ -0,0 +1,126 @@ +# Quick Start + +From `composer require` to reading validated request input in a few minutes. + +## 1. Pick a style + +### The facade — zero setup + +The facade builds one `Inputs` from the superglobals on first use and reuses +it for the rest of the request. + +```php +get('name', 'John'); +``` + +Pass the sources in to make the object self-contained (great for tests): + +```php +$input = new Inputs( + get: ['name' => 'Jane'], + post: ['email' => 'jane@example.com'], + raw: ['token' => 'abc123'], +); +``` + +## 2. Read a value from one source + +```php +$input->get('name', 'guest'); // from $_GET +$input->post('email'); // from $_POST +$input->raw('token'); // from the JSON request body +``` + +The second argument is the **default**, returned when the key is absent +(`null` when you omit it). + +## 3. Read with a priority order + +When a value may live in more than one place, the priority helpers return +the **first source that has the key**: + +```php +// Look in the query string first, then the form body. +$year = $input->getPost('year', 2015); +``` + +The full set: `getPost`, `getRaw`, `getPostRaw`, `getRawPost`, `postGet`, +`postRaw`, `postGetRaw`, `postRawGet`, `rawGet`, `rawPost`, `rawGetPost`, +`rawPostGet`. See [Source Priority](Source-Priority.md). + +## 4. Validate as you read + +Pass a list of [validation rules](https://github.com/InitPHP/Validation) as +the third argument. A value that fails its rules yields the default: + +```php +// Accept a year between 1970 and 2070, else fall back to 2015. +$year = $input->getPost('year', 2015, ['range(1970...2070)']); + +// Require a password that matches the confirmation field. +$pwd = $input->post('password', null, ['required', 'again(password_retype)']); +``` + +See [Validation](Validation.md). + +## 5. Check whether a key was sent + +```php +if ($input->hasPost('newsletter')) { + // the checkbox was submitted (even if its value is empty) +} +``` + +See [Presence Checks](Presence-Checks.md). + +## A complete example + +```php + 'shoes', 'page' => '2'], + post: ['sort' => 'price'], +); + +$query = $input->get('q', ''); // 'shoes' +$page = (int) $input->get('page', 1, ['integer']); // 2 +$sort = $input->getPost('sort', 'newest', ['only(price,newest,rating)']); + +// $query = 'shoes', $page = 2, $sort = 'price' +``` + +> Values come back exactly as the source provides them — query and form +> values are **strings**. Cast them yourself, or validate with a rule like +> `['integer']` and convert afterwards. + +## Next + +- [Reading Sources](Reading-Sources.md) — the three accessors in depth. +- [Source Priority](Source-Priority.md) — the priority model. +- [Validation](Validation.md) — rules and the no-fall-through behaviour. diff --git a/docs/README.md b/docs/README.md deleted file mode 100644 index 860249a..0000000 --- a/docs/README.md +++ /dev/null @@ -1,40 +0,0 @@ -# Documentation - -Developer documentation for the `initphp/input` package. The project -[README](../README.md) gives a one-page overview; this directory goes -deeper. - -## Index - -- [Getting started](getting-started.md) — install, instantiate, and read - your first value. -- **Usage** - - [Reading sources](usage/reading-sources.md) — `get`, `post`, `raw` - and defaults. - - [Source priority](usage/source-priority.md) — the twelve priority - helpers and the "first source that has the key wins" rule. - - [Validation](usage/validation.md) — per-call rules and the - no-fall-through behaviour. - - [Presence checks](usage/presence-checks.md) — `hasGet`, `hasPost`, - `hasRaw`. - - [The facade](usage/facade.md) — the static proxy, `setInstance()` - and `reset()`. -- [API reference](api-reference.md) — every public method, listed. -- [FAQ](faq.md) — common pitfalls and clarifications. - -## How to read these docs - -Every page is structured as **Goal → Working example → Expected output → -Common mistakes**. Snippets are copy-paste ready against the released -package; outputs were verified against the test suite. - -## The three sources at a glance - -| Source | Backed by | Accessor | Presence check | -|--------|----------------|----------|----------------| -| `get` | `$_GET` | `get()` | `hasGet()` | -| `post` | `$_POST` | `post()` | `hasPost()` | -| `raw` | `php://input`* | `raw()` | `hasRaw()` | - -\* The raw body is read once and JSON-decoded. A non-object/array or -malformed payload is treated as empty. diff --git a/docs/Reading-Sources.md b/docs/Reading-Sources.md new file mode 100644 index 0000000..38ad70d --- /dev/null +++ b/docs/Reading-Sources.md @@ -0,0 +1,136 @@ +# Reading Sources + +The package recognises **three** input sources, each with its own accessor +and presence check. + +| Method | Source | Presence | +| -------- | ------------------------------- | -------- | +| `get()` | `$_GET` (query string) | `hasGet()` | +| `post()` | `$_POST` (submitted form fields)| `hasPost()` | +| `raw()` | decoded JSON `php://input` body | `hasRaw()` | + +All three share the same signature: + +```php +public function get(string $key, mixed $default = null, ?array $validation = null): mixed; +``` + +- **`$key`** — the parameter name. Matched **case-sensitively**. +- **`$default`** — returned when the key is absent (or fails validation). + Defaults to `null`. +- **`$validation`** — an optional list of rules; see [Validation](Validation.md). + +## Working example + +```php +use InitPHP\Input\Inputs; + +$input = new Inputs( + get: ['q' => 'shoes', 'page' => '2'], + post: ['email' => 'jane@example.com'], + raw: ['filters' => ['size' => 42], 'inStock' => true], +); + +$input->get('q'); // 'shoes' +$input->get('page', 1); // '2' — query values are strings +$input->get('sort', 'newest'); // 'newest' — absent, so the default + +$input->post('email'); // 'jane@example.com' + +$input->raw('inStock'); // true — JSON keeps its decoded type +$input->raw('filters'); // ['size' => 42] +``` + +## Defaults and value types + +The default is the **second** argument; when omitted it is `null`. + +```php +$input = new Inputs(get: ['page' => '2']); + +$input->get('page', 1); // '2' (string — not the int 2) +$input->get('missing', 1); // 1 (the default) +$input->get('missing'); // null +``` + +> Query and form values are always **strings** — that is what PHP's SAPI +> provides. JSON-body values keep the type they decode to (`int`, `bool`, +> `array`, …). The library never casts for you. + +## The `raw` (JSON body) source + +`raw()` reads the request body once from `php://input` and JSON-decodes it. +Only a JSON **object** or **array** becomes usable data; anything else is +treated as empty: + +```php +// Request body: {"name":"Jane","tags":["a","b"]} +$input = new Inputs(); // raw read from php://input +$input->raw('name'); // 'Jane' +$input->raw('tags'); // ['a', 'b'] + +// Request body: 42 (a bare scalar) +$input = new Inputs(); +$input->raw('anything', 'x'); // 'x' — a scalar body decodes to nothing +``` + +### Already decoded the body? + +If you have the decoded body in hand, pass it directly and skip the +`php://input` read entirely: + +```php +$body = json_decode(file_get_contents('php://input'), true); +$input = new Inputs(raw: is_array($body) ? $body : []); +``` + +### The safe decoder is reusable + +The exact guard the constructor uses is exposed as a static helper, so you +can decode a body yourself without risking a `TypeError`: + +```php +use InitPHP\Input\Inputs; + +Inputs::decodeJsonBody('{"a":1}'); // ['a' => 1] +Inputs::decodeJsonBody('[1,2,3]'); // [1, 2, 3] +Inputs::decodeJsonBody('42'); // [] — scalar +Inputs::decodeJsonBody('"hi"'); // [] — scalar +Inputs::decodeJsonBody('oops'); // [] — invalid JSON +Inputs::decodeJsonBody(''); // [] — empty body +``` + +## Sources are flat — no dot paths + +Each source is stored as a **flat** bag, so a dotted key is a literal key, +not a path into nested data: + +```php +$input = new Inputs(raw: ['user' => ['name' => 'Jane']]); + +$input->raw('user.name'); // null — there is no literal 'user.name' key +$input->raw('user')['name'] ?? null; // 'Jane' — read the array, then index it +``` + +## Expected output + +| Call | Result | +| --- | --- | +| `get('page', 1)` | `'2'` (string) | +| `get('sort', 'newest')` | `'newest'` | +| `raw('inStock')` | `true` (bool) | +| `decodeJsonBody('42')` | `[]` | + +## Common mistakes + +- **Reading `php://input` twice.** The body stream can usually be read only + once per request. Build `Inputs` once (or use the facade) and reuse it. +- **Putting the default in the wrong argument.** The default is the second + argument; the third is the validation rule list. +- **Expecting type casting.** `get('page', 1)` returns `'2'`, a string. + +## Next + +- [Source Priority](Source-Priority.md) +- [Validation](Validation.md) +- [Presence Checks](Presence-Checks.md) diff --git a/docs/Recipes.md b/docs/Recipes.md new file mode 100644 index 0000000..8afc4e4 --- /dev/null +++ b/docs/Recipes.md @@ -0,0 +1,150 @@ +# Recipes + +Copy-paste patterns for common tasks. Each one uses only the public API. + +## Pagination parameters + +Read `page` and `perPage` from the query string, validated and clamped to +sane bounds. + +```php +use InitPHP\Input\Facade\Inputs as Input; + +$page = (int) Input::get('page', 1, ['integer', 'range(1...)']); +$per = (int) Input::get('perPage', 20, ['integer', 'range(1...100)']); + +// GET /?page=3&perPage=50 → $page = 3, $per = 50 +// GET /?page=abc → $page = 1 (invalid → default) +$offset = ($page - 1) * $per; +``` + +> `range(1...)` is an open upper bound — "at least 1". See the +> [Rules Reference](https://github.com/InitPHP/Validation/wiki/Rules-Reference). + +## Search filters from the query string + +```php +use InitPHP\Input\Facade\Inputs as Input; + +$filters = [ + 'q' => Input::get('q', ''), + 'sort' => Input::get('sort', 'newest', ['only(newest,price,rating)']), + 'inStock' => Input::hasGet('inStock'), +]; +``` + +## A JSON API endpoint + +Read the request body once and pull validated fields from it. + +```php +use InitPHP\Input\Inputs; + +// Body: {"email":"ada@example.com","age":34} +$input = new Inputs(); // raw read from php://input + +$email = $input->raw('email', null, ['required', 'mail']); +$age = $input->raw('age', null, ['integer', 'range(18...120)']); + +if ($email === null || $age === null) { + http_response_code(422); + return; +} +``` + +## Accept a value from the query *or* the JSON body + +Useful for endpoints that take parameters either in the URL or the body. + +```php +use InitPHP\Input\Facade\Inputs as Input; + +// Checks $_GET first, then the JSON body. +$apiKey = Input::getRaw('api_key', null, ['required']); +``` + +## A login form + +```php +use InitPHP\Input\Inputs; + +$input = new Inputs(); // reads $_POST + +$email = $input->post('email', null, ['required', 'mail']); +$password = $input->post('password', null, ['required', 'length(8...)']); + +if ($email === null || $password === null) { + // show the form again with an error +} +``` + +## A registration form with password confirmation + +```php +use InitPHP\Input\Inputs; + +$input = new Inputs(); // reads $_POST + +$password = $input->post('password', null, [ + 'required', + 'length(8...)', + 'again(password_confirm)', // must equal the password_confirm field +]); + +// $password is null when missing, too short, or the confirmation differs. +``` + +## Dependency injection with the interface + +Type-hint `InputInterface` so your services do not depend on the concrete +class or the facade — and are trivial to test. + +```php +use InitPHP\Input\InputInterface; + +final class SearchController +{ + public function __construct(private InputInterface $input) {} + + public function index(): array + { + return [ + 'query' => $this->input->get('q', ''), + 'page' => (int) $this->input->get('page', 1, ['integer', 'range(1...)']), + ]; + } +} + +// Wiring (in your container / front controller): +$controller = new SearchController(new \InitPHP\Input\Inputs()); +``` + +In a test you pass an `Inputs` seeded with explicit data — no globals, no +HTTP: + +```php +$controller = new SearchController(new \InitPHP\Input\Inputs( + get: ['q' => 'shoes', 'page' => '2'], +)); +``` + +## Wrapping an existing request array + +Already have the request data as arrays (from a framework, a PSR-7 request, +or a test fixture)? Hand them in directly: + +```php +use InitPHP\Input\Inputs; + +$input = new Inputs( + get: $request->getQueryParams(), + post: (array) $request->getParsedBody(), + raw: json_decode((string) $request->getBody(), true) ?: [], +); +``` + +## Next + +- [Validation](Validation.md) +- [Testing](Testing.md) +- [API Reference](API-Reference.md) diff --git a/docs/Source-Priority.md b/docs/Source-Priority.md new file mode 100644 index 0000000..8dba900 --- /dev/null +++ b/docs/Source-Priority.md @@ -0,0 +1,114 @@ +# Source Priority + +Sometimes a value could arrive in more than one place — a query string +*or* a form field *or* a JSON body. The priority helpers read several +sources in a defined order and hand you the first match. + +## The rule + +> A priority helper walks its sources in the order its name reads, left to +> right, and returns the value of **the first source that contains the +> key**. Once a source owns the key the lookup stops — remaining sources +> are never consulted, even if validation later rejects that value. + +```php +use InitPHP\Input\Inputs; + +// "year" is in both the query string and the form body. +$input = new Inputs( + get: ['year' => '1999'], + post: ['year' => '2003'], +); + +$input->getPost('year'); // '1999' — get is checked first and has it +$input->postGet('year'); // '2003' — post is checked first and has it +``` + +When the earlier sources do not have the key, the helper falls through to +the next one, and finally to the default: + +```php +$input = new Inputs(post: ['year' => '2003']); // no "year" in the query + +$input->getPost('year', 2015); // '2003' — fell through to post +$input->getPost('age', 2015); // 2015 — no source has it, so the default +``` + +## The twelve helpers + +| Method | Order | +| -------------- | ------------------ | +| `getPost` | get → post | +| `getRaw` | get → raw | +| `getPostRaw` | get → post → raw | +| `getRawPost` | get → raw → post | +| `postGet` | post → get | +| `postRaw` | post → raw | +| `postGetRaw` | post → get → raw | +| `postRawGet` | post → raw → get | +| `rawGet` | raw → get | +| `rawPost` | raw → post | +| `rawGetPost` | raw → get → post | +| `rawPostGet` | raw → post → get | + +Read the method name literally: `postRawGet` is **post, then raw, then +get**. Every helper shares the single-source signature: + +```php +public function getPostRaw(string $key, mixed $default = null, ?array $validation = null): mixed; +``` + +## Worked example + +```php +$input = new Inputs( + get: ['token' => 'from-query'], + post: ['token' => 'from-form'], + raw: ['token' => 'from-body'], +); + +$input->getPostRaw('token'); // 'from-query' +$input->postRawGet('token'); // 'from-form' +$input->rawGetPost('token'); // 'from-body' +``` + +Remove a source and the order keeps working: + +```php +$input = new Inputs(raw: ['token' => 'from-body']); // only the body has it + +$input->getPostRaw('token', 'none'); // 'from-body' — skipped get and post +$input->postGet('token', 'none'); // 'none' — neither post nor get has it +``` + +## Presence decides priority — not validity + +This is the one subtlety worth internalising. Priority is decided by +**presence**, not by whether the value is valid. If the first source has +the key but the value fails validation, you get the **default** — the +helper does **not** try the next source. + +```php +$input = new Inputs( + get: ['year' => '3000'], // present but out of range + post: ['year' => '1999'], // valid, but never reached +); + +$input->getPost('year', 2015, ['range(1970...2070)']); // 2015 +``` + +If you actually want the valid POST value here, either read the sources +separately and decide yourself, or order the helper so the source you +trust comes first. See [Validation](Validation.md) for the full discussion. + +## Common mistakes + +- **Expecting "first valid value" semantics.** It is "first *present* + value". A present-but-invalid value returns the default, full stop. +- **Confusing the order.** The name is the order: `rawPostGet` ≠ + `rawGetPost`. + +## Next + +- [Validation](Validation.md) +- [API Reference](API-Reference.md) diff --git a/docs/Testing.md b/docs/Testing.md new file mode 100644 index 0000000..c381a4c --- /dev/null +++ b/docs/Testing.md @@ -0,0 +1,117 @@ +# Testing + +The package is designed to be tested without touching `$_GET`, `$_POST` or +`php://input`. You inject the data instead. + +## Testing code that takes an `Inputs` instance + +Construct `Inputs` with explicit sources and assert on the result. No +globals, no HTTP request. + +```php +use InitPHP\Input\Inputs; +use PHPUnit\Framework\TestCase; + +final class ExampleTest extends TestCase +{ + public function testReadsTheQueryValue(): void + { + $input = new Inputs(get: ['name' => 'Jane']); + + self::assertSame('Jane', $input->get('name')); + } + + public function testInvalidValueFallsBackToDefault(): void + { + $input = new Inputs(get: ['year' => '3000']); + + self::assertSame(2015, $input->get('year', 2015, ['range(1970...2070)'])); + } +} +``` + +## Testing the JSON body decoder + +`decodeJsonBody()` is a pure static method — ideal for table-driven tests. + +```php +use InitPHP\Input\Inputs; + +self::assertSame(['a' => 1], Inputs::decodeJsonBody('{"a":1}')); +self::assertSame([], Inputs::decodeJsonBody('42')); // scalar +self::assertSame([], Inputs::decodeJsonBody('oops')); // invalid +self::assertSame([], Inputs::decodeJsonBody('')); // empty +``` + +## Testing code that uses the facade + +When the code under test calls the facade statically, inject a seeded +instance with `setInstance()` and clear it in `tearDown()` so tests stay +isolated. + +```php +use InitPHP\Input\Facade\Inputs as Input; +use InitPHP\Input\Inputs; +use PHPUnit\Framework\TestCase; + +final class FacadeConsumerTest extends TestCase +{ + protected function tearDown(): void + { + Input::reset(); + } + + public function testItReadsFromTheFacade(): void + { + Input::setInstance(new Inputs(get: ['name' => 'Jane'])); + + // ... exercise the code that calls Input::get('name') ... + + self::assertSame('Jane', Input::get('name')); + } +} +``` + +> Always `reset()` (or `setInstance()`) between tests. The facade caches its +> backing instance for the whole process, so a leaked instance would bleed +> into later tests. + +## Driving the superglobal path + +If you really want to exercise the `new Inputs()`-reads-globals branch, set +the superglobals and restore them afterwards: + +```php +public function testReadsFromGlobals(): void +{ + $original = $_GET; + $_GET = ['name' => 'Jane']; + + try { + self::assertSame('Jane', (new Inputs())->get('name')); + } finally { + $_GET = $original; + } +} +``` + +Prefer injecting data over this whenever you can — it is cleaner and has no +global side effects. + +## Running the package's own test suite + +If you are contributing to the package itself: + +```bash +composer test # PHPUnit +composer stan # PHPStan (level max) +composer cs-check # PHP-CS-Fixer (dry-run) +composer ci # all three +``` + +The suite ships at 100% line coverage and is green on PHP 8.2–8.5. + +## Next + +- [The Facade](The-Facade.md) +- [Recipes](Recipes.md) diff --git a/docs/The-Facade.md b/docs/The-Facade.md new file mode 100644 index 0000000..d448054 --- /dev/null +++ b/docs/The-Facade.md @@ -0,0 +1,91 @@ +# The Facade + +`InitPHP\Input\Facade\Inputs` is a thin **static proxy** over a single +`InputInterface` instance. On the first call it lazily builds an `Inputs` +from the superglobals and the request body, then reuses it for the rest of +the request. + +```php +use InitPHP\Input\Facade\Inputs as Input; + +Input::get('name', 'John'); +Input::getPost('year', 2015, ['range(1970...2070)']); +Input::hasPost('email'); +``` + +Every method documented for [`Inputs`](API-Reference.md#class-inputs) is +callable statically through the facade — same names, same arguments, same +return values. + +## How it works + +The facade forwards static calls to its backing instance via +`__callStatic`. The instance is created once and cached: + +```php +// First call: builds new Inputs() from $_GET, $_POST and php://input. +Input::get('name'); + +// Later calls: reuse the same instance. +Input::post('email'); +``` + +## Injecting a backing instance + +`setInstance()` replaces the instance the facade delegates to. This is the +seam for tests and for feeding request data that does not come from the +superglobals. + +```php +use InitPHP\Input\Facade\Inputs as Input; +use InitPHP\Input\Inputs; + +Input::setInstance(new Inputs( + get: ['name' => 'Jane'], + post: ['email' => 'jane@example.com'], +)); + +Input::get('name'); // 'Jane' +Input::hasPost('email'); // true +``` + +## Resetting + +`reset()` forgets the backing instance; the next call rebuilds it from the +current superglobals / body. Call it in your test teardown so one test +cannot leak into the next: + +```php +protected function tearDown(): void +{ + \InitPHP\Input\Facade\Inputs::reset(); +} +``` + +See [Testing](Testing.md) for the full pattern. + +## Facade vs. instance + +| | Facade | Instance | +| --- | --- | --- | +| Setup | none | `new Inputs(...)` | +| Access | `Input::get(...)` | `$input->get(...)` | +| Best for | application code, quick reads | DI, services, isolated tests | +| Swap data | `setInstance()` / `reset()` | constructor arguments | + +Both share the same behaviour; the facade simply holds one instance for +you. For dependency injection, prefer type-hinting +[`InputInterface`](API-Reference.md#interface-inputinterface) and injecting an +`Inputs` instance rather than reaching for the facade. + +## Common mistakes + +- **Leaking state between tests.** The facade caches its instance for the + whole process. Always `reset()` (or `setInstance()`) between tests. +- **Expecting the facade and an ad-hoc `new Inputs()` to share data.** They + are independent objects, each with its own sources. + +## Next + +- [API Reference](API-Reference.md) +- [Testing](Testing.md) diff --git a/docs/Validation.md b/docs/Validation.md new file mode 100644 index 0000000..4ee01a2 --- /dev/null +++ b/docs/Validation.md @@ -0,0 +1,155 @@ +# Validation + +Every accessor takes an optional **third argument**: a list of validation +rules. When the resolved value fails them, the accessor returns the default +instead. Validation is powered by +[initphp/validation](https://github.com/InitPHP/Validation), so any rule +that package understands is available here. + +```php +public function get(string $key, mixed $default = null, ?array $validation = null): mixed; +``` + +When the list is empty (`[]`) or `null`, no validation runs. + +## Working example + +```php +use InitPHP\Input\Inputs; + +$input = new Inputs(get: ['year' => '1999']); + +// Accept only a year between 1970 and 2070, else 2015. +$input->get('year', 2015, ['range(1970...2070)']); // '1999' +``` + +```php +$input = new Inputs(get: ['year' => '3000']); + +$input->get('year', 2015, ['range(1970...2070)']); // 2015 — out of range +``` + +## Rules are a list + +Each entry is either a **rule string** or a **callable**. A rule string can +chain several checks with `|`, and you can pass several entries: + +```php +$input = new Inputs(post: [ + 'password' => 's3cret', + 'password_retype' => 's3cret', +]); + +$input->post('password', null, ['required', 'again(password_retype)']); +// 's3cret' — present and equal to password_retype +``` + +A few rules you will reach for often: + +| Rule | Passes when the value… | +| --- | --- | +| `required` | is present and not empty | +| `integer` | is an int or an int-looking string (`'42'`) | +| `mail` | is a valid e-mail address | +| `range(1...10)` | is a number within the bounds | +| `length(3...20)` | has a length within the bounds | +| `again(other)` | equals the `other` field in the same source | +| `only(a, b, c)` | is one of the listed values | + +The full catalogue lives in the Validation wiki's +[Rules Reference](https://github.com/InitPHP/Validation/wiki/Rules-Reference). + +### Cross-field rules + +Rules such as `again(password_retype)` work because the **whole source +bag** is handed to the validator, so sibling fields resolve. The sibling +must live in the *same* source you are reading from: + +```php +// both fields come from $_POST, so again() can see password_retype +$input->post('password', null, ['required', 'again(password_retype)']); +``` + +### Callable rules + +Pass a closure for a one-off check. It receives the value and returns a +boolean: + +```php +$even = static fn ($value): bool => is_numeric($value) && (int) $value % 2 === 0; + +$input = new Inputs(get: ['n' => '20']); +$input->get('n', null, [$even]); // '20' +``` + +## Priority + validation: no fall-through + +In a [priority helper](Source-Priority.md), the first source that **owns** the +key is the one validated. A present-but-invalid value returns the default; +it does **not** roll over to the next source. + +```php +$input = new Inputs( + get: ['year' => '3000'], // present but invalid + post: ['year' => '1999'], // valid, but never reached +); + +$input->getPost('year', 2015, ['range(1970...2070)']); // 2015 +``` + +If you want the valid POST value here, read the sources separately: + +```php +$year = 2015; +if ($input->hasGet('year') && $input->get('year', null, ['range(1970...2070)']) !== null) { + $year = $input->get('year'); +} elseif ($input->hasPost('year')) { + $candidate = $input->post('year', null, ['range(1970...2070)']); + if ($candidate !== null) { + $year = $candidate; + } +} +``` + +…or simply order the helper so the trusted source comes first. + +## Bringing your own validator + +The fourth constructor argument accepts a preconfigured +`InitPHP\Validation\Validation` — for example one with a custom locale or +`extend()`-ed rules. It is used for every validated lookup: + +```php +use InitPHP\Input\Inputs; +use InitPHP\Validation\Validation; + +$validator = (new Validation()) + ->extend('even', static fn ($v): bool => is_numeric($v) && (int) $v % 2 === 0); + +$input = new Inputs(get: ['n' => '4'], validation: $validator); + +$input->get('n', null, ['even']); // '4' — uses your custom rule +``` + +## Expected output + +| Scenario | Result | +| --- | --- | +| `get('year', 2015, ['range(1970...2070)'])` with `1999` | `'1999'` | +| the same call with `3000` | `2015` | +| `post('password', null, ['required', 'again(password_retype)'])`, retype matches | the password | +| the same call, retype differs | `null` (the default) | + +## Common mistakes + +- **Passing a rule string instead of a list.** The argument is an + **array**: `['required']`, not `'required'`. +- **Expecting fall-through on invalid.** It does not happen — see above. +- **Cross-field rule, wrong source.** `again(other)` needs `other` in the + *same* source you are reading. + +## Next + +- [Source Priority](Source-Priority.md) +- [Recipes](Recipes.md) +- [Rules Reference (Validation wiki)](https://github.com/InitPHP/Validation/wiki/Rules-Reference) diff --git a/docs/_Footer.md b/docs/_Footer.md new file mode 100644 index 0000000..0cd94fe --- /dev/null +++ b/docs/_Footer.md @@ -0,0 +1,8 @@ +**`initphp/input`** · MIT License · part of the [InitPHP](https://github.com/InitPHP) family + +[Source](https://github.com/InitPHP/Input) · +[Issues](https://github.com/InitPHP/Input/issues) · +[Discussions](https://github.com/orgs/InitPHP/discussions) · +[Packagist](https://packagist.org/packages/initphp/input) · +[Contributing](https://github.com/InitPHP/.github/blob/main/CONTRIBUTING.md) · +[Security Policy](https://github.com/InitPHP/.github/blob/main/SECURITY.md) diff --git a/docs/_Sidebar.md b/docs/_Sidebar.md new file mode 100644 index 0000000..3b768b7 --- /dev/null +++ b/docs/_Sidebar.md @@ -0,0 +1,21 @@ +### [Home](Home.md) + +**Getting Started** +- [Installation](Installation.md) +- [Quick Start](Quick-Start.md) + +**Usage** +- [Reading Sources](Reading-Sources.md) +- [Source Priority](Source-Priority.md) +- [Validation](Validation.md) +- [Presence Checks](Presence-Checks.md) +- [The Facade](The-Facade.md) + +**Reference** +- [API Reference](API-Reference.md) +- [Recipes](Recipes.md) +- [Testing](Testing.md) + +**Other** +- [Migration from 1.x](Migration-from-1.x.md) +- [FAQ](FAQ.md) diff --git a/docs/api-reference.md b/docs/api-reference.md deleted file mode 100644 index e2e31fa..0000000 --- a/docs/api-reference.md +++ /dev/null @@ -1,112 +0,0 @@ -# API reference - -Every public symbol in the package, grouped by type. Unless noted, the -shared accessor signature is: - -```php -function (string $key, mixed $default = null, ?array $validation = null): mixed -``` - -- `$key` — the parameter name (case-sensitive). -- `$default` — returned when the key is absent or the value fails - validation. Defaults to `null`. -- `$validation` — a list of [validation rules](https://github.com/InitPHP/Validation) - (DSL strings and/or callables). Empty or `null` skips validation. - ---- - -## Interface `InitPHP\Input\InputInterface` - -### Single source - -| Method | Reads from | -|----------|----------------------------------| -| `get()` | `$_GET` | -| `post()` | `$_POST` | -| `raw()` | decoded JSON `php://input` body | - -### Priority (first source that has the key wins) - -| Method | Order | -|----------------|----------------------| -| `getPost()` | get → post | -| `getRaw()` | get → raw | -| `getPostRaw()` | get → post → raw | -| `getRawPost()` | get → raw → post | -| `postGet()` | post → get | -| `postRaw()` | post → raw | -| `postGetRaw()` | post → get → raw | -| `postRawGet()` | post → raw → get | -| `rawGet()` | raw → get | -| `rawPost()` | raw → post | -| `rawGetPost()` | raw → get → post | -| `rawPostGet()` | raw → post → get | - -### Presence - -| Method | Returns | -|------------------------------|--------------------------------------| -| `hasGet(string $key): bool` | whether `$key` exists in `$_GET` | -| `hasPost(string $key): bool` | whether `$key` exists in `$_POST` | -| `hasRaw(string $key): bool` | whether `$key` exists in the body | - -A key whose stored value is `null` still counts as present. - ---- - -## Class `InitPHP\Input\Inputs` - -`final`, implements `InputInterface`. - -### `__construct()` - -```php -public function __construct( - ?array $get = null, - ?array $post = null, - ?array $raw = null, - ?\InitPHP\Validation\Validation $validation = null -) -``` - -Each `null` source falls back to its global: `$get` → `$_GET`, `$post` → -`$_POST`, `$raw` → the decoded `php://input` body. `$validation` lets you -supply a preconfigured validator (e.g. with custom rules or a locale); -omitted, a fresh one is created. - -### `decodeJsonBody()` - -```php -public static function decodeJsonBody(string $body): array -``` - -JSON-decode a raw request body into an input array. An empty string, a -scalar (`5`, `"x"`, `true`), or malformed JSON returns `[]`, so a scalar -payload can never reach the underlying container. - ---- - -## Facade `InitPHP\Input\Facade\Inputs` - -`final`. A static proxy over a single `InputInterface` instance; all -`InputInterface` methods are callable statically (e.g. `Inputs::get(...)`). - -| Method | Description | -|----------------------------------------------|---------------------------------------------------------| -| `setInstance(InputInterface $instance): void`| Replace the backing instance (tests, DI). | -| `reset(): void` | Forget the backing instance; the next call rebuilds it. | - ---- - -## Behaviour notes - -- **Case sensitivity:** keys are matched exactly; `name` and `Name` - differ. -- **Value types:** values are returned as the source provides them — - query/form values are strings, JSON-body values keep their decoded - type. -- **No fall-through on invalid:** in a priority helper, the first source - that has the key is committed to; an invalid value returns the default - rather than trying the next source. -- **Isolation:** instances share no static state; two `Inputs` objects - never interfere. diff --git a/docs/getting-started.md b/docs/getting-started.md deleted file mode 100644 index 6acf554..0000000 --- a/docs/getting-started.md +++ /dev/null @@ -1,90 +0,0 @@ -# Getting started - -**Goal:** install the package, create an `Inputs` instance (or use the -facade), and read your first request value. - -## Install - -```bash -composer require initphp/input -``` - -Requirements: PHP 8.1+, `ext-json`, and the `initphp/parameterbag ^2.0` -and `initphp/validation ^2.0` packages (pulled in automatically). - -## Two ways to use it - -### 1. The facade (zero setup) - -The facade builds a single backing instance from the superglobals on -first use and reuses it for the rest of the request. - -```php -require_once 'vendor/autoload.php'; - -use InitPHP\Input\Facade\Inputs as Input; - -// GET /?name=Jane -echo Input::get('name', 'John'); -``` - -**Expected output:** `Jane` (or `John` when `name` is absent). - -### 2. An instance - -```php -use InitPHP\Input\Inputs; - -$input = new Inputs(); // reads $_GET, $_POST and php://input - -echo $input->get('name', 'John'); -``` - -`new Inputs()` with no arguments reads the live superglobals and request -body. To make the object self-contained — for tests, CLI tooling, or a -custom request abstraction — pass the sources in: - -```php -$input = new Inputs( - get: ['name' => 'Jane'], - post: ['email' => 'jane@example.com'], - raw: ['token' => 'abc123'], -); - -echo $input->get('name'); // 'Jane' -echo $input->post('email'); // 'jane@example.com' -echo $input->raw('token'); // 'abc123' -``` - -Any argument left as `null` falls back to its global: `get` to `$_GET`, -`post` to `$_POST`, and `raw` to the decoded `php://input` body. - -## What you get back - -Every accessor returns either the stored value or the **default** you -pass as the second argument (`null` when omitted): - -```php -$input = new Inputs(get: ['page' => '2']); - -$input->get('page', 1); // '2' (note: still a string from the query) -$input->get('missing', 1); // 1 (the default) -$input->get('missing'); // null -``` - -> Values are returned exactly as the source provides them. Query and form -> values are strings; JSON-body values keep their decoded type -> (`int`, `bool`, `array`, …). - -## Common mistakes - -- **Expecting type casting.** `get('page', 1)` returns the *string* - `'2'`, not an integer. Cast it yourself, or validate with a rule such - as `['integer']`. -- **Assuming case-insensitive keys.** `get('Name')` and `get('name')` - are different keys. See the [FAQ](faq.md). - -## Next - -- [Reading sources](usage/reading-sources.md) -- [Source priority](usage/source-priority.md) diff --git a/docs/usage/facade.md b/docs/usage/facade.md deleted file mode 100644 index 264e687..0000000 --- a/docs/usage/facade.md +++ /dev/null @@ -1,76 +0,0 @@ -# The facade - -**Goal:** call the input API statically, and control the instance behind -it for tests or dependency injection. - -`InitPHP\Input\Facade\Inputs` is a thin static proxy over a single -`InputInterface` instance. On the first call it lazily builds an -`Inputs` from the superglobals and the request body, then reuses it. - -```php -use InitPHP\Input\Facade\Inputs as Input; - -Input::get('name', 'John'); -Input::getPost('year', 2015, ['range(1970...2070)']); -Input::hasPost('email'); -``` - -Every method documented for `Inputs` is callable statically through the -facade. - -## Injecting a backing instance - -`setInstance()` replaces the instance the facade delegates to. This is -the seam for tests and for feeding request data that does not come from -the superglobals. - -```php -use InitPHP\Input\Facade\Inputs as Input; -use InitPHP\Input\Inputs; - -Input::setInstance(new Inputs( - get: ['name' => 'Jane'], - post: ['email' => 'jane@example.com'], -)); - -Input::get('name'); // 'Jane' -Input::hasPost('email'); // true -``` - -## Resetting - -`reset()` forgets the backing instance; the next call rebuilds it from -the current superglobals / body. Call it in your test teardown so one -test cannot leak into the next: - -```php -protected function tearDown(): void -{ - \InitPHP\Input\Facade\Inputs::reset(); -} -``` - -## Facade vs. instance - -| | Facade | Instance | -|---|--------|----------| -| Setup | none | `new Inputs(...)` | -| Access | `Input::get(...)` | `$input->get(...)` | -| Best for | app code, quick reads | DI, services, isolated tests | -| Swap data | `setInstance()` / `reset()` | constructor arguments | - -Both share the same behaviour; the facade simply holds one instance for -you. - -## Common mistakes - -- **Leaking state between tests.** The facade caches its instance for the - whole process. Always `reset()` (or `setInstance()`) between tests. -- **Mixing facade and ad-hoc instances expecting shared data.** They are - independent objects. The facade reads its own instance; a separate - `new Inputs()` reads its own sources. - -## Next - -- [API reference](../api-reference.md) -- [Getting started](../getting-started.md) diff --git a/docs/usage/presence-checks.md b/docs/usage/presence-checks.md deleted file mode 100644 index 8b91e9a..0000000 --- a/docs/usage/presence-checks.md +++ /dev/null @@ -1,67 +0,0 @@ -# Presence checks - -**Goal:** test whether a key exists in a source without reading its -value. - -```php -public function hasGet(string $key): bool; -public function hasPost(string $key): bool; -public function hasRaw(string $key): bool; -``` - -Each is the equivalent of `array_key_exists()` against its source — and, -like `array_key_exists()`, a key whose value is `null` still counts as -present. - -## Working example - -```php -use InitPHP\Input\Inputs; - -$input = new Inputs( - get: ['debug' => '1', 'note' => null], - post: ['email' => 'jane@example.com'], - raw: ['token' => 'abc'], -); - -$input->hasGet('debug'); // true -$input->hasGet('note'); // true — present even though the value is null -$input->hasGet('email'); // false — that key is in post, not get - -$input->hasPost('email'); // true -$input->hasRaw('token'); // true -$input->hasRaw('debug'); // false -``` - -## Presence vs. truthiness - -`hasGet()` answers "is the key there?", not "does it hold a useful -value?". Use it to distinguish an absent field from one submitted empty: - -```php -$input = new Inputs(get: ['newsletter' => '']); - -$input->hasGet('newsletter'); // true — the checkbox was submitted -$input->get('newsletter') === ''; // true — but it is empty -``` - -## Expected output - -| Call | Result | -|---------------------|---------| -| `hasGet('note')` | `true` | -| `hasGet('email')` | `false` | -| `hasRaw('token')` | `true` | - -## Common mistakes - -- **Assuming case-insensitivity.** `hasGet('Debug')` is `false` when the - key is `debug`. Keys are case-sensitive. -- **Using presence as a truthiness test.** A present key can still be an - empty string. Combine with a value read or a `required` rule when you - need a non-empty value. - -## Next - -- [The facade](facade.md) -- [Reading sources](reading-sources.md) diff --git a/docs/usage/reading-sources.md b/docs/usage/reading-sources.md deleted file mode 100644 index 386e237..0000000 --- a/docs/usage/reading-sources.md +++ /dev/null @@ -1,95 +0,0 @@ -# Reading sources - -**Goal:** read a value from one specific source and understand defaults -and value types. - -The three single-source accessors are: - -| Method | Source | -|----------|---------------------------------| -| `get()` | `$_GET` (query string) | -| `post()` | `$_POST` (submitted form fields)| -| `raw()` | decoded JSON `php://input` body | - -Each has the same signature: - -```php -public function get(string $key, mixed $default = null, ?array $validation = null): mixed; -``` - -## Working example - -```php -use InitPHP\Input\Inputs; - -$input = new Inputs( - get: ['q' => 'shoes', 'page' => '2'], - post: ['email' => 'jane@example.com'], - raw: ['filters' => ['size' => 42], 'inStock' => true], -); - -$input->get('q'); // 'shoes' -$input->get('page', 1); // '2' — query values are strings -$input->get('sort', 'newest'); // 'newest' — absent, so the default - -$input->post('email'); // 'jane@example.com' - -$input->raw('inStock'); // true — JSON keeps its decoded type -$input->raw('filters'); // ['size' => 42] -``` - -## The raw (JSON body) source - -`raw()` reads the request body once from `php://input` and JSON-decodes -it. Only a JSON **object** or **array** becomes usable data; anything -else is treated as empty: - -```php -// Request body: {"name":"Jane","tags":["a","b"]} -$input = new Inputs(); // raw read from php://input -$input->raw('name'); // 'Jane' -$input->raw('tags'); // ['a', 'b'] - -// Request body: 42 (a bare scalar) -$input = new Inputs(); -$input->raw('anything', 'x'); // 'x' — a scalar body decodes to nothing -``` - -If you already have the decoded body, pass it in directly and skip the -`php://input` read: - -```php -$body = json_decode(file_get_contents('php://input'), true); -$input = new Inputs(raw: is_array($body) ? $body : []); -``` - -The same guard the constructor uses is exposed as a static helper: - -```php -Inputs::decodeJsonBody('{"a":1}'); // ['a' => 1] -Inputs::decodeJsonBody('42'); // [] — scalar -Inputs::decodeJsonBody('oops'); // [] — invalid JSON -Inputs::decodeJsonBody(''); // [] — empty body -``` - -## Expected output - -| Call | Result | -|-----------------------------------|----------------------| -| `get('page', 1)` | `'2'` (string) | -| `get('sort', 'newest')` | `'newest'` | -| `raw('inStock')` | `true` (bool) | -| `decodeJsonBody('42')` | `[]` | - -## Common mistakes - -- **Reading `php://input` twice.** The body stream can usually be read - only once per request. Construct `Inputs` once (or use the facade) and - reuse it. -- **Forgetting the default is the *second* argument.** The third - argument is the validation rule list, not the default. - -## Next - -- [Source priority](source-priority.md) -- [Validation](validation.md) diff --git a/docs/usage/source-priority.md b/docs/usage/source-priority.md deleted file mode 100644 index 6629406..0000000 --- a/docs/usage/source-priority.md +++ /dev/null @@ -1,85 +0,0 @@ -# Source priority - -**Goal:** read a value that may live in more than one source, choosing -the source by a defined order. - -## The rule - -A priority helper walks its sources in the order its name reads, left to -right, and returns the value of **the first source that contains the -key**. Remaining sources are never consulted once a source owns the key — -even if validation later rejects that value (see -[Validation](validation.md)). - -```php -use InitPHP\Input\Inputs; - -// "year" is in both the query string and the form body. -$input = new Inputs( - get: ['year' => '1999'], - post: ['year' => '2003'], -); - -$input->getPost('year'); // '1999' — get is checked first and has it -$input->postGet('year'); // '2003' — post is checked first and has it -``` - -When the earlier sources do not have the key, the helper falls through: - -```php -$input = new Inputs(post: ['year' => '2003']); // no "year" in the query - -$input->getPost('year', 2015); // '2003' — fell through to post -$input->getPost('age', 2015); // 2015 — no source has it, so the default -``` - -## The twelve helpers - -| Method | Order | -|----------------|--------------------------------| -| `getPost` | get → post | -| `getRaw` | get → raw | -| `getPostRaw` | get → post → raw | -| `getRawPost` | get → raw → post | -| `postGet` | post → get | -| `postRaw` | post → raw | -| `postGetRaw` | post → get → raw | -| `postRawGet` | post → raw → get | -| `rawGet` | raw → get | -| `rawPost` | raw → post | -| `rawGetPost` | raw → get → post | -| `rawPostGet` | raw → post → get | - -All share the single-source signature: - -```php -public function getPostRaw(string $key, mixed $default = null, ?array $validation = null): mixed; -``` - -## Worked example - -```php -$input = new Inputs( - get: ['token' => 'from-query'], - post: ['token' => 'from-form'], - raw: ['token' => 'from-body'], -); - -$input->getPostRaw('token'); // 'from-query' -$input->postRawGet('token'); // 'from-form' -$input->rawGetPost('token'); // 'from-body' -``` - -## Common mistakes - -- **Expecting "first valid value" semantics.** Priority is decided by - *presence*, not validity. If the first source has the key but the value - fails validation, you get the default — the next source is not tried. - See [Validation](validation.md). -- **Confusing the order.** Read the method name literally: - `postRawGet` is post, then raw, then get. - -## Next - -- [Validation](validation.md) -- [API reference](../api-reference.md) diff --git a/docs/usage/validation.md b/docs/usage/validation.md deleted file mode 100644 index b17f823..0000000 --- a/docs/usage/validation.md +++ /dev/null @@ -1,99 +0,0 @@ -# Validation - -**Goal:** accept a value only when it satisfies a set of rules, and fall -back to a default otherwise. - -Every accessor takes an optional **third argument**: a list of validation -rules. The list is passed straight to -[initphp/validation](https://github.com/InitPHP/Validation), so any rule -that package understands is available here. - -```php -public function get(string $key, mixed $default = null, ?array $validation = null): mixed; -``` - -When the list is empty or `null`, no validation runs. - -## Working example - -```php -use InitPHP\Input\Inputs; - -$input = new Inputs(get: ['year' => '1999']); - -// Accept only a year between 1970 and 2070, else 2015. -$input->get('year', 2015, ['range(1970...2070)']); // '1999' -``` - -```php -$input = new Inputs(get: ['year' => '3000']); - -$input->get('year', 2015, ['range(1970...2070)']); // 2015 — out of range -``` - -## Rules are a list - -Each entry is either a rule string or a callable. Strings may chain -several checks; you can also pass several entries: - -```php -$input = new Inputs(post: [ - 'password' => 's3cret', - 'password_retype' => 's3cret', -]); - -$input->post('password', null, ['required', 'again(password_retype)']); -// 's3cret' — present and equal to password_retype -``` - -Cross-field rules such as `again(password_retype)` work because the whole -source bag is handed to the validator, so sibling fields resolve. - -### Callable rules - -```php -$even = static fn ($value): bool => is_numeric($value) && (int) $value % 2 === 0; - -$input = new Inputs(get: ['n' => '20']); -$input->get('n', null, [$even]); // '20' -``` - -## Priority + validation: no fall-through - -The first source that **owns** the key is the one validated. A present -but invalid value returns the default; it does **not** roll over to the -next source. - -```php -$input = new Inputs( - get: ['year' => '3000'], // present but invalid - post: ['year' => '1999'], // valid, but never reached -); - -$input->getPost('year', 2015, ['range(1970...2070)']); // 2015 -``` - -If you want the valid POST value here, read the sources separately and -decide yourself, or order the helper so the source you trust comes first. - -## Expected output - -| Scenario | Result | -|--------------------------------------------|----------| -| `get('year','d',['range(1970...2070)'])` with `1999` | `'1999'` | -| same with `3000` | `'d'` | -| `post('password',…,['required','again(password_retype)'])` matching | the value | -| same, mismatched retype | the default | - -## Common mistakes - -- **Passing a rule string instead of a list.** The argument is an - **array**: `['required']`, not `'required'`. -- **Expecting fall-through on invalid.** It does not happen — see above. -- **Forgetting cross-field data.** `again(other)` needs `other` to exist - in the *same* source you are reading from. - -## Next - -- [Presence checks](presence-checks.md) -- [Source priority](source-priority.md)