Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
148 changes: 148 additions & 0 deletions docs/API-Reference.md
Original file line number Diff line number Diff line change
@@ -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)
79 changes: 56 additions & 23 deletions docs/faq.md → docs/FAQ.md
Original file line number Diff line number Diff line change
@@ -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(
Expand All @@ -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?

Expand All @@ -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())
Expand All @@ -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)
92 changes: 92 additions & 0 deletions docs/Home.md
Original file line number Diff line number Diff line change
@@ -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.
Loading
Loading