Skip to content

CkDictionary

Job: read one typed value out of a bag — a decoded JSON payload, a form, a database row turned into an array, a configuration map — in a single call.

After CkPayload turns wire text into a bag of keys and values, this class gets the values out: CkDictionary::Integer(dictionary: $payload, key: 'age') looks the key up and converts the value in one step, exactly as if you had done the lookup yourself and handed the result to the right CommonKit reader. That makes it step 2 of the pipeline. Nothing here throws: a missing bag, a missing key, a null or a value that cannot be read all answer the method's fallback — 0, false, '', an empty array, or whatever you pass as fallback. Only Value and At answer null, because for the raw escape hatch null honestly means "nothing there".

Quick look

use SafeCoder\CommonKit\CkDictionary;

$json = '{ "name": "Mary", "age": "42.7", "vip": "yes", "tags": ["a", "b"] }';
$payload = json_decode($json, true);

CkDictionary::String(dictionary: $payload, key: 'name');    // -> 'Mary'
CkDictionary::Integer(dictionary: $payload, key: 'age');        // -> 43  ('42.7' rounds)
CkDictionary::Bool(dictionary: $payload, key: 'vip');       // -> true
CkDictionary::Strings(dictionary: $payload, key: 'tags');   // -> ['a', 'b']

CkDictionary::Integer(
    dictionary: $payload,
    key: 'score',
    fallback: -1
);                                                          // -> -1  (no such key)
CkDictionary::At($payload, 'customer.address.zip');         // -> null  (a value down a dotted path — none here)
CkDictionary::MissingKeys($payload, 'name', 'email');       // -> ['email']

For the current request, the bag and these readers come as one call: CkRequest reads the request on first use, and on a POST CkRequest::String('name') is CkDictionary::String(CkRequest::Bag()->Body(), 'name').

What counts as a bag

The dictionary parameter is mixed on purpose, and an array is the bag — any array with named entries:

  • the array json_decode($json, true) makes of a payload, and the one CkPayload hands back;
  • $_POST and $_GET, or a framework's request bag — $request->all() in Laravel, $input->getArray() in Joomla!;
  • a database row fetched as an associative array, a configuration map.

A nested array is a nested bag, so Map and Maps walk it as far down as it goes. A list is a bag too — its names are its indexes, so lines.0.sku reaches into one — and an integer key is a name like any other: PHP writes '1' and 1 as the same key. Anything else is not a bag: null is "no dictionary", and a string, a number, a boolean or an object is refused by name — "a stdClass is not a dictionary", which is what json_decode($json) without the second argument gives you. Decode with true.

Keys are matched exactly, and JSON keys are case-sensitive — 'name' does not find 'Name'. One kindness: when your key has stray spaces around it, it is tried once more trimmed.

use SafeCoder\CommonKit\CkDictionary;

$row = json_decode('{ "id": 7 }', true);

CkDictionary::Integer(dictionary: $row, key: ' id ');                        // -> 7  (your key, trimmed and retried)
CkDictionary::Integer(dictionary: json_decode('{ "id": 7 }'), key: 'id');    // -> 0  (objects are not a bag — decode with true)

Methods

String

One entry as clean text.

static function String(
    mixed $dictionary = null,
    ?string $key = null,
    mixed $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
fallback mixed null Backup text when the entry is missing or unreadable; it is cleaned the same way, and '' stands in when none was given.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry holds one readable value The clean text: 'Mary Smith' The clean text: 'Mary Smith'
Rejected: missing entry, null, no usable text, or a nested array The cleaned fallback; '' when none was given Throws CkDictionaryException — carries Input, Key and Reason

A boolean comes back as 'True'/'False' — the library's own spelling, not JSON's.

String reads one entry as tidy text: a string value goes through CkText::String (markup stripped, whitespace collapsed), and a value of another kind is written with the library's own invariant writers — so a true becomes 'True', a number is written with CkText::NumberToString, a CkDay becomes '2026-08-31', a moment becomes '2026-08-31T14:05:00Z' (CkDate::Iso8601), an identifier its canonical text (CkUuid::Canonical), and an object that writes itself as text is read as that text. Missing or unreadable answers the fallback, cleaned the same way; '' when none was given.

use SafeCoder\CommonKit\CkDictionary;

$person = json_decode('{ "name": " Mary  Smith ", "qty": 12, "ok": true }', true);

CkDictionary::String(dictionary: $person, key: 'name');    // -> 'Mary Smith'
CkDictionary::String(dictionary: $person, key: 'qty');     // -> '12'
CkDictionary::String(dictionary: $person, key: 'ok');      // -> 'True'

CkDictionary::String(
    dictionary: $person,
    key: 'gone',
    fallback: 'n/a'
);                                                         // -> 'n/a'

Strings

A list of clean text.

static function Strings(
    mixed $dictionary = null,
    ?string $key = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering an empty list.

Returns

When Default With throwIfInvalid: true
The entry is a list, or one lone value The clean items: ['red', '7', 'blue'] — the empty ones dropped The clean items: ['red', '7', 'blue'] — the empty ones dropped
Rejected: missing entry, null, or a value that is itself a map Empty list Throws CkDictionaryException — carries Input, Key and Reason

A lone value still lists: 'solo' answers ['solo'], never a list of characters.

Strings reads a list of entries the same way as String, dropping the ones that came out empty — and a single value where a list was allowed still comes back as a one-item list.

use SafeCoder\CommonKit\CkDictionary;

$bag = json_decode('{ "tags": [" red ", "", 7, "blue"], "one": "solo" }', true);

CkDictionary::Strings(dictionary: $bag, key: 'tags');   // -> ['red', '7', 'blue']  (empty item dropped)
CkDictionary::Strings(dictionary: $bag, key: 'one');    // -> ['solo']  (one value still lists)
CkDictionary::Strings(dictionary: $bag, key: 'gone');   // -> []  (no such key)

The next seven sections are the number readers — Float for PHP's float, five named for the database column the value is bound for (TinyInt to BigInt, each with an unsigned switch that is on by default; there is no plain Int, so a whole number is always judged by the column that will hold it), and Decimal, the exact one — each handing the found value to its CkNumber twin, so the same rules apply: fractions round to the nearest whole number for the whole-number readers (exact: true refuses them instead), out-of-range and not-a-number answer the fallback, 0 unless you pick another. Each member below only tells you the type you get and what it holds; the shared exact and fallback moves are shown once, under Integer.

Float

A decimal number, about 15 digits.

static function Float(
    mixed $dictionary = null,
    ?string $key = null,
    float $fallback = 0.0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): float
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
fallback float 0.0 What comes back when the entry is missing or cannot be converted.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text, that a float holds The converted float: 3.14159 The converted float: 3.14159
Rejected: missing entry, null, not a finite number, or not a number The fallback (default 0.0) Throws CkDictionaryException — carries Input, Key and Reason

Fractions are kept — the two fractional readers take no exact.

You get a float, precise to about 15 significant digits (the digits that carry meaning, counted from the first non-zero one) — the type a decoded JSON number with a fraction arrives as. An amount of money is read by CkMoney::Amount, which knows the currency: hand it Value.

use SafeCoder\CommonKit\CkDictionary;

$circle = json_decode('{ "pi": "3.14159" }', true);

CkDictionary::Float(dictionary: $circle, key: 'pi');   // -> 3.14159

TinyInt

A whole number for a TINYINT column.

static function TinyInt(
    mixed $dictionary = null,
    ?string $key = null,
    bool $unsigned = true,
    bool $exact = false,
    int $fallback = 0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): int
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
unsigned bool true true for a column declared UNSIGNED, 0 to 255; false for a signed one, -128 to 127.
exact bool false false rounds a fractional value to the nearest whole number first; true accepts only whole values.
fallback int 0 What comes back when the entry is missing or cannot be converted.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text, in the column's range The converted int: 200 The converted int: 200
Rejected: missing entry, null, out of range, or not a number The fallback (default 0) Throws CkDictionaryException — carries Input, Key and Reason

Fractions round to nearest by default (exact: true refuses them); out of range answers the fallback, never a clamp.

You get an int that fits a one-byte column — right for tiny counts and flags. The unsigned switch is on by default, so a negative value is refused; turn it off for a signed column.

use SafeCoder\CommonKit\CkDictionary;

$levels = json_decode('{ "level": 200, "big": 300, "offset": -5 }', true);

CkDictionary::TinyInt(dictionary: $levels, key: 'level');    // -> 200
CkDictionary::TinyInt(dictionary: $levels, key: 'big');      // -> 0  (300 is out of range — the fallback)
CkDictionary::TinyInt(dictionary: $levels, key: 'offset');   // -> 0  (negative, and the column is unsigned)

CkDictionary::TinyInt(
    dictionary: $levels,
    key: 'offset',
    unsigned: false
);                                                           // -> -5  (a signed column holds it)

SmallInt

A whole number for a SMALLINT column.

static function SmallInt(
    mixed $dictionary = null,
    ?string $key = null,
    bool $unsigned = true,
    bool $exact = false,
    int $fallback = 0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): int
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
unsigned bool true true for a column declared UNSIGNED, 0 to 65,535; false for a signed one, -32,768 to 32,767.
exact bool false false rounds a fractional value to the nearest whole number first; true accepts only whole values.
fallback int 0 What comes back when the entry is missing or cannot be converted.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text, in the column's range The converted int: 8080 The converted int: 8080
Rejected: missing entry, null, out of range, or not a number The fallback (default 0) Throws CkDictionaryException — carries Input, Key and Reason

Fractions round to nearest by default (exact: true refuses them); out of range answers the fallback, never a clamp.

You get an int that fits a two-byte column — 0 to 65,535 unsigned, the classic fit for a network port.

use SafeCoder\CommonKit\CkDictionary;

$net = json_decode('{ "port": 8080 }', true);

CkDictionary::SmallInt(dictionary: $net, key: 'port');   // -> 8080

MediumInt

A whole number for a MEDIUMINT column.

static function MediumInt(
    mixed $dictionary = null,
    ?string $key = null,
    bool $unsigned = true,
    bool $exact = false,
    int $fallback = 0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): int
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
unsigned bool true true for a column declared UNSIGNED, 0 to 16,777,215; false for a signed one, -8,388,608 to 8,388,607.
exact bool false false rounds a fractional value to the nearest whole number first; true accepts only whole values.
fallback int 0 What comes back when the entry is missing or cannot be converted.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text, in the column's range The converted int: 16777215 The converted int: 16777215
Rejected: missing entry, null, out of range, or not a number The fallback (default 0) Throws CkDictionaryException — carries Input, Key and Reason

Fractions round to nearest by default (exact: true refuses them); out of range answers the fallback, never a clamp.

You get an int that fits a three-byte column — 0 to 16,777,215 unsigned, which is exactly a 24-bit colour.

use SafeCoder\CommonKit\CkDictionary;

$paint = json_decode('{ "colour": 16777215 }', true);

CkDictionary::MediumInt(dictionary: $paint, key: 'colour');   // -> 16777215

Integer

A whole number for an INT column.

static function Integer(
    mixed $dictionary = null,
    ?string $key = null,
    bool $unsigned = true,
    bool $exact = false,
    int $fallback = 0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): int
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
unsigned bool true true for a column declared UNSIGNED, 0 to 4,294,967,295; false for a signed one, -2,147,483,648 to 2,147,483,647.
exact bool false false rounds a fractional value to the nearest whole number first; true accepts only whole values.
fallback int 0 What comes back when the entry is missing or cannot be converted.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text, in the column's range The converted int: 3000000000 The converted int: 3000000000
Rejected: missing entry, null, out of range, or not a number The fallback (default 0) Throws CkDictionaryException — carries Input, Key and Reason

Fractions round to nearest by default (exact: true refuses them); out of range answers the fallback, never a clamp.

You get an int that fits a four-byte column — the everyday INT, about ±2.1 billion signed, twice that with no negatives, the column most ids and counts live in — and the one this example uses to show the family's shared exact and fallback moves. For a value bound for another column, ask for that column's reader — SmallInt for SMALLINT, BigInt for BIGINT — so the value is judged by what will hold it; there is no plain Int, on purpose.

use SafeCoder\CommonKit\CkDictionary;

$order = json_decode('{ "id": 7, "qty": "3.7", "note": "n/a", "views": 3000000000 }', true);

CkDictionary::Integer(dictionary: $order, key: 'id');      // -> 7
CkDictionary::Integer(dictionary: $order, key: 'qty');     // -> 4  ('3.7' rounds to nearest)

CkDictionary::Integer(
    dictionary: $order,
    key: 'qty',
    exact: true
);                                                         // -> 0  (a fraction is refused)

CkDictionary::Integer(
    dictionary: $order,
    key: 'note',
    fallback: -1
);                                                         // -> -1  ('n/a' is not a number)

CkDictionary::Integer(dictionary: $order, key: 'views');   // -> 3000000000  (too big for a signed INT, fine unsigned)

CkDictionary::Integer(
    dictionary: $order,
    key: 'views',
    unsigned: false
);                                                         // -> 0  (a signed INT stops at 2,147,483,647)

BigInt

A whole number for a BIGINT column.

static function BigInt(
    mixed $dictionary = null,
    ?string $key = null,
    bool $unsigned = true,
    bool $exact = false,
    int $fallback = 0,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): int
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
unsigned bool true true for a column declared UNSIGNED, 0 to 9,223,372,036,854,775,807 — where a PHP int stops; false for a signed one, the whole int range.
exact bool false false rounds a fractional value to the nearest whole number first; true accepts only whole values.
fallback int 0 What comes back when the entry is missing or cannot be converted.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text, in the column's range The converted int: 5000000000 The converted int: 5000000000
Rejected: missing entry, null, out of range, or not a number The fallback (default 0) Throws CkDictionaryException — carries Input, Key and Reason

Fractions round to nearest by default (exact: true refuses them); out of range answers the fallback, never a clamp.

You get an int for an eight-byte column — the widest a database holds and the widest a PHP int holds, so an unsigned BIGINT value past 9,223,372,036,854,775,807 cannot come back as an int at all: read it with Decimal, which keeps every digit.

use SafeCoder\CommonKit\CkDictionary;

$file = json_decode('{ "bytes": 5000000000, "huge": "18446744073709551615" }', true);

CkDictionary::BigInt(dictionary: $file, key: 'bytes');    // -> 5000000000
CkDictionary::BigInt(dictionary: $file, key: 'huge');     // -> 0  (past a PHP int — Decimal reads it)
CkDictionary::Decimal(dictionary: $file, key: 'huge');    // -> '18446744073709551615'

Decimal

The exact one for a DECIMAL column, as text.

static function Decimal(
    mixed $dictionary = null,
    ?string $key = null,
    string $fallback = '0',
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): string
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
fallback string '0' What comes back when the entry is missing or cannot be converted; numeric text.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a number, or numeric text The value as numeric text, every digit kept: '19.99' The value as numeric text, every digit kept: '19.99'
Rejected: missing entry, null, or not a number The fallback (default '0') Throws CkDictionaryException — carries Input, Key and Reason

Fractions are kept — the two fractional readers take no exact.

You get numeric text — the number, not its spelling ('12.50' reads as '12.5'), exact on every digit and with no ceiling: what a DECIMAL column travels in, where a float keeps about fifteen digits, and what every CkMoney method reads back.

use SafeCoder\CommonKit\CkDictionary;

$cart = json_decode('{ "price": "19.99", "total": "12.50" }', true);

CkDictionary::Decimal(dictionary: $cart, key: 'price');   // -> '19.99'
CkDictionary::Decimal(dictionary: $cart, key: 'total');   // -> '12.5'  (the number, not its spelling)

Bool

True and false, strictly.

static function Bool(
    mixed $dictionary = null,
    ?string $key = null,
    bool $fallback = false,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): bool
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
fallback bool false What comes back when the entry is missing or not a recognized boolean — an unreadable value is not read as false.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry is a real boolean, a listed word, or a number that is exactly 1 or 0 The boolean: true The boolean: true
Rejected: missing entry, null, or not a boolean — 'published', 2, a date The fallback (default false) Throws CkDictionaryException — carries Input, Key and Reason

Unreadable is not false — it answers the fallback, so map your own status words with CkBool::FromText.

The value goes to CkBool, so the library's one boolean rule applies. A real boolean passes straight through. Text is read case-insensitively from a fixed list: true, t, yes, y, on mean true; false, f, no, n, off mean false. A number counts only when it is exactly 1 or 0 — as a number, or as numeric text such as '1' or '1.0'. Anything else — 'published', 2, a date — is not silently false: it is unreadable, so you get the fallback (false unless you pick another). That is deliberately not PHP's own truthiness, to which 'no' and 'off' are true.

use SafeCoder\CommonKit\CkDictionary;

$flags = json_decode('{ "a": true, "b": "YES", "c": 0, "d": "published" }', true);

CkDictionary::Bool(dictionary: $flags, key: 'a');   // -> true
CkDictionary::Bool(dictionary: $flags, key: 'b');   // -> true   ('YES' is on the list)
CkDictionary::Bool(dictionary: $flags, key: 'c');   // -> false  (the number 0)
CkDictionary::Bool(dictionary: $flags, key: 'd');   // -> false  (the fallback — not a reading)

CkDictionary::Bool(
    dictionary: $flags,
    key: 'd',
    fallback: true
);                                                  // -> true   (the fallback again)

When "unknown" must not become "no" — a nullable column, a consent flag — take the entry with Value and hand it to CkBool::FromValueOrNull, which answers null for a missing or unreadable value:

use SafeCoder\CommonKit\CkBool;
use SafeCoder\CommonKit\CkDictionary;

$flags = json_decode('{ "c": 0, "d": "published" }', true);

CkBool::FromValueOrNull(CkDictionary::Value(dictionary: $flags, key: 'c'));   // -> false  (said no)
CkBool::FromValueOrNull(CkDictionary::Value(dictionary: $flags, key: 'd'));   // -> null   (unreadable)
CkBool::FromValueOrNull(CkDictionary::Value(dictionary: $flags, key: 'e'));   // -> null   (no such entry)

The two date readers follow the column type: Carbon hands the value to CkDate::ToCarbon and answers a moment — a Carbon in UTC — and CarbonDay to CkDate::ToCarbonDay and answers a calendar day — a CkDay, a Carbon at midnight UTC that says it is a day. Every shape that class reads works here: ISO 8601, compact Ymd, slashed dates in your declared order, Unix timestamps, date objects. format is a PHP date format, 'd.m.Y'. assumeZone says which clock a zone-less value was written on (CkSettings::DefaultAssumeZone behind it); zone, on CarbonDay, says whose calendar day a moment belongs to (CkSettings::DefaultZone behind it) — a date with no time of day is never moved by either. SQL placeholder dates such as 1900-01-01 count as missing by default (treatSentinelsAsMissing). Missing or unreadable answers your fallback — the year-one sentinel when none was given, a date no real record has.

Carbon

A date with its time of day.

static function Carbon(
    mixed $dictionary = null,
    ?string $key = null,
    DateOrder $order = CkSettings::DefaultDateOrder,
    ?string $format = null,
    ?string $assumeZone = CkSettings::DefaultAssumeZone,
    bool $treatSentinelsAsMissing = true,
    ?\DateTimeInterface $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): Carbon
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
order DateOrder CkSettings::DefaultDateOrder (DateOrder::MonthFirst) How a slashed date orders its parts.
format ?string null An exact PHP date format the text must match — 'd.m.Y' — when one is declared.
assumeZone ?string CkSettings::DefaultAssumeZone (null) A time zone id for zone-less values, converted to UTC — see CkDate.
treatSentinelsAsMissing bool true Reads SQL placeholder dates such as 1900-01-01 as missing.
fallback ?\DateTimeInterface null What comes back when the entry is missing or unreadable, read as a moment in UTC and checked the same way — a placeholder fallback such as 1900-01-01 is no fallback while treatSentinelsAsMissing is true; year one when not given.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry holds a readable date The moment, a Carbon in UTC: Carbon 2023-11-14T22:13:20Z The moment, a Carbon in UTC: Carbon 2023-11-14T22:13:20Z
Rejected: missing entry, null, a placeholder date, or unreadable text The fallback, in UTC; year one (Carbon 0001-01-01T00:00:00Z) when none was given or the fallback is a placeholder too Throws CkDictionaryException — carries Input, Key and Reason

A number is read as a Unix timestamp.

Carbon reads a moment in time — a calendar date together with a time of day — and hands it out as CkDate::ToCarbon does: a Carbon in UTC, or, once CkSettings::DefaultAssumeZone names the clock your database stores, a Carbon carrying that zone, the same moment shown on it.

use SafeCoder\CommonKit\CkDictionary;

$visit = json_decode('{ "since": "2024-03-01", "stamp": 1700000000, "local": "2024-03-01 09:30" }', true);

CkDictionary::Carbon(dictionary: $visit, key: 'stamp');   // -> Carbon 2023-11-14T22:13:20Z  (Unix seconds)
CkDictionary::Carbon(dictionary: $visit, key: 'since');   // -> Carbon 2024-03-01T00:00:00Z  (a date alone is midnight UTC)
CkDictionary::Carbon(
    dictionary: $visit,
    key: 'local',
    assumeZone: 'America/Chicago'
);                                                          // -> Carbon 2024-03-01T15:30:00Z  (09:30 on Chicago's clock)
CkDictionary::Carbon(dictionary: $visit, key: 'gone');    // -> Carbon 0001-01-01T00:00:00Z  (year one — the sentinel)

CarbonDay

A calendar date alone.

static function CarbonDay(
    mixed $dictionary = null,
    ?string $key = null,
    DateOrder $order = CkSettings::DefaultDateOrder,
    ?string $format = null,
    ?string $assumeZone = CkSettings::DefaultAssumeZone,
    ?string $zone = CkSettings::DefaultZone,
    bool $treatSentinelsAsMissing = true,
    ?\DateTimeInterface $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): Carbon
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
order DateOrder CkSettings::DefaultDateOrder (DateOrder::MonthFirst) How a slashed date orders its parts.
format ?string null An exact PHP date format the text must match — 'd.m.Y' — when one is declared.
assumeZone ?string CkSettings::DefaultAssumeZone (null) The time zone the value's digits are wall-clock in, when the value carries a time of day and declares no zone of its own. null means zone-less digits count as UTC. A date alone is never moved by it.
zone ?string CkSettings::DefaultZone (null) The time zone whose calendar day counts, as an IANA or Windows id; null for the UTC day. Only a value with a time of day is placed: a date alone is that day everywhere, and no zone moves it — see CkDate.
treatSentinelsAsMissing bool true Reads SQL placeholder dates such as 1900-01-01 as missing.
fallback ?\DateTimeInterface null What comes back when the entry is missing or unreadable, read as a day and checked the same way — a placeholder fallback such as 1900-01-01 is no fallback while treatSentinelsAsMissing is true; year one when not given.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The entry holds a readable date The day, a CkDay at midnight UTC: CkDay 2024-03-01T00:00:00Z The day, a CkDay at midnight UTC: CkDay 2024-03-01T00:00:00Z
Rejected: missing entry, null, a placeholder date, or unreadable text The fallback; year one (Carbon 0001-01-01T00:00:00Z) when none was given or the fallback is a placeholder too Throws CkDictionaryException — carries Input, Key and Reason

SQL placeholder dates such as 1900-01-01 count as missing unless you switch treatSentinelsAsMissing off.

Works like Carbon but answers a CkDay — a Carbon at midnight UTC that says it is a day, IsDateAlone(), and is read back by the library as a date alone, never moved by a zone. A value that carries a time of day is placed on zone's calendar first, so a moment just after midnight UTC is still the evening before in Chicago; a date alone is never moved.

use SafeCoder\CommonKit\CkDictionary;

$visit = json_decode('{ "since": "2024-03-01", "stamp": 1700000000 }', true);

CkDictionary::CarbonDay(dictionary: $visit, key: 'since');   // -> CkDay 2024-03-01T00:00:00Z
CkDictionary::CarbonDay(dictionary: $visit, key: 'stamp');   // -> CkDay 2023-11-14T00:00:00Z  (the UTC day of the Unix seconds)
CkDictionary::CarbonDay(
    dictionary: $visit,
    key: 'stamp',
    zone: 'Asia/Tokyo'
);                                                             // -> CkDay 2023-11-15T00:00:00Z  (22:13 UTC is 07:13 the next morning in Tokyo)
CkDictionary::CarbonDay(dictionary: $visit, key: 'since')->IsDateAlone();   // -> true

Uuid

Identifiers out.

static function Uuid(
    mixed $dictionary = null,
    ?string $key = null,
    bool $treatZerosAsMissing = true,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): UuidInterface
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
treatZerosAsMissing bool true Reads an all-zeros UUID in the data as missing, as CkUuid does.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the nil UUID.

Returns

When Default With throwIfInvalid: true
The entry is a UUID in any shape CkUuid reads The identifier, a UuidInterface: Uuid 0f8fad5b-d9cb-469f-a165-70867728950e The identifier: Uuid 0f8fad5b-d9cb-469f-a165-70867728950e
Rejected: missing entry, null, an all-zeros UUID, or unreadable text The nil UUID, Uuid 00000000-0000-0000-0000-000000000000 Throws CkDictionaryException — carries Input, Key and Reason

No substitute fallback for an identity — a rejected id is the nil UUID, never an invented one.

Reads a UUID (a 128-bit unique id) in any shape CkUuid accepts — hyphenated, bare hex, braced, urn:uuid: — and hands it back as the identifier object CkUuid::ToUuid hands out. As everywhere in CkUuid, there is no substitute fallback for an identity: missing or unreadable answers the nil UUID (all zeros), never an invented id. An all-zeros value in the data also counts as missing by default (treatZerosAsMissing).

use SafeCoder\CommonKit\CkDictionary;

$record = json_decode('{ "id": "0F8FAD5B-D9CB-469F-A165-70867728950E" }', true);

CkDictionary::Uuid(dictionary: $record, key: 'id');     // -> Uuid 0f8fad5b-d9cb-469f-a165-70867728950e
CkDictionary::Uuid(dictionary: $record, key: 'gone');   // -> Uuid 00000000-0000-0000-0000-000000000000  (the nil UUID)

Enum

A word or a number into your enum.

static function Enum(
    mixed $dictionary = null,
    ?string $key = null,
    string $enumClass = '',
    ?\UnitEnum $fallback = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): ?\UnitEnum
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
enumClass string '' The enum to read a case of, named by its class: Status::class.
fallback ?\UnitEnum null What comes back when the entry is missing or names no case; the enum's first case when not given — and when what was given is a case of another enum.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering the fallback.

Returns

When Default With throwIfInvalid: true
The value names a case, or is its backing value The case: Status::Approved The case: Status::Approved
Rejected: missing entry, an unknown name, or a number no case carries The fallback — the enum's first case when not given Throws CkDictionaryException — carries Input, Key and Reason
enumClass names no enum null, whatever the fallback Throws CkDictionaryException — the reason is "not an enum type"

Only defined cases come back — no stray values, nothing invented.

Reads a case of your own enum type, named by its class. A case name matches in any casing; a number — or numeric text — must be the backing value of a case. Either way the answer is always a case of that enum — an unknown name or number answers the fallback, the enum's first case unless you pick another. The library's own enums work the same way: DayOfWeek::class reads 'monday'.

use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\Enums\DayOfWeek;

enum Status: int { case Unknown = 0; case Draft = 1; case Approved = 2; }

$ticket = json_decode('{ "a": "approved", "b": 2, "c": "banana", "d": 99, "day": "monday" }', true);

CkDictionary::Enum(dictionary: $ticket, key: 'a', enumClass: Status::class);   // -> Status::Approved  (any casing)
CkDictionary::Enum(dictionary: $ticket, key: 'b', enumClass: Status::class);   // -> Status::Approved  (by value)
CkDictionary::Enum(dictionary: $ticket, key: 'c', enumClass: Status::class);   // -> Status::Unknown   (the first case)

CkDictionary::Enum(
    dictionary: $ticket,
    key: 'd',
    enumClass: Status::class,
    fallback: Status::Draft
);                                                                               // -> Status::Draft  (99 is not defined)

CkDictionary::Enum(dictionary: $ticket, key: 'day', enumClass: DayOfWeek::class);   // -> DayOfWeek::Monday

The next three readers walk nested data. All three answer empty — never null — when there is nothing usable. And one scalar always wraps to a one-item list: a single piece of text becomes ['text'], never a list of its characters.

Map

A nested object as a new bag.

static function Map(
    mixed $dictionary = null,
    ?string $key = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering an empty array.

Returns

When Default With throwIfInvalid: true
The entry is a map — a nested array with named entries A new bag of its entries: ['id' => 7, 'address' => [ … ]] in the example A new bag of its entries: ['id' => 7, 'address' => [ … ]] in the example
Rejected: missing entry, null, or a value that is not a map — a scalar, or a plain list Empty array Throws CkDictionaryException — carries Input, Key and Reason

The bag you get is a copy, ready to pass straight back into any method here.

Map reads a nested object as a new bag you can pass straight back into any method here — that is how you walk into deeper JSON, one level per call. (A dotted path does the same in one call: CkDictionary::String($payload, 'member.address.zip') — see At.)

use SafeCoder\CommonKit\CkDictionary;

$payload = json_decode('{ "member": { "id": 7, "address": { "zip": "78701" } } }', true);

$member = CkDictionary::Map(dictionary: $payload, key: 'member');
CkDictionary::Integer(dictionary: $member, key: 'id');        // -> 7

$address = CkDictionary::Map(dictionary: $member, key: 'address');
CkDictionary::String(dictionary: $address, key: 'zip');   // -> '78701'

CkDictionary::Map(dictionary: $payload, key: 'gone');     // -> []  (no such key)

Maps

A list of nested objects.

static function Maps(
    mixed $dictionary = null,
    ?string $key = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering an empty list.

Returns

When Default With throwIfInvalid: true
The entry is a list of maps, or one bare map One bag per map, as a list: [['id' => 1], ['id' => 2]] — a single map still lists One bag per map, as a list: [['id' => 1], ['id' => 2]] — a single map still lists
Rejected: missing entry, null, or a value that is neither a list nor a map Empty list Throws CkDictionaryException — carries Input, Key and Reason

Items that are not maps are left out silently; with throwIfInvalid: true they are reported instead.

Maps reads a list of objects ("members": [ { … }, { … } ]) as a list of bags; a single object where a list was allowed comes back as a one-item list.

use SafeCoder\CommonKit\CkDictionary;

$lists = json_decode('{ "members": [ { "id": 1 }, { "id": 2 } ], "single": { "id": 3 }, "mixed": [1, "two", true] }', true);

CkDictionary::Maps(dictionary: $lists, key: 'members');   // -> [['id' => 1], ['id' => 2]]  (two bags, ready for a loop)
CkDictionary::Maps(dictionary: $lists, key: 'single');    // -> [['id' => 3]]  (a one-item list of bags)
CkDictionary::Maps(dictionary: $lists, key: 'mixed');     // -> []  (none of the items is a map)

Items

A list of raw values.

static function Items(
    mixed $dictionary = null,
    ?string $key = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): array
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering an empty list.

Returns

When Default With throwIfInvalid: true
The entry is a list, or one lone value The raw values: [1, 'two', true] The raw values: [1, 'two', true]
Rejected: missing entry, null, or a value that is itself a map Empty list Throws CkDictionaryException — carries Input, Key and Reason

The values come back as stored — the 1 in [1, 'two', true] is an int.

Items reads a list of raw values the way Value hands them back: as stored, not converted.

use SafeCoder\CommonKit\CkDictionary;

$lists = json_decode('{ "mixed": [1, "two", true], "one": "solo" }', true);

CkDictionary::Items(dictionary: $lists, key: 'mixed');   // -> [1, 'two', true]  (raw values)
CkDictionary::Items(dictionary: $lists, key: 'one');     // -> ['solo']  (one value still lists)

Value

The raw escape hatch.

static function Value(
    mixed $dictionary = null,
    ?string $key = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): mixed
Parameter Type Default What it does
dictionary mixed null The bag to read from — an array with named entries; see What counts as a bag.
key ?string null The key, matched exactly; tried once more trimmed when the exact key is absent.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says why, instead of answering null, when the entry is missing — a found null never throws.

Returns

When Default With throwIfInvalid: true
The entry holds a value The value as stored: 7 (an int — a whole JSON number arrives as one); a nested list or map as the array it is The value as stored
The entry exists but holds null null null — an honest nothing never throws
No bag, no key, or no entry under the key null Throws CkDictionaryException — carries Input, Key and Reason

null honestly means "nothing there" — this is the one method here that answers it.

When no typed method fits, Value hands the entry back as it sits in the bag, not converted, ready for any other CommonKit reader that takes any value. A null answer means "nothing there" — no bag, no key, or a null in the data.

use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkMoney;

$vrow = json_decode('{ "amount": "$1,250.00", "score": 7, "email": "ANA@Example.com" }', true);

// no CkDictionary::Amount exists — compose with Value:
CkMoney::Amount(CkDictionary::Value(dictionary: $vrow, key: 'amount'));   // -> 1250.0

// the classes that read text — CkEmail, CkIntl, CkUS — compose with String instead:
CkEmail::Address(CkDictionary::String(dictionary: $vrow, key: 'email'));  // -> 'ana@example.com'

CkDictionary::Value(dictionary: $vrow, key: 'score');   // -> 7  (an int — a whole JSON number arrives as one)
CkDictionary::Value(dictionary: $vrow, key: 'gone');    // -> null

At

A value down a dotted path.

static function At(
    mixed $dictionary = null,
    ?string $path = null,
    bool $throwIfInvalid = CkSettings::DefaultThrowIfInvalid
): mixed
Parameter Type Default What it does
dictionary mixed null The bag — an array with named entries.
path ?string null A dotted path, 'customer.address.zip', or a plain key.
throwIfInvalid bool CkSettings::DefaultThrowIfInvalid (false) Pass true to throw a CkDictionaryException that says which segment failed, instead of answering null.

Returns

When Default With throwIfInvalid: true
The path leads to a value The value, as stored The value
It leads nowhere, or to a null null Throws CkDictionaryException — the reason names the segment

Every reader on this page takes the same paths — Int($payload, 'order.total') works — so At is the spelling for when you want the raw value, or the intent on the page. The bag is asked for the whole key first, so a key that holds a dot literally still wins; the path is walked only when no such entry exists. A list is a bag whose names are its indexes, so a path reaches into one: 'lines.1.sku'.

use SafeCoder\CommonKit\CkDictionary;

$payload = json_decode('{ "customer": { "address": { "zip": "02134" }, "phone": null }, "order": { "total": "12.50" }, "lines": [ { "sku": "A-1" }, { "sku": "B-2" } ] }', true);

CkDictionary::At($payload, 'customer.address.zip');   // -> '02134'
CkDictionary::Decimal($payload, 'order.total');       // -> '12.5'  (every reader takes a path)
CkDictionary::At($payload, 'lines.1.sku');            // -> 'B-2'  (into a list, by index)
CkDictionary::At($payload, 'customer.phone');         // -> null

Has

Is the key there at all?

static function Has(
    mixed $dictionary = null,
    ?string $key = null
): bool
Parameter Type Default What it does
dictionary mixed null The bag — an array with named entries.
key ?string null The key, or a dotted path.

Returns

When You get
An entry exists under the key, whatever its value — a null included true
No bag, no key, or no such entry false — it never throws

The question Value cannot answer, since it says null both for "absent" and for "present but null".

use SafeCoder\CommonKit\CkDictionary;

$payload = json_decode('{ "customer": { "phone": null } }', true);

CkDictionary::Has($payload, 'customer.phone');   // -> true  (present, even though it is null)
CkDictionary::Has($payload, 'customer.fax');     // -> false

MissingKeys

The required fields that are not there.

static function MissingKeys(
    mixed $dictionary = null,
    mixed ...$keys
): array
Parameter Type Default What it does
dictionary mixed null The bag — an array with named entries.
keys mixed ... — The keys that must be present, plain or dotted — loose, or as one list. Null, blank and non-text entries are skipped.

Returns

When You get
Some keys are absent Those keys, trimmed, in the order asked
All are present, or no keys were asked An empty array — it never throws

The required-fields check for a form or a payload, in one call, judged as Has judges: present whatever the value. With no bag, every key is missing.

use SafeCoder\CommonKit\CkDictionary;

$payload = json_decode('{ "name": "Mary", "address": { "zip": "02134" } }', true);

CkDictionary::MissingKeys($payload, 'name', 'email', 'address.zip');   // -> ['email']
CkDictionary::MissingKeys($payload, ['name', 'email', 'phone']);        // -> ['email', 'phone']  (a list works too)

$missing = CkDictionary::MissingKeys($payload, 'name', 'email');
if ($missing !== []) {
    // "email is required"
}

Good to know

  • Dotted keys are paths. 'customer.address.zip' walks nested maps in every reader, after the bag has been asked for the whole key once — a key that holds a dot literally still wins. At is the explicit spelling; Has and MissingKeys take paths too. A stray leading or trailing dot is ignored, and a list is walked by index: 'lines.0.sku'.
  • Every kind of "nothing" behaves the same. No bag, no entry under the key and a null in the data all take the same road: the method's fallback (or null from Value).
  • Keys are case-sensitive. Exact match first; only your key's own surrounding spaces get one trimmed retry. 'name' never finds 'Name'.
  • A repeated key: the last value wins, everywhere. A bag built by CkPayload::FromJson or by json_decode, a form, a query — all answer the last value, which is every common parser's answer. That matters for a gate: the value the library judges is the value the application's own request handling will use, so a payload cannot show one URL to the check and another to the code.
  • Whole JSON numbers arrive as int. That is what Value and Items hand you for 7, and a fraction is a float; the typed readers convert onward, so you only notice at the escape hatch.
  • Decode with true. json_decode($json) on its own gives objects, and an object is not a bag: every reader answers its fallback with the reason "a stdClass is not a dictionary". json_decode($json, true) — or CkPayload, which already does it — gives the arrays this class reads.
  • Bags are plain arrays, so they are yours. What Map and Maps hand you is a copy: change it and nothing in the payload changes.
  • 'published' is not false. Bool answers the fallback for anything off its token list; check the fallback path, do not assume "unreadable means false".
  • Enum never invents cases. Only the enum's own cases come back — no stray values — and the enum is named by its class, Status::class.
  • Text never splits into characters. Items and Strings wrap one scalar into a one-item list; a lone 'solo' is ['solo'], not ['s', 'o', 'l', 'o'].

If you want errors instead

Every reader takes throwIfInvalid: true. A missing entry or an unreadable value then raises a CkDictionaryException (from SafeCoder\CommonKit\Exceptions) instead of answering the fallback. On top of the usual Input and Reason, this one carries the Key that failed, so the one-line message tells you exactly which field of the payload to look at — CkDictionary.Integer: cannot read key "gone" (String) — no entry under the key. — and when one of the library's own readers refused the value, its exception rides in getPrevious().

use SafeCoder\CommonKit\CkDictionary;

$strict = json_decode('{ "id": 7 }', true);

CkDictionary::Integer(
    dictionary: $strict,
    key: 'gone',
    throwIfInvalid: true
);   // throws CkDictionaryException