Skip to content

Common mistakes

Every trap on this page is one of using the library itself: a rejection value read as a real one, a fallback taken for an answer, a sentinel that looks like data. Each follows logically from the five rules — but each one has caught someone anyway. Read them once now, or debug them one at a time later. Each section names the mistake, shows the wrong assumption next to the right call, and says why in a sentence or two. PHP's own traps — the cast, strtotime, json_decode, the locale — are a page of their own, Why not just cast?.

A rejected calculation is zero

Every CkMoney calculation answers its fallback when a value cannot be used, and the fallback is '0' — text, as every amount the calculations write is:

use SafeCoder\CommonKit\CkMoney;

CkMoney::Multiply(
    input: '19.99',
    factor: '8.25%'
);   // -> '0'   ("8.25%" is not a plain number)

On a form that is a convenience. In a checkout it is an order for nothing. Wherever a wrong number costs money, pass throwIfInvalid: true on every line that reads an amount, so the order fails instead of charging nothing.

A bare number is not a percent

CkNumber::Percent reads values as rates — the fraction you multiply by. A trailing % divides by 100; a value without one is taken as the rate it already is:

use SafeCoder\CommonKit\CkNumber;

CkNumber::Percent('15%');    // -> 0.15
CkNumber::Percent('0.15');   // -> 0.15   (a bare value is the rate as it stands)
CkNumber::Percent(15);       // -> 15.0   (that is 1,500%!)

The method cannot guess that your 15 meant fifteen percent — 0.15 is also a perfectly good bare rate. Only the % mark says "divide me".

"published" is not false

The boolean readers — CkBool, and CkDictionary::Bool, which reads through it — accept a real boolean, a word from a declared list (true/t/yes/y/on and false/f/no/n/off, any casing), or a number that is exactly 1 or 0. Anything else is unreadable, and unreadable means you get the fallback, not false:

use SafeCoder\CommonKit\CkDictionary;
use SafeCoder\CommonKit\CkPayload;

$flags = CkPayload::FromJson('{ "visible": "yes", "status": "published" }');

CkDictionary::Bool(
    dictionary: $flags,
    key: 'visible'
);                          // -> true   ("yes" is on the list)

CkDictionary::Bool(
    dictionary: $flags,
    key: 'status'
);                          // -> false   (the fallback, not a reading)

CkDictionary::Bool(
    dictionary: $flags,
    key: 'status',
    fallback: true
);                          // -> true   (same unread value, other fallback)

A false from Bool can mean "the value said no" or "the value said nothing I recognise". When that difference matters, read the entry with the OrNull twin, which answers null for anything unreadable — and when the column holds your own status words, declare them:

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

$flags = CkPayload::FromJson('{ "visible": "yes", "status": "published" }');

CkBool::FromValueOrNull(CkDictionary::Value(
    dictionary: $flags,
    key: 'status'
));                         // -> null   (unknown stays unknown)

CkBool::FromText(
    input: CkDictionary::Value(dictionary: $flags, key: 'status'),
    trueWords: ['published'],
    falseWords: ['draft', 'archived']
);                          // -> true   (read, by your own vocabulary)

The same goes for numbers: 2 is not true. Only exactly 1 and 0 are booleans, so a count that lands in a flag column is caught instead of becoming a confident yes.

Zero means missing until you say otherwise

The OrNull readers treat a sentinel — a value that parses but really means "nobody filled this in" — as missing. For numbers and money, the sentinel is zero, and the treatment is on by default:

use SafeCoder\CommonKit\CkNumber;

CkNumber::IntegerOrNull('0');    // -> null   (zero reads as "nobody filled this in")
CkNumber::IntegerOrNull(
    input: '0',
    treatZeroAsMissing: false
);                           // -> 0   (you said zero is real)

When zero is a legitimate value — a balance, a count, a temperature — switch the flag off. Each class names its own: treatZeroAsMissing on numbers and money, treatSentinelsAsMissing on dates, treatZerosAsMissing on UUIDs — and on CkSentinel::ToNull, which applies the same verdicts on the way to storage, where a zero written as plain numeric text, '0' or '0.00', counts as a zero amount too.

A rejected date looks like a real date

A date has no safe "obviously wrong" value: the plain reader, CkDate::ToCarbon, rejects to year one — 0001-01-01T00:00:00Z — which is a Carbon like any other. It takes addDays, it formats, it compares, and a legacy SQL datetime column cannot even hold it:

use SafeCoder\CommonKit\CkDate;

CkDate::ToCarbon('not a date');          // -> Carbon 0001-01-01T00:00:00Z   (the rejection)
CkDate::ToCarbon('1900-01-01');          // -> Carbon 0001-01-01T00:00:00Z   (a placeholder is missing: the same rejection)
CkDate::ToCarbonOrNull('not a date');    // -> null   (clearly rejected)
CkDate::IsPlaceholder(CkDate::ToCarbon('not a date'));   // -> true   (the library knows its own sentinel)
CkDate::Format(
    input: CkDate::ToCarbon('not a date'),
    into: 'Y-m-d'
);                                       // -> ''   (and its writers refuse it)

Use the plain reader only when a wrong-but-obvious date is acceptable. ToCarbonOrNull is the honest reader — null and a real date can never be confused — IsPlaceholder is how a sentinel is found again, and CkSentinel::ToNull turns it into a real null on the way to the database.

Querying only for "" when the database also holds NULL

Once the CkSentinel::ToNull save hook is in place, new saves write NULL where older rows hold '' — the two live side by side in the same column, so a query for "missing" must ask for both, WHERE referrer IS NULL OR referrer = '':

// no-check
$wrong   = Member::where('referrer', '')->get();
$missing = Member::where(static fn ($query) => $query->whereNull('referrer')->orWhere('referrer', ''))->get();

Nothing errors to warn you when you check only one form. You never know what the whole data set holds — rows saved before the hook existed, imports, other applications writing to the same tables — so check both, every time.

A mask is not a validator

The display masks — CkUS::SsnMask and friends — exist to put something safe on screen, so they never return empty. An invalid value comes back fully masked, indistinguishable at a glance from a masked real one:

use SafeCoder\CommonKit\CkUS;

CkUS::SsnMask('garbage');        // -> '***-**-****'   (fully masked, not empty)
CkUS::Ssn('garbage');            // -> ''   (empty means rejected)
CkUS::Ssn('123-45-6789');        // -> '123-45-6789'
CkUS::SsnMask('123-45-6789');    // -> '***-**-6789'

"Non-empty in, empty out means rejected" does not apply to masks — they opted out of that rule on purpose. When you need to know whether a value is valid, call the reader (Ssn, Phone, …) and check for '', ask its yes-or-no twin (IsSsn, IsPhone, …), or ask Explain for the reason.

A false verdict has no reason

The validators — IsSsn, IsAddress, IsDate and their siblings — answer false for a value that is wrong and for one that is unusable: missing, blank, markup with nothing in it. One bool cannot say which, and it was never meant to. When the difference matters, ask Explain, which answers the reason in the reader's own words and '' when the value passes:

use SafeCoder\CommonKit\CkEmail;

CkEmail::IsAddress('');                 // -> false
CkEmail::IsAddress('mary.smith');       // -> false   (the same false)
CkEmail::Explain('');                   // -> 'no value'
CkEmail::Explain('mary.smith');         // -> 'no @ in the value'

A form shows the reason; a job that must stop passes throwIfInvalid: true to the reader and gets the same words in the exception. The validator's false is for code that only needs the verdict — an if, a filter, a count.

Html extracts text — it does not make text safe

CkText::Html answers one question: "what does this markup say?" Its output is plain text, and plain text can still contain <, > and quotes — everything a browser needs to misread it as markup again:

use SafeCoder\CommonKit\CkText;

CkText::Html('<b>Hello</b> <i>world</i>');   // -> 'Hello world'
CkText::Html('5 < 6 and 7 > 3');             // -> '5 < 6 and 7 > 3'   ("<" survives)

XSS (cross-site scripting — smuggling script into a page through data) is prevented by encoding at render time, in the page that displays the value: htmlspecialchars(), or the escaping your template engine does on its own. Html strips markup with regular expressions, not a parser, and makes no safety promise; never paste its output into a page as-is.

When the markup itself is what you want to keep — a description written in an editor, bold and links and all — the answer is CkSanitizer::Html: it parses the value for real, keeps the formatting and the media and nothing else, and writes it anew so that it is safe in the body of a page.

Where next

  • Why not just cast? — the traps (bool), (int), strtotime, json_decode and the locale lay for you, and the library's answer to each.
  • Writing a validator — every problem with a payload, reported at once.
  • How it works — the five rules, and which reader to call.