CkPayload
Job: turn raw wire text — a JSON body, a form post, a URL — into the standard bag the rest of the library reads.
"Wire text" is the text that arrives over HTTP: a webhook body, an API response, the
query part of a URL. CkPayload is step one of the pipeline: it
parses that text into a PHP array — the bag, the shape json_decode($json, true)
gives a payload — and CkDictionary then pulls typed values out of it,
so you never write the decoding ceremony yourself. Unreadable input answers an empty
array — never null — so you can read the result straight away, without a null check.
And because a plugin on some platforms is handed nothing but the superglobals, every reader
here reads PHP's input when nothing is passed: CkPayload::FromJson() is the request's
body as JSON, FromForm() the form it carries, FromQuery() its query string — never
$_REQUEST, never the $_GET and $_POST whose keys PHP rewrote. A null is still no value,
so a missing value never reads as the request.
Quick look
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;
$payload = CkPayload::FromJson('{ "id": 7, "active": true }');
$id = CkDictionary::Integer(dictionary: $payload, key: 'id'); // -> 7
$query = CkPayload::FromQuery('https://api.example.com/members?page=2');
$page = CkDictionary::Integer(dictionary: $query, key: 'page'); // -> 2
CkPayload::FromJson('not json'); // -> [] (unreadable — never null)
CkPayload::FromCsv('Smith, John,"Boston, MA",42'); // -> ['Smith', ' John', 'Boston, MA', '42'] (4 fields, not 5)
CkPayload::Explain('{ not json'); // -> 'not valid JSON'
CkPayload::FromJson(); // -> [] (nothing passed: the request's body — none here, on the command line)
Methods
FromJson
A JSON body into the bag.
static function FromJson(
mixed $json = CkPayload::Input,
bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
| Parameter | Type | Default | What it does |
|---|---|---|---|
json |
mixed |
CkPayload::Input |
The JSON text; its root must be a JSON object. A value that is not text is refused by name. Left out, the request's body — PHP's input. |
throwIfInvalid |
bool |
CkSettings::DefaultThrowIfInvalid (false) |
Pass true to throw a CkPayloadException that says why, instead of answering an empty array. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The text is a JSON object | The payload as an array: 'id' reads 7 |
The payload as an array: 'id' reads 7 |
| Rejected: missing, over the length cap, not valid JSON, or the root is not a JSON object | Empty array | Throws CkPayloadException — carries Input and Reason |
An array at the root is rejected too — that shape belongs to FromJsonMaps.
Parses JSON text whose root is a JSON object — { ... } — into the standard bag, the
shape json_decode($json, true) gives: text, a whole number as an int, a fraction as a
float, a boolean and null as themselves, and a nested object or array as a nested
array, ready for CkDictionary::Map, Maps or Items to open. The JSON is read
strictly: no comments, no trailing commas, no single quotes, nesting up to 64 levels. A
number too large for a float — 1e400 — arrives as its text, never as infinity.
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;
$body = '{ "member": { "id": 7, "address": { "zip": "78701" } } }';
$payload = CkPayload::FromJson($body);
$member = CkDictionary::Map(dictionary: $payload, key: 'member');
$address = CkDictionary::Map(dictionary: $member, key: 'address');
$id = CkDictionary::Integer(dictionary: $member, key: 'id'); // -> 7
$zip = CkDictionary::String(dictionary: $address, key: 'zip'); // -> '78701'
CkPayload::FromJson('[1, 2]'); // -> [] (an array root belongs to FromJsonMaps)
CkPayload::FromJson('not json'); // -> [] (unreadable)
CkPayload::FromJson('{ "n": 1e400 }'); // -> ['n' => '1e400'] (too large for a float: its text, not infinity)
FromJsonMaps
A JSON list into one bag per item.
static function FromJsonMaps(
mixed $json = CkPayload::Input,
bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
| Parameter | Type | Default | What it does |
|---|---|---|---|
json |
mixed |
CkPayload::Input |
The JSON text; its root must be a JSON array of objects, or one object. Left out, the request's body. |
throwIfInvalid |
bool |
CkSettings::DefaultThrowIfInvalid (false) |
Pass true to throw a CkPayloadException that says why, instead of answering an empty or shortened list. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| The text is a JSON array of objects — or one object on its own | One array per item, as a list: 'eventId' reads 1, then 2 |
One array per item, as a list: 'eventId' reads 1, then 2 |
| Rejected: missing, over the length cap, not valid JSON, or the root is not list-shaped | Empty list | Throws CkPayloadException — carries Input and Reason |
Without the flag an item that is not an object is left out quietly; with it, one such item makes the whole read throw.
For JSON whose root is an array of objects — a batch webhook body, a list endpoint's response. You get one bag per item. A single object where a list was allowed still works: it comes back as a one-item list. Items that are not objects are left out quietly (or reported, when you ask for errors — see the end of this page).
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;
$body = '[ { "eventId": 1 }, { "eventId": 2 } ]';
foreach (CkPayload::FromJsonMaps($body) as $item) {
$id = CkDictionary::Integer(dictionary: $item, key: 'eventId'); // 1, then 2
}
CkPayload::FromJsonMaps('{ "eventId": 7 }'); // -> [['eventId' => 7]] (a single object still lists)
CkPayload::FromJsonMaps('[1, 2, 3]'); // -> [] (numbers are not objects)
FromForm
A form body into the bag.
static function FromForm(
mixed $form = CkPayload::Input,
bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
| Parameter | Type | Default | What it does |
|---|---|---|---|
form |
mixed |
CkPayload::Input |
The form-encoded body. Left out, the form the request carries: the raw body, or $_POST for a multipart body on POST — unslashed under CkSettings::RequestUnslash. |
throwIfInvalid |
bool |
CkSettings::DefaultThrowIfInvalid (false) |
Pass true to throw a CkPayloadException that says why, instead of answering an empty array. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The text holds key=value pairs |
The pairs as an array: 'scope' reads 'read write' |
The pairs as an array: 'scope' reads 'read write' |
| Rejected: missing, over the length cap, or no usable pairs | Empty array | Throws CkPayloadException — carries Input and Reason |
A repeated key keeps only its last value, and a key with no = gets an empty one.
Parses an application/x-www-form-urlencoded body — the format HTML forms, OAuth2 token
endpoints and many webhook providers send, like a=1&b=hello+world. Keys and values are
percent-decoded (%C3%A9 becomes é) and a + is read as a space. Keys are literal —
tags[] stays one key named tags[], and a[b] is never walked into a nested array,
which is what $_POST would do. Every value in the bag is text — the typed
CkDictionary readers turn '2' into 2 from there.
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;
$form = CkPayload::FromForm('grant_type=client_credentials&scope=read+write');
$grant = CkDictionary::String(dictionary: $form, key: 'grant_type'); // -> 'client_credentials'
$scope = CkDictionary::String(dictionary: $form, key: 'scope'); // -> 'read write'
CkPayload::FromForm('a=1&a=2'); // -> ['a' => '2'] (a repeated key: the last value wins)
CkPayload::FromForm('name=Mary&flag'); // -> ['name' => 'Mary', 'flag' => ''] (a key with no "=" gets an empty value)
CkPayload::FromForm('tags[]=red&tags[]=blue'); // -> ['tags[]' => 'blue'] (keys are literal — no array magic)
Nothing passed is the form the request carries — for a multipart body on POST, the fields PHP
has already consumed into $_POST. Both the declared body length and the combined length
of field names and text values must fit CkSettings::MaxPayloadInputLength. Nested arrays'
keys and text values count too, before unslashing. Lengths count UTF-16 units, so an emoji
counts as two.
use SafeCoder\CommonKit\CkPayload;
$_SERVER['REQUEST_METHOD'] = 'POST';
$_SERVER['CONTENT_TYPE'] = 'multipart/form-data';
$_POST = ['name' => 'Ana', 'newsletter' => 'on'];
CkPayload::FromForm(); // -> ['name' => 'Ana', 'newsletter' => 'on'] (nothing passed: PHP's input)
FromQuery
A URL's parameters into the bag.
static function FromQuery(
mixed $url = CkPayload::Input,
bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
| Parameter | Type | Default | What it does |
|---|---|---|---|
url |
mixed |
CkPayload::Input |
The URL, or a bare query string. Left out, the request's raw query string, $_SERVER['QUERY_STRING'] — never $_GET — unslashed under CkSettings::RequestUnslash. |
throwIfInvalid |
bool |
CkSettings::DefaultThrowIfInvalid (false) |
Pass true to throw a CkPayloadException that says why, instead of answering an empty array. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
The URL (or the bare query) holds key=value pairs |
The parameters as an array: 'sort' reads 'name' |
The parameters as an array: 'sort' reads 'name' |
Rejected: missing, over the length cap, a URL with no ?, or no usable pairs |
Empty array | Throws CkPayloadException — carries Input and Reason |
The fragment is cut before the ? is looked for, so page#section?a=1 holds no query.
Takes a full URL, or just the query string on its own, and turns the part after ? into
the bag — decoded by the same rules as FromForm; the two share one syntax. The fragment
(the #... part at the end of a URL) is cut off first, because by the URL grammar it is
not part of the query.
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;
$query = CkPayload::FromQuery('https://api.example.com/members?page=2&sort=name#top');
$page = CkDictionary::Integer(dictionary: $query, key: 'page'); // -> 2
$sort = CkDictionary::String(dictionary: $query, key: 'sort'); // -> 'name'
CkPayload::FromQuery('page=2&sort=name'); // -> ['page' => '2', 'sort' => 'name'] (a bare query works too)
CkPayload::FromQuery('https://example.com/path'); // -> [] (no "?" means no query)
CkPayload::FromQuery('https://example.com/page#section?page=2'); // -> [] (the "?" sits inside the fragment, so the fragment hides the query)
Nothing passed is the request's own query string, as the web server set it:
use SafeCoder\CommonKit\CkPayload;
$_SERVER['QUERY_STRING'] = 'page=2&sort=name';
CkPayload::FromQuery(); // -> ['page' => '2', 'sort' => 'name'] (nothing passed: PHP's input)
CkPayload::FromQuery(null); // -> [] (a null is no value, never the request)
FromCsv
One CSV line, by the real rules.
static function FromCsv(
mixed $line = CkPayload::Input,
string $separator = ',',
bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
| Parameter | Type | Default | What it does |
|---|---|---|---|
line |
mixed |
CkPayload::Input |
One record of CSV text. Left out, the request's body. |
separator |
string |
',' |
The field separator, exactly one character; ';' or "\t" for the other conventions. Anything longer is refused — "the separator must be one character". |
throwIfInvalid |
bool |
CkSettings::DefaultThrowIfInvalid (false) |
Pass true to throw a CkPayloadException that says why, instead of answering an empty array, when the line cannot be read. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| One record | Its fields, in order, quotes removed, nothing trimmed | The fields |
| Rejected: missing, more than one record, an unclosed quote, or a separator that is not one character | An empty array | Throws CkPayloadException — carries Input and Reason |
A quoted field may hold the separator and line breaks, and a doubled quote inside it is
one quote — so Smith, John,"Boston, MA",42 is four fields, not five. Splitting on
the comma yourself is the classic import bug. Clean each field with the reader it
belongs to.
use SafeCoder\CommonKit\CkPayload;
CkPayload::FromCsv('Smith, John,"Boston, MA",42'); // -> ['Smith', ' John', 'Boston, MA', '42']
CkPayload::FromCsv('"say ""hi""",2'); // -> ['say "hi"', '2'] (a doubled quote is one quote)
CkPayload::FromCsv(
line: 'a;b;"c;d"',
separator: ';'
); // -> ['a', 'b', 'c;d']
CkPayload::FromCsv('"a,b'); // -> [] (an unclosed quote)
FromCsvMaps
A CSV file as bags, one per row.
static function FromCsvMaps(
mixed $text = CkPayload::Input,
string $separator = ',',
bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
| Parameter | Type | Default | What it does |
|---|---|---|---|
text |
mixed |
CkPayload::Input |
The CSV text, header row first. Left out, the request's body. |
separator |
string |
',' |
The field separator, exactly one character. |
throwIfInvalid |
bool |
CkSettings::DefaultThrowIfInvalid (false) |
Pass true to throw a CkPayloadException that says why, instead of answering an empty array, when the text cannot be read. |
Returns
| When | Default | With throwIfInvalid: true |
|---|---|---|
| A header and rows | One bag per row, keyed by column, values as text; short rows hold null in their missing columns |
The bags |
| A header alone | An empty array | An empty array |
| Rejected: a blank or duplicate column name, a row longer than the header, an unclosed quote | An empty array | Throws CkPayloadException — carries Input and Reason — the reason names the line or column |
The shape FromJsonMaps gives a JSON array, so an import goes through the same CkDictionary readers as a webhook does. Strict where it matters: a row longer than the header rejects the file, since that is what a broken quote looks like. Empty lines are skipped.
use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkMoney;
use SafeCoder\CommonKit\CkPayload;
$csv = "sku,amount,note\nA-1,12.50,\"Boston, MA\"\nB-2,5";
CkPayload::FromCsvMaps($csv); // -> [['sku' => 'A-1', 'amount' => '12.50', 'note' => 'Boston, MA'], ['sku' => 'B-2', 'amount' => '5', 'note' => null]]
foreach (CkPayload::FromCsvMaps($csv) as $row) {
$amount = CkMoney::Amount(CkDictionary::Value(dictionary: $row, key: 'amount')); // 12.5, then 5.0
}
Explain
Why not — in words, without an exception.
static function Explain(
mixed $input = CkPayload::Input,
?string $what = 'FromJson',
string $separator = ','
): string
| Parameter | Type | Default | What it does |
|---|---|---|---|
input |
mixed |
CkPayload::Input |
The wire text. Left out, the request's input, as the reader named would read it. |
what |
?string |
'FromJson' |
The reader to judge by, in any casing: FromJson, FromJsonMaps, FromForm, FromQuery, FromCsv or FromCsvMaps. |
separator |
string |
',' |
The field separator, for the CSV readers. |
Returns
| When | You get |
|---|---|
| The value passes the reader | '' |
| It does not | The reason, the same words the exception would carry — an answer, not a failure; it never throws |
what names no reader |
A note saying so: 'not a CkPayload reader: …' |
The form-friendly twin of throwIfInvalid: the message to show beside the field,
without a try and catch. Every class with a reader has one, on the reader's own
rules, so the reason is exactly what the reader would say. what names the reader to judge by.
use SafeCoder\CommonKit\CkPayload;
CkPayload::Explain('{ not json'); // -> 'not valid JSON'
CkPayload::Explain('[1, 2]'); // -> 'a JSON Array is not a dictionary'
CkPayload::Explain('"a,b', 'FromCsv'); // -> 'an unclosed quote'
CkPayload::Explain("a,b\n1,2,3", 'FromCsvMaps'); // -> 'line 2 has more fields than the header'
CkPayload::Explain('https://example.com/path', 'FromQuery'); // -> 'no query in the URL'
Good to know
- Unreadable in, empty out — never null. That is this class's version of the standard CommonKit signal: an empty array means the text could not be read.
- The bag is a plain array. The shape
json_decode($json, true)gives, and what$_POST,$_GETand a framework's request bag already are — so a bag from here and a bag from the framework go through the same CkDictionary readers. - A repeated key: the last value wins. In JSON as in a form body — the answer
json_decodegives, so what this bag holds is what the application's own decoder would hold, and a check made on the bag holds for the value the code then uses. - JSON numbers keep their kind. A whole number arrives as an
int, a fraction as afloat, and a number too large for a float (1e400) as its text, never as infinity. - JSON is strict. A comment or a trailing comma — things some editors tolerate — makes the whole text unreadable, so you notice instead of silently losing data.
- Whitespace and a BOM are fine. Space around the text and a byte-order mark (an invisible marker character some tools put at the very start of a file) are trimmed off before parsing.
- There is a size cap. Text over
CkSettings::MaxPayloadInputLengthcharacters (16,777,216 — about 16 MB) is rejected, so a runaway payload cannot eat your memory. - Form and query keys are literal.
tags[]=red&tags[]=bluegives one key namedtags[]holding'blue', anda.bstaysa.b— no hidden array magic, and a repeated key keeps only its last value.$_GETand$_POSTwould have rewritten both. - A fragment can hide the query. The
#is cut before the?is looked for, so inpage#section?a=1there is no query at all. That is correct URL behaviour, but it surprises people. - Form and query values are all text. Numbers and booleans only become typed values when a CkDictionary reader pulls them out.
- Nothing passed is the request. Every reader reads PHP's input when its text is left out —
CkPayload::Inputstands in the parameter's place — the raw body for the JSON and CSV readers,$_POSTfor a multipart form on POST, the raw query string forFromQuery; never$_REQUEST, and nothing in the superglobals is changed. A body whose declaredContent-Lengthis over the cap is refused unread. The raw body is also read under a finite bound and refused when its actual length exceeds the cap, including surrounding padding, even without a length header. Explicit text arguments keep the readers' usual whitespace rules. On a host that adds backslashes to what it hands over, setCkSettings::RequestUnslashonce. CkRequest reads the same input, once, through the reader the content type names, with the typed readers on it. - A null is no value, never the request.
FromJson($row['meta'])with a NULL column answers empty, as every reader does for null; only a left-out argument reads the input.
If you want errors instead
Pass throwIfInvalid: true and text that cannot be read raises a CkPayloadException
(from SafeCoder\CommonKit\Exceptions) instead of answering an empty bag or list. The
exception carries the Input and a short Reason, flattened into a one-line message.
With it, FromJsonMaps also reports list items that are not objects, instead of quietly
leaving them out.
use SafeCoder\CommonKit\CkPayload;
CkPayload::FromJson(
json: 'not json',
throwIfInvalid: true
); // throws CkPayloadException — the message says why