Skip to content

How it works

Every class in CommonKit follows the same five rules. Learn them once and you know the whole library — and reading a value becomes one small decision, made once per value.

Rule 1 — nothing throws by default

You can pass anything to any method: null, an empty string, garbage text, the wrong type, an array, a huge input. The method never crashes your app — not with an exception, not with a TypeError, not with a warning. It answers with a rejection value instead — a calm, predictable "this could not be used".

use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkNumber;
use SafeCoder\CommonKit\CkUuid;

CkEmail::Address(null);              // -> ''   (no crash)
CkEmail::Address('not an email');    // -> ''
CkNumber::Integer('banana');             // -> 0    (the default fallback)
CkUuid::ToUuid('oops');              // -> Uuid 00000000-0000-0000-0000-000000000000

The throw switch

Every throwIfInvalid parameter defaults to CkSettings::DefaultThrowIfInvalid, a constant that ships as false. Set it to true and it overrides every call — throwIfInvalid: false included — so every rejected value surfaces at once as a Ck<Class>Exception carrying the input, what was expected and the reason, instead of slipping by as a fallback nobody checked. That is a development switch: set it true while an app is being built, by you or by an AI agent, and back to false to ship. It is a class constant in CkSettings.php, so changing it means editing the library's source, which is why it is for teams that carry the library as source. Two things it never touches: Explain (Rule 4) and the …OrNull readers (Rule 3) — the reason and null are their whole answers.

Rule 2 — the rejection value depends on the return type

Every value you read — a quantity, a birthday, a price — is one of three calls: the plain method, its …OrNull twin, or the plain method with throwIfInvalid: true. All three clean and validate the value exactly the same way; the only difference is what comes back when the value is bad. One table settles it:

Your situation Call Bad input gives
I need a value no matter what — a property that cannot be null, and a default is fine the plain method, with a fallback your fallback
The column is nullable / I need to know whether it was really there the …OrNull twin null
Bad data must STOP the show — an import, a job that must not continue the plain method with throwIfInvalid: true that class's exception
I want the reason in words — a form, a validator that reports every problem the class's Explain the reason, '' when the value passes

Two words worth defining once: a non-nullable type cannot hold null — an int, a Carbon. A nullable type wears a ? — ?int, ?Carbon — and can. Databases call a missing value NULL, so nullable columns and the …OrNull twins go together.

What the plain method answers depends on what it returns:

You call… Bad input gives you…
a string method (CkText::String, CkEmail::Address, …) '' — an empty string
a number or money method your fallback parameter (default 0 — 0.0 for a float, '0' where the answer is exact numeric text)
any …OrNull method null
CkUuid::ToUuid the nil UUID, 00000000-0000-0000-0000-000000000000 (the text methods of the class, Canonical and Format, answer '')
a date reader (CkDate::ToCarbon, CkDate::ToCarbonDay) year one — a Carbon at 0001-01-01T00:00:00Z
a geo reader the North Pole (90, 0); geo calculations give NAN
a method that answers a list an empty array [] — never null
CkFile::FromBase64, the one method that answers bytes '' — no bytes
a display mask (SsnMask, CkEmail::Mask, …) a safe placeholder — never empty

For string methods this gives you a simple test: non-empty in, empty out means the value was rejected. Check for '' at the call site when it matters.

The plain method is for code that needs something to work with either way and a sensible default is fine. An order quantity, say — if the field is missing or unreadable, treating it as one item is a reasonable choice, and the program moves on:

use SafeCoder\CommonKit\CkNumber;

$raw = '3';

$quantity = CkNumber::Integer(
    input: $raw,
    fallback: 1
);

CkNumber::Integer(input: '3', fallback: 1);           // -> 3
CkNumber::Integer(input: '', fallback: 1);            // -> 1   (missing — the fallback steps in)
CkNumber::Integer(input: 'banana', fallback: 1);      // -> 1   (unreadable — same answer)

No if, no try, no null — the answer is always an int you can use. The cost: you cannot tell a real 1 from a fallback 1. When that difference matters, pick one of the other calls. The fallback goes through the exact same cleaning and validation as the input; a bad fallback is rejected too. When you need to detect a rejection through a fallback, choose one you can distinguish from real data — say -1 for a quantity that is never negative.

use SafeCoder\CommonKit\CkCountry;
use SafeCoder\CommonKit\CkNumber;

CkCountry::Alpha2(input: '???', fallback: 'US');    // -> 'US'   (the value is unusable)
CkNumber::Integer(input: 'banana', fallback: -1);       // -> -1

Rule 3 — when you want null, use the OrNull family

Databases have NULL; the rejection values above are not NULL. So the readers that feed nullable columns come in a second form: IntegerOrNull, AmountOrNull, ToCarbonOrNull, ToCarbonDayOrNull, ToUuidOrNull, ToMoneyOrNull, LatitudeOrNull, LongitudeOrNull — and seven more numeric ones. Use one when "nothing" is a real, honest answer you want to keep. An optional birthday, say — some people gave one, some did not, and the nullable column can say which:

use SafeCoder\CommonKit\CkDate;

$birthday = CkDate::ToCarbonDayOrNull('1985-04-12');   // -> CkDay 1985-04-12T00:00:00Z

CkDate::ToCarbonDayOrNull('');             // -> null   (missing)
CkDate::ToCarbonDayOrNull('junk');         // -> null   (unreadable)
CkDate::ToCarbonDayOrNull('1900-01-01');   // -> null   (a placeholder date — "nobody filled this in")

A CkDay is what every method that answers a calendar day hands out: a Carbon at midnight UTC that says it is a day — read back by the library, it is that day on every clock, never moved by a time zone.

One promise comes with the family: an OrNull method never throws — at all. It does not even take a throwIfInvalid parameter, and the throw switch does not reach it. Whatever goes wrong — a missing value, garbage text, a placeholder — null is the answer, because null is exactly what you asked for by choosing this reader. When you want errors instead, use the plain sibling (Integer, Amount, ToCarbon, …) with throwIfInvalid: true.

They answer null for three kinds of input:

  1. A missing value — null, or a string that is empty once cleaned.
  2. An unreadable value — 'banana' is not a number.
  3. A sentinel — a value that technically parses but really means "nobody filled this in": the number 0, placeholder dates like 1900-01-01, the all-zeros UUID. This is on by default and switchable per call — each class names its own flag (treatZeroAsMissing: false for numbers and money, treatSentinelsAsMissing: false for dates, treatZerosAsMissing: false for UUIDs).
use SafeCoder\CommonKit\CkDate;
use SafeCoder\CommonKit\CkNumber;

CkNumber::IntegerOrNull('42');                            // -> 42
CkNumber::IntegerOrNull('');                              // -> null   (missing)
CkNumber::IntegerOrNull('0');                             // -> null   (zero = sentinel)
CkNumber::IntegerOrNull(
    input: '0',
    treatZeroAsMissing: false
);                                                    // -> 0      (you said zero is real)
CkDate::ToCarbonOrNull('1900-01-01');                 // -> null   (placeholder date)

A yes-or-no value is where this family earns its keep, because a plain bool has no room for "unknown": a missing consent answer would be stored as a refusal. CkBool::FromValueOrNull keeps the three apart — and a boolean has no sentinel to watch for: false is always something somebody said.

use SafeCoder\CommonKit\CkBool;

$optIn = CkBool::FromValueOrNull('yes');   // -> true

CkBool::FromValueOrNull('no');      // -> false   (declined — a real answer)
CkBool::FromValueOrNull('');        // -> null    (never answered)

Strings are different

String methods have no OrNull twins — with one exception, CkText::ToStringOrNull, the nullable version of free-text cleaning:

use SafeCoder\CommonKit\CkText;

CkText::ToStringOrNull(' hi  there ');   // -> 'hi there'
CkText::ToStringOrNull('   ');           // -> null   (nothing left once cleaned)

For every other string method — CkEmail::Address, CkUS::Phone, CkText::Name, … — the rejection value is '', and the bridge to null is CkText::NullIfEmpty:

use SafeCoder\CommonKit\CkEmail;
use SafeCoder\CommonKit\CkText;

$email = CkText::NullIfEmpty(CkEmail::Address(' Mary.Smith@GMAIL.com '));   // -> 'mary.smith@gmail.com'

CkText::NullIfEmpty(CkEmail::Address('not an email'));                       // -> null

Read it inside-out: CkEmail::Address cleans and validates, answering '' for a bad address; CkText::NullIfEmpty turns that '' into the null your nullable column wants. Two small calls, one honest value. Saving through a framework's model, one hook can do this for every attribute at once — CkSentinel::ToNull, shown on Using it with Laravel, Joomla! and WordPress.

Rule 4 — when you want errors, ask with throwIfInvalid

Sometimes silence is wrong: an import that must not load garbage, a job that must stop at the first bad row, a test. Every cleaning and converting method takes throwIfInvalid: true. Then a value that cannot be used raises that class's own exception — CkTextException, CkNumberException, CkDateException, … — all final, all extending CkException, so one catch (CkException $error) covers them all when you want a single net. Every one carries the Input that failed and a short Reason, as public read-only properties:

use SafeCoder\CommonKit\CkMoney;
use SafeCoder\CommonKit\Exceptions\CkMoneyException;

$importRows = ['$19.99', 'ten dollars'];

foreach ($importRows as $raw) {
    try {
        $amount = CkMoney::Amount(
            input: $raw,
            throwIfInvalid: true
        );
        // ... save the amount ...
    } catch (CkMoneyException $error) {
        echo $error->getMessage() . PHP_EOL;   // one log-safe line: the method, the input, the reason
        echo $error->Reason . PHP_EOL;         // short and lowercase — for $raw = 'ten dollars': letters in the amount
    }
}

The row that says 'ten dollars' stops its loop iteration with a reason you can log or show an analyst, instead of quietly becoming 0.00 in the database.

A few members have nothing to throw about and take no flag: the display masks, the counters (WordCount, CharacterCount), CkText::Join / Split / SameText / Similarity, the In… allow-list checks (CkCountry::InCountries, CkMoney::InCurrencies, …), CkDictionary::Has / MissingKeys and their CkRequest twins, CkSentinel::ToNull — and Explain.

Explain — the reason without the exception

An exception stops at the first problem. A form, or a validator that reports everything wrong with a payload, wants the reason for each field and no exception in the flow. Every class with a reader has an Explain for that — CkEmail::Explain($input), CkDate::Explain($input), CkUS::Explain(input: $input, what: 'Ssn') where a class has several readers. The same rules, the same words the exception would carry, '' when the value passes; it never throws, not even with the throw switch on.

use SafeCoder\CommonKit\CkMoney;

CkMoney::Explain('ten dollars');   // -> 'letters in the amount'
CkMoney::Explain('$19.99');        // -> ''

Writing a validator builds a whole-payload check out of it.

Rule 5 — write data out the invariant way

Reading is half the job; the other half is writing values out — into JSON, a CSV, an API call. PHP's own writers each have a habit of their own. echo, a cast and a string with a variable in it write a float to the server's precision setting — fourteen significant digits by default, and whatever the host set it to — so the same value prints as 0.8 on one machine and 0.7999999999999999 on another. number_format groups the thousands with a comma and rounds to a whole number unless told otherwise, so 1234.5 leaves as "1,235". printf('%f') follows the server's locale and writes a decimal comma on a German or French one. A boolean cast is 1 or nothing at all. And date() writes the server's time zone. Any of those quietly corrupts your payload.

CommonKit's writers always write the invariant way — the same output on every machine:

use SafeCoder\CommonKit\CkBool;
use SafeCoder\CommonKit\CkDate;
use SafeCoder\CommonKit\CkText;

CkText::NumberToString(1234.5);                 // -> '1234.5'   (never '1,235')
CkBool::Format(true);                           // -> 'true'     (what JSON, XML and URLs expect)
CkDate::Iso8601(
    new \DateTimeImmutable('2026-09-02 10:30:00', new \DateTimeZone('UTC'))
);                                              // -> '2026-09-02T10:30:00Z'
CkDate::Format(
    input: CkDate::ToCarbonDay('2026-09-02'),
    into: 'Y-m-d'
);                                              // -> '2026-09-02'

A boolean has more than one written form, so CkBool::Format takes the spelling: lowercase true/false by default, 1/0 for a database flag, Y/N for a legacy column. (True/False — what CkText::BoolToString writes — is not valid JSON.) A moment is written by CkDate::Iso8601, always in UTC with the Z that says so; a calendar day by CkDate::Format with a date-only format.

Rule of thumb: data leaving your process goes through a CommonKit writer, never a raw echo, a cast or number_format.

Behind the rules

  • Everything is length-capped. A ten-megabyte "name" is rejected, not processed. Every cap and default is a public constant in CkSettings (for example CkSettings::MaxTextInputLength), so you can read the limits in one place. A cap counts content, not padding: a CHAR(255) column hands "42" back followed by 253 spaces, and CkNumber::IntOrNull still reads 42.
  • Every method is static and pure. No setup, no state, no container, nothing to construct — the classes cannot even be instantiated — call from anywhere.
  • A value of any type is accepted. Every reader's input is mixed: an array where a string was expected (name[]=x in a form), a number from JSON, false from a driver — each is judged, and what is not the kind of value asked for is rejected by name ("a Array is not text"), never with a TypeError. Options — a length, a TextCase, a flag — stay strictly typed: a wrong option is a programming mistake, and a TypeError is the right answer to it.
  • The server's locale and time zone are never consulted, reading or writing. setlocale and date_default_timezone_set change nothing; a comma-decimal locale on the server changes nothing.
  • Accents are composed on the way in. A base letter plus a combining mark, the way macOS writes "é", becomes the one composed letter in every reader of every class, so it counts, compares and stores like text typed anywhere else.

Where next

  • Your first payload — a fifteen-minute tutorial: a messy order payload to clean, typed values, and the whole handler at the end.
  • Common mistakes — the traps everyone hits once with the library itself.
  • Writing a validator — every problem with a payload, reported at once.
  • Setting up your file places — the platform's folders for every kind of file, or one root of your own, and the rules each place keeps.
  • Using it with a framework — Laravel, Joomla! and WordPress: the way in, reading the request, validating, one ToNull on the way to the database, and where the files go.